The Pedigree Project  0.1
sqlite3.c
1 /*
2  * Copyright (c) 2008-2014, Pedigree Developers
3  *
4  * Please see the CONTRIB file in the root of the source tree for a full
5  * list of contributors.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /******************************************************************************
21 ** This file is an amalgamation of many separate C source files from SQLite
22 ** version 3.15.1. By combining all the individual C code files into this
23 ** single large file, the entire code can be compiled as a single translation
24 ** unit. This allows many compilers to do optimizations that would not be
25 ** possible if the files were compiled separately. Performance improvements
26 ** of 5% or more are commonly seen when SQLite is compiled as a single
27 ** translation unit.
28 **
29 ** This file is all you need to compile SQLite. To use SQLite in other
30 ** programs, you need this file and the "sqlite3.h" header file that defines
31 ** the programming interface to the SQLite library. (If you do not have
32 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
33 ** the text of this file. Search for "Begin file sqlite3.h" to find the start
34 ** of the embedded sqlite3.h header file.) Additional code files may be needed
35 ** if you want a wrapper to interface SQLite with your choice of programming
36 ** language. The code for the "sqlite3" command-line shell is also in a
37 ** separate file. This file contains only code for the core SQLite library.
38 */
39 #define SQLITE_CORE 1
40 #define SQLITE_AMALGAMATION 1
41 #ifndef SQLITE_PRIVATE
42 # define SQLITE_PRIVATE static
43 #endif
44 /************** Begin file sqliteInt.h ***************************************/
45 /*
46 ** 2001 September 15
47 **
48 ** The author disclaims copyright to this source code. In place of
49 ** a legal notice, here is a blessing:
50 **
51 ** May you do good and not evil.
52 ** May you find forgiveness for yourself and forgive others.
53 ** May you share freely, never taking more than you give.
54 **
55 *************************************************************************
56 ** Internal interface definitions for SQLite.
57 **
58 */
59 #ifndef SQLITEINT_H
60 #define SQLITEINT_H
61 
62 /* Special Comments:
63 **
64 ** Some comments have special meaning to the tools that measure test
65 ** coverage:
66 **
67 ** NO_TEST - The branches on this line are not
68 ** measured by branch coverage. This is
69 ** used on lines of code that actually
70 ** implement parts of coverage testing.
71 **
72 ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
73 ** and the correct answer is still obtained,
74 ** though perhaps more slowly.
75 **
76 ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
77 ** and the correct answer is still obtained,
78 ** though perhaps more slowly.
79 **
80 ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
81 ** that would be harmless and undetectable
82 ** if it did occur.
83 **
84 ** In all cases, the special comment must be enclosed in the usual
85 ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
86 ** asterisks and the comment text.
87 */
88 
89 /*
90 ** Make sure the Tcl calling convention macro is defined. This macro is
91 ** only used by test code and Tcl integration code.
92 */
93 #ifndef SQLITE_TCLAPI
94 # define SQLITE_TCLAPI
95 #endif
96 
97 /*
98 ** Make sure that rand_s() is available on Windows systems with MSVC 2005
99 ** or higher.
100 */
101 #if defined(_MSC_VER) && _MSC_VER>=1400
102 # define _CRT_RAND_S
103 #endif
104 
105 /*
106 ** Include the header file used to customize the compiler options for MSVC.
107 ** This should be done first so that it can successfully prevent spurious
108 ** compiler warnings due to subsequent content in this file and other files
109 ** that are included by this file.
110 */
111 /************** Include msvc.h in the middle of sqliteInt.h ******************/
112 /************** Begin file msvc.h ********************************************/
113 /*
114 ** 2015 January 12
115 **
116 ** The author disclaims copyright to this source code. In place of
117 ** a legal notice, here is a blessing:
118 **
119 ** May you do good and not evil.
120 ** May you find forgiveness for yourself and forgive others.
121 ** May you share freely, never taking more than you give.
122 **
123 ******************************************************************************
124 **
125 ** This file contains code that is specific to MSVC.
126 */
127 #ifndef SQLITE_MSVC_H
128 #define SQLITE_MSVC_H
129 
130 #if defined(_MSC_VER)
131 #pragma warning(disable : 4054)
132 #pragma warning(disable : 4055)
133 #pragma warning(disable : 4100)
134 #pragma warning(disable : 4127)
135 #pragma warning(disable : 4130)
136 #pragma warning(disable : 4152)
137 #pragma warning(disable : 4189)
138 #pragma warning(disable : 4206)
139 #pragma warning(disable : 4210)
140 #pragma warning(disable : 4232)
141 #pragma warning(disable : 4244)
142 #pragma warning(disable : 4305)
143 #pragma warning(disable : 4306)
144 #pragma warning(disable : 4702)
145 #pragma warning(disable : 4706)
146 #endif /* defined(_MSC_VER) */
147 
148 #endif /* SQLITE_MSVC_H */
149 
150 /************** End of msvc.h ************************************************/
151 /************** Continuing where we left off in sqliteInt.h ******************/
152 
153 /*
154 ** Special setup for VxWorks
155 */
156 /************** Include vxworks.h in the middle of sqliteInt.h ***************/
157 /************** Begin file vxworks.h *****************************************/
158 /*
159 ** 2015-03-02
160 **
161 ** The author disclaims copyright to this source code. In place of
162 ** a legal notice, here is a blessing:
163 **
164 ** May you do good and not evil.
165 ** May you find forgiveness for yourself and forgive others.
166 ** May you share freely, never taking more than you give.
167 **
168 ******************************************************************************
169 **
170 ** This file contains code that is specific to Wind River's VxWorks
171 */
172 #if defined(__RTP__) || defined(_WRS_KERNEL)
173 /* This is VxWorks. Set up things specially for that OS
174 */
175 #include <vxWorks.h>
176 #include <pthread.h> /* amalgamator: dontcache */
177 #define OS_VXWORKS 1
178 #define SQLITE_OS_OTHER 0
179 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
180 #define SQLITE_OMIT_LOAD_EXTENSION 1
181 #define SQLITE_ENABLE_LOCKING_STYLE 0
182 #define HAVE_UTIME 1
183 #else
184 /* This is not VxWorks. */
185 #define OS_VXWORKS 0
186 #define HAVE_FCHOWN 1
187 #define HAVE_READLINK 1
188 #define HAVE_LSTAT 1
189 #endif /* defined(_WRS_KERNEL) */
190 
191 /************** End of vxworks.h *********************************************/
192 /************** Continuing where we left off in sqliteInt.h ******************/
193 
194 /*
195 ** These #defines should enable >2GB file support on POSIX if the
196 ** underlying operating system supports it. If the OS lacks
197 ** large file support, or if the OS is windows, these should be no-ops.
198 **
199 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
200 ** system #includes. Hence, this block of code must be the very first
201 ** code in all source files.
202 **
203 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
204 ** on the compiler command line. This is necessary if you are compiling
205 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
206 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
207 ** without this option, LFS is enable. But LFS does not exist in the kernel
208 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
209 ** portability you should omit LFS.
210 **
211 ** The previous paragraph was written in 2005. (This paragraph is written
212 ** on 2008-11-28.) These days, all Linux kernels support large files, so
213 ** you should probably leave LFS enabled. But some embedded platforms might
214 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
215 **
216 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
217 */
218 #ifndef SQLITE_DISABLE_LFS
219 # define _LARGE_FILE 1
220 # ifndef _FILE_OFFSET_BITS
221 # define _FILE_OFFSET_BITS 64
222 # endif
223 # define _LARGEFILE_SOURCE 1
224 #endif
225 
226 /* What version of GCC is being used. 0 means GCC is not being used */
227 #ifdef __GNUC__
228 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
229 #else
230 # define GCC_VERSION 0
231 #endif
232 
233 /* Needed for various definitions... */
234 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
235 # define _GNU_SOURCE
236 #endif
237 
238 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
239 # define _BSD_SOURCE
240 #endif
241 
242 /*
243 ** For MinGW, check to see if we can include the header file containing its
244 ** version information, among other things. Normally, this internal MinGW
245 ** header file would [only] be included automatically by other MinGW header
246 ** files; however, the contained version information is now required by this
247 ** header file to work around binary compatibility issues (see below) and
248 ** this is the only known way to reliably obtain it. This entire #if block
249 ** would be completely unnecessary if there was any other way of detecting
250 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
251 ** some MinGW-specific macros). When compiling for MinGW, either the
252 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
253 ** defined; otherwise, detection of conditions specific to MinGW will be
254 ** disabled.
255 */
256 #if defined(_HAVE_MINGW_H)
257 # include "mingw.h"
258 #elif defined(_HAVE__MINGW_H)
259 # include "_mingw.h"
260 #endif
261 
262 /*
263 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
264 ** define is required to maintain binary compatibility with the MSVC runtime
265 ** library in use (e.g. for Windows XP).
266 */
267 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
268  defined(_WIN32) && !defined(_WIN64) && \
269  defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
270  defined(__MSVCRT__)
271 # define _USE_32BIT_TIME_T
272 #endif
273 
274 /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
275 ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
276 ** MinGW.
277 */
278 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
279 /************** Begin file sqlite3.h *****************************************/
280 /*
281 ** 2001 September 15
282 **
283 ** The author disclaims copyright to this source code. In place of
284 ** a legal notice, here is a blessing:
285 **
286 ** May you do good and not evil.
287 ** May you find forgiveness for yourself and forgive others.
288 ** May you share freely, never taking more than you give.
289 **
290 *************************************************************************
291 ** This header file defines the interface that the SQLite library
292 ** presents to client programs. If a C-function, structure, datatype,
293 ** or constant definition does not appear in this file, then it is
294 ** not a published API of SQLite, is subject to change without
295 ** notice, and should not be referenced by programs that use SQLite.
296 **
297 ** Some of the definitions that are in this file are marked as
298 ** "experimental". Experimental interfaces are normally new
299 ** features recently added to SQLite. We do not anticipate changes
300 ** to experimental interfaces but reserve the right to make minor changes
301 ** if experience from use "in the wild" suggest such changes are prudent.
302 **
303 ** The official C-language API documentation for SQLite is derived
304 ** from comments in this file. This file is the authoritative source
305 ** on how SQLite interfaces are supposed to operate.
306 **
307 ** The name of this file under configuration management is "sqlite.h.in".
308 ** The makefile makes some minor changes to this file (such as inserting
309 ** the version number) and changes its name to "sqlite3.h" as
310 ** part of the build process.
311 */
312 #ifndef SQLITE3_H
313 #define SQLITE3_H
314 #include <stdarg.h> /* Needed for the definition of va_list */
315 
316 /*
317 ** Make sure we can call this stuff from C++.
318 */
319 #if 0
320 extern "C" {
321 #endif
322 
323 
324 /*
325 ** Provide the ability to override linkage features of the interface.
326 */
327 #ifndef SQLITE_EXTERN
328 # define SQLITE_EXTERN extern
329 #endif
330 #ifndef SQLITE_API
331 # define SQLITE_API
332 #endif
333 #ifndef SQLITE_CDECL
334 # define SQLITE_CDECL
335 #endif
336 #ifndef SQLITE_APICALL
337 # define SQLITE_APICALL
338 #endif
339 #ifndef SQLITE_STDCALL
340 # define SQLITE_STDCALL SQLITE_APICALL
341 #endif
342 #ifndef SQLITE_CALLBACK
343 # define SQLITE_CALLBACK
344 #endif
345 #ifndef SQLITE_SYSAPI
346 # define SQLITE_SYSAPI
347 #endif
348 
349 /*
350 ** These no-op macros are used in front of interfaces to mark those
351 ** interfaces as either deprecated or experimental. New applications
352 ** should not use deprecated interfaces - they are supported for backwards
353 ** compatibility only. Application writers should be aware that
354 ** experimental interfaces are subject to change in point releases.
355 **
356 ** These macros used to resolve to various kinds of compiler magic that
357 ** would generate warning messages when they were used. But that
358 ** compiler magic ended up generating such a flurry of bug reports
359 ** that we have taken it all out and gone back to using simple
360 ** noop macros.
361 */
362 #define SQLITE_DEPRECATED
363 #define SQLITE_EXPERIMENTAL
364 
365 /*
366 ** Ensure these symbols were not defined by some previous header file.
367 */
368 #ifdef SQLITE_VERSION
369 # undef SQLITE_VERSION
370 #endif
371 #ifdef SQLITE_VERSION_NUMBER
372 # undef SQLITE_VERSION_NUMBER
373 #endif
374 
375 /*
376 ** CAPI3REF: Compile-Time Library Version Numbers
377 **
378 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
379 ** evaluates to a string literal that is the SQLite version in the
380 ** format "X.Y.Z" where X is the major version number (always 3 for
381 ** SQLite3) and Y is the minor version number and Z is the release number.)^
382 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
383 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
384 ** numbers used in [SQLITE_VERSION].)^
385 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
386 ** be larger than the release from which it is derived. Either Y will
387 ** be held constant and Z will be incremented or else Y will be incremented
388 ** and Z will be reset to zero.
389 **
390 ** Since [version 3.6.18] ([dateof:3.6.18]),
391 ** SQLite source code has been stored in the
392 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
393 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
394 ** a string which identifies a particular check-in of SQLite
395 ** within its configuration management system. ^The SQLITE_SOURCE_ID
396 ** string contains the date and time of the check-in (UTC) and an SHA1
397 ** hash of the entire source tree.
398 **
399 ** See also: [sqlite3_libversion()],
400 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
401 ** [sqlite_version()] and [sqlite_source_id()].
402 */
403 #define SQLITE_VERSION "3.15.1"
404 #define SQLITE_VERSION_NUMBER 3015001
405 #define SQLITE_SOURCE_ID "2016-11-04 12:08:49 1136863c76576110e710dd5d69ab6bf347c65e36"
406 
407 /*
408 ** CAPI3REF: Run-Time Library Version Numbers
409 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
410 **
411 ** These interfaces provide the same information as the [SQLITE_VERSION],
412 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
413 ** but are associated with the library instead of the header file. ^(Cautious
414 ** programmers might include assert() statements in their application to
415 ** verify that values returned by these interfaces match the macros in
416 ** the header, and thus ensure that the application is
417 ** compiled with matching library and header files.
418 **
419 ** <blockquote><pre>
420 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
421 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
422 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
423 ** </pre></blockquote>)^
424 **
425 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
426 ** macro. ^The sqlite3_libversion() function returns a pointer to the
427 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
428 ** function is provided for use in DLLs since DLL users usually do not have
429 ** direct access to string constants within the DLL. ^The
430 ** sqlite3_libversion_number() function returns an integer equal to
431 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
432 ** a pointer to a string constant whose value is the same as the
433 ** [SQLITE_SOURCE_ID] C preprocessor macro.
434 **
435 ** See also: [sqlite_version()] and [sqlite_source_id()].
436 */
437 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
438 SQLITE_API const char *sqlite3_libversion(void);
439 SQLITE_API const char *sqlite3_sourceid(void);
440 SQLITE_API int sqlite3_libversion_number(void);
441 
442 /*
443 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
444 **
445 ** ^The sqlite3_compileoption_used() function returns 0 or 1
446 ** indicating whether the specified option was defined at
447 ** compile time. ^The SQLITE_ prefix may be omitted from the
448 ** option name passed to sqlite3_compileoption_used().
449 **
450 ** ^The sqlite3_compileoption_get() function allows iterating
451 ** over the list of options that were defined at compile time by
452 ** returning the N-th compile time option string. ^If N is out of range,
453 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
454 ** prefix is omitted from any strings returned by
455 ** sqlite3_compileoption_get().
456 **
457 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
458 ** and sqlite3_compileoption_get() may be omitted by specifying the
459 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
460 **
461 ** See also: SQL functions [sqlite_compileoption_used()] and
462 ** [sqlite_compileoption_get()] and the [compile_options pragma].
463 */
464 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
465 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
466 SQLITE_API const char *sqlite3_compileoption_get(int N);
467 #endif
468 
469 /*
470 ** CAPI3REF: Test To See If The Library Is Threadsafe
471 **
472 ** ^The sqlite3_threadsafe() function returns zero if and only if
473 ** SQLite was compiled with mutexing code omitted due to the
474 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
475 **
476 ** SQLite can be compiled with or without mutexes. When
477 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
478 ** are enabled and SQLite is threadsafe. When the
479 ** [SQLITE_THREADSAFE] macro is 0,
480 ** the mutexes are omitted. Without the mutexes, it is not safe
481 ** to use SQLite concurrently from more than one thread.
482 **
483 ** Enabling mutexes incurs a measurable performance penalty.
484 ** So if speed is of utmost importance, it makes sense to disable
485 ** the mutexes. But for maximum safety, mutexes should be enabled.
486 ** ^The default behavior is for mutexes to be enabled.
487 **
488 ** This interface can be used by an application to make sure that the
489 ** version of SQLite that it is linking against was compiled with
490 ** the desired setting of the [SQLITE_THREADSAFE] macro.
491 **
492 ** This interface only reports on the compile-time mutex setting
493 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
494 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
495 ** can be fully or partially disabled using a call to [sqlite3_config()]
496 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
497 ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
498 ** sqlite3_threadsafe() function shows only the compile-time setting of
499 ** thread safety, not any run-time changes to that setting made by
500 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
501 ** is unchanged by calls to sqlite3_config().)^
502 **
503 ** See the [threading mode] documentation for additional information.
504 */
505 SQLITE_API int sqlite3_threadsafe(void);
506 
507 /*
508 ** CAPI3REF: Database Connection Handle
509 ** KEYWORDS: {database connection} {database connections}
510 **
511 ** Each open SQLite database is represented by a pointer to an instance of
512 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
513 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
514 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
515 ** and [sqlite3_close_v2()] are its destructors. There are many other
516 ** interfaces (such as
517 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
518 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
519 ** sqlite3 object.
520 */
521 typedef struct sqlite3 sqlite3;
522 
523 /*
524 ** CAPI3REF: 64-Bit Integer Types
525 ** KEYWORDS: sqlite_int64 sqlite_uint64
526 **
527 ** Because there is no cross-platform way to specify 64-bit integer types
528 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
529 **
530 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
531 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
532 ** compatibility only.
533 **
534 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
535 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
536 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
537 ** between 0 and +18446744073709551615 inclusive.
538 */
539 #ifdef SQLITE_INT64_TYPE
540  typedef SQLITE_INT64_TYPE sqlite_int64;
541  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
542 #elif defined(_MSC_VER) || defined(__BORLANDC__)
543  typedef __int64 sqlite_int64;
544  typedef unsigned __int64 sqlite_uint64;
545 #else
546  typedef long long int sqlite_int64;
547  typedef unsigned long long int sqlite_uint64;
548 #endif
549 typedef sqlite_int64 sqlite3_int64;
550 typedef sqlite_uint64 sqlite3_uint64;
551 
552 /*
553 ** If compiling for a processor that lacks floating point support,
554 ** substitute integer for floating-point.
555 */
556 #ifdef SQLITE_OMIT_FLOATING_POINT
557 # define double sqlite3_int64
558 #endif
559 
560 /*
561 ** CAPI3REF: Closing A Database Connection
562 ** DESTRUCTOR: sqlite3
563 **
564 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
565 ** for the [sqlite3] object.
566 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
567 ** the [sqlite3] object is successfully destroyed and all associated
568 ** resources are deallocated.
569 **
570 ** ^If the database connection is associated with unfinalized prepared
571 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
572 ** will leave the database connection open and return [SQLITE_BUSY].
573 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
574 ** and/or unfinished sqlite3_backups, then the database connection becomes
575 ** an unusable "zombie" which will automatically be deallocated when the
576 ** last prepared statement is finalized or the last sqlite3_backup is
577 ** finished. The sqlite3_close_v2() interface is intended for use with
578 ** host languages that are garbage collected, and where the order in which
579 ** destructors are called is arbitrary.
580 **
581 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
582 ** [sqlite3_blob_close | close] all [BLOB handles], and
583 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
584 ** with the [sqlite3] object prior to attempting to close the object. ^If
585 ** sqlite3_close_v2() is called on a [database connection] that still has
586 ** outstanding [prepared statements], [BLOB handles], and/or
587 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
588 ** of resources is deferred until all [prepared statements], [BLOB handles],
589 ** and [sqlite3_backup] objects are also destroyed.
590 **
591 ** ^If an [sqlite3] object is destroyed while a transaction is open,
592 ** the transaction is automatically rolled back.
593 **
594 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
595 ** must be either a NULL
596 ** pointer or an [sqlite3] object pointer obtained
597 ** from [sqlite3_open()], [sqlite3_open16()], or
598 ** [sqlite3_open_v2()], and not previously closed.
599 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
600 ** argument is a harmless no-op.
601 */
602 SQLITE_API int sqlite3_close(sqlite3*);
603 SQLITE_API int sqlite3_close_v2(sqlite3*);
604 
605 /*
606 ** The type for a callback function.
607 ** This is legacy and deprecated. It is included for historical
608 ** compatibility and is not documented.
609 */
610 typedef int (*sqlite3_callback)(void*,int,char**, char**);
611 
612 /*
613 ** CAPI3REF: One-Step Query Execution Interface
614 ** METHOD: sqlite3
615 **
616 ** The sqlite3_exec() interface is a convenience wrapper around
617 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
618 ** that allows an application to run multiple statements of SQL
619 ** without having to use a lot of C code.
620 **
621 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
622 ** semicolon-separate SQL statements passed into its 2nd argument,
623 ** in the context of the [database connection] passed in as its 1st
624 ** argument. ^If the callback function of the 3rd argument to
625 ** sqlite3_exec() is not NULL, then it is invoked for each result row
626 ** coming out of the evaluated SQL statements. ^The 4th argument to
627 ** sqlite3_exec() is relayed through to the 1st argument of each
628 ** callback invocation. ^If the callback pointer to sqlite3_exec()
629 ** is NULL, then no callback is ever invoked and result rows are
630 ** ignored.
631 **
632 ** ^If an error occurs while evaluating the SQL statements passed into
633 ** sqlite3_exec(), then execution of the current statement stops and
634 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
635 ** is not NULL then any error message is written into memory obtained
636 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
637 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
638 ** on error message strings returned through the 5th parameter of
639 ** sqlite3_exec() after the error message string is no longer needed.
640 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
641 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
642 ** NULL before returning.
643 **
644 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
645 ** routine returns SQLITE_ABORT without invoking the callback again and
646 ** without running any subsequent SQL statements.
647 **
648 ** ^The 2nd argument to the sqlite3_exec() callback function is the
649 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
650 ** callback is an array of pointers to strings obtained as if from
651 ** [sqlite3_column_text()], one for each column. ^If an element of a
652 ** result row is NULL then the corresponding string pointer for the
653 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
654 ** sqlite3_exec() callback is an array of pointers to strings where each
655 ** entry represents the name of corresponding result column as obtained
656 ** from [sqlite3_column_name()].
657 **
658 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
659 ** to an empty string, or a pointer that contains only whitespace and/or
660 ** SQL comments, then no SQL statements are evaluated and the database
661 ** is not changed.
662 **
663 ** Restrictions:
664 **
665 ** <ul>
666 ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
667 ** is a valid and open [database connection].
668 ** <li> The application must not close the [database connection] specified by
669 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
670 ** <li> The application must not modify the SQL statement text passed into
671 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
672 ** </ul>
673 */
674 SQLITE_API int sqlite3_exec(
675  sqlite3*, /* An open database */
676  const char *sql, /* SQL to be evaluated */
677  int (*callback)(void*,int,char**,char**), /* Callback function */
678  void *, /* 1st argument to callback */
679  char **errmsg /* Error msg written here */
680 );
681 
682 /*
683 ** CAPI3REF: Result Codes
684 ** KEYWORDS: {result code definitions}
685 **
686 ** Many SQLite functions return an integer result code from the set shown
687 ** here in order to indicate success or failure.
688 **
689 ** New error codes may be added in future versions of SQLite.
690 **
691 ** See also: [extended result code definitions]
692 */
693 #define SQLITE_OK 0 /* Successful result */
694 /* beginning-of-error-codes */
695 #define SQLITE_ERROR 1 /* SQL error or missing database */
696 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
697 #define SQLITE_PERM 3 /* Access permission denied */
698 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
699 #define SQLITE_BUSY 5 /* The database file is locked */
700 #define SQLITE_LOCKED 6 /* A table in the database is locked */
701 #define SQLITE_NOMEM 7 /* A malloc() failed */
702 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
703 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
704 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
705 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
706 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
707 #define SQLITE_FULL 13 /* Insertion failed because database is full */
708 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
709 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
710 #define SQLITE_EMPTY 16 /* Database is empty */
711 #define SQLITE_SCHEMA 17 /* The database schema changed */
712 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
713 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
714 #define SQLITE_MISMATCH 20 /* Data type mismatch */
715 #define SQLITE_MISUSE 21 /* Library used incorrectly */
716 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
717 #define SQLITE_AUTH 23 /* Authorization denied */
718 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
719 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
720 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
721 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
722 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
723 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
724 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
725 /* end-of-error-codes */
726 
727 /*
728 ** CAPI3REF: Extended Result Codes
729 ** KEYWORDS: {extended result code definitions}
730 **
731 ** In its default configuration, SQLite API routines return one of 30 integer
732 ** [result codes]. However, experience has shown that many of
733 ** these result codes are too coarse-grained. They do not provide as
734 ** much information about problems as programmers might like. In an effort to
735 ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
736 ** and later) include
737 ** support for additional result codes that provide more detailed information
738 ** about errors. These [extended result codes] are enabled or disabled
739 ** on a per database connection basis using the
740 ** [sqlite3_extended_result_codes()] API. Or, the extended code for
741 ** the most recent error can be obtained using
742 ** [sqlite3_extended_errcode()].
743 */
744 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
745 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
746 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
747 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
748 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
749 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
750 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
751 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
752 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
753 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
754 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
755 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
756 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
757 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
758 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
759 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
760 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
761 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
762 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
763 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
764 #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
765 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
766 #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
767 #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
768 #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
769 #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
770 #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
771 #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
772 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
773 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
774 #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
775 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
776 #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
777 #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
778 #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
779 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
780 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
781 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
782 #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
783 #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
784 #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
785 #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
786 #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
787 #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
788 #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
789 #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
790 #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
791 #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
792 #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
793 #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
794 #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
795 #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
796 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
797 #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
798 #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
799 #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
800 
801 /*
802 ** CAPI3REF: Flags For File Open Operations
803 **
804 ** These bit values are intended for use in the
805 ** 3rd parameter to the [sqlite3_open_v2()] interface and
806 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
807 */
808 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
809 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
810 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
811 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
812 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
813 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
814 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
815 #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
816 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
817 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
818 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
819 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
820 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
821 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
822 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
823 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
824 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
825 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
826 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
827 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
828 
829 /* Reserved: 0x00F00000 */
830 
831 /*
832 ** CAPI3REF: Device Characteristics
833 **
834 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
835 ** object returns an integer which is a vector of these
836 ** bit values expressing I/O characteristics of the mass storage
837 ** device that holds the file that the [sqlite3_io_methods]
838 ** refers to.
839 **
840 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
841 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
842 ** mean that writes of blocks that are nnn bytes in size and
843 ** are aligned to an address which is an integer multiple of
844 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
845 ** that when data is appended to a file, the data is appended
846 ** first then the size of the file is extended, never the other
847 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
848 ** information is written to disk in the same order as calls
849 ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
850 ** after reboot following a crash or power loss, the only bytes in a
851 ** file that were written at the application level might have changed
852 ** and that adjacent bytes, even bytes within the same sector are
853 ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
854 ** flag indicate that a file cannot be deleted when open. The
855 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
856 ** read-only media and cannot be changed even by processes with
857 ** elevated privileges.
858 */
859 #define SQLITE_IOCAP_ATOMIC 0x00000001
860 #define SQLITE_IOCAP_ATOMIC512 0x00000002
861 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
862 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
863 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
864 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
865 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
866 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
867 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
868 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
869 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
870 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
871 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
872 #define SQLITE_IOCAP_IMMUTABLE 0x00002000
873 
874 /*
875 ** CAPI3REF: File Locking Levels
876 **
877 ** SQLite uses one of these integer values as the second
878 ** argument to calls it makes to the xLock() and xUnlock() methods
879 ** of an [sqlite3_io_methods] object.
880 */
881 #define SQLITE_LOCK_NONE 0
882 #define SQLITE_LOCK_SHARED 1
883 #define SQLITE_LOCK_RESERVED 2
884 #define SQLITE_LOCK_PENDING 3
885 #define SQLITE_LOCK_EXCLUSIVE 4
886 
887 /*
888 ** CAPI3REF: Synchronization Type Flags
889 **
890 ** When SQLite invokes the xSync() method of an
891 ** [sqlite3_io_methods] object it uses a combination of
892 ** these integer values as the second argument.
893 **
894 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
895 ** sync operation only needs to flush data to mass storage. Inode
896 ** information need not be flushed. If the lower four bits of the flag
897 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
898 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
899 ** to use Mac OS X style fullsync instead of fsync().
900 **
901 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
902 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
903 ** settings. The [synchronous pragma] determines when calls to the
904 ** xSync VFS method occur and applies uniformly across all platforms.
905 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
906 ** energetic or rigorous or forceful the sync operations are and
907 ** only make a difference on Mac OSX for the default SQLite code.
908 ** (Third-party VFS implementations might also make the distinction
909 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
910 ** operating systems natively supported by SQLite, only Mac OSX
911 ** cares about the difference.)
912 */
913 #define SQLITE_SYNC_NORMAL 0x00002
914 #define SQLITE_SYNC_FULL 0x00003
915 #define SQLITE_SYNC_DATAONLY 0x00010
916 
917 /*
918 ** CAPI3REF: OS Interface Open File Handle
919 **
920 ** An [sqlite3_file] object represents an open file in the
921 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
922 ** implementations will
923 ** want to subclass this object by appending additional fields
924 ** for their own use. The pMethods entry is a pointer to an
925 ** [sqlite3_io_methods] object that defines methods for performing
926 ** I/O operations on the open file.
927 */
928 typedef struct sqlite3_file sqlite3_file;
929 struct sqlite3_file {
930  const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
931 };
932 
933 /*
934 ** CAPI3REF: OS Interface File Virtual Methods Object
935 **
936 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
937 ** [sqlite3_file] object (or, more commonly, a subclass of the
938 ** [sqlite3_file] object) with a pointer to an instance of this object.
939 ** This object defines the methods used to perform various operations
940 ** against the open file represented by the [sqlite3_file] object.
941 **
942 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
943 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
944 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
945 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
946 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
947 ** to NULL.
948 **
949 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
950 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
951 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
952 ** flag may be ORed in to indicate that only the data of the file
953 ** and not its inode needs to be synced.
954 **
955 ** The integer values to xLock() and xUnlock() are one of
956 ** <ul>
957 ** <li> [SQLITE_LOCK_NONE],
958 ** <li> [SQLITE_LOCK_SHARED],
959 ** <li> [SQLITE_LOCK_RESERVED],
960 ** <li> [SQLITE_LOCK_PENDING], or
961 ** <li> [SQLITE_LOCK_EXCLUSIVE].
962 ** </ul>
963 ** xLock() increases the lock. xUnlock() decreases the lock.
964 ** The xCheckReservedLock() method checks whether any database connection,
965 ** either in this process or in some other process, is holding a RESERVED,
966 ** PENDING, or EXCLUSIVE lock on the file. It returns true
967 ** if such a lock exists and false otherwise.
968 **
969 ** The xFileControl() method is a generic interface that allows custom
970 ** VFS implementations to directly control an open file using the
971 ** [sqlite3_file_control()] interface. The second "op" argument is an
972 ** integer opcode. The third argument is a generic pointer intended to
973 ** point to a structure that may contain arguments or space in which to
974 ** write return values. Potential uses for xFileControl() might be
975 ** functions to enable blocking locks with timeouts, to change the
976 ** locking strategy (for example to use dot-file locks), to inquire
977 ** about the status of a lock, or to break stale locks. The SQLite
978 ** core reserves all opcodes less than 100 for its own use.
979 ** A [file control opcodes | list of opcodes] less than 100 is available.
980 ** Applications that define a custom xFileControl method should use opcodes
981 ** greater than 100 to avoid conflicts. VFS implementations should
982 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
983 ** recognize.
984 **
985 ** The xSectorSize() method returns the sector size of the
986 ** device that underlies the file. The sector size is the
987 ** minimum write that can be performed without disturbing
988 ** other bytes in the file. The xDeviceCharacteristics()
989 ** method returns a bit vector describing behaviors of the
990 ** underlying device:
991 **
992 ** <ul>
993 ** <li> [SQLITE_IOCAP_ATOMIC]
994 ** <li> [SQLITE_IOCAP_ATOMIC512]
995 ** <li> [SQLITE_IOCAP_ATOMIC1K]
996 ** <li> [SQLITE_IOCAP_ATOMIC2K]
997 ** <li> [SQLITE_IOCAP_ATOMIC4K]
998 ** <li> [SQLITE_IOCAP_ATOMIC8K]
999 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1000 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1001 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1002 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1003 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1004 ** </ul>
1005 **
1006 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1007 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1008 ** mean that writes of blocks that are nnn bytes in size and
1009 ** are aligned to an address which is an integer multiple of
1010 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1011 ** that when data is appended to a file, the data is appended
1012 ** first then the size of the file is extended, never the other
1013 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1014 ** information is written to disk in the same order as calls
1015 ** to xWrite().
1016 **
1017 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1018 ** in the unread portions of the buffer with zeros. A VFS that
1019 ** fails to zero-fill short reads might seem to work. However,
1020 ** failure to zero-fill short reads will eventually lead to
1021 ** database corruption.
1022 */
1023 typedef struct sqlite3_io_methods sqlite3_io_methods;
1024 struct sqlite3_io_methods {
1025  int iVersion;
1026  int (*xClose)(sqlite3_file*);
1027  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1028  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1029  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1030  int (*xSync)(sqlite3_file*, int flags);
1031  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1032  int (*xLock)(sqlite3_file*, int);
1033  int (*xUnlock)(sqlite3_file*, int);
1034  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1035  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1036  int (*xSectorSize)(sqlite3_file*);
1037  int (*xDeviceCharacteristics)(sqlite3_file*);
1038  /* Methods above are valid for version 1 */
1039  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1040  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1041  void (*xShmBarrier)(sqlite3_file*);
1042  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1043  /* Methods above are valid for version 2 */
1044  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1045  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1046  /* Methods above are valid for version 3 */
1047  /* Additional methods may be added in future releases */
1048 };
1049 
1050 /*
1051 ** CAPI3REF: Standard File Control Opcodes
1052 ** KEYWORDS: {file control opcodes} {file control opcode}
1053 **
1054 ** These integer constants are opcodes for the xFileControl method
1055 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1056 ** interface.
1057 **
1058 ** <ul>
1059 ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1060 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1061 ** opcode causes the xFileControl method to write the current state of
1062 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1063 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1064 ** into an integer that the pArg argument points to. This capability
1065 ** is used during testing and is only available when the SQLITE_TEST
1066 ** compile-time option is used.
1067 **
1068 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1069 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1070 ** layer a hint of how large the database file will grow to be during the
1071 ** current transaction. This hint is not guaranteed to be accurate but it
1072 ** is often close. The underlying VFS might choose to preallocate database
1073 ** file space based on this hint in order to help writes to the database
1074 ** file run faster.
1075 **
1076 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1077 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1078 ** extends and truncates the database file in chunks of a size specified
1079 ** by the user. The fourth argument to [sqlite3_file_control()] should
1080 ** point to an integer (type int) containing the new chunk-size to use
1081 ** for the nominated database. Allocating database file space in large
1082 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1083 ** improve performance on some systems.
1084 **
1085 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1086 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1087 ** to the [sqlite3_file] object associated with a particular database
1088 ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1089 **
1090 ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1091 ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1092 ** to the [sqlite3_file] object associated with the journal file (either
1093 ** the [rollback journal] or the [write-ahead log]) for a particular database
1094 ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1095 **
1096 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1097 ** No longer in use.
1098 **
1099 ** <li>[[SQLITE_FCNTL_SYNC]]
1100 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1101 ** sent to the VFS immediately before the xSync method is invoked on a
1102 ** database file descriptor. Or, if the xSync method is not invoked
1103 ** because the user has configured SQLite with
1104 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1105 ** of the xSync method. In most cases, the pointer argument passed with
1106 ** this file-control is NULL. However, if the database file is being synced
1107 ** as part of a multi-database commit, the argument points to a nul-terminated
1108 ** string containing the transactions master-journal file name. VFSes that
1109 ** do not need this signal should silently ignore this opcode. Applications
1110 ** should not call [sqlite3_file_control()] with this opcode as doing so may
1111 ** disrupt the operation of the specialized VFSes that do require it.
1112 **
1113 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1114 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1115 ** and sent to the VFS after a transaction has been committed immediately
1116 ** but before the database is unlocked. VFSes that do not need this signal
1117 ** should silently ignore this opcode. Applications should not call
1118 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1119 ** operation of the specialized VFSes that do require it.
1120 **
1121 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1122 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1123 ** retry counts and intervals for certain disk I/O operations for the
1124 ** windows [VFS] in order to provide robustness in the presence of
1125 ** anti-virus programs. By default, the windows VFS will retry file read,
1126 ** file write, and file delete operations up to 10 times, with a delay
1127 ** of 25 milliseconds before the first retry and with the delay increasing
1128 ** by an additional 25 milliseconds with each subsequent retry. This
1129 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1130 ** to be adjusted. The values are changed for all database connections
1131 ** within the same process. The argument is a pointer to an array of two
1132 ** integers where the first integer i the new retry count and the second
1133 ** integer is the delay. If either integer is negative, then the setting
1134 ** is not changed but instead the prior value of that setting is written
1135 ** into the array entry, allowing the current retry settings to be
1136 ** interrogated. The zDbName parameter is ignored.
1137 **
1138 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1139 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1140 ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1141 ** write ahead log and shared memory files used for transaction control
1142 ** are automatically deleted when the latest connection to the database
1143 ** closes. Setting persistent WAL mode causes those files to persist after
1144 ** close. Persisting the files is useful when other processes that do not
1145 ** have write permission on the directory containing the database file want
1146 ** to read the database file, as the WAL and shared memory files must exist
1147 ** in order for the database to be readable. The fourth parameter to
1148 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1149 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1150 ** WAL mode. If the integer is -1, then it is overwritten with the current
1151 ** WAL persistence setting.
1152 **
1153 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1154 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1155 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1156 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1157 ** xDeviceCharacteristics methods. The fourth parameter to
1158 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1159 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1160 ** mode. If the integer is -1, then it is overwritten with the current
1161 ** zero-damage mode setting.
1162 **
1163 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1164 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1165 ** a write transaction to indicate that, unless it is rolled back for some
1166 ** reason, the entire database file will be overwritten by the current
1167 ** transaction. This is used by VACUUM operations.
1168 **
1169 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1170 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1171 ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
1172 ** final bottom-level VFS are written into memory obtained from
1173 ** [sqlite3_malloc()] and the result is stored in the char* variable
1174 ** that the fourth parameter of [sqlite3_file_control()] points to.
1175 ** The caller is responsible for freeing the memory when done. As with
1176 ** all file-control actions, there is no guarantee that this will actually
1177 ** do anything. Callers should initialize the char* variable to a NULL
1178 ** pointer in case this file-control is not implemented. This file-control
1179 ** is intended for diagnostic use only.
1180 **
1181 ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1182 ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1183 ** [VFSes] currently in use. ^(The argument X in
1184 ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1185 ** of type "[sqlite3_vfs] **". This opcodes will set *X
1186 ** to a pointer to the top-level VFS.)^
1187 ** ^When there are multiple VFS shims in the stack, this opcode finds the
1188 ** upper-most shim only.
1189 **
1190 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1191 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1192 ** file control is sent to the open [sqlite3_file] object corresponding
1193 ** to the database file to which the pragma statement refers. ^The argument
1194 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1195 ** pointers to strings (char**) in which the second element of the array
1196 ** is the name of the pragma and the third element is the argument to the
1197 ** pragma or NULL if the pragma has no argument. ^The handler for an
1198 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1199 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1200 ** or the equivalent and that string will become the result of the pragma or
1201 ** the error message if the pragma fails. ^If the
1202 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1203 ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1204 ** file control returns [SQLITE_OK], then the parser assumes that the
1205 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1206 ** prepared statement if result string is NULL, or that returns a copy
1207 ** of the result string if the string is non-NULL.
1208 ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1209 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1210 ** that the VFS encountered an error while handling the [PRAGMA] and the
1211 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1212 ** file control occurs at the beginning of pragma statement analysis and so
1213 ** it is able to override built-in [PRAGMA] statements.
1214 **
1215 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1216 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1217 ** file-control may be invoked by SQLite on the database file handle
1218 ** shortly after it is opened in order to provide a custom VFS with access
1219 ** to the connections busy-handler callback. The argument is of type (void **)
1220 ** - an array of two (void *) values. The first (void *) actually points
1221 ** to a function of type (int (*)(void *)). In order to invoke the connections
1222 ** busy-handler, this function should be invoked with the second (void *) in
1223 ** the array as the only argument. If it returns non-zero, then the operation
1224 ** should be retried. If it returns zero, the custom VFS should abandon the
1225 ** current operation.
1226 **
1227 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1228 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1229 ** to have SQLite generate a
1230 ** temporary filename using the same algorithm that is followed to generate
1231 ** temporary filenames for TEMP tables and other internal uses. The
1232 ** argument should be a char** which will be filled with the filename
1233 ** written into memory obtained from [sqlite3_malloc()]. The caller should
1234 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1235 **
1236 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1237 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1238 ** maximum number of bytes that will be used for memory-mapped I/O.
1239 ** The argument is a pointer to a value of type sqlite3_int64 that
1240 ** is an advisory maximum number of bytes in the file to memory map. The
1241 ** pointer is overwritten with the old value. The limit is not changed if
1242 ** the value originally pointed to is negative, and so the current limit
1243 ** can be queried by passing in a pointer to a negative number. This
1244 ** file-control is used internally to implement [PRAGMA mmap_size].
1245 **
1246 ** <li>[[SQLITE_FCNTL_TRACE]]
1247 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1248 ** to the VFS about what the higher layers of the SQLite stack are doing.
1249 ** This file control is used by some VFS activity tracing [shims].
1250 ** The argument is a zero-terminated string. Higher layers in the
1251 ** SQLite stack may generate instances of this file control if
1252 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1253 **
1254 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1255 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1256 ** pointer to an integer and it writes a boolean into that integer depending
1257 ** on whether or not the file has been renamed, moved, or deleted since it
1258 ** was first opened.
1259 **
1260 ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
1261 ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
1262 ** underlying native file handle associated with a file handle. This file
1263 ** control interprets its argument as a pointer to a native file handle and
1264 ** writes the resulting value there.
1265 **
1266 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1267 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1268 ** opcode causes the xFileControl method to swap the file handle with the one
1269 ** pointed to by the pArg argument. This capability is used during testing
1270 ** and only needs to be supported when SQLITE_TEST is defined.
1271 **
1272 ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1273 ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1274 ** be advantageous to block on the next WAL lock if the lock is not immediately
1275 ** available. The WAL subsystem issues this signal during rare
1276 ** circumstances in order to fix a problem with priority inversion.
1277 ** Applications should <em>not</em> use this file-control.
1278 **
1279 ** <li>[[SQLITE_FCNTL_ZIPVFS]]
1280 ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1281 ** VFS should return SQLITE_NOTFOUND for this opcode.
1282 **
1283 ** <li>[[SQLITE_FCNTL_RBU]]
1284 ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1285 ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
1286 ** this opcode.
1287 ** </ul>
1288 */
1289 #define SQLITE_FCNTL_LOCKSTATE 1
1290 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
1291 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
1292 #define SQLITE_FCNTL_LAST_ERRNO 4
1293 #define SQLITE_FCNTL_SIZE_HINT 5
1294 #define SQLITE_FCNTL_CHUNK_SIZE 6
1295 #define SQLITE_FCNTL_FILE_POINTER 7
1296 #define SQLITE_FCNTL_SYNC_OMITTED 8
1297 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
1298 #define SQLITE_FCNTL_PERSIST_WAL 10
1299 #define SQLITE_FCNTL_OVERWRITE 11
1300 #define SQLITE_FCNTL_VFSNAME 12
1301 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1302 #define SQLITE_FCNTL_PRAGMA 14
1303 #define SQLITE_FCNTL_BUSYHANDLER 15
1304 #define SQLITE_FCNTL_TEMPFILENAME 16
1305 #define SQLITE_FCNTL_MMAP_SIZE 18
1306 #define SQLITE_FCNTL_TRACE 19
1307 #define SQLITE_FCNTL_HAS_MOVED 20
1308 #define SQLITE_FCNTL_SYNC 21
1309 #define SQLITE_FCNTL_COMMIT_PHASETWO 22
1310 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
1311 #define SQLITE_FCNTL_WAL_BLOCK 24
1312 #define SQLITE_FCNTL_ZIPVFS 25
1313 #define SQLITE_FCNTL_RBU 26
1314 #define SQLITE_FCNTL_VFS_POINTER 27
1315 #define SQLITE_FCNTL_JOURNAL_POINTER 28
1316 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
1317 
1318 /* deprecated names */
1319 #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
1320 #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
1321 #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
1322 
1323 
1324 /*
1325 ** CAPI3REF: Mutex Handle
1326 **
1327 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1328 ** abstract type for a mutex object. The SQLite core never looks
1329 ** at the internal representation of an [sqlite3_mutex]. It only
1330 ** deals with pointers to the [sqlite3_mutex] object.
1331 **
1332 ** Mutexes are created using [sqlite3_mutex_alloc()].
1333 */
1334 typedef struct sqlite3_mutex sqlite3_mutex;
1335 
1336 /*
1337 ** CAPI3REF: Loadable Extension Thunk
1338 **
1339 ** A pointer to the opaque sqlite3_api_routines structure is passed as
1340 ** the third parameter to entry points of [loadable extensions]. This
1341 ** structure must be typedefed in order to work around compiler warnings
1342 ** on some platforms.
1343 */
1344 typedef struct sqlite3_api_routines sqlite3_api_routines;
1345 
1346 /*
1347 ** CAPI3REF: OS Interface Object
1348 **
1349 ** An instance of the sqlite3_vfs object defines the interface between
1350 ** the SQLite core and the underlying operating system. The "vfs"
1351 ** in the name of the object stands for "virtual file system". See
1352 ** the [VFS | VFS documentation] for further information.
1353 **
1354 ** The value of the iVersion field is initially 1 but may be larger in
1355 ** future versions of SQLite. Additional fields may be appended to this
1356 ** object when the iVersion value is increased. Note that the structure
1357 ** of the sqlite3_vfs object changes in the transaction between
1358 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1359 ** modified.
1360 **
1361 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1362 ** structure used by this VFS. mxPathname is the maximum length of
1363 ** a pathname in this VFS.
1364 **
1365 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1366 ** the pNext pointer. The [sqlite3_vfs_register()]
1367 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1368 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1369 ** searches the list. Neither the application code nor the VFS
1370 ** implementation should use the pNext pointer.
1371 **
1372 ** The pNext field is the only field in the sqlite3_vfs
1373 ** structure that SQLite will ever modify. SQLite will only access
1374 ** or modify this field while holding a particular static mutex.
1375 ** The application should never modify anything within the sqlite3_vfs
1376 ** object once the object has been registered.
1377 **
1378 ** The zName field holds the name of the VFS module. The name must
1379 ** be unique across all VFS modules.
1380 **
1381 ** [[sqlite3_vfs.xOpen]]
1382 ** ^SQLite guarantees that the zFilename parameter to xOpen
1383 ** is either a NULL pointer or string obtained
1384 ** from xFullPathname() with an optional suffix added.
1385 ** ^If a suffix is added to the zFilename parameter, it will
1386 ** consist of a single "-" character followed by no more than
1387 ** 11 alphanumeric and/or "-" characters.
1388 ** ^SQLite further guarantees that
1389 ** the string will be valid and unchanged until xClose() is
1390 ** called. Because of the previous sentence,
1391 ** the [sqlite3_file] can safely store a pointer to the
1392 ** filename if it needs to remember the filename for some reason.
1393 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1394 ** must invent its own temporary name for the file. ^Whenever the
1395 ** xFilename parameter is NULL it will also be the case that the
1396 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1397 **
1398 ** The flags argument to xOpen() includes all bits set in
1399 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1400 ** or [sqlite3_open16()] is used, then flags includes at least
1401 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1402 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1403 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1404 **
1405 ** ^(SQLite will also add one of the following flags to the xOpen()
1406 ** call, depending on the object being opened:
1407 **
1408 ** <ul>
1409 ** <li> [SQLITE_OPEN_MAIN_DB]
1410 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1411 ** <li> [SQLITE_OPEN_TEMP_DB]
1412 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1413 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1414 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1415 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1416 ** <li> [SQLITE_OPEN_WAL]
1417 ** </ul>)^
1418 **
1419 ** The file I/O implementation can use the object type flags to
1420 ** change the way it deals with files. For example, an application
1421 ** that does not care about crash recovery or rollback might make
1422 ** the open of a journal file a no-op. Writes to this journal would
1423 ** also be no-ops, and any attempt to read the journal would return
1424 ** SQLITE_IOERR. Or the implementation might recognize that a database
1425 ** file will be doing page-aligned sector reads and writes in a random
1426 ** order and set up its I/O subsystem accordingly.
1427 **
1428 ** SQLite might also add one of the following flags to the xOpen method:
1429 **
1430 ** <ul>
1431 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1432 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1433 ** </ul>
1434 **
1435 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1436 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1437 ** will be set for TEMP databases and their journals, transient
1438 ** databases, and subjournals.
1439 **
1440 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1441 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1442 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1443 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1444 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1445 ** be created, and that it is an error if it already exists.
1446 ** It is <i>not</i> used to indicate the file should be opened
1447 ** for exclusive access.
1448 **
1449 ** ^At least szOsFile bytes of memory are allocated by SQLite
1450 ** to hold the [sqlite3_file] structure passed as the third
1451 ** argument to xOpen. The xOpen method does not have to
1452 ** allocate the structure; it should just fill it in. Note that
1453 ** the xOpen method must set the sqlite3_file.pMethods to either
1454 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1455 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1456 ** element will be valid after xOpen returns regardless of the success
1457 ** or failure of the xOpen call.
1458 **
1459 ** [[sqlite3_vfs.xAccess]]
1460 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1461 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1462 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1463 ** to test whether a file is at least readable. The file can be a
1464 ** directory.
1465 **
1466 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1467 ** output buffer xFullPathname. The exact size of the output buffer
1468 ** is also passed as a parameter to both methods. If the output buffer
1469 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1470 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1471 ** to prevent this by setting mxPathname to a sufficiently large value.
1472 **
1473 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1474 ** interfaces are not strictly a part of the filesystem, but they are
1475 ** included in the VFS structure for completeness.
1476 ** The xRandomness() function attempts to return nBytes bytes
1477 ** of good-quality randomness into zOut. The return value is
1478 ** the actual number of bytes of randomness obtained.
1479 ** The xSleep() method causes the calling thread to sleep for at
1480 ** least the number of microseconds given. ^The xCurrentTime()
1481 ** method returns a Julian Day Number for the current date and time as
1482 ** a floating point value.
1483 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1484 ** Day Number multiplied by 86400000 (the number of milliseconds in
1485 ** a 24-hour day).
1486 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1487 ** date and time if that method is available (if iVersion is 2 or
1488 ** greater and the function pointer is not NULL) and will fall back
1489 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1490 **
1491 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1492 ** are not used by the SQLite core. These optional interfaces are provided
1493 ** by some VFSes to facilitate testing of the VFS code. By overriding
1494 ** system calls with functions under its control, a test program can
1495 ** simulate faults and error conditions that would otherwise be difficult
1496 ** or impossible to induce. The set of system calls that can be overridden
1497 ** varies from one VFS to another, and from one version of the same VFS to the
1498 ** next. Applications that use these interfaces must be prepared for any
1499 ** or all of these interfaces to be NULL or for their behavior to change
1500 ** from one release to the next. Applications must not attempt to access
1501 ** any of these methods if the iVersion of the VFS is less than 3.
1502 */
1503 typedef struct sqlite3_vfs sqlite3_vfs;
1504 typedef void (*sqlite3_syscall_ptr)(void);
1505 struct sqlite3_vfs {
1506  int iVersion; /* Structure version number (currently 3) */
1507  int szOsFile; /* Size of subclassed sqlite3_file */
1508  int mxPathname; /* Maximum file pathname length */
1509  sqlite3_vfs *pNext; /* Next registered VFS */
1510  const char *zName; /* Name of this virtual file system */
1511  void *pAppData; /* Pointer to application-specific data */
1512  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1513  int flags, int *pOutFlags);
1514  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1515  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1516  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1517  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1518  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1519  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1520  void (*xDlClose)(sqlite3_vfs*, void*);
1521  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1522  int (*xSleep)(sqlite3_vfs*, int microseconds);
1523  int (*xCurrentTime)(sqlite3_vfs*, double*);
1524  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1525  /*
1526  ** The methods above are in version 1 of the sqlite_vfs object
1527  ** definition. Those that follow are added in version 2 or later
1528  */
1529  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1530  /*
1531  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1532  ** Those below are for version 3 and greater.
1533  */
1534  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1535  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1536  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1537  /*
1538  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1539  ** New fields may be appended in future versions. The iVersion
1540  ** value will increment whenever this happens.
1541  */
1542 };
1543 
1544 /*
1545 ** CAPI3REF: Flags for the xAccess VFS method
1546 **
1547 ** These integer constants can be used as the third parameter to
1548 ** the xAccess method of an [sqlite3_vfs] object. They determine
1549 ** what kind of permissions the xAccess method is looking for.
1550 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1551 ** simply checks whether the file exists.
1552 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1553 ** checks whether the named directory is both readable and writable
1554 ** (in other words, if files can be added, removed, and renamed within
1555 ** the directory).
1556 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1557 ** [temp_store_directory pragma], though this could change in a future
1558 ** release of SQLite.
1559 ** With SQLITE_ACCESS_READ, the xAccess method
1560 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1561 ** currently unused, though it might be used in a future release of
1562 ** SQLite.
1563 */
1564 #define SQLITE_ACCESS_EXISTS 0
1565 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1566 #define SQLITE_ACCESS_READ 2 /* Unused */
1567 
1568 /*
1569 ** CAPI3REF: Flags for the xShmLock VFS method
1570 **
1571 ** These integer constants define the various locking operations
1572 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1573 ** following are the only legal combinations of flags to the
1574 ** xShmLock method:
1575 **
1576 ** <ul>
1577 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1578 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1579 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1580 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1581 ** </ul>
1582 **
1583 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1584 ** was given on the corresponding lock.
1585 **
1586 ** The xShmLock method can transition between unlocked and SHARED or
1587 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1588 ** and EXCLUSIVE.
1589 */
1590 #define SQLITE_SHM_UNLOCK 1
1591 #define SQLITE_SHM_LOCK 2
1592 #define SQLITE_SHM_SHARED 4
1593 #define SQLITE_SHM_EXCLUSIVE 8
1594 
1595 /*
1596 ** CAPI3REF: Maximum xShmLock index
1597 **
1598 ** The xShmLock method on [sqlite3_io_methods] may use values
1599 ** between 0 and this upper bound as its "offset" argument.
1600 ** The SQLite core will never attempt to acquire or release a
1601 ** lock outside of this range
1602 */
1603 #define SQLITE_SHM_NLOCK 8
1604 
1605 
1606 /*
1607 ** CAPI3REF: Initialize The SQLite Library
1608 **
1609 ** ^The sqlite3_initialize() routine initializes the
1610 ** SQLite library. ^The sqlite3_shutdown() routine
1611 ** deallocates any resources that were allocated by sqlite3_initialize().
1612 ** These routines are designed to aid in process initialization and
1613 ** shutdown on embedded systems. Workstation applications using
1614 ** SQLite normally do not need to invoke either of these routines.
1615 **
1616 ** A call to sqlite3_initialize() is an "effective" call if it is
1617 ** the first time sqlite3_initialize() is invoked during the lifetime of
1618 ** the process, or if it is the first time sqlite3_initialize() is invoked
1619 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1620 ** of sqlite3_initialize() does any initialization. All other calls
1621 ** are harmless no-ops.)^
1622 **
1623 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1624 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1625 ** an effective call to sqlite3_shutdown() does any deinitialization.
1626 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1627 **
1628 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1629 ** is not. The sqlite3_shutdown() interface must only be called from a
1630 ** single thread. All open [database connections] must be closed and all
1631 ** other SQLite resources must be deallocated prior to invoking
1632 ** sqlite3_shutdown().
1633 **
1634 ** Among other things, ^sqlite3_initialize() will invoke
1635 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1636 ** will invoke sqlite3_os_end().
1637 **
1638 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1639 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1640 ** the library (perhaps it is unable to allocate a needed resource such
1641 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1642 **
1643 ** ^The sqlite3_initialize() routine is called internally by many other
1644 ** SQLite interfaces so that an application usually does not need to
1645 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1646 ** calls sqlite3_initialize() so the SQLite library will be automatically
1647 ** initialized when [sqlite3_open()] is called if it has not be initialized
1648 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1649 ** compile-time option, then the automatic calls to sqlite3_initialize()
1650 ** are omitted and the application must call sqlite3_initialize() directly
1651 ** prior to using any other SQLite interface. For maximum portability,
1652 ** it is recommended that applications always invoke sqlite3_initialize()
1653 ** directly prior to using any other SQLite interface. Future releases
1654 ** of SQLite may require this. In other words, the behavior exhibited
1655 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1656 ** default behavior in some future release of SQLite.
1657 **
1658 ** The sqlite3_os_init() routine does operating-system specific
1659 ** initialization of the SQLite library. The sqlite3_os_end()
1660 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1661 ** performed by these routines include allocation or deallocation
1662 ** of static resources, initialization of global variables,
1663 ** setting up a default [sqlite3_vfs] module, or setting up
1664 ** a default configuration using [sqlite3_config()].
1665 **
1666 ** The application should never invoke either sqlite3_os_init()
1667 ** or sqlite3_os_end() directly. The application should only invoke
1668 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1669 ** interface is called automatically by sqlite3_initialize() and
1670 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1671 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1672 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1673 ** When [custom builds | built for other platforms]
1674 ** (using the [SQLITE_OS_OTHER=1] compile-time
1675 ** option) the application must supply a suitable implementation for
1676 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1677 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1678 ** must return [SQLITE_OK] on success and some other [error code] upon
1679 ** failure.
1680 */
1681 SQLITE_API int sqlite3_initialize(void);
1682 SQLITE_API int sqlite3_shutdown(void);
1683 SQLITE_API int sqlite3_os_init(void);
1684 SQLITE_API int sqlite3_os_end(void);
1685 
1686 /*
1687 ** CAPI3REF: Configuring The SQLite Library
1688 **
1689 ** The sqlite3_config() interface is used to make global configuration
1690 ** changes to SQLite in order to tune SQLite to the specific needs of
1691 ** the application. The default configuration is recommended for most
1692 ** applications and so this routine is usually not necessary. It is
1693 ** provided to support rare applications with unusual needs.
1694 **
1695 ** <b>The sqlite3_config() interface is not threadsafe. The application
1696 ** must ensure that no other SQLite interfaces are invoked by other
1697 ** threads while sqlite3_config() is running.</b>
1698 **
1699 ** The sqlite3_config() interface
1700 ** may only be invoked prior to library initialization using
1701 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1702 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1703 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1704 ** Note, however, that ^sqlite3_config() can be called as part of the
1705 ** implementation of an application-defined [sqlite3_os_init()].
1706 **
1707 ** The first argument to sqlite3_config() is an integer
1708 ** [configuration option] that determines
1709 ** what property of SQLite is to be configured. Subsequent arguments
1710 ** vary depending on the [configuration option]
1711 ** in the first argument.
1712 **
1713 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1714 ** ^If the option is unknown or SQLite is unable to set the option
1715 ** then this routine returns a non-zero [error code].
1716 */
1717 SQLITE_API int sqlite3_config(int, ...);
1718 
1719 /*
1720 ** CAPI3REF: Configure database connections
1721 ** METHOD: sqlite3
1722 **
1723 ** The sqlite3_db_config() interface is used to make configuration
1724 ** changes to a [database connection]. The interface is similar to
1725 ** [sqlite3_config()] except that the changes apply to a single
1726 ** [database connection] (specified in the first argument).
1727 **
1728 ** The second argument to sqlite3_db_config(D,V,...) is the
1729 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1730 ** that indicates what aspect of the [database connection] is being configured.
1731 ** Subsequent arguments vary depending on the configuration verb.
1732 **
1733 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1734 ** the call is considered successful.
1735 */
1736 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1737 
1738 /*
1739 ** CAPI3REF: Memory Allocation Routines
1740 **
1741 ** An instance of this object defines the interface between SQLite
1742 ** and low-level memory allocation routines.
1743 **
1744 ** This object is used in only one place in the SQLite interface.
1745 ** A pointer to an instance of this object is the argument to
1746 ** [sqlite3_config()] when the configuration option is
1747 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1748 ** By creating an instance of this object
1749 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1750 ** during configuration, an application can specify an alternative
1751 ** memory allocation subsystem for SQLite to use for all of its
1752 ** dynamic memory needs.
1753 **
1754 ** Note that SQLite comes with several [built-in memory allocators]
1755 ** that are perfectly adequate for the overwhelming majority of applications
1756 ** and that this object is only useful to a tiny minority of applications
1757 ** with specialized memory allocation requirements. This object is
1758 ** also used during testing of SQLite in order to specify an alternative
1759 ** memory allocator that simulates memory out-of-memory conditions in
1760 ** order to verify that SQLite recovers gracefully from such
1761 ** conditions.
1762 **
1763 ** The xMalloc, xRealloc, and xFree methods must work like the
1764 ** malloc(), realloc() and free() functions from the standard C library.
1765 ** ^SQLite guarantees that the second argument to
1766 ** xRealloc is always a value returned by a prior call to xRoundup.
1767 **
1768 ** xSize should return the allocated size of a memory allocation
1769 ** previously obtained from xMalloc or xRealloc. The allocated size
1770 ** is always at least as big as the requested size but may be larger.
1771 **
1772 ** The xRoundup method returns what would be the allocated size of
1773 ** a memory allocation given a particular requested size. Most memory
1774 ** allocators round up memory allocations at least to the next multiple
1775 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1776 ** Every memory allocation request coming in through [sqlite3_malloc()]
1777 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1778 ** that causes the corresponding memory allocation to fail.
1779 **
1780 ** The xInit method initializes the memory allocator. For example,
1781 ** it might allocate any require mutexes or initialize internal data
1782 ** structures. The xShutdown method is invoked (indirectly) by
1783 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1784 ** by xInit. The pAppData pointer is used as the only parameter to
1785 ** xInit and xShutdown.
1786 **
1787 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1788 ** the xInit method, so the xInit method need not be threadsafe. The
1789 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1790 ** not need to be threadsafe either. For all other methods, SQLite
1791 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1792 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1793 ** it is by default) and so the methods are automatically serialized.
1794 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1795 ** methods must be threadsafe or else make their own arrangements for
1796 ** serialization.
1797 **
1798 ** SQLite will never invoke xInit() more than once without an intervening
1799 ** call to xShutdown().
1800 */
1801 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1802 struct sqlite3_mem_methods {
1803  void *(*xMalloc)(int); /* Memory allocation function */
1804  void (*xFree)(void*); /* Free a prior allocation */
1805  void *(*xRealloc)(void*,int); /* Resize an allocation */
1806  int (*xSize)(void*); /* Return the size of an allocation */
1807  int (*xRoundup)(int); /* Round up request size to allocation size */
1808  int (*xInit)(void*); /* Initialize the memory allocator */
1809  void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1810  void *pAppData; /* Argument to xInit() and xShutdown() */
1811 };
1812 
1813 /*
1814 ** CAPI3REF: Configuration Options
1815 ** KEYWORDS: {configuration option}
1816 **
1817 ** These constants are the available integer configuration options that
1818 ** can be passed as the first argument to the [sqlite3_config()] interface.
1819 **
1820 ** New configuration options may be added in future releases of SQLite.
1821 ** Existing configuration options might be discontinued. Applications
1822 ** should check the return code from [sqlite3_config()] to make sure that
1823 ** the call worked. The [sqlite3_config()] interface will return a
1824 ** non-zero [error code] if a discontinued or unsupported configuration option
1825 ** is invoked.
1826 **
1827 ** <dl>
1828 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1829 ** <dd>There are no arguments to this option. ^This option sets the
1830 ** [threading mode] to Single-thread. In other words, it disables
1831 ** all mutexing and puts SQLite into a mode where it can only be used
1832 ** by a single thread. ^If SQLite is compiled with
1833 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1834 ** it is not possible to change the [threading mode] from its default
1835 ** value of Single-thread and so [sqlite3_config()] will return
1836 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1837 ** configuration option.</dd>
1838 **
1839 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1840 ** <dd>There are no arguments to this option. ^This option sets the
1841 ** [threading mode] to Multi-thread. In other words, it disables
1842 ** mutexing on [database connection] and [prepared statement] objects.
1843 ** The application is responsible for serializing access to
1844 ** [database connections] and [prepared statements]. But other mutexes
1845 ** are enabled so that SQLite will be safe to use in a multi-threaded
1846 ** environment as long as no two threads attempt to use the same
1847 ** [database connection] at the same time. ^If SQLite is compiled with
1848 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1849 ** it is not possible to set the Multi-thread [threading mode] and
1850 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1851 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1852 **
1853 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1854 ** <dd>There are no arguments to this option. ^This option sets the
1855 ** [threading mode] to Serialized. In other words, this option enables
1856 ** all mutexes including the recursive
1857 ** mutexes on [database connection] and [prepared statement] objects.
1858 ** In this mode (which is the default when SQLite is compiled with
1859 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1860 ** to [database connections] and [prepared statements] so that the
1861 ** application is free to use the same [database connection] or the
1862 ** same [prepared statement] in different threads at the same time.
1863 ** ^If SQLite is compiled with
1864 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1865 ** it is not possible to set the Serialized [threading mode] and
1866 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1867 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1868 **
1869 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1870 ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
1871 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
1872 ** The argument specifies
1873 ** alternative low-level memory allocation routines to be used in place of
1874 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1875 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1876 ** before the [sqlite3_config()] call returns.</dd>
1877 **
1878 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1879 ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1880 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1881 ** The [sqlite3_mem_methods]
1882 ** structure is filled with the currently defined memory allocation routines.)^
1883 ** This option can be used to overload the default memory allocation
1884 ** routines with a wrapper that simulations memory allocation failure or
1885 ** tracks memory usage, for example. </dd>
1886 **
1887 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1888 ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1889 ** interpreted as a boolean, which enables or disables the collection of
1890 ** memory allocation statistics. ^(When memory allocation statistics are
1891 ** disabled, the following SQLite interfaces become non-operational:
1892 ** <ul>
1893 ** <li> [sqlite3_memory_used()]
1894 ** <li> [sqlite3_memory_highwater()]
1895 ** <li> [sqlite3_soft_heap_limit64()]
1896 ** <li> [sqlite3_status64()]
1897 ** </ul>)^
1898 ** ^Memory allocation statistics are enabled by default unless SQLite is
1899 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1900 ** allocation statistics are disabled by default.
1901 ** </dd>
1902 **
1903 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1904 ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1905 ** that SQLite can use for scratch memory. ^(There are three arguments
1906 ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
1907 ** aligned memory buffer from which the scratch allocations will be
1908 ** drawn, the size of each scratch allocation (sz),
1909 ** and the maximum number of scratch allocations (N).)^
1910 ** The first argument must be a pointer to an 8-byte aligned buffer
1911 ** of at least sz*N bytes of memory.
1912 ** ^SQLite will not use more than one scratch buffers per thread.
1913 ** ^SQLite will never request a scratch buffer that is more than 6
1914 ** times the database page size.
1915 ** ^If SQLite needs needs additional
1916 ** scratch memory beyond what is provided by this configuration option, then
1917 ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1918 ** ^When the application provides any amount of scratch memory using
1919 ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1920 ** [sqlite3_malloc|heap allocations].
1921 ** This can help [Robson proof|prevent memory allocation failures] due to heap
1922 ** fragmentation in low-memory embedded systems.
1923 ** </dd>
1924 **
1925 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1926 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
1927 ** that SQLite can use for the database page cache with the default page
1928 ** cache implementation.
1929 ** This configuration option is a no-op if an application-define page
1930 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
1931 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1932 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
1933 ** and the number of cache lines (N).
1934 ** The sz argument should be the size of the largest database page
1935 ** (a power of two between 512 and 65536) plus some extra bytes for each
1936 ** page header. ^The number of extra bytes needed by the page header
1937 ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
1938 ** ^It is harmless, apart from the wasted memory,
1939 ** for the sz parameter to be larger than necessary. The pMem
1940 ** argument must be either a NULL pointer or a pointer to an 8-byte
1941 ** aligned block of memory of at least sz*N bytes, otherwise
1942 ** subsequent behavior is undefined.
1943 ** ^When pMem is not NULL, SQLite will strive to use the memory provided
1944 ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
1945 ** a page cache line is larger than sz bytes or if all of the pMem buffer
1946 ** is exhausted.
1947 ** ^If pMem is NULL and N is non-zero, then each database connection
1948 ** does an initial bulk allocation for page cache memory
1949 ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
1950 ** of -1024*N bytes if N is negative, . ^If additional
1951 ** page cache memory is needed beyond what is provided by the initial
1952 ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
1953 ** additional cache line. </dd>
1954 **
1955 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1956 ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
1957 ** that SQLite will use for all of its dynamic memory allocation needs
1958 ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1959 ** [SQLITE_CONFIG_PAGECACHE].
1960 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1961 ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1962 ** [SQLITE_ERROR] if invoked otherwise.
1963 ** ^There are three arguments to SQLITE_CONFIG_HEAP:
1964 ** An 8-byte aligned pointer to the memory,
1965 ** the number of bytes in the memory buffer, and the minimum allocation size.
1966 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1967 ** to using its default memory allocator (the system malloc() implementation),
1968 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
1969 ** memory pointer is not NULL then the alternative memory
1970 ** allocator is engaged to handle all of SQLites memory allocation needs.
1971 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1972 ** boundary or subsequent behavior of SQLite will be undefined.
1973 ** The minimum allocation size is capped at 2**12. Reasonable values
1974 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1975 **
1976 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1977 ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1978 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
1979 ** The argument specifies alternative low-level mutex routines to be used
1980 ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
1981 ** the content of the [sqlite3_mutex_methods] structure before the call to
1982 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1983 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1984 ** the entire mutexing subsystem is omitted from the build and hence calls to
1985 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1986 ** return [SQLITE_ERROR].</dd>
1987 **
1988 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1989 ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1990 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
1991 ** [sqlite3_mutex_methods]
1992 ** structure is filled with the currently defined mutex routines.)^
1993 ** This option can be used to overload the default mutex allocation
1994 ** routines with a wrapper used to track mutex usage for performance
1995 ** profiling or testing, for example. ^If SQLite is compiled with
1996 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1997 ** the entire mutexing subsystem is omitted from the build and hence calls to
1998 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1999 ** return [SQLITE_ERROR].</dd>
2000 **
2001 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2002 ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
2003 ** the default size of lookaside memory on each [database connection].
2004 ** The first argument is the
2005 ** size of each lookaside buffer slot and the second is the number of
2006 ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
2007 ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2008 ** option to [sqlite3_db_config()] can be used to change the lookaside
2009 ** configuration on individual connections.)^ </dd>
2010 **
2011 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2012 ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
2013 ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
2014 ** the interface to a custom page cache implementation.)^
2015 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
2016 **
2017 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2018 ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
2019 ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
2020 ** the current page cache implementation into that object.)^ </dd>
2021 **
2022 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2023 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2024 ** global [error log].
2025 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2026 ** function with a call signature of void(*)(void*,int,const char*),
2027 ** and a pointer to void. ^If the function pointer is not NULL, it is
2028 ** invoked by [sqlite3_log()] to process each logging event. ^If the
2029 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2030 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2031 ** passed through as the first parameter to the application-defined logger
2032 ** function whenever that function is invoked. ^The second parameter to
2033 ** the logger function is a copy of the first parameter to the corresponding
2034 ** [sqlite3_log()] call and is intended to be a [result code] or an
2035 ** [extended result code]. ^The third parameter passed to the logger is
2036 ** log message after formatting via [sqlite3_snprintf()].
2037 ** The SQLite logging interface is not reentrant; the logger function
2038 ** supplied by the application must not invoke any SQLite interface.
2039 ** In a multi-threaded application, the application-defined logger
2040 ** function must be threadsafe. </dd>
2041 **
2042 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2043 ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2044 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2045 ** then URI handling is globally disabled.)^ ^If URI handling is globally
2046 ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2047 ** [sqlite3_open16()] or
2048 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2049 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2050 ** connection is opened. ^If it is globally disabled, filenames are
2051 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2052 ** database connection is opened. ^(By default, URI handling is globally
2053 ** disabled. The default value may be changed by compiling with the
2054 ** [SQLITE_USE_URI] symbol defined.)^
2055 **
2056 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2057 ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2058 ** argument which is interpreted as a boolean in order to enable or disable
2059 ** the use of covering indices for full table scans in the query optimizer.
2060 ** ^The default setting is determined
2061 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2062 ** if that compile-time option is omitted.
2063 ** The ability to disable the use of covering indices for full table scans
2064 ** is because some incorrectly coded legacy applications might malfunction
2065 ** when the optimization is enabled. Providing the ability to
2066 ** disable the optimization allows the older, buggy application code to work
2067 ** without change even with newer versions of SQLite.
2068 **
2069 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2070 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2071 ** <dd> These options are obsolete and should not be used by new code.
2072 ** They are retained for backwards compatibility but are now no-ops.
2073 ** </dd>
2074 **
2075 ** [[SQLITE_CONFIG_SQLLOG]]
2076 ** <dt>SQLITE_CONFIG_SQLLOG
2077 ** <dd>This option is only available if sqlite is compiled with the
2078 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2079 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2080 ** The second should be of type (void*). The callback is invoked by the library
2081 ** in three separate circumstances, identified by the value passed as the
2082 ** fourth parameter. If the fourth parameter is 0, then the database connection
2083 ** passed as the second argument has just been opened. The third argument
2084 ** points to a buffer containing the name of the main database file. If the
2085 ** fourth parameter is 1, then the SQL statement that the third parameter
2086 ** points to has just been executed. Or, if the fourth parameter is 2, then
2087 ** the connection being passed as the second parameter is being closed. The
2088 ** third parameter is passed NULL In this case. An example of using this
2089 ** configuration option can be seen in the "test_sqllog.c" source file in
2090 ** the canonical SQLite source tree.</dd>
2091 **
2092 ** [[SQLITE_CONFIG_MMAP_SIZE]]
2093 ** <dt>SQLITE_CONFIG_MMAP_SIZE
2094 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2095 ** that are the default mmap size limit (the default setting for
2096 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2097 ** ^The default setting can be overridden by each database connection using
2098 ** either the [PRAGMA mmap_size] command, or by using the
2099 ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
2100 ** will be silently truncated if necessary so that it does not exceed the
2101 ** compile-time maximum mmap size set by the
2102 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2103 ** ^If either argument to this option is negative, then that argument is
2104 ** changed to its compile-time default.
2105 **
2106 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2107 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2108 ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2109 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2110 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2111 ** that specifies the maximum size of the created heap.
2112 **
2113 ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2114 ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2115 ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2116 ** is a pointer to an integer and writes into that integer the number of extra
2117 ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2118 ** The amount of extra space required can change depending on the compiler,
2119 ** target platform, and SQLite version.
2120 **
2121 ** [[SQLITE_CONFIG_PMASZ]]
2122 ** <dt>SQLITE_CONFIG_PMASZ
2123 ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2124 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2125 ** sorter to that integer. The default minimum PMA Size is set by the
2126 ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2127 ** to help with sort operations when multithreaded sorting
2128 ** is enabled (using the [PRAGMA threads] command) and the amount of content
2129 ** to be sorted exceeds the page size times the minimum of the
2130 ** [PRAGMA cache_size] setting and this value.
2131 **
2132 ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2133 ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2134 ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2135 ** becomes the [statement journal] spill-to-disk threshold.
2136 ** [Statement journals] are held in memory until their size (in bytes)
2137 ** exceeds this threshold, at which point they are written to disk.
2138 ** Or if the threshold is -1, statement journals are always held
2139 ** exclusively in memory.
2140 ** Since many statement journals never become large, setting the spill
2141 ** threshold to a value such as 64KiB can greatly reduce the amount of
2142 ** I/O required to support statement rollback.
2143 ** The default value for this setting is controlled by the
2144 ** [SQLITE_STMTJRNL_SPILL] compile-time option.
2145 ** </dl>
2146 */
2147 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
2148 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
2149 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
2150 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
2151 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
2152 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
2153 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
2154 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
2155 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
2156 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
2157 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
2158 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2159 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
2160 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
2161 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2162 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
2163 #define SQLITE_CONFIG_URI 17 /* int */
2164 #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
2165 #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
2166 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
2167 #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
2168 #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
2169 #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
2170 #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
2171 #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
2172 #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
2173 
2174 /*
2175 ** CAPI3REF: Database Connection Configuration Options
2176 **
2177 ** These constants are the available integer configuration options that
2178 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2179 **
2180 ** New configuration options may be added in future releases of SQLite.
2181 ** Existing configuration options might be discontinued. Applications
2182 ** should check the return code from [sqlite3_db_config()] to make sure that
2183 ** the call worked. ^The [sqlite3_db_config()] interface will return a
2184 ** non-zero [error code] if a discontinued or unsupported configuration option
2185 ** is invoked.
2186 **
2187 ** <dl>
2188 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2189 ** <dd> ^This option takes three additional arguments that determine the
2190 ** [lookaside memory allocator] configuration for the [database connection].
2191 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2192 ** pointer to a memory buffer to use for lookaside memory.
2193 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2194 ** may be NULL in which case SQLite will allocate the
2195 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2196 ** size of each lookaside buffer slot. ^The third argument is the number of
2197 ** slots. The size of the buffer in the first argument must be greater than
2198 ** or equal to the product of the second and third arguments. The buffer
2199 ** must be aligned to an 8-byte boundary. ^If the second argument to
2200 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2201 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2202 ** configuration for a database connection can only be changed when that
2203 ** connection is not currently using lookaside memory, or in other words
2204 ** when the "current value" returned by
2205 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2206 ** Any attempt to change the lookaside memory configuration when lookaside
2207 ** memory is in use leaves the configuration unchanged and returns
2208 ** [SQLITE_BUSY].)^</dd>
2209 **
2210 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2211 ** <dd> ^This option is used to enable or disable the enforcement of
2212 ** [foreign key constraints]. There should be two additional arguments.
2213 ** The first argument is an integer which is 0 to disable FK enforcement,
2214 ** positive to enable FK enforcement or negative to leave FK enforcement
2215 ** unchanged. The second parameter is a pointer to an integer into which
2216 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2217 ** following this call. The second parameter may be a NULL pointer, in
2218 ** which case the FK enforcement setting is not reported back. </dd>
2219 **
2220 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2221 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2222 ** There should be two additional arguments.
2223 ** The first argument is an integer which is 0 to disable triggers,
2224 ** positive to enable triggers or negative to leave the setting unchanged.
2225 ** The second parameter is a pointer to an integer into which
2226 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2227 ** following this call. The second parameter may be a NULL pointer, in
2228 ** which case the trigger setting is not reported back. </dd>
2229 **
2230 ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2231 ** <dd> ^This option is used to enable or disable the two-argument
2232 ** version of the [fts3_tokenizer()] function which is part of the
2233 ** [FTS3] full-text search engine extension.
2234 ** There should be two additional arguments.
2235 ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2236 ** positive to enable fts3_tokenizer() or negative to leave the setting
2237 ** unchanged.
2238 ** The second parameter is a pointer to an integer into which
2239 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2240 ** following this call. The second parameter may be a NULL pointer, in
2241 ** which case the new setting is not reported back. </dd>
2242 **
2243 ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2244 ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2245 ** interface independently of the [load_extension()] SQL function.
2246 ** The [sqlite3_enable_load_extension()] API enables or disables both the
2247 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2248 ** There should be two additional arguments.
2249 ** When the first argument to this interface is 1, then only the C-API is
2250 ** enabled and the SQL function remains disabled. If the first argument to
2251 ** this interface is 0, then both the C-API and the SQL function are disabled.
2252 ** If the first argument is -1, then no changes are made to state of either the
2253 ** C-API or the SQL function.
2254 ** The second parameter is a pointer to an integer into which
2255 ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2256 ** is disabled or enabled following this call. The second parameter may
2257 ** be a NULL pointer, in which case the new setting is not reported back.
2258 ** </dd>
2259 **
2260 ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
2261 ** <dd> ^This option is used to change the name of the "main" database
2262 ** schema. ^The sole argument is a pointer to a constant UTF8 string
2263 ** which will become the new schema name in place of "main". ^SQLite
2264 ** does not make a copy of the new main schema name string, so the application
2265 ** must ensure that the argument passed into this DBCONFIG option is unchanged
2266 ** until after the database connection closes.
2267 ** </dd>
2268 **
2269 ** </dl>
2270 */
2271 #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
2272 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2273 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2274 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2275 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2276 #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
2277 
2278 
2279 /*
2280 ** CAPI3REF: Enable Or Disable Extended Result Codes
2281 ** METHOD: sqlite3
2282 **
2283 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2284 ** [extended result codes] feature of SQLite. ^The extended result
2285 ** codes are disabled by default for historical compatibility.
2286 */
2287 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2288 
2289 /*
2290 ** CAPI3REF: Last Insert Rowid
2291 ** METHOD: sqlite3
2292 **
2293 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2294 ** has a unique 64-bit signed
2295 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2296 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2297 ** names are not also used by explicitly declared columns. ^If
2298 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2299 ** is another alias for the rowid.
2300 **
2301 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
2302 ** most recent successful [INSERT] into a rowid table or [virtual table]
2303 ** on database connection D.
2304 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
2305 ** ^If no successful [INSERT]s into rowid tables
2306 ** have ever occurred on the database connection D,
2307 ** then sqlite3_last_insert_rowid(D) returns zero.
2308 **
2309 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2310 ** method, then this routine will return the [rowid] of the inserted
2311 ** row as long as the trigger or virtual table method is running.
2312 ** But once the trigger or virtual table method ends, the value returned
2313 ** by this routine reverts to what it was before the trigger or virtual
2314 ** table method began.)^
2315 **
2316 ** ^An [INSERT] that fails due to a constraint violation is not a
2317 ** successful [INSERT] and does not change the value returned by this
2318 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2319 ** and INSERT OR ABORT make no changes to the return value of this
2320 ** routine when their insertion fails. ^(When INSERT OR REPLACE
2321 ** encounters a constraint violation, it does not fail. The
2322 ** INSERT continues to completion after deleting rows that caused
2323 ** the constraint problem so INSERT OR REPLACE will always change
2324 ** the return value of this interface.)^
2325 **
2326 ** ^For the purposes of this routine, an [INSERT] is considered to
2327 ** be successful even if it is subsequently rolled back.
2328 **
2329 ** This function is accessible to SQL statements via the
2330 ** [last_insert_rowid() SQL function].
2331 **
2332 ** If a separate thread performs a new [INSERT] on the same
2333 ** database connection while the [sqlite3_last_insert_rowid()]
2334 ** function is running and thus changes the last insert [rowid],
2335 ** then the value returned by [sqlite3_last_insert_rowid()] is
2336 ** unpredictable and might not equal either the old or the new
2337 ** last insert [rowid].
2338 */
2339 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2340 
2341 /*
2342 ** CAPI3REF: Count The Number Of Rows Modified
2343 ** METHOD: sqlite3
2344 **
2345 ** ^This function returns the number of rows modified, inserted or
2346 ** deleted by the most recently completed INSERT, UPDATE or DELETE
2347 ** statement on the database connection specified by the only parameter.
2348 ** ^Executing any other type of SQL statement does not modify the value
2349 ** returned by this function.
2350 **
2351 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2352 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2353 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2354 **
2355 ** Changes to a view that are intercepted by
2356 ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2357 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2358 ** DELETE statement run on a view is always zero. Only changes made to real
2359 ** tables are counted.
2360 **
2361 ** Things are more complicated if the sqlite3_changes() function is
2362 ** executed while a trigger program is running. This may happen if the
2363 ** program uses the [changes() SQL function], or if some other callback
2364 ** function invokes sqlite3_changes() directly. Essentially:
2365 **
2366 ** <ul>
2367 ** <li> ^(Before entering a trigger program the value returned by
2368 ** sqlite3_changes() function is saved. After the trigger program
2369 ** has finished, the original value is restored.)^
2370 **
2371 ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2372 ** statement sets the value returned by sqlite3_changes()
2373 ** upon completion as normal. Of course, this value will not include
2374 ** any changes performed by sub-triggers, as the sqlite3_changes()
2375 ** value will be saved and restored after each sub-trigger has run.)^
2376 ** </ul>
2377 **
2378 ** ^This means that if the changes() SQL function (or similar) is used
2379 ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2380 ** returns the value as set when the calling statement began executing.
2381 ** ^If it is used by the second or subsequent such statement within a trigger
2382 ** program, the value returned reflects the number of rows modified by the
2383 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
2384 **
2385 ** See also the [sqlite3_total_changes()] interface, the
2386 ** [count_changes pragma], and the [changes() SQL function].
2387 **
2388 ** If a separate thread makes changes on the same database connection
2389 ** while [sqlite3_changes()] is running then the value returned
2390 ** is unpredictable and not meaningful.
2391 */
2392 SQLITE_API int sqlite3_changes(sqlite3*);
2393 
2394 /*
2395 ** CAPI3REF: Total Number Of Rows Modified
2396 ** METHOD: sqlite3
2397 **
2398 ** ^This function returns the total number of rows inserted, modified or
2399 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2400 ** since the database connection was opened, including those executed as
2401 ** part of trigger programs. ^Executing any other type of SQL statement
2402 ** does not affect the value returned by sqlite3_total_changes().
2403 **
2404 ** ^Changes made as part of [foreign key actions] are included in the
2405 ** count, but those made as part of REPLACE constraint resolution are
2406 ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2407 ** are not counted.
2408 **
2409 ** See also the [sqlite3_changes()] interface, the
2410 ** [count_changes pragma], and the [total_changes() SQL function].
2411 **
2412 ** If a separate thread makes changes on the same database connection
2413 ** while [sqlite3_total_changes()] is running then the value
2414 ** returned is unpredictable and not meaningful.
2415 */
2416 SQLITE_API int sqlite3_total_changes(sqlite3*);
2417 
2418 /*
2419 ** CAPI3REF: Interrupt A Long-Running Query
2420 ** METHOD: sqlite3
2421 **
2422 ** ^This function causes any pending database operation to abort and
2423 ** return at its earliest opportunity. This routine is typically
2424 ** called in response to a user action such as pressing "Cancel"
2425 ** or Ctrl-C where the user wants a long query operation to halt
2426 ** immediately.
2427 **
2428 ** ^It is safe to call this routine from a thread different from the
2429 ** thread that is currently running the database operation. But it
2430 ** is not safe to call this routine with a [database connection] that
2431 ** is closed or might close before sqlite3_interrupt() returns.
2432 **
2433 ** ^If an SQL operation is very nearly finished at the time when
2434 ** sqlite3_interrupt() is called, then it might not have an opportunity
2435 ** to be interrupted and might continue to completion.
2436 **
2437 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2438 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2439 ** that is inside an explicit transaction, then the entire transaction
2440 ** will be rolled back automatically.
2441 **
2442 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2443 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2444 ** that are started after the sqlite3_interrupt() call and before the
2445 ** running statements reaches zero are interrupted as if they had been
2446 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2447 ** that are started after the running statement count reaches zero are
2448 ** not effected by the sqlite3_interrupt().
2449 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2450 ** SQL statements is a no-op and has no effect on SQL statements
2451 ** that are started after the sqlite3_interrupt() call returns.
2452 **
2453 ** If the database connection closes while [sqlite3_interrupt()]
2454 ** is running then bad things will likely happen.
2455 */
2456 SQLITE_API void sqlite3_interrupt(sqlite3*);
2457 
2458 /*
2459 ** CAPI3REF: Determine If An SQL Statement Is Complete
2460 **
2461 ** These routines are useful during command-line input to determine if the
2462 ** currently entered text seems to form a complete SQL statement or
2463 ** if additional input is needed before sending the text into
2464 ** SQLite for parsing. ^These routines return 1 if the input string
2465 ** appears to be a complete SQL statement. ^A statement is judged to be
2466 ** complete if it ends with a semicolon token and is not a prefix of a
2467 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2468 ** string literals or quoted identifier names or comments are not
2469 ** independent tokens (they are part of the token in which they are
2470 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2471 ** and comments that follow the final semicolon are ignored.
2472 **
2473 ** ^These routines return 0 if the statement is incomplete. ^If a
2474 ** memory allocation fails, then SQLITE_NOMEM is returned.
2475 **
2476 ** ^These routines do not parse the SQL statements thus
2477 ** will not detect syntactically incorrect SQL.
2478 **
2479 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2480 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2481 ** automatically by sqlite3_complete16(). If that initialization fails,
2482 ** then the return value from sqlite3_complete16() will be non-zero
2483 ** regardless of whether or not the input SQL is complete.)^
2484 **
2485 ** The input to [sqlite3_complete()] must be a zero-terminated
2486 ** UTF-8 string.
2487 **
2488 ** The input to [sqlite3_complete16()] must be a zero-terminated
2489 ** UTF-16 string in native byte order.
2490 */
2491 SQLITE_API int sqlite3_complete(const char *sql);
2492 SQLITE_API int sqlite3_complete16(const void *sql);
2493 
2494 /*
2495 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2496 ** KEYWORDS: {busy-handler callback} {busy handler}
2497 ** METHOD: sqlite3
2498 **
2499 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2500 ** that might be invoked with argument P whenever
2501 ** an attempt is made to access a database table associated with
2502 ** [database connection] D when another thread
2503 ** or process has the table locked.
2504 ** The sqlite3_busy_handler() interface is used to implement
2505 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2506 **
2507 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
2508 ** is returned immediately upon encountering the lock. ^If the busy callback
2509 ** is not NULL, then the callback might be invoked with two arguments.
2510 **
2511 ** ^The first argument to the busy handler is a copy of the void* pointer which
2512 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2513 ** the busy handler callback is the number of times that the busy handler has
2514 ** been invoked previously for the same locking event. ^If the
2515 ** busy callback returns 0, then no additional attempts are made to
2516 ** access the database and [SQLITE_BUSY] is returned
2517 ** to the application.
2518 ** ^If the callback returns non-zero, then another attempt
2519 ** is made to access the database and the cycle repeats.
2520 **
2521 ** The presence of a busy handler does not guarantee that it will be invoked
2522 ** when there is lock contention. ^If SQLite determines that invoking the busy
2523 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2524 ** to the application instead of invoking the
2525 ** busy handler.
2526 ** Consider a scenario where one process is holding a read lock that
2527 ** it is trying to promote to a reserved lock and
2528 ** a second process is holding a reserved lock that it is trying
2529 ** to promote to an exclusive lock. The first process cannot proceed
2530 ** because it is blocked by the second and the second process cannot
2531 ** proceed because it is blocked by the first. If both processes
2532 ** invoke the busy handlers, neither will make any progress. Therefore,
2533 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2534 ** will induce the first process to release its read lock and allow
2535 ** the second process to proceed.
2536 **
2537 ** ^The default busy callback is NULL.
2538 **
2539 ** ^(There can only be a single busy handler defined for each
2540 ** [database connection]. Setting a new busy handler clears any
2541 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2542 ** or evaluating [PRAGMA busy_timeout=N] will change the
2543 ** busy handler and thus clear any previously set busy handler.
2544 **
2545 ** The busy callback should not take any actions which modify the
2546 ** database connection that invoked the busy handler. In other words,
2547 ** the busy handler is not reentrant. Any such actions
2548 ** result in undefined behavior.
2549 **
2550 ** A busy handler must not close the database connection
2551 ** or [prepared statement] that invoked the busy handler.
2552 */
2553 SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
2554 
2555 /*
2556 ** CAPI3REF: Set A Busy Timeout
2557 ** METHOD: sqlite3
2558 **
2559 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2560 ** for a specified amount of time when a table is locked. ^The handler
2561 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2562 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2563 ** the handler returns 0 which causes [sqlite3_step()] to return
2564 ** [SQLITE_BUSY].
2565 **
2566 ** ^Calling this routine with an argument less than or equal to zero
2567 ** turns off all busy handlers.
2568 **
2569 ** ^(There can only be a single busy handler for a particular
2570 ** [database connection] at any given moment. If another busy handler
2571 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2572 ** this routine, that other busy handler is cleared.)^
2573 **
2574 ** See also: [PRAGMA busy_timeout]
2575 */
2576 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2577 
2578 /*
2579 ** CAPI3REF: Convenience Routines For Running Queries
2580 ** METHOD: sqlite3
2581 **
2582 ** This is a legacy interface that is preserved for backwards compatibility.
2583 ** Use of this interface is not recommended.
2584 **
2585 ** Definition: A <b>result table</b> is memory data structure created by the
2586 ** [sqlite3_get_table()] interface. A result table records the
2587 ** complete query results from one or more queries.
2588 **
2589 ** The table conceptually has a number of rows and columns. But
2590 ** these numbers are not part of the result table itself. These
2591 ** numbers are obtained separately. Let N be the number of rows
2592 ** and M be the number of columns.
2593 **
2594 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2595 ** There are (N+1)*M elements in the array. The first M pointers point
2596 ** to zero-terminated strings that contain the names of the columns.
2597 ** The remaining entries all point to query results. NULL values result
2598 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2599 ** string representation as returned by [sqlite3_column_text()].
2600 **
2601 ** A result table might consist of one or more memory allocations.
2602 ** It is not safe to pass a result table directly to [sqlite3_free()].
2603 ** A result table should be deallocated using [sqlite3_free_table()].
2604 **
2605 ** ^(As an example of the result table format, suppose a query result
2606 ** is as follows:
2607 **
2608 ** <blockquote><pre>
2609 ** Name | Age
2610 ** -----------------------
2611 ** Alice | 43
2612 ** Bob | 28
2613 ** Cindy | 21
2614 ** </pre></blockquote>
2615 **
2616 ** There are two column (M==2) and three rows (N==3). Thus the
2617 ** result table has 8 entries. Suppose the result table is stored
2618 ** in an array names azResult. Then azResult holds this content:
2619 **
2620 ** <blockquote><pre>
2621 ** azResult&#91;0] = "Name";
2622 ** azResult&#91;1] = "Age";
2623 ** azResult&#91;2] = "Alice";
2624 ** azResult&#91;3] = "43";
2625 ** azResult&#91;4] = "Bob";
2626 ** azResult&#91;5] = "28";
2627 ** azResult&#91;6] = "Cindy";
2628 ** azResult&#91;7] = "21";
2629 ** </pre></blockquote>)^
2630 **
2631 ** ^The sqlite3_get_table() function evaluates one or more
2632 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2633 ** string of its 2nd parameter and returns a result table to the
2634 ** pointer given in its 3rd parameter.
2635 **
2636 ** After the application has finished with the result from sqlite3_get_table(),
2637 ** it must pass the result table pointer to sqlite3_free_table() in order to
2638 ** release the memory that was malloced. Because of the way the
2639 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2640 ** function must not try to call [sqlite3_free()] directly. Only
2641 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2642 **
2643 ** The sqlite3_get_table() interface is implemented as a wrapper around
2644 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2645 ** to any internal data structures of SQLite. It uses only the public
2646 ** interface defined here. As a consequence, errors that occur in the
2647 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2648 ** reflected in subsequent calls to [sqlite3_errcode()] or
2649 ** [sqlite3_errmsg()].
2650 */
2651 SQLITE_API int sqlite3_get_table(
2652  sqlite3 *db, /* An open database */
2653  const char *zSql, /* SQL to be evaluated */
2654  char ***pazResult, /* Results of the query */
2655  int *pnRow, /* Number of result rows written here */
2656  int *pnColumn, /* Number of result columns written here */
2657  char **pzErrmsg /* Error msg written here */
2658 );
2659 SQLITE_API void sqlite3_free_table(char **result);
2660 
2661 /*
2662 ** CAPI3REF: Formatted String Printing Functions
2663 **
2664 ** These routines are work-alikes of the "printf()" family of functions
2665 ** from the standard C library.
2666 ** These routines understand most of the common K&R formatting options,
2667 ** plus some additional non-standard formats, detailed below.
2668 ** Note that some of the more obscure formatting options from recent
2669 ** C-library standards are omitted from this implementation.
2670 **
2671 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2672 ** results into memory obtained from [sqlite3_malloc()].
2673 ** The strings returned by these two routines should be
2674 ** released by [sqlite3_free()]. ^Both routines return a
2675 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2676 ** memory to hold the resulting string.
2677 **
2678 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2679 ** the standard C library. The result is written into the
2680 ** buffer supplied as the second parameter whose size is given by
2681 ** the first parameter. Note that the order of the
2682 ** first two parameters is reversed from snprintf().)^ This is an
2683 ** historical accident that cannot be fixed without breaking
2684 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2685 ** returns a pointer to its buffer instead of the number of
2686 ** characters actually written into the buffer.)^ We admit that
2687 ** the number of characters written would be a more useful return
2688 ** value but we cannot change the implementation of sqlite3_snprintf()
2689 ** now without breaking compatibility.
2690 **
2691 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2692 ** guarantees that the buffer is always zero-terminated. ^The first
2693 ** parameter "n" is the total size of the buffer, including space for
2694 ** the zero terminator. So the longest string that can be completely
2695 ** written will be n-1 characters.
2696 **
2697 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2698 **
2699 ** These routines all implement some additional formatting
2700 ** options that are useful for constructing SQL statements.
2701 ** All of the usual printf() formatting options apply. In addition, there
2702 ** is are "%q", "%Q", "%w" and "%z" options.
2703 **
2704 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2705 ** string from the argument list. But %q also doubles every '\'' character.
2706 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2707 ** character it escapes that character and allows it to be inserted into
2708 ** the string.
2709 **
2710 ** For example, assume the string variable zText contains text as follows:
2711 **
2712 ** <blockquote><pre>
2713 ** char *zText = "It's a happy day!";
2714 ** </pre></blockquote>
2715 **
2716 ** One can use this text in an SQL statement as follows:
2717 **
2718 ** <blockquote><pre>
2719 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2720 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2721 ** sqlite3_free(zSQL);
2722 ** </pre></blockquote>
2723 **
2724 ** Because the %q format string is used, the '\'' character in zText
2725 ** is escaped and the SQL generated is as follows:
2726 **
2727 ** <blockquote><pre>
2728 ** INSERT INTO table1 VALUES('It''s a happy day!')
2729 ** </pre></blockquote>
2730 **
2731 ** This is correct. Had we used %s instead of %q, the generated SQL
2732 ** would have looked like this:
2733 **
2734 ** <blockquote><pre>
2735 ** INSERT INTO table1 VALUES('It's a happy day!');
2736 ** </pre></blockquote>
2737 **
2738 ** This second example is an SQL syntax error. As a general rule you should
2739 ** always use %q instead of %s when inserting text into a string literal.
2740 **
2741 ** ^(The %Q option works like %q except it also adds single quotes around
2742 ** the outside of the total string. Additionally, if the parameter in the
2743 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2744 ** single quotes).)^ So, for example, one could say:
2745 **
2746 ** <blockquote><pre>
2747 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2748 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2749 ** sqlite3_free(zSQL);
2750 ** </pre></blockquote>
2751 **
2752 ** The code above will render a correct SQL statement in the zSQL
2753 ** variable even if the zText variable is a NULL pointer.
2754 **
2755 ** ^(The "%w" formatting option is like "%q" except that it expects to
2756 ** be contained within double-quotes instead of single quotes, and it
2757 ** escapes the double-quote character instead of the single-quote
2758 ** character.)^ The "%w" formatting option is intended for safely inserting
2759 ** table and column names into a constructed SQL statement.
2760 **
2761 ** ^(The "%z" formatting option works like "%s" but with the
2762 ** addition that after the string has been read and copied into
2763 ** the result, [sqlite3_free()] is called on the input string.)^
2764 */
2765 SQLITE_API char *sqlite3_mprintf(const char*,...);
2766 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2767 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2768 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2769 
2770 /*
2771 ** CAPI3REF: Memory Allocation Subsystem
2772 **
2773 ** The SQLite core uses these three routines for all of its own
2774 ** internal memory allocation needs. "Core" in the previous sentence
2775 ** does not include operating-system specific VFS implementation. The
2776 ** Windows VFS uses native malloc() and free() for some operations.
2777 **
2778 ** ^The sqlite3_malloc() routine returns a pointer to a block
2779 ** of memory at least N bytes in length, where N is the parameter.
2780 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2781 ** memory, it returns a NULL pointer. ^If the parameter N to
2782 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2783 ** a NULL pointer.
2784 **
2785 ** ^The sqlite3_malloc64(N) routine works just like
2786 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2787 ** of a signed 32-bit integer.
2788 **
2789 ** ^Calling sqlite3_free() with a pointer previously returned
2790 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2791 ** that it might be reused. ^The sqlite3_free() routine is
2792 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2793 ** to sqlite3_free() is harmless. After being freed, memory
2794 ** should neither be read nor written. Even reading previously freed
2795 ** memory might result in a segmentation fault or other severe error.
2796 ** Memory corruption, a segmentation fault, or other severe error
2797 ** might result if sqlite3_free() is called with a non-NULL pointer that
2798 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2799 **
2800 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
2801 ** prior memory allocation X to be at least N bytes.
2802 ** ^If the X parameter to sqlite3_realloc(X,N)
2803 ** is a NULL pointer then its behavior is identical to calling
2804 ** sqlite3_malloc(N).
2805 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2806 ** negative then the behavior is exactly the same as calling
2807 ** sqlite3_free(X).
2808 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2809 ** of at least N bytes in size or NULL if insufficient memory is available.
2810 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2811 ** of the prior allocation are copied into the beginning of buffer returned
2812 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
2813 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2814 ** prior allocation is not freed.
2815 **
2816 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
2817 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2818 ** of a 32-bit signed integer.
2819 **
2820 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2821 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2822 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2823 ** ^The value returned by sqlite3_msize(X) might be larger than the number
2824 ** of bytes requested when X was allocated. ^If X is a NULL pointer then
2825 ** sqlite3_msize(X) returns zero. If X points to something that is not
2826 ** the beginning of memory allocation, or if it points to a formerly
2827 ** valid memory allocation that has now been freed, then the behavior
2828 ** of sqlite3_msize(X) is undefined and possibly harmful.
2829 **
2830 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2831 ** sqlite3_malloc64(), and sqlite3_realloc64()
2832 ** is always aligned to at least an 8 byte boundary, or to a
2833 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2834 ** option is used.
2835 **
2836 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2837 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2838 ** implementation of these routines to be omitted. That capability
2839 ** is no longer provided. Only built-in memory allocators can be used.
2840 **
2841 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2842 ** the system malloc() and free() directly when converting
2843 ** filenames between the UTF-8 encoding used by SQLite
2844 ** and whatever filename encoding is used by the particular Windows
2845 ** installation. Memory allocation errors were detected, but
2846 ** they were reported back as [SQLITE_CANTOPEN] or
2847 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2848 **
2849 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2850 ** must be either NULL or else pointers obtained from a prior
2851 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2852 ** not yet been released.
2853 **
2854 ** The application must not read or write any part of
2855 ** a block of memory after it has been released using
2856 ** [sqlite3_free()] or [sqlite3_realloc()].
2857 */
2858 SQLITE_API void *sqlite3_malloc(int);
2859 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
2860 SQLITE_API void *sqlite3_realloc(void*, int);
2861 SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
2862 SQLITE_API void sqlite3_free(void*);
2863 SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
2864 
2865 /*
2866 ** CAPI3REF: Memory Allocator Statistics
2867 **
2868 ** SQLite provides these two interfaces for reporting on the status
2869 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2870 ** routines, which form the built-in memory allocation subsystem.
2871 **
2872 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2873 ** of memory currently outstanding (malloced but not freed).
2874 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2875 ** value of [sqlite3_memory_used()] since the high-water mark
2876 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2877 ** [sqlite3_memory_highwater()] include any overhead
2878 ** added by SQLite in its implementation of [sqlite3_malloc()],
2879 ** but not overhead added by the any underlying system library
2880 ** routines that [sqlite3_malloc()] may call.
2881 **
2882 ** ^The memory high-water mark is reset to the current value of
2883 ** [sqlite3_memory_used()] if and only if the parameter to
2884 ** [sqlite3_memory_highwater()] is true. ^The value returned
2885 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2886 ** prior to the reset.
2887 */
2888 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2889 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2890 
2891 /*
2892 ** CAPI3REF: Pseudo-Random Number Generator
2893 **
2894 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2895 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2896 ** already uses the largest possible [ROWID]. The PRNG is also used for
2897 ** the build-in random() and randomblob() SQL functions. This interface allows
2898 ** applications to access the same PRNG for other purposes.
2899 **
2900 ** ^A call to this routine stores N bytes of randomness into buffer P.
2901 ** ^The P parameter can be a NULL pointer.
2902 **
2903 ** ^If this routine has not been previously called or if the previous
2904 ** call had N less than one or a NULL pointer for P, then the PRNG is
2905 ** seeded using randomness obtained from the xRandomness method of
2906 ** the default [sqlite3_vfs] object.
2907 ** ^If the previous call to this routine had an N of 1 or more and a
2908 ** non-NULL P then the pseudo-randomness is generated
2909 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2910 ** method.
2911 */
2912 SQLITE_API void sqlite3_randomness(int N, void *P);
2913 
2914 /*
2915 ** CAPI3REF: Compile-Time Authorization Callbacks
2916 ** METHOD: sqlite3
2917 **
2918 ** ^This routine registers an authorizer callback with a particular
2919 ** [database connection], supplied in the first argument.
2920 ** ^The authorizer callback is invoked as SQL statements are being compiled
2921 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2922 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2923 ** points during the compilation process, as logic is being created
2924 ** to perform various actions, the authorizer callback is invoked to
2925 ** see if those actions are allowed. ^The authorizer callback should
2926 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2927 ** specific action but allow the SQL statement to continue to be
2928 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2929 ** rejected with an error. ^If the authorizer callback returns
2930 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2931 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2932 ** the authorizer will fail with an error message.
2933 **
2934 ** When the callback returns [SQLITE_OK], that means the operation
2935 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2936 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2937 ** authorizer will fail with an error message explaining that
2938 ** access is denied.
2939 **
2940 ** ^The first parameter to the authorizer callback is a copy of the third
2941 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2942 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2943 ** the particular action to be authorized. ^The third through sixth parameters
2944 ** to the callback are zero-terminated strings that contain additional
2945 ** details about the action to be authorized.
2946 **
2947 ** ^If the action code is [SQLITE_READ]
2948 ** and the callback returns [SQLITE_IGNORE] then the
2949 ** [prepared statement] statement is constructed to substitute
2950 ** a NULL value in place of the table column that would have
2951 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2952 ** return can be used to deny an untrusted user access to individual
2953 ** columns of a table.
2954 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2955 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2956 ** [truncate optimization] is disabled and all rows are deleted individually.
2957 **
2958 ** An authorizer is used when [sqlite3_prepare | preparing]
2959 ** SQL statements from an untrusted source, to ensure that the SQL statements
2960 ** do not try to access data they are not allowed to see, or that they do not
2961 ** try to execute malicious statements that damage the database. For
2962 ** example, an application may allow a user to enter arbitrary
2963 ** SQL queries for evaluation by a database. But the application does
2964 ** not want the user to be able to make arbitrary changes to the
2965 ** database. An authorizer could then be put in place while the
2966 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2967 ** disallows everything except [SELECT] statements.
2968 **
2969 ** Applications that need to process SQL from untrusted sources
2970 ** might also consider lowering resource limits using [sqlite3_limit()]
2971 ** and limiting database size using the [max_page_count] [PRAGMA]
2972 ** in addition to using an authorizer.
2973 **
2974 ** ^(Only a single authorizer can be in place on a database connection
2975 ** at a time. Each call to sqlite3_set_authorizer overrides the
2976 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2977 ** The authorizer is disabled by default.
2978 **
2979 ** The authorizer callback must not do anything that will modify
2980 ** the database connection that invoked the authorizer callback.
2981 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2982 ** database connections for the meaning of "modify" in this paragraph.
2983 **
2984 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2985 ** statement might be re-prepared during [sqlite3_step()] due to a
2986 ** schema change. Hence, the application should ensure that the
2987 ** correct authorizer callback remains in place during the [sqlite3_step()].
2988 **
2989 ** ^Note that the authorizer callback is invoked only during
2990 ** [sqlite3_prepare()] or its variants. Authorization is not
2991 ** performed during statement evaluation in [sqlite3_step()], unless
2992 ** as stated in the previous paragraph, sqlite3_step() invokes
2993 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2994 */
2995 SQLITE_API int sqlite3_set_authorizer(
2996  sqlite3*,
2997  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2998  void *pUserData
2999 );
3000 
3001 /*
3002 ** CAPI3REF: Authorizer Return Codes
3003 **
3004 ** The [sqlite3_set_authorizer | authorizer callback function] must
3005 ** return either [SQLITE_OK] or one of these two constants in order
3006 ** to signal SQLite whether or not the action is permitted. See the
3007 ** [sqlite3_set_authorizer | authorizer documentation] for additional
3008 ** information.
3009 **
3010 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
3011 ** returned from the [sqlite3_vtab_on_conflict()] interface.
3012 */
3013 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
3014 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
3015 
3016 /*
3017 ** CAPI3REF: Authorizer Action Codes
3018 **
3019 ** The [sqlite3_set_authorizer()] interface registers a callback function
3020 ** that is invoked to authorize certain SQL statement actions. The
3021 ** second parameter to the callback is an integer code that specifies
3022 ** what action is being authorized. These are the integer action codes that
3023 ** the authorizer callback may be passed.
3024 **
3025 ** These action code values signify what kind of operation is to be
3026 ** authorized. The 3rd and 4th parameters to the authorization
3027 ** callback function will be parameters or NULL depending on which of these
3028 ** codes is used as the second parameter. ^(The 5th parameter to the
3029 ** authorizer callback is the name of the database ("main", "temp",
3030 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
3031 ** is the name of the inner-most trigger or view that is responsible for
3032 ** the access attempt or NULL if this access attempt is directly from
3033 ** top-level SQL code.
3034 */
3035 /******************************************* 3rd ************ 4th ***********/
3036 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
3037 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
3038 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
3039 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
3040 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
3041 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
3042 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
3043 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
3044 #define SQLITE_DELETE 9 /* Table Name NULL */
3045 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
3046 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
3047 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
3048 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
3049 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
3050 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
3051 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
3052 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
3053 #define SQLITE_INSERT 18 /* Table Name NULL */
3054 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
3055 #define SQLITE_READ 20 /* Table Name Column Name */
3056 #define SQLITE_SELECT 21 /* NULL NULL */
3057 #define SQLITE_TRANSACTION 22 /* Operation NULL */
3058 #define SQLITE_UPDATE 23 /* Table Name Column Name */
3059 #define SQLITE_ATTACH 24 /* Filename NULL */
3060 #define SQLITE_DETACH 25 /* Database Name NULL */
3061 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
3062 #define SQLITE_REINDEX 27 /* Index Name NULL */
3063 #define SQLITE_ANALYZE 28 /* Table Name NULL */
3064 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3065 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3066 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3067 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3068 #define SQLITE_COPY 0 /* No longer used */
3069 #define SQLITE_RECURSIVE 33 /* NULL NULL */
3070 
3071 /*
3072 ** CAPI3REF: Tracing And Profiling Functions
3073 ** METHOD: sqlite3
3074 **
3075 ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3076 ** instead of the routines described here.
3077 **
3078 ** These routines register callback functions that can be used for
3079 ** tracing and profiling the execution of SQL statements.
3080 **
3081 ** ^The callback function registered by sqlite3_trace() is invoked at
3082 ** various times when an SQL statement is being run by [sqlite3_step()].
3083 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3084 ** SQL statement text as the statement first begins executing.
3085 ** ^(Additional sqlite3_trace() callbacks might occur
3086 ** as each triggered subprogram is entered. The callbacks for triggers
3087 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3088 **
3089 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3090 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
3091 **
3092 ** ^The callback function registered by sqlite3_profile() is invoked
3093 ** as each SQL statement finishes. ^The profile callback contains
3094 ** the original statement text and an estimate of wall-clock time
3095 ** of how long that statement took to run. ^The profile callback
3096 ** time is in units of nanoseconds, however the current implementation
3097 ** is only capable of millisecond resolution so the six least significant
3098 ** digits in the time are meaningless. Future versions of SQLite
3099 ** might provide greater resolution on the profiler callback. The
3100 ** sqlite3_profile() function is considered experimental and is
3101 ** subject to change in future versions of SQLite.
3102 */
3103 SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
3104  void(*xTrace)(void*,const char*), void*);
3105 SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
3106  void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3107 
3108 /*
3109 ** CAPI3REF: SQL Trace Event Codes
3110 ** KEYWORDS: SQLITE_TRACE
3111 **
3112 ** These constants identify classes of events that can be monitored
3113 ** using the [sqlite3_trace_v2()] tracing logic. The third argument
3114 ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
3115 ** the following constants. ^The first argument to the trace callback
3116 ** is one of the following constants.
3117 **
3118 ** New tracing constants may be added in future releases.
3119 **
3120 ** ^A trace callback has four arguments: xCallback(T,C,P,X).
3121 ** ^The T argument is one of the integer type codes above.
3122 ** ^The C argument is a copy of the context pointer passed in as the
3123 ** fourth argument to [sqlite3_trace_v2()].
3124 ** The P and X arguments are pointers whose meanings depend on T.
3125 **
3126 ** <dl>
3127 ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3128 ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3129 ** first begins running and possibly at other times during the
3130 ** execution of the prepared statement, such as at the start of each
3131 ** trigger subprogram. ^The P argument is a pointer to the
3132 ** [prepared statement]. ^The X argument is a pointer to a string which
3133 ** is the unexpanded SQL text of the prepared statement or an SQL comment
3134 ** that indicates the invocation of a trigger. ^The callback can compute
3135 ** the same text that would have been returned by the legacy [sqlite3_trace()]
3136 ** interface by using the X argument when X begins with "--" and invoking
3137 ** [sqlite3_expanded_sql(P)] otherwise.
3138 **
3139 ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3140 ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3141 ** information as is provided by the [sqlite3_profile()] callback.
3142 ** ^The P argument is a pointer to the [prepared statement] and the
3143 ** X argument points to a 64-bit integer which is the estimated of
3144 ** the number of nanosecond that the prepared statement took to run.
3145 ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3146 **
3147 ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3148 ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3149 ** statement generates a single row of result.
3150 ** ^The P argument is a pointer to the [prepared statement] and the
3151 ** X argument is unused.
3152 **
3153 ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
3154 ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3155 ** connection closes.
3156 ** ^The P argument is a pointer to the [database connection] object
3157 ** and the X argument is unused.
3158 ** </dl>
3159 */
3160 #define SQLITE_TRACE_STMT 0x01
3161 #define SQLITE_TRACE_PROFILE 0x02
3162 #define SQLITE_TRACE_ROW 0x04
3163 #define SQLITE_TRACE_CLOSE 0x08
3164 
3165 /*
3166 ** CAPI3REF: SQL Trace Hook
3167 ** METHOD: sqlite3
3168 **
3169 ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
3170 ** function X against [database connection] D, using property mask M
3171 ** and context pointer P. ^If the X callback is
3172 ** NULL or if the M mask is zero, then tracing is disabled. The
3173 ** M argument should be the bitwise OR-ed combination of
3174 ** zero or more [SQLITE_TRACE] constants.
3175 **
3176 ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
3177 ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
3178 **
3179 ** ^The X callback is invoked whenever any of the events identified by
3180 ** mask M occur. ^The integer return value from the callback is currently
3181 ** ignored, though this may change in future releases. Callback
3182 ** implementations should return zero to ensure future compatibility.
3183 **
3184 ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
3185 ** ^The T argument is one of the [SQLITE_TRACE]
3186 ** constants to indicate why the callback was invoked.
3187 ** ^The C argument is a copy of the context pointer.
3188 ** The P and X arguments are pointers whose meanings depend on T.
3189 **
3190 ** The sqlite3_trace_v2() interface is intended to replace the legacy
3191 ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
3192 ** are deprecated.
3193 */
3194 SQLITE_API int sqlite3_trace_v2(
3195  sqlite3*,
3196  unsigned uMask,
3197  int(*xCallback)(unsigned,void*,void*,void*),
3198  void *pCtx
3199 );
3200 
3201 /*
3202 ** CAPI3REF: Query Progress Callbacks
3203 ** METHOD: sqlite3
3204 **
3205 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3206 ** function X to be invoked periodically during long running calls to
3207 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3208 ** database connection D. An example use for this
3209 ** interface is to keep a GUI updated during a large query.
3210 **
3211 ** ^The parameter P is passed through as the only parameter to the
3212 ** callback function X. ^The parameter N is the approximate number of
3213 ** [virtual machine instructions] that are evaluated between successive
3214 ** invocations of the callback X. ^If N is less than one then the progress
3215 ** handler is disabled.
3216 **
3217 ** ^Only a single progress handler may be defined at one time per
3218 ** [database connection]; setting a new progress handler cancels the
3219 ** old one. ^Setting parameter X to NULL disables the progress handler.
3220 ** ^The progress handler is also disabled by setting N to a value less
3221 ** than 1.
3222 **
3223 ** ^If the progress callback returns non-zero, the operation is
3224 ** interrupted. This feature can be used to implement a
3225 ** "Cancel" button on a GUI progress dialog box.
3226 **
3227 ** The progress handler callback must not do anything that will modify
3228 ** the database connection that invoked the progress handler.
3229 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3230 ** database connections for the meaning of "modify" in this paragraph.
3231 **
3232 */
3233 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3234 
3235 /*
3236 ** CAPI3REF: Opening A New Database Connection
3237 ** CONSTRUCTOR: sqlite3
3238 **
3239 ** ^These routines open an SQLite database file as specified by the
3240 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3241 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3242 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3243 ** returned in *ppDb, even if an error occurs. The only exception is that
3244 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3245 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3246 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3247 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
3248 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3249 ** an English language description of the error following a failure of any
3250 ** of the sqlite3_open() routines.
3251 **
3252 ** ^The default encoding will be UTF-8 for databases created using
3253 ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
3254 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
3255 **
3256 ** Whether or not an error occurs when it is opened, resources
3257 ** associated with the [database connection] handle should be released by
3258 ** passing it to [sqlite3_close()] when it is no longer required.
3259 **
3260 ** The sqlite3_open_v2() interface works like sqlite3_open()
3261 ** except that it accepts two additional parameters for additional control
3262 ** over the new database connection. ^(The flags parameter to
3263 ** sqlite3_open_v2() can take one of
3264 ** the following three values, optionally combined with the
3265 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3266 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3267 **
3268 ** <dl>
3269 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3270 ** <dd>The database is opened in read-only mode. If the database does not
3271 ** already exist, an error is returned.</dd>)^
3272 **
3273 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3274 ** <dd>The database is opened for reading and writing if possible, or reading
3275 ** only if the file is write protected by the operating system. In either
3276 ** case the database must already exist, otherwise an error is returned.</dd>)^
3277 **
3278 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3279 ** <dd>The database is opened for reading and writing, and is created if
3280 ** it does not already exist. This is the behavior that is always used for
3281 ** sqlite3_open() and sqlite3_open16().</dd>)^
3282 ** </dl>
3283 **
3284 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3285 ** combinations shown above optionally combined with other
3286 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3287 ** then the behavior is undefined.
3288 **
3289 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3290 ** opens in the multi-thread [threading mode] as long as the single-thread
3291 ** mode has not been set at compile-time or start-time. ^If the
3292 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3293 ** in the serialized [threading mode] unless single-thread was
3294 ** previously selected at compile-time or start-time.
3295 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3296 ** eligible to use [shared cache mode], regardless of whether or not shared
3297 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
3298 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3299 ** participate in [shared cache mode] even if it is enabled.
3300 **
3301 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3302 ** [sqlite3_vfs] object that defines the operating system interface that
3303 ** the new database connection should use. ^If the fourth parameter is
3304 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3305 **
3306 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3307 ** is created for the connection. ^This in-memory database will vanish when
3308 ** the database connection is closed. Future versions of SQLite might
3309 ** make use of additional special filenames that begin with the ":" character.
3310 ** It is recommended that when a database filename actually does begin with
3311 ** a ":" character you should prefix the filename with a pathname such as
3312 ** "./" to avoid ambiguity.
3313 **
3314 ** ^If the filename is an empty string, then a private, temporary
3315 ** on-disk database will be created. ^This private database will be
3316 ** automatically deleted as soon as the database connection is closed.
3317 **
3318 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3319 **
3320 ** ^If [URI filename] interpretation is enabled, and the filename argument
3321 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3322 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3323 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3324 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3325 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3326 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3327 ** by default, but future releases of SQLite might enable URI filename
3328 ** interpretation by default. See "[URI filenames]" for additional
3329 ** information.
3330 **
3331 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3332 ** authority, then it must be either an empty string or the string
3333 ** "localhost". ^If the authority is not an empty string or "localhost", an
3334 ** error is returned to the caller. ^The fragment component of a URI, if
3335 ** present, is ignored.
3336 **
3337 ** ^SQLite uses the path component of the URI as the name of the disk file
3338 ** which contains the database. ^If the path begins with a '/' character,
3339 ** then it is interpreted as an absolute path. ^If the path does not begin
3340 ** with a '/' (meaning that the authority section is omitted from the URI)
3341 ** then the path is interpreted as a relative path.
3342 ** ^(On windows, the first component of an absolute path
3343 ** is a drive specification (e.g. "C:").)^
3344 **
3345 ** [[core URI query parameters]]
3346 ** The query component of a URI may contain parameters that are interpreted
3347 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3348 ** SQLite and its built-in [VFSes] interpret the
3349 ** following query parameters:
3350 **
3351 ** <ul>
3352 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3353 ** a VFS object that provides the operating system interface that should
3354 ** be used to access the database file on disk. ^If this option is set to
3355 ** an empty string the default VFS object is used. ^Specifying an unknown
3356 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3357 ** present, then the VFS specified by the option takes precedence over
3358 ** the value passed as the fourth parameter to sqlite3_open_v2().
3359 **
3360 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3361 ** "rwc", or "memory". Attempting to set it to any other value is
3362 ** an error)^.
3363 ** ^If "ro" is specified, then the database is opened for read-only
3364 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3365 ** third argument to sqlite3_open_v2(). ^If the mode option is set to
3366 ** "rw", then the database is opened for read-write (but not create)
3367 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3368 ** been set. ^Value "rwc" is equivalent to setting both
3369 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
3370 ** set to "memory" then a pure [in-memory database] that never reads
3371 ** or writes from disk is used. ^It is an error to specify a value for
3372 ** the mode parameter that is less restrictive than that specified by
3373 ** the flags passed in the third parameter to sqlite3_open_v2().
3374 **
3375 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3376 ** "private". ^Setting it to "shared" is equivalent to setting the
3377 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3378 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3379 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3380 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3381 ** a URI filename, its value overrides any behavior requested by setting
3382 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3383 **
3384 ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3385 ** [powersafe overwrite] property does or does not apply to the
3386 ** storage media on which the database file resides.
3387 **
3388 ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3389 ** which if set disables file locking in rollback journal modes. This
3390 ** is useful for accessing a database on a filesystem that does not
3391 ** support locking. Caution: Database corruption might result if two
3392 ** or more processes write to the same database and any one of those
3393 ** processes uses nolock=1.
3394 **
3395 ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3396 ** parameter that indicates that the database file is stored on
3397 ** read-only media. ^When immutable is set, SQLite assumes that the
3398 ** database file cannot be changed, even by a process with higher
3399 ** privilege, and so the database is opened read-only and all locking
3400 ** and change detection is disabled. Caution: Setting the immutable
3401 ** property on a database file that does in fact change can result
3402 ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
3403 ** See also: [SQLITE_IOCAP_IMMUTABLE].
3404 **
3405 ** </ul>
3406 **
3407 ** ^Specifying an unknown parameter in the query component of a URI is not an
3408 ** error. Future versions of SQLite might understand additional query
3409 ** parameters. See "[query parameters with special meaning to SQLite]" for
3410 ** additional information.
3411 **
3412 ** [[URI filename examples]] <h3>URI filename examples</h3>
3413 **
3414 ** <table border="1" align=center cellpadding=5>
3415 ** <tr><th> URI filenames <th> Results
3416 ** <tr><td> file:data.db <td>
3417 ** Open the file "data.db" in the current directory.
3418 ** <tr><td> file:/home/fred/data.db<br>
3419 ** file:///home/fred/data.db <br>
3420 ** file://localhost/home/fred/data.db <br> <td>
3421 ** Open the database file "/home/fred/data.db".
3422 ** <tr><td> file://darkstar/home/fred/data.db <td>
3423 ** An error. "darkstar" is not a recognized authority.
3424 ** <tr><td style="white-space:nowrap">
3425 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3426 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
3427 ** C:. Note that the %20 escaping in this example is not strictly
3428 ** necessary - space characters can be used literally
3429 ** in URI filenames.
3430 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3431 ** Open file "data.db" in the current directory for read-only access.
3432 ** Regardless of whether or not shared-cache mode is enabled by
3433 ** default, use a private cache.
3434 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3435 ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3436 ** that uses dot-files in place of posix advisory locking.
3437 ** <tr><td> file:data.db?mode=readonly <td>
3438 ** An error. "readonly" is not a valid option for the "mode" parameter.
3439 ** </table>
3440 **
3441 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3442 ** query components of a URI. A hexadecimal escape sequence consists of a
3443 ** percent sign - "%" - followed by exactly two hexadecimal digits
3444 ** specifying an octet value. ^Before the path or query components of a
3445 ** URI filename are interpreted, they are encoded using UTF-8 and all
3446 ** hexadecimal escape sequences replaced by a single byte containing the
3447 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3448 ** the results are undefined.
3449 **
3450 ** <b>Note to Windows users:</b> The encoding used for the filename argument
3451 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3452 ** codepage is currently defined. Filenames containing international
3453 ** characters must be converted to UTF-8 prior to passing them into
3454 ** sqlite3_open() or sqlite3_open_v2().
3455 **
3456 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
3457 ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
3458 ** features that require the use of temporary files may fail.
3459 **
3460 ** See also: [sqlite3_temp_directory]
3461 */
3462 SQLITE_API int sqlite3_open(
3463  const char *filename, /* Database filename (UTF-8) */
3464  sqlite3 **ppDb /* OUT: SQLite db handle */
3465 );
3466 SQLITE_API int sqlite3_open16(
3467  const void *filename, /* Database filename (UTF-16) */
3468  sqlite3 **ppDb /* OUT: SQLite db handle */
3469 );
3470 SQLITE_API int sqlite3_open_v2(
3471  const char *filename, /* Database filename (UTF-8) */
3472  sqlite3 **ppDb, /* OUT: SQLite db handle */
3473  int flags, /* Flags */
3474  const char *zVfs /* Name of VFS module to use */
3475 );
3476 
3477 /*
3478 ** CAPI3REF: Obtain Values For URI Parameters
3479 **
3480 ** These are utility routines, useful to VFS implementations, that check
3481 ** to see if a database file was a URI that contained a specific query
3482 ** parameter, and if so obtains the value of that query parameter.
3483 **
3484 ** If F is the database filename pointer passed into the xOpen() method of
3485 ** a VFS implementation when the flags parameter to xOpen() has one or
3486 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3487 ** P is the name of the query parameter, then
3488 ** sqlite3_uri_parameter(F,P) returns the value of the P
3489 ** parameter if it exists or a NULL pointer if P does not appear as a
3490 ** query parameter on F. If P is a query parameter of F
3491 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3492 ** a pointer to an empty string.
3493 **
3494 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3495 ** parameter and returns true (1) or false (0) according to the value
3496 ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3497 ** value of query parameter P is one of "yes", "true", or "on" in any
3498 ** case or if the value begins with a non-zero number. The
3499 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3500 ** query parameter P is one of "no", "false", or "off" in any case or
3501 ** if the value begins with a numeric zero. If P is not a query
3502 ** parameter on F or if the value of P is does not match any of the
3503 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3504 **
3505 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3506 ** 64-bit signed integer and returns that integer, or D if P does not
3507 ** exist. If the value of P is something other than an integer, then
3508 ** zero is returned.
3509 **
3510 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3511 ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
3512 ** is not a database file pathname pointer that SQLite passed into the xOpen
3513 ** VFS method, then the behavior of this routine is undefined and probably
3514 ** undesirable.
3515 */
3516 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3517 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3518 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3519 
3520 
3521 /*
3522 ** CAPI3REF: Error Codes And Messages
3523 ** METHOD: sqlite3
3524 **
3525 ** ^If the most recent sqlite3_* API call associated with
3526 ** [database connection] D failed, then the sqlite3_errcode(D) interface
3527 ** returns the numeric [result code] or [extended result code] for that
3528 ** API call.
3529 ** If the most recent API call was successful,
3530 ** then the return value from sqlite3_errcode() is undefined.
3531 ** ^The sqlite3_extended_errcode()
3532 ** interface is the same except that it always returns the
3533 ** [extended result code] even when extended result codes are
3534 ** disabled.
3535 **
3536 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3537 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3538 ** ^(Memory to hold the error message string is managed internally.
3539 ** The application does not need to worry about freeing the result.
3540 ** However, the error string might be overwritten or deallocated by
3541 ** subsequent calls to other SQLite interface functions.)^
3542 **
3543 ** ^The sqlite3_errstr() interface returns the English-language text
3544 ** that describes the [result code], as UTF-8.
3545 ** ^(Memory to hold the error message string is managed internally
3546 ** and must not be freed by the application)^.
3547 **
3548 ** When the serialized [threading mode] is in use, it might be the
3549 ** case that a second error occurs on a separate thread in between
3550 ** the time of the first error and the call to these interfaces.
3551 ** When that happens, the second error will be reported since these
3552 ** interfaces always report the most recent result. To avoid
3553 ** this, each thread can obtain exclusive use of the [database connection] D
3554 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3555 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3556 ** all calls to the interfaces listed here are completed.
3557 **
3558 ** If an interface fails with SQLITE_MISUSE, that means the interface
3559 ** was invoked incorrectly by the application. In that case, the
3560 ** error code and message may or may not be set.
3561 */
3562 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3563 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3564 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3565 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3566 SQLITE_API const char *sqlite3_errstr(int);
3567 
3568 /*
3569 ** CAPI3REF: Prepared Statement Object
3570 ** KEYWORDS: {prepared statement} {prepared statements}
3571 **
3572 ** An instance of this object represents a single SQL statement that
3573 ** has been compiled into binary form and is ready to be evaluated.
3574 **
3575 ** Think of each SQL statement as a separate computer program. The
3576 ** original SQL text is source code. A prepared statement object
3577 ** is the compiled object code. All SQL must be converted into a
3578 ** prepared statement before it can be run.
3579 **
3580 ** The life-cycle of a prepared statement object usually goes like this:
3581 **
3582 ** <ol>
3583 ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
3584 ** <li> Bind values to [parameters] using the sqlite3_bind_*()
3585 ** interfaces.
3586 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3587 ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
3588 ** to step 2. Do this zero or more times.
3589 ** <li> Destroy the object using [sqlite3_finalize()].
3590 ** </ol>
3591 */
3592 typedef struct sqlite3_stmt sqlite3_stmt;
3593 
3594 /*
3595 ** CAPI3REF: Run-time Limits
3596 ** METHOD: sqlite3
3597 **
3598 ** ^(This interface allows the size of various constructs to be limited
3599 ** on a connection by connection basis. The first parameter is the
3600 ** [database connection] whose limit is to be set or queried. The
3601 ** second parameter is one of the [limit categories] that define a
3602 ** class of constructs to be size limited. The third parameter is the
3603 ** new limit for that construct.)^
3604 **
3605 ** ^If the new limit is a negative number, the limit is unchanged.
3606 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3607 ** [limits | hard upper bound]
3608 ** set at compile-time by a C preprocessor macro called
3609 ** [limits | SQLITE_MAX_<i>NAME</i>].
3610 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3611 ** ^Attempts to increase a limit above its hard upper bound are
3612 ** silently truncated to the hard upper bound.
3613 **
3614 ** ^Regardless of whether or not the limit was changed, the
3615 ** [sqlite3_limit()] interface returns the prior value of the limit.
3616 ** ^Hence, to find the current value of a limit without changing it,
3617 ** simply invoke this interface with the third parameter set to -1.
3618 **
3619 ** Run-time limits are intended for use in applications that manage
3620 ** both their own internal database and also databases that are controlled
3621 ** by untrusted external sources. An example application might be a
3622 ** web browser that has its own databases for storing history and
3623 ** separate databases controlled by JavaScript applications downloaded
3624 ** off the Internet. The internal databases can be given the
3625 ** large, default limits. Databases managed by external sources can
3626 ** be given much smaller limits designed to prevent a denial of service
3627 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3628 ** interface to further control untrusted SQL. The size of the database
3629 ** created by an untrusted script can be contained using the
3630 ** [max_page_count] [PRAGMA].
3631 **
3632 ** New run-time limit categories may be added in future releases.
3633 */
3634 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3635 
3636 /*
3637 ** CAPI3REF: Run-Time Limit Categories
3638 ** KEYWORDS: {limit category} {*limit categories}
3639 **
3640 ** These constants define various performance limits
3641 ** that can be lowered at run-time using [sqlite3_limit()].
3642 ** The synopsis of the meanings of the various limits is shown below.
3643 ** Additional information is available at [limits | Limits in SQLite].
3644 **
3645 ** <dl>
3646 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3647 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3648 **
3649 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3650 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3651 **
3652 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3653 ** <dd>The maximum number of columns in a table definition or in the
3654 ** result set of a [SELECT] or the maximum number of columns in an index
3655 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3656 **
3657 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3658 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3659 **
3660 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3661 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3662 **
3663 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3664 ** <dd>The maximum number of instructions in a virtual machine program
3665 ** used to implement an SQL statement. This limit is not currently
3666 ** enforced, though that might be added in some future release of
3667 ** SQLite.</dd>)^
3668 **
3669 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3670 ** <dd>The maximum number of arguments on a function.</dd>)^
3671 **
3672 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3673 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3674 **
3675 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3676 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3677 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3678 ** [GLOB] operators.</dd>)^
3679 **
3680 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3681 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3682 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3683 **
3684 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3685 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3686 **
3687 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3688 ** <dd>The maximum number of auxiliary worker threads that a single
3689 ** [prepared statement] may start.</dd>)^
3690 ** </dl>
3691 */
3692 #define SQLITE_LIMIT_LENGTH 0
3693 #define SQLITE_LIMIT_SQL_LENGTH 1
3694 #define SQLITE_LIMIT_COLUMN 2
3695 #define SQLITE_LIMIT_EXPR_DEPTH 3
3696 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3697 #define SQLITE_LIMIT_VDBE_OP 5
3698 #define SQLITE_LIMIT_FUNCTION_ARG 6
3699 #define SQLITE_LIMIT_ATTACHED 7
3700 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3701 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3702 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3703 #define SQLITE_LIMIT_WORKER_THREADS 11
3704 
3705 /*
3706 ** CAPI3REF: Compiling An SQL Statement
3707 ** KEYWORDS: {SQL statement compiler}
3708 ** METHOD: sqlite3
3709 ** CONSTRUCTOR: sqlite3_stmt
3710 **
3711 ** To execute an SQL query, it must first be compiled into a byte-code
3712 ** program using one of these routines.
3713 **
3714 ** The first argument, "db", is a [database connection] obtained from a
3715 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3716 ** [sqlite3_open16()]. The database connection must not have been closed.
3717 **
3718 ** The second argument, "zSql", is the statement to be compiled, encoded
3719 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3720 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3721 ** use UTF-16.
3722 **
3723 ** ^If the nByte argument is negative, then zSql is read up to the
3724 ** first zero terminator. ^If nByte is positive, then it is the
3725 ** number of bytes read from zSql. ^If nByte is zero, then no prepared
3726 ** statement is generated.
3727 ** If the caller knows that the supplied string is nul-terminated, then
3728 ** there is a small performance advantage to passing an nByte parameter that
3729 ** is the number of bytes in the input string <i>including</i>
3730 ** the nul-terminator.
3731 **
3732 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3733 ** past the end of the first SQL statement in zSql. These routines only
3734 ** compile the first statement in zSql, so *pzTail is left pointing to
3735 ** what remains uncompiled.
3736 **
3737 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3738 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3739 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3740 ** string or a comment) then *ppStmt is set to NULL.
3741 ** The calling procedure is responsible for deleting the compiled
3742 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3743 ** ppStmt may not be NULL.
3744 **
3745 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3746 ** otherwise an [error code] is returned.
3747 **
3748 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3749 ** recommended for all new programs. The two older interfaces are retained
3750 ** for backwards compatibility, but their use is discouraged.
3751 ** ^In the "v2" interfaces, the prepared statement
3752 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3753 ** original SQL text. This causes the [sqlite3_step()] interface to
3754 ** behave differently in three ways:
3755 **
3756 ** <ol>
3757 ** <li>
3758 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3759 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3760 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3761 ** retries will occur before sqlite3_step() gives up and returns an error.
3762 ** </li>
3763 **
3764 ** <li>
3765 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3766 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3767 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3768 ** and the application would have to make a second call to [sqlite3_reset()]
3769 ** in order to find the underlying cause of the problem. With the "v2" prepare
3770 ** interfaces, the underlying reason for the error is returned immediately.
3771 ** </li>
3772 **
3773 ** <li>
3774 ** ^If the specific value bound to [parameter | host parameter] in the
3775 ** WHERE clause might influence the choice of query plan for a statement,
3776 ** then the statement will be automatically recompiled, as if there had been
3777 ** a schema change, on the first [sqlite3_step()] call following any change
3778 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3779 ** ^The specific value of WHERE-clause [parameter] might influence the
3780 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3781 ** or [GLOB] operator or if the parameter is compared to an indexed column
3782 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3783 ** </li>
3784 ** </ol>
3785 */
3786 SQLITE_API int sqlite3_prepare(
3787  sqlite3 *db, /* Database handle */
3788  const char *zSql, /* SQL statement, UTF-8 encoded */
3789  int nByte, /* Maximum length of zSql in bytes. */
3790  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3791  const char **pzTail /* OUT: Pointer to unused portion of zSql */
3792 );
3793 SQLITE_API int sqlite3_prepare_v2(
3794  sqlite3 *db, /* Database handle */
3795  const char *zSql, /* SQL statement, UTF-8 encoded */
3796  int nByte, /* Maximum length of zSql in bytes. */
3797  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3798  const char **pzTail /* OUT: Pointer to unused portion of zSql */
3799 );
3800 SQLITE_API int sqlite3_prepare16(
3801  sqlite3 *db, /* Database handle */
3802  const void *zSql, /* SQL statement, UTF-16 encoded */
3803  int nByte, /* Maximum length of zSql in bytes. */
3804  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3805  const void **pzTail /* OUT: Pointer to unused portion of zSql */
3806 );
3807 SQLITE_API int sqlite3_prepare16_v2(
3808  sqlite3 *db, /* Database handle */
3809  const void *zSql, /* SQL statement, UTF-16 encoded */
3810  int nByte, /* Maximum length of zSql in bytes. */
3811  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3812  const void **pzTail /* OUT: Pointer to unused portion of zSql */
3813 );
3814 
3815 /*
3816 ** CAPI3REF: Retrieving Statement SQL
3817 ** METHOD: sqlite3_stmt
3818 **
3819 ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
3820 ** SQL text used to create [prepared statement] P if P was
3821 ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3822 ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
3823 ** string containing the SQL text of prepared statement P with
3824 ** [bound parameters] expanded.
3825 **
3826 ** ^(For example, if a prepared statement is created using the SQL
3827 ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
3828 ** and parameter :xyz is unbound, then sqlite3_sql() will return
3829 ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
3830 ** will return "SELECT 2345,NULL".)^
3831 **
3832 ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
3833 ** is available to hold the result, or if the result would exceed the
3834 ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
3835 **
3836 ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
3837 ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
3838 ** option causes sqlite3_expanded_sql() to always return NULL.
3839 **
3840 ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
3841 ** automatically freed when the prepared statement is finalized.
3842 ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
3843 ** is obtained from [sqlite3_malloc()] and must be free by the application
3844 ** by passing it to [sqlite3_free()].
3845 */
3846 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3847 SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
3848 
3849 /*
3850 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3851 ** METHOD: sqlite3_stmt
3852 **
3853 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3854 ** and only if the [prepared statement] X makes no direct changes to
3855 ** the content of the database file.
3856 **
3857 ** Note that [application-defined SQL functions] or
3858 ** [virtual tables] might change the database indirectly as a side effect.
3859 ** ^(For example, if an application defines a function "eval()" that
3860 ** calls [sqlite3_exec()], then the following SQL statement would
3861 ** change the database file through side-effects:
3862 **
3863 ** <blockquote><pre>
3864 ** SELECT eval('DELETE FROM t1') FROM t2;
3865 ** </pre></blockquote>
3866 **
3867 ** But because the [SELECT] statement does not change the database file
3868 ** directly, sqlite3_stmt_readonly() would still return true.)^
3869 **
3870 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3871 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3872 ** since the statements themselves do not actually modify the database but
3873 ** rather they control the timing of when other statements modify the
3874 ** database. ^The [ATTACH] and [DETACH] statements also cause
3875 ** sqlite3_stmt_readonly() to return true since, while those statements
3876 ** change the configuration of a database connection, they do not make
3877 ** changes to the content of the database files on disk.
3878 */
3879 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3880 
3881 /*
3882 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3883 ** METHOD: sqlite3_stmt
3884 **
3885 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3886 ** [prepared statement] S has been stepped at least once using
3887 ** [sqlite3_step(S)] but has neither run to completion (returned
3888 ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
3889 ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
3890 ** interface returns false if S is a NULL pointer. If S is not a
3891 ** NULL pointer and is not a pointer to a valid [prepared statement]
3892 ** object, then the behavior is undefined and probably undesirable.
3893 **
3894 ** This interface can be used in combination [sqlite3_next_stmt()]
3895 ** to locate all prepared statements associated with a database
3896 ** connection that are in need of being reset. This can be used,
3897 ** for example, in diagnostic routines to search for prepared
3898 ** statements that are holding a transaction open.
3899 */
3900 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3901 
3902 /*
3903 ** CAPI3REF: Dynamically Typed Value Object
3904 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3905 **
3906 ** SQLite uses the sqlite3_value object to represent all values
3907 ** that can be stored in a database table. SQLite uses dynamic typing
3908 ** for the values it stores. ^Values stored in sqlite3_value objects
3909 ** can be integers, floating point values, strings, BLOBs, or NULL.
3910 **
3911 ** An sqlite3_value object may be either "protected" or "unprotected".
3912 ** Some interfaces require a protected sqlite3_value. Other interfaces
3913 ** will accept either a protected or an unprotected sqlite3_value.
3914 ** Every interface that accepts sqlite3_value arguments specifies
3915 ** whether or not it requires a protected sqlite3_value. The
3916 ** [sqlite3_value_dup()] interface can be used to construct a new
3917 ** protected sqlite3_value from an unprotected sqlite3_value.
3918 **
3919 ** The terms "protected" and "unprotected" refer to whether or not
3920 ** a mutex is held. An internal mutex is held for a protected
3921 ** sqlite3_value object but no mutex is held for an unprotected
3922 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3923 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3924 ** or if SQLite is run in one of reduced mutex modes
3925 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3926 ** then there is no distinction between protected and unprotected
3927 ** sqlite3_value objects and they can be used interchangeably. However,
3928 ** for maximum code portability it is recommended that applications
3929 ** still make the distinction between protected and unprotected
3930 ** sqlite3_value objects even when not strictly required.
3931 **
3932 ** ^The sqlite3_value objects that are passed as parameters into the
3933 ** implementation of [application-defined SQL functions] are protected.
3934 ** ^The sqlite3_value object returned by
3935 ** [sqlite3_column_value()] is unprotected.
3936 ** Unprotected sqlite3_value objects may only be used with
3937 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3938 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3939 ** interfaces require protected sqlite3_value objects.
3940 */
3941 typedef struct Mem sqlite3_value;
3942 
3943 /*
3944 ** CAPI3REF: SQL Function Context Object
3945 **
3946 ** The context in which an SQL function executes is stored in an
3947 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3948 ** is always first parameter to [application-defined SQL functions].
3949 ** The application-defined SQL function implementation will pass this
3950 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3951 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3952 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3953 ** and/or [sqlite3_set_auxdata()].
3954 */
3955 typedef struct sqlite3_context sqlite3_context;
3956 
3957 /*
3958 ** CAPI3REF: Binding Values To Prepared Statements
3959 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3960 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3961 ** METHOD: sqlite3_stmt
3962 **
3963 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3964 ** literals may be replaced by a [parameter] that matches one of following
3965 ** templates:
3966 **
3967 ** <ul>
3968 ** <li> ?
3969 ** <li> ?NNN
3970 ** <li> :VVV
3971 ** <li> @VVV
3972 ** <li> $VVV
3973 ** </ul>
3974 **
3975 ** In the templates above, NNN represents an integer literal,
3976 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3977 ** parameters (also called "host parameter names" or "SQL parameters")
3978 ** can be set using the sqlite3_bind_*() routines defined here.
3979 **
3980 ** ^The first argument to the sqlite3_bind_*() routines is always
3981 ** a pointer to the [sqlite3_stmt] object returned from
3982 ** [sqlite3_prepare_v2()] or its variants.
3983 **
3984 ** ^The second argument is the index of the SQL parameter to be set.
3985 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3986 ** SQL parameter is used more than once, second and subsequent
3987 ** occurrences have the same index as the first occurrence.
3988 ** ^The index for named parameters can be looked up using the
3989 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3990 ** for "?NNN" parameters is the value of NNN.
3991 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3992 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3993 **
3994 ** ^The third argument is the value to bind to the parameter.
3995 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3996 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3997 ** is ignored and the end result is the same as sqlite3_bind_null().
3998 **
3999 ** ^(In those routines that have a fourth argument, its value is the
4000 ** number of bytes in the parameter. To be clear: the value is the
4001 ** number of <u>bytes</u> in the value, not the number of characters.)^
4002 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4003 ** is negative, then the length of the string is
4004 ** the number of bytes up to the first zero terminator.
4005 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
4006 ** the behavior is undefined.
4007 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
4008 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
4009 ** that parameter must be the byte offset
4010 ** where the NUL terminator would occur assuming the string were NUL
4011 ** terminated. If any NUL characters occur at byte offsets less than
4012 ** the value of the fourth parameter then the resulting string value will
4013 ** contain embedded NULs. The result of expressions involving strings
4014 ** with embedded NULs is undefined.
4015 **
4016 ** ^The fifth argument to the BLOB and string binding interfaces
4017 ** is a destructor used to dispose of the BLOB or
4018 ** string after SQLite has finished with it. ^The destructor is called
4019 ** to dispose of the BLOB or string even if the call to bind API fails.
4020 ** ^If the fifth argument is
4021 ** the special value [SQLITE_STATIC], then SQLite assumes that the
4022 ** information is in static, unmanaged space and does not need to be freed.
4023 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
4024 ** SQLite makes its own private copy of the data immediately, before
4025 ** the sqlite3_bind_*() routine returns.
4026 **
4027 ** ^The sixth argument to sqlite3_bind_text64() must be one of
4028 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
4029 ** to specify the encoding of the text in the third parameter. If
4030 ** the sixth argument to sqlite3_bind_text64() is not one of the
4031 ** allowed values shown above, or if the text encoding is different
4032 ** from the encoding specified by the sixth parameter, then the behavior
4033 ** is undefined.
4034 **
4035 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
4036 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
4037 ** (just an integer to hold its size) while it is being processed.
4038 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
4039 ** content is later written using
4040 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
4041 ** ^A negative value for the zeroblob results in a zero-length BLOB.
4042 **
4043 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
4044 ** for the [prepared statement] or with a prepared statement for which
4045 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
4046 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
4047 ** routine is passed a [prepared statement] that has been finalized, the
4048 ** result is undefined and probably harmful.
4049 **
4050 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
4051 ** ^Unbound parameters are interpreted as NULL.
4052 **
4053 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
4054 ** [error code] if anything goes wrong.
4055 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
4056 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
4057 ** [SQLITE_MAX_LENGTH].
4058 ** ^[SQLITE_RANGE] is returned if the parameter
4059 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
4060 **
4061 ** See also: [sqlite3_bind_parameter_count()],
4062 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
4063 */
4064 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
4065 SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
4066  void(*)(void*));
4067 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
4068 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
4069 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
4070 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
4071 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
4072 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
4073 SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
4074  void(*)(void*), unsigned char encoding);
4075 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
4076 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
4077 SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
4078 
4079 /*
4080 ** CAPI3REF: Number Of SQL Parameters
4081 ** METHOD: sqlite3_stmt
4082 **
4083 ** ^This routine can be used to find the number of [SQL parameters]
4084 ** in a [prepared statement]. SQL parameters are tokens of the
4085 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
4086 ** placeholders for values that are [sqlite3_bind_blob | bound]
4087 ** to the parameters at a later time.
4088 **
4089 ** ^(This routine actually returns the index of the largest (rightmost)
4090 ** parameter. For all forms except ?NNN, this will correspond to the
4091 ** number of unique parameters. If parameters of the ?NNN form are used,
4092 ** there may be gaps in the list.)^
4093 **
4094 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
4095 ** [sqlite3_bind_parameter_name()], and
4096 ** [sqlite3_bind_parameter_index()].
4097 */
4098 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
4099 
4100 /*
4101 ** CAPI3REF: Name Of A Host Parameter
4102 ** METHOD: sqlite3_stmt
4103 **
4104 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
4105 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
4106 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
4107 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
4108 ** respectively.
4109 ** In other words, the initial ":" or "$" or "@" or "?"
4110 ** is included as part of the name.)^
4111 ** ^Parameters of the form "?" without a following integer have no name
4112 ** and are referred to as "nameless" or "anonymous parameters".
4113 **
4114 ** ^The first host parameter has an index of 1, not 0.
4115 **
4116 ** ^If the value N is out of range or if the N-th parameter is
4117 ** nameless, then NULL is returned. ^The returned string is
4118 ** always in UTF-8 encoding even if the named parameter was
4119 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
4120 ** [sqlite3_prepare16_v2()].
4121 **
4122 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
4123 ** [sqlite3_bind_parameter_count()], and
4124 ** [sqlite3_bind_parameter_index()].
4125 */
4126 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
4127 
4128 /*
4129 ** CAPI3REF: Index Of A Parameter With A Given Name
4130 ** METHOD: sqlite3_stmt
4131 **
4132 ** ^Return the index of an SQL parameter given its name. ^The
4133 ** index value returned is suitable for use as the second
4134 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
4135 ** is returned if no matching parameter is found. ^The parameter
4136 ** name must be given in UTF-8 even if the original statement
4137 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
4138 **
4139 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
4140 ** [sqlite3_bind_parameter_count()], and
4141 ** [sqlite3_bind_parameter_name()].
4142 */
4143 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
4144 
4145 /*
4146 ** CAPI3REF: Reset All Bindings On A Prepared Statement
4147 ** METHOD: sqlite3_stmt
4148 **
4149 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
4150 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
4151 ** ^Use this routine to reset all host parameters to NULL.
4152 */
4153 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
4154 
4155 /*
4156 ** CAPI3REF: Number Of Columns In A Result Set
4157 ** METHOD: sqlite3_stmt
4158 **
4159 ** ^Return the number of columns in the result set returned by the
4160 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
4161 ** statement that does not return data (for example an [UPDATE]).
4162 **
4163 ** See also: [sqlite3_data_count()]
4164 */
4165 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
4166 
4167 /*
4168 ** CAPI3REF: Column Names In A Result Set
4169 ** METHOD: sqlite3_stmt
4170 **
4171 ** ^These routines return the name assigned to a particular column
4172 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
4173 ** interface returns a pointer to a zero-terminated UTF-8 string
4174 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
4175 ** UTF-16 string. ^The first parameter is the [prepared statement]
4176 ** that implements the [SELECT] statement. ^The second parameter is the
4177 ** column number. ^The leftmost column is number 0.
4178 **
4179 ** ^The returned string pointer is valid until either the [prepared statement]
4180 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
4181 ** reprepared by the first call to [sqlite3_step()] for a particular run
4182 ** or until the next call to
4183 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
4184 **
4185 ** ^If sqlite3_malloc() fails during the processing of either routine
4186 ** (for example during a conversion from UTF-8 to UTF-16) then a
4187 ** NULL pointer is returned.
4188 **
4189 ** ^The name of a result column is the value of the "AS" clause for
4190 ** that column, if there is an AS clause. If there is no AS clause
4191 ** then the name of the column is unspecified and may change from
4192 ** one release of SQLite to the next.
4193 */
4194 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
4195 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
4196 
4197 /*
4198 ** CAPI3REF: Source Of Data In A Query Result
4199 ** METHOD: sqlite3_stmt
4200 **
4201 ** ^These routines provide a means to determine the database, table, and
4202 ** table column that is the origin of a particular result column in
4203 ** [SELECT] statement.
4204 ** ^The name of the database or table or column can be returned as
4205 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
4206 ** the database name, the _table_ routines return the table name, and
4207 ** the origin_ routines return the column name.
4208 ** ^The returned string is valid until the [prepared statement] is destroyed
4209 ** using [sqlite3_finalize()] or until the statement is automatically
4210 ** reprepared by the first call to [sqlite3_step()] for a particular run
4211 ** or until the same information is requested
4212 ** again in a different encoding.
4213 **
4214 ** ^The names returned are the original un-aliased names of the
4215 ** database, table, and column.
4216 **
4217 ** ^The first argument to these interfaces is a [prepared statement].
4218 ** ^These functions return information about the Nth result column returned by
4219 ** the statement, where N is the second function argument.
4220 ** ^The left-most column is column 0 for these routines.
4221 **
4222 ** ^If the Nth column returned by the statement is an expression or
4223 ** subquery and is not a column value, then all of these functions return
4224 ** NULL. ^These routine might also return NULL if a memory allocation error
4225 ** occurs. ^Otherwise, they return the name of the attached database, table,
4226 ** or column that query result column was extracted from.
4227 **
4228 ** ^As with all other SQLite APIs, those whose names end with "16" return
4229 ** UTF-16 encoded strings and the other functions return UTF-8.
4230 **
4231 ** ^These APIs are only available if the library was compiled with the
4232 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4233 **
4234 ** If two or more threads call one or more of these routines against the same
4235 ** prepared statement and column at the same time then the results are
4236 ** undefined.
4237 **
4238 ** If two or more threads call one or more
4239 ** [sqlite3_column_database_name | column metadata interfaces]
4240 ** for the same [prepared statement] and result column
4241 ** at the same time then the results are undefined.
4242 */
4243 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4244 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4245 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
4246 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
4247 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
4248 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
4249 
4250 /*
4251 ** CAPI3REF: Declared Datatype Of A Query Result
4252 ** METHOD: sqlite3_stmt
4253 **
4254 ** ^(The first parameter is a [prepared statement].
4255 ** If this statement is a [SELECT] statement and the Nth column of the
4256 ** returned result set of that [SELECT] is a table column (not an
4257 ** expression or subquery) then the declared type of the table
4258 ** column is returned.)^ ^If the Nth column of the result set is an
4259 ** expression or subquery, then a NULL pointer is returned.
4260 ** ^The returned string is always UTF-8 encoded.
4261 **
4262 ** ^(For example, given the database schema:
4263 **
4264 ** CREATE TABLE t1(c1 VARIANT);
4265 **
4266 ** and the following statement to be compiled:
4267 **
4268 ** SELECT c1 + 1, c1 FROM t1;
4269 **
4270 ** this routine would return the string "VARIANT" for the second result
4271 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4272 **
4273 ** ^SQLite uses dynamic run-time typing. ^So just because a column
4274 ** is declared to contain a particular type does not mean that the
4275 ** data stored in that column is of the declared type. SQLite is
4276 ** strongly typed, but the typing is dynamic not static. ^Type
4277 ** is associated with individual values, not with the containers
4278 ** used to hold those values.
4279 */
4280 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4281 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4282 
4283 /*
4284 ** CAPI3REF: Evaluate An SQL Statement
4285 ** METHOD: sqlite3_stmt
4286 **
4287 ** After a [prepared statement] has been prepared using either
4288 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4289 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4290 ** must be called one or more times to evaluate the statement.
4291 **
4292 ** The details of the behavior of the sqlite3_step() interface depend
4293 ** on whether the statement was prepared using the newer "v2" interface
4294 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4295 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
4296 ** new "v2" interface is recommended for new applications but the legacy
4297 ** interface will continue to be supported.
4298 **
4299 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4300 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4301 ** ^With the "v2" interface, any of the other [result codes] or
4302 ** [extended result codes] might be returned as well.
4303 **
4304 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4305 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
4306 ** or occurs outside of an explicit transaction, then you can retry the
4307 ** statement. If the statement is not a [COMMIT] and occurs within an
4308 ** explicit transaction then you should rollback the transaction before
4309 ** continuing.
4310 **
4311 ** ^[SQLITE_DONE] means that the statement has finished executing
4312 ** successfully. sqlite3_step() should not be called again on this virtual
4313 ** machine without first calling [sqlite3_reset()] to reset the virtual
4314 ** machine back to its initial state.
4315 **
4316 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4317 ** is returned each time a new row of data is ready for processing by the
4318 ** caller. The values may be accessed using the [column access functions].
4319 ** sqlite3_step() is called again to retrieve the next row of data.
4320 **
4321 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4322 ** violation) has occurred. sqlite3_step() should not be called again on
4323 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4324 ** ^With the legacy interface, a more specific error code (for example,
4325 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4326 ** can be obtained by calling [sqlite3_reset()] on the
4327 ** [prepared statement]. ^In the "v2" interface,
4328 ** the more specific error code is returned directly by sqlite3_step().
4329 **
4330 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4331 ** Perhaps it was called on a [prepared statement] that has
4332 ** already been [sqlite3_finalize | finalized] or on one that had
4333 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
4334 ** be the case that the same database connection is being used by two or
4335 ** more threads at the same moment in time.
4336 **
4337 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4338 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4339 ** other than [SQLITE_ROW] before any subsequent invocation of
4340 ** sqlite3_step(). Failure to reset the prepared statement using
4341 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4342 ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
4343 ** sqlite3_step() began
4344 ** calling [sqlite3_reset()] automatically in this circumstance rather
4345 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
4346 ** break because any application that ever receives an SQLITE_MISUSE error
4347 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
4348 ** can be used to restore the legacy behavior.
4349 **
4350 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4351 ** API always returns a generic error code, [SQLITE_ERROR], following any
4352 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
4353 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4354 ** specific [error codes] that better describes the error.
4355 ** We admit that this is a goofy design. The problem has been fixed
4356 ** with the "v2" interface. If you prepare all of your SQL statements
4357 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4358 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4359 ** then the more specific [error codes] are returned directly
4360 ** by sqlite3_step(). The use of the "v2" interface is recommended.
4361 */
4362 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4363 
4364 /*
4365 ** CAPI3REF: Number of columns in a result set
4366 ** METHOD: sqlite3_stmt
4367 **
4368 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4369 ** current row of the result set of [prepared statement] P.
4370 ** ^If prepared statement P does not have results ready to return
4371 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4372 ** interfaces) then sqlite3_data_count(P) returns 0.
4373 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4374 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4375 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
4376 ** will return non-zero if previous call to [sqlite3_step](P) returned
4377 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4378 ** where it always returns zero since each step of that multi-step
4379 ** pragma returns 0 columns of data.
4380 **
4381 ** See also: [sqlite3_column_count()]
4382 */
4383 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4384 
4385 /*
4386 ** CAPI3REF: Fundamental Datatypes
4387 ** KEYWORDS: SQLITE_TEXT
4388 **
4389 ** ^(Every value in SQLite has one of five fundamental datatypes:
4390 **
4391 ** <ul>
4392 ** <li> 64-bit signed integer
4393 ** <li> 64-bit IEEE floating point number
4394 ** <li> string
4395 ** <li> BLOB
4396 ** <li> NULL
4397 ** </ul>)^
4398 **
4399 ** These constants are codes for each of those types.
4400 **
4401 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4402 ** for a completely different meaning. Software that links against both
4403 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4404 ** SQLITE_TEXT.
4405 */
4406 #define SQLITE_INTEGER 1
4407 #define SQLITE_FLOAT 2
4408 #define SQLITE_BLOB 4
4409 #define SQLITE_NULL 5
4410 #ifdef SQLITE_TEXT
4411 # undef SQLITE_TEXT
4412 #else
4413 # define SQLITE_TEXT 3
4414 #endif
4415 #define SQLITE3_TEXT 3
4416 
4417 /*
4418 ** CAPI3REF: Result Values From A Query
4419 ** KEYWORDS: {column access functions}
4420 ** METHOD: sqlite3_stmt
4421 **
4422 ** ^These routines return information about a single column of the current
4423 ** result row of a query. ^In every case the first argument is a pointer
4424 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4425 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4426 ** and the second argument is the index of the column for which information
4427 ** should be returned. ^The leftmost column of the result set has the index 0.
4428 ** ^The number of columns in the result can be determined using
4429 ** [sqlite3_column_count()].
4430 **
4431 ** If the SQL statement does not currently point to a valid row, or if the
4432 ** column index is out of range, the result is undefined.
4433 ** These routines may only be called when the most recent call to
4434 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4435 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4436 ** If any of these routines are called after [sqlite3_reset()] or
4437 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4438 ** something other than [SQLITE_ROW], the results are undefined.
4439 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4440 ** are called from a different thread while any of these routines
4441 ** are pending, then the results are undefined.
4442 **
4443 ** ^The sqlite3_column_type() routine returns the
4444 ** [SQLITE_INTEGER | datatype code] for the initial data type
4445 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
4446 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
4447 ** returned by sqlite3_column_type() is only meaningful if no type
4448 ** conversions have occurred as described below. After a type conversion,
4449 ** the value returned by sqlite3_column_type() is undefined. Future
4450 ** versions of SQLite may change the behavior of sqlite3_column_type()
4451 ** following a type conversion.
4452 **
4453 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4454 ** routine returns the number of bytes in that BLOB or string.
4455 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4456 ** the string to UTF-8 and then returns the number of bytes.
4457 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4458 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4459 ** the number of bytes in that string.
4460 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4461 **
4462 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4463 ** routine returns the number of bytes in that BLOB or string.
4464 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4465 ** the string to UTF-16 and then returns the number of bytes.
4466 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4467 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4468 ** the number of bytes in that string.
4469 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4470 **
4471 ** ^The values returned by [sqlite3_column_bytes()] and
4472 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4473 ** of the string. ^For clarity: the values returned by
4474 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4475 ** bytes in the string, not the number of characters.
4476 **
4477 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4478 ** even empty strings, are always zero-terminated. ^The return
4479 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4480 **
4481 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
4482 ** [unprotected sqlite3_value] object. In a multithreaded environment,
4483 ** an unprotected sqlite3_value object may only be used safely with
4484 ** [sqlite3_bind_value()] and [sqlite3_result_value()].
4485 ** If the [unprotected sqlite3_value] object returned by
4486 ** [sqlite3_column_value()] is used in any other way, including calls
4487 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4488 ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
4489 **
4490 ** These routines attempt to convert the value where appropriate. ^For
4491 ** example, if the internal representation is FLOAT and a text result
4492 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4493 ** conversion automatically. ^(The following table details the conversions
4494 ** that are applied:
4495 **
4496 ** <blockquote>
4497 ** <table border="1">
4498 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
4499 **
4500 ** <tr><td> NULL <td> INTEGER <td> Result is 0
4501 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
4502 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
4503 ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
4504 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
4505 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
4506 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
4507 ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
4508 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
4509 ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
4510 ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
4511 ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
4512 ** <tr><td> TEXT <td> BLOB <td> No change
4513 ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
4514 ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
4515 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
4516 ** </table>
4517 ** </blockquote>)^
4518 **
4519 ** Note that when type conversions occur, pointers returned by prior
4520 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4521 ** sqlite3_column_text16() may be invalidated.
4522 ** Type conversions and pointer invalidations might occur
4523 ** in the following cases:
4524 **
4525 ** <ul>
4526 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4527 ** sqlite3_column_text16() is called. A zero-terminator might
4528 ** need to be added to the string.</li>
4529 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4530 ** sqlite3_column_text16() is called. The content must be converted
4531 ** to UTF-16.</li>
4532 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4533 ** sqlite3_column_text() is called. The content must be converted
4534 ** to UTF-8.</li>
4535 ** </ul>
4536 **
4537 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4538 ** not invalidate a prior pointer, though of course the content of the buffer
4539 ** that the prior pointer references will have been modified. Other kinds
4540 ** of conversion are done in place when it is possible, but sometimes they
4541 ** are not possible and in those cases prior pointers are invalidated.
4542 **
4543 ** The safest policy is to invoke these routines
4544 ** in one of the following ways:
4545 **
4546 ** <ul>
4547 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4548 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4549 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4550 ** </ul>
4551 **
4552 ** In other words, you should call sqlite3_column_text(),
4553 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4554 ** into the desired format, then invoke sqlite3_column_bytes() or
4555 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
4556 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4557 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4558 ** with calls to sqlite3_column_bytes().
4559 **
4560 ** ^The pointers returned are valid until a type conversion occurs as
4561 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4562 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
4563 ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
4564 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4565 ** [sqlite3_free()].
4566 **
4567 ** ^(If a memory allocation error occurs during the evaluation of any
4568 ** of these routines, a default value is returned. The default value
4569 ** is either the integer 0, the floating point number 0.0, or a NULL
4570 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
4571 ** [SQLITE_NOMEM].)^
4572 */
4573 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4574 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4575 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4576 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4577 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4578 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4579 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4580 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4581 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4582 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4583 
4584 /*
4585 ** CAPI3REF: Destroy A Prepared Statement Object
4586 ** DESTRUCTOR: sqlite3_stmt
4587 **
4588 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4589 ** ^If the most recent evaluation of the statement encountered no errors
4590 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4591 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
4592 ** sqlite3_finalize(S) returns the appropriate [error code] or
4593 ** [extended error code].
4594 **
4595 ** ^The sqlite3_finalize(S) routine can be called at any point during
4596 ** the life cycle of [prepared statement] S:
4597 ** before statement S is ever evaluated, after
4598 ** one or more calls to [sqlite3_reset()], or after any call
4599 ** to [sqlite3_step()] regardless of whether or not the statement has
4600 ** completed execution.
4601 **
4602 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4603 **
4604 ** The application must finalize every [prepared statement] in order to avoid
4605 ** resource leaks. It is a grievous error for the application to try to use
4606 ** a prepared statement after it has been finalized. Any use of a prepared
4607 ** statement after it has been finalized can result in undefined and
4608 ** undesirable behavior such as segfaults and heap corruption.
4609 */
4610 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4611 
4612 /*
4613 ** CAPI3REF: Reset A Prepared Statement Object
4614 ** METHOD: sqlite3_stmt
4615 **
4616 ** The sqlite3_reset() function is called to reset a [prepared statement]
4617 ** object back to its initial state, ready to be re-executed.
4618 ** ^Any SQL statement variables that had values bound to them using
4619 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4620 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4621 **
4622 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4623 ** back to the beginning of its program.
4624 **
4625 ** ^If the most recent call to [sqlite3_step(S)] for the
4626 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4627 ** or if [sqlite3_step(S)] has never before been called on S,
4628 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4629 **
4630 ** ^If the most recent call to [sqlite3_step(S)] for the
4631 ** [prepared statement] S indicated an error, then
4632 ** [sqlite3_reset(S)] returns an appropriate [error code].
4633 **
4634 ** ^The [sqlite3_reset(S)] interface does not change the values
4635 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4636 */
4637 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4638 
4639 /*
4640 ** CAPI3REF: Create Or Redefine SQL Functions
4641 ** KEYWORDS: {function creation routines}
4642 ** KEYWORDS: {application-defined SQL function}
4643 ** KEYWORDS: {application-defined SQL functions}
4644 ** METHOD: sqlite3
4645 **
4646 ** ^These functions (collectively known as "function creation routines")
4647 ** are used to add SQL functions or aggregates or to redefine the behavior
4648 ** of existing SQL functions or aggregates. The only differences between
4649 ** these routines are the text encoding expected for
4650 ** the second parameter (the name of the function being created)
4651 ** and the presence or absence of a destructor callback for
4652 ** the application data pointer.
4653 **
4654 ** ^The first parameter is the [database connection] to which the SQL
4655 ** function is to be added. ^If an application uses more than one database
4656 ** connection then application-defined SQL functions must be added
4657 ** to each database connection separately.
4658 **
4659 ** ^The second parameter is the name of the SQL function to be created or
4660 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
4661 ** representation, exclusive of the zero-terminator. ^Note that the name
4662 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4663 ** ^Any attempt to create a function with a longer name
4664 ** will result in [SQLITE_MISUSE] being returned.
4665 **
4666 ** ^The third parameter (nArg)
4667 ** is the number of arguments that the SQL function or
4668 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4669 ** aggregate may take any number of arguments between 0 and the limit
4670 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4671 ** parameter is less than -1 or greater than 127 then the behavior is
4672 ** undefined.
4673 **
4674 ** ^The fourth parameter, eTextRep, specifies what
4675 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4676 ** its parameters. The application should set this parameter to
4677 ** [SQLITE_UTF16LE] if the function implementation invokes
4678 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4679 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4680 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4681 ** otherwise. ^The same SQL function may be registered multiple times using
4682 ** different preferred text encodings, with different implementations for
4683 ** each encoding.
4684 ** ^When multiple implementations of the same function are available, SQLite
4685 ** will pick the one that involves the least amount of data conversion.
4686 **
4687 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4688 ** to signal that the function will always return the same result given
4689 ** the same inputs within a single SQL statement. Most SQL functions are
4690 ** deterministic. The built-in [random()] SQL function is an example of a
4691 ** function that is not deterministic. The SQLite query planner is able to
4692 ** perform additional optimizations on deterministic functions, so use
4693 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4694 **
4695 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4696 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4697 **
4698 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4699 ** pointers to C-language functions that implement the SQL function or
4700 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4701 ** callback only; NULL pointers must be passed as the xStep and xFinal
4702 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4703 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4704 ** SQL function or aggregate, pass NULL pointers for all three function
4705 ** callbacks.
4706 **
4707 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4708 ** then it is destructor for the application data pointer.
4709 ** The destructor is invoked when the function is deleted, either by being
4710 ** overloaded or when the database connection closes.)^
4711 ** ^The destructor is also invoked if the call to
4712 ** sqlite3_create_function_v2() fails.
4713 ** ^When the destructor callback of the tenth parameter is invoked, it
4714 ** is passed a single argument which is a copy of the application data
4715 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4716 **
4717 ** ^It is permitted to register multiple implementations of the same
4718 ** functions with the same name but with either differing numbers of
4719 ** arguments or differing preferred text encodings. ^SQLite will use
4720 ** the implementation that most closely matches the way in which the
4721 ** SQL function is used. ^A function implementation with a non-negative
4722 ** nArg parameter is a better match than a function implementation with
4723 ** a negative nArg. ^A function where the preferred text encoding
4724 ** matches the database encoding is a better
4725 ** match than a function where the encoding is different.
4726 ** ^A function where the encoding difference is between UTF16le and UTF16be
4727 ** is a closer match than a function where the encoding difference is
4728 ** between UTF8 and UTF16.
4729 **
4730 ** ^Built-in functions may be overloaded by new application-defined functions.
4731 **
4732 ** ^An application-defined function is permitted to call other
4733 ** SQLite interfaces. However, such calls must not
4734 ** close the database connection nor finalize or reset the prepared
4735 ** statement in which the function is running.
4736 */
4737 SQLITE_API int sqlite3_create_function(
4738  sqlite3 *db,
4739  const char *zFunctionName,
4740  int nArg,
4741  int eTextRep,
4742  void *pApp,
4743  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4744  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4745  void (*xFinal)(sqlite3_context*)
4746 );
4747 SQLITE_API int sqlite3_create_function16(
4748  sqlite3 *db,
4749  const void *zFunctionName,
4750  int nArg,
4751  int eTextRep,
4752  void *pApp,
4753  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4754  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4755  void (*xFinal)(sqlite3_context*)
4756 );
4757 SQLITE_API int sqlite3_create_function_v2(
4758  sqlite3 *db,
4759  const char *zFunctionName,
4760  int nArg,
4761  int eTextRep,
4762  void *pApp,
4763  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4764  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4765  void (*xFinal)(sqlite3_context*),
4766  void(*xDestroy)(void*)
4767 );
4768 
4769 /*
4770 ** CAPI3REF: Text Encodings
4771 **
4772 ** These constant define integer codes that represent the various
4773 ** text encodings supported by SQLite.
4774 */
4775 #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
4776 #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
4777 #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
4778 #define SQLITE_UTF16 4 /* Use native byte order */
4779 #define SQLITE_ANY 5 /* Deprecated */
4780 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4781 
4782 /*
4783 ** CAPI3REF: Function Flags
4784 **
4785 ** These constants may be ORed together with the
4786 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4787 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4788 ** [sqlite3_create_function_v2()].
4789 */
4790 #define SQLITE_DETERMINISTIC 0x800
4791 
4792 /*
4793 ** CAPI3REF: Deprecated Functions
4794 ** DEPRECATED
4795 **
4796 ** These functions are [deprecated]. In order to maintain
4797 ** backwards compatibility with older code, these functions continue
4798 ** to be supported. However, new applications should avoid
4799 ** the use of these functions. To encourage programmers to avoid
4800 ** these functions, we will not explain what they do.
4801 */
4802 #ifndef SQLITE_OMIT_DEPRECATED
4803 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4804 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4805 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4806 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4807 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4808 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4809  void*,sqlite3_int64);
4810 #endif
4811 
4812 /*
4813 ** CAPI3REF: Obtaining SQL Values
4814 ** METHOD: sqlite3_value
4815 **
4816 ** The C-language implementation of SQL functions and aggregates uses
4817 ** this set of interface routines to access the parameter values on
4818 ** the function or aggregate.
4819 **
4820 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4821 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4822 ** define callbacks that implement the SQL functions and aggregates.
4823 ** The 3rd parameter to these callbacks is an array of pointers to
4824 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4825 ** each parameter to the SQL function. These routines are used to
4826 ** extract values from the [sqlite3_value] objects.
4827 **
4828 ** These routines work only with [protected sqlite3_value] objects.
4829 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4830 ** object results in undefined behavior.
4831 **
4832 ** ^These routines work just like the corresponding [column access functions]
4833 ** except that these routines take a single [protected sqlite3_value] object
4834 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4835 **
4836 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4837 ** in the native byte-order of the host machine. ^The
4838 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4839 ** extract UTF-16 strings as big-endian and little-endian respectively.
4840 **
4841 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4842 ** numeric affinity to the value. This means that an attempt is
4843 ** made to convert the value to an integer or floating point. If
4844 ** such a conversion is possible without loss of information (in other
4845 ** words, if the value is a string that looks like a number)
4846 ** then the conversion is performed. Otherwise no conversion occurs.
4847 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4848 **
4849 ** Please pay particular attention to the fact that the pointer returned
4850 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4851 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4852 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4853 ** or [sqlite3_value_text16()].
4854 **
4855 ** These routines must be called from the same thread as
4856 ** the SQL function that supplied the [sqlite3_value*] parameters.
4857 */
4858 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4859 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4860 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4861 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4862 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4863 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4864 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4865 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4866 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4867 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4868 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4869 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4870 
4871 /*
4872 ** CAPI3REF: Finding The Subtype Of SQL Values
4873 ** METHOD: sqlite3_value
4874 **
4875 ** The sqlite3_value_subtype(V) function returns the subtype for
4876 ** an [application-defined SQL function] argument V. The subtype
4877 ** information can be used to pass a limited amount of context from
4878 ** one SQL function to another. Use the [sqlite3_result_subtype()]
4879 ** routine to set the subtype for the return value of an SQL function.
4880 **
4881 ** SQLite makes no use of subtype itself. It merely passes the subtype
4882 ** from the result of one [application-defined SQL function] into the
4883 ** input of another.
4884 */
4885 SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
4886 
4887 /*
4888 ** CAPI3REF: Copy And Free SQL Values
4889 ** METHOD: sqlite3_value
4890 **
4891 ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
4892 ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
4893 ** is a [protected sqlite3_value] object even if the input is not.
4894 ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
4895 ** memory allocation fails.
4896 **
4897 ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
4898 ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
4899 ** then sqlite3_value_free(V) is a harmless no-op.
4900 */
4901 SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
4902 SQLITE_API void sqlite3_value_free(sqlite3_value*);
4903 
4904 /*
4905 ** CAPI3REF: Obtain Aggregate Function Context
4906 ** METHOD: sqlite3_context
4907 **
4908 ** Implementations of aggregate SQL functions use this
4909 ** routine to allocate memory for storing their state.
4910 **
4911 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4912 ** for a particular aggregate function, SQLite
4913 ** allocates N of memory, zeroes out that memory, and returns a pointer
4914 ** to the new memory. ^On second and subsequent calls to
4915 ** sqlite3_aggregate_context() for the same aggregate function instance,
4916 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4917 ** called once for each invocation of the xStep callback and then one
4918 ** last time when the xFinal callback is invoked. ^(When no rows match
4919 ** an aggregate query, the xStep() callback of the aggregate function
4920 ** implementation is never called and xFinal() is called exactly once.
4921 ** In those cases, sqlite3_aggregate_context() might be called for the
4922 ** first time from within xFinal().)^
4923 **
4924 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4925 ** when first called if N is less than or equal to zero or if a memory
4926 ** allocate error occurs.
4927 **
4928 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4929 ** determined by the N parameter on first successful call. Changing the
4930 ** value of N in subsequent call to sqlite3_aggregate_context() within
4931 ** the same aggregate function instance will not resize the memory
4932 ** allocation.)^ Within the xFinal callback, it is customary to set
4933 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4934 ** pointless memory allocations occur.
4935 **
4936 ** ^SQLite automatically frees the memory allocated by
4937 ** sqlite3_aggregate_context() when the aggregate query concludes.
4938 **
4939 ** The first parameter must be a copy of the
4940 ** [sqlite3_context | SQL function context] that is the first parameter
4941 ** to the xStep or xFinal callback routine that implements the aggregate
4942 ** function.
4943 **
4944 ** This routine must be called from the same thread in which
4945 ** the aggregate SQL function is running.
4946 */
4947 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4948 
4949 /*
4950 ** CAPI3REF: User Data For Functions
4951 ** METHOD: sqlite3_context
4952 **
4953 ** ^The sqlite3_user_data() interface returns a copy of
4954 ** the pointer that was the pUserData parameter (the 5th parameter)
4955 ** of the [sqlite3_create_function()]
4956 ** and [sqlite3_create_function16()] routines that originally
4957 ** registered the application defined function.
4958 **
4959 ** This routine must be called from the same thread in which
4960 ** the application-defined function is running.
4961 */
4962 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4963 
4964 /*
4965 ** CAPI3REF: Database Connection For Functions
4966 ** METHOD: sqlite3_context
4967 **
4968 ** ^The sqlite3_context_db_handle() interface returns a copy of
4969 ** the pointer to the [database connection] (the 1st parameter)
4970 ** of the [sqlite3_create_function()]
4971 ** and [sqlite3_create_function16()] routines that originally
4972 ** registered the application defined function.
4973 */
4974 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4975 
4976 /*
4977 ** CAPI3REF: Function Auxiliary Data
4978 ** METHOD: sqlite3_context
4979 **
4980 ** These functions may be used by (non-aggregate) SQL functions to
4981 ** associate metadata with argument values. If the same value is passed to
4982 ** multiple invocations of the same SQL function during query execution, under
4983 ** some circumstances the associated metadata may be preserved. An example
4984 ** of where this might be useful is in a regular-expression matching
4985 ** function. The compiled version of the regular expression can be stored as
4986 ** metadata associated with the pattern string.
4987 ** Then as long as the pattern string remains the same,
4988 ** the compiled regular expression can be reused on multiple
4989 ** invocations of the same function.
4990 **
4991 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4992 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4993 ** value to the application-defined function. ^If there is no metadata
4994 ** associated with the function argument, this sqlite3_get_auxdata() interface
4995 ** returns a NULL pointer.
4996 **
4997 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4998 ** argument of the application-defined function. ^Subsequent
4999 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
5000 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
5001 ** NULL if the metadata has been discarded.
5002 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
5003 ** SQLite will invoke the destructor function X with parameter P exactly
5004 ** once, when the metadata is discarded.
5005 ** SQLite is free to discard the metadata at any time, including: <ul>
5006 ** <li> ^(when the corresponding function parameter changes)^, or
5007 ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
5008 ** SQL statement)^, or
5009 ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
5010 ** parameter)^, or
5011 ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
5012 ** allocation error occurs.)^ </ul>
5013 **
5014 ** Note the last bullet in particular. The destructor X in
5015 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
5016 ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
5017 ** should be called near the end of the function implementation and the
5018 ** function implementation should not make any use of P after
5019 ** sqlite3_set_auxdata() has been called.
5020 **
5021 ** ^(In practice, metadata is preserved between function calls for
5022 ** function parameters that are compile-time constants, including literal
5023 ** values and [parameters] and expressions composed from the same.)^
5024 **
5025 ** These routines must be called from the same thread in which
5026 ** the SQL function is running.
5027 */
5028 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
5029 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
5030 
5031 
5032 /*
5033 ** CAPI3REF: Constants Defining Special Destructor Behavior
5034 **
5035 ** These are special values for the destructor that is passed in as the
5036 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
5037 ** argument is SQLITE_STATIC, it means that the content pointer is constant
5038 ** and will never change. It does not need to be destroyed. ^The
5039 ** SQLITE_TRANSIENT value means that the content will likely change in
5040 ** the near future and that SQLite should make its own private copy of
5041 ** the content before returning.
5042 **
5043 ** The typedef is necessary to work around problems in certain
5044 ** C++ compilers.
5045 */
5046 typedef void (*sqlite3_destructor_type)(void*);
5047 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
5048 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
5049 
5050 /*
5051 ** CAPI3REF: Setting The Result Of An SQL Function
5052 ** METHOD: sqlite3_context
5053 **
5054 ** These routines are used by the xFunc or xFinal callbacks that
5055 ** implement SQL functions and aggregates. See
5056 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
5057 ** for additional information.
5058 **
5059 ** These functions work very much like the [parameter binding] family of
5060 ** functions used to bind values to host parameters in prepared statements.
5061 ** Refer to the [SQL parameter] documentation for additional information.
5062 **
5063 ** ^The sqlite3_result_blob() interface sets the result from
5064 ** an application-defined function to be the BLOB whose content is pointed
5065 ** to by the second parameter and which is N bytes long where N is the
5066 ** third parameter.
5067 **
5068 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
5069 ** interfaces set the result of the application-defined function to be
5070 ** a BLOB containing all zero bytes and N bytes in size.
5071 **
5072 ** ^The sqlite3_result_double() interface sets the result from
5073 ** an application-defined function to be a floating point value specified
5074 ** by its 2nd argument.
5075 **
5076 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
5077 ** cause the implemented SQL function to throw an exception.
5078 ** ^SQLite uses the string pointed to by the
5079 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
5080 ** as the text of an error message. ^SQLite interprets the error
5081 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
5082 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
5083 ** byte order. ^If the third parameter to sqlite3_result_error()
5084 ** or sqlite3_result_error16() is negative then SQLite takes as the error
5085 ** message all text up through the first zero character.
5086 ** ^If the third parameter to sqlite3_result_error() or
5087 ** sqlite3_result_error16() is non-negative then SQLite takes that many
5088 ** bytes (not characters) from the 2nd parameter as the error message.
5089 ** ^The sqlite3_result_error() and sqlite3_result_error16()
5090 ** routines make a private copy of the error message text before
5091 ** they return. Hence, the calling function can deallocate or
5092 ** modify the text after they return without harm.
5093 ** ^The sqlite3_result_error_code() function changes the error code
5094 ** returned by SQLite as a result of an error in a function. ^By default,
5095 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
5096 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
5097 **
5098 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
5099 ** error indicating that a string or BLOB is too long to represent.
5100 **
5101 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
5102 ** error indicating that a memory allocation failed.
5103 **
5104 ** ^The sqlite3_result_int() interface sets the return value
5105 ** of the application-defined function to be the 32-bit signed integer
5106 ** value given in the 2nd argument.
5107 ** ^The sqlite3_result_int64() interface sets the return value
5108 ** of the application-defined function to be the 64-bit signed integer
5109 ** value given in the 2nd argument.
5110 **
5111 ** ^The sqlite3_result_null() interface sets the return value
5112 ** of the application-defined function to be NULL.
5113 **
5114 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
5115 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
5116 ** set the return value of the application-defined function to be
5117 ** a text string which is represented as UTF-8, UTF-16 native byte order,
5118 ** UTF-16 little endian, or UTF-16 big endian, respectively.
5119 ** ^The sqlite3_result_text64() interface sets the return value of an
5120 ** application-defined function to be a text string in an encoding
5121 ** specified by the fifth (and last) parameter, which must be one
5122 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
5123 ** ^SQLite takes the text result from the application from
5124 ** the 2nd parameter of the sqlite3_result_text* interfaces.
5125 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5126 ** is negative, then SQLite takes result text from the 2nd parameter
5127 ** through the first zero character.
5128 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5129 ** is non-negative, then as many bytes (not characters) of the text
5130 ** pointed to by the 2nd parameter are taken as the application-defined
5131 ** function result. If the 3rd parameter is non-negative, then it
5132 ** must be the byte offset into the string where the NUL terminator would
5133 ** appear if the string where NUL terminated. If any NUL characters occur
5134 ** in the string at a byte offset that is less than the value of the 3rd
5135 ** parameter, then the resulting string will contain embedded NULs and the
5136 ** result of expressions operating on strings with embedded NULs is undefined.
5137 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
5138 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
5139 ** function as the destructor on the text or BLOB result when it has
5140 ** finished using that result.
5141 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
5142 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
5143 ** assumes that the text or BLOB result is in constant space and does not
5144 ** copy the content of the parameter nor call a destructor on the content
5145 ** when it has finished using that result.
5146 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
5147 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
5148 ** then SQLite makes a copy of the result into space obtained from
5149 ** from [sqlite3_malloc()] before it returns.
5150 **
5151 ** ^The sqlite3_result_value() interface sets the result of
5152 ** the application-defined function to be a copy of the
5153 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
5154 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
5155 ** so that the [sqlite3_value] specified in the parameter may change or
5156 ** be deallocated after sqlite3_result_value() returns without harm.
5157 ** ^A [protected sqlite3_value] object may always be used where an
5158 ** [unprotected sqlite3_value] object is required, so either
5159 ** kind of [sqlite3_value] object can be used with this interface.
5160 **
5161 ** If these routines are called from within the different thread
5162 ** than the one containing the application-defined function that received
5163 ** the [sqlite3_context] pointer, the results are undefined.
5164 */
5165 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
5166 SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
5167  sqlite3_uint64,void(*)(void*));
5168 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
5169 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
5170 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
5171 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
5172 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
5173 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
5174 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
5175 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
5176 SQLITE_API void sqlite3_result_null(sqlite3_context*);
5177 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
5178 SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
5179  void(*)(void*), unsigned char encoding);
5180 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
5181 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
5182 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
5183 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
5184 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
5185 SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
5186 
5187 
5188 /*
5189 ** CAPI3REF: Setting The Subtype Of An SQL Function
5190 ** METHOD: sqlite3_context
5191 **
5192 ** The sqlite3_result_subtype(C,T) function causes the subtype of
5193 ** the result from the [application-defined SQL function] with
5194 ** [sqlite3_context] C to be the value T. Only the lower 8 bits
5195 ** of the subtype T are preserved in current versions of SQLite;
5196 ** higher order bits are discarded.
5197 ** The number of subtype bytes preserved by SQLite might increase
5198 ** in future releases of SQLite.
5199 */
5200 SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
5201 
5202 /*
5203 ** CAPI3REF: Define New Collating Sequences
5204 ** METHOD: sqlite3
5205 **
5206 ** ^These functions add, remove, or modify a [collation] associated
5207 ** with the [database connection] specified as the first argument.
5208 **
5209 ** ^The name of the collation is a UTF-8 string
5210 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
5211 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
5212 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
5213 ** considered to be the same name.
5214 **
5215 ** ^(The third argument (eTextRep) must be one of the constants:
5216 ** <ul>
5217 ** <li> [SQLITE_UTF8],
5218 ** <li> [SQLITE_UTF16LE],
5219 ** <li> [SQLITE_UTF16BE],
5220 ** <li> [SQLITE_UTF16], or
5221 ** <li> [SQLITE_UTF16_ALIGNED].
5222 ** </ul>)^
5223 ** ^The eTextRep argument determines the encoding of strings passed
5224 ** to the collating function callback, xCallback.
5225 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
5226 ** force strings to be UTF16 with native byte order.
5227 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
5228 ** on an even byte address.
5229 **
5230 ** ^The fourth argument, pArg, is an application data pointer that is passed
5231 ** through as the first argument to the collating function callback.
5232 **
5233 ** ^The fifth argument, xCallback, is a pointer to the collating function.
5234 ** ^Multiple collating functions can be registered using the same name but
5235 ** with different eTextRep parameters and SQLite will use whichever
5236 ** function requires the least amount of data transformation.
5237 ** ^If the xCallback argument is NULL then the collating function is
5238 ** deleted. ^When all collating functions having the same name are deleted,
5239 ** that collation is no longer usable.
5240 **
5241 ** ^The collating function callback is invoked with a copy of the pArg
5242 ** application data pointer and with two strings in the encoding specified
5243 ** by the eTextRep argument. The collating function must return an
5244 ** integer that is negative, zero, or positive
5245 ** if the first string is less than, equal to, or greater than the second,
5246 ** respectively. A collating function must always return the same answer
5247 ** given the same inputs. If two or more collating functions are registered
5248 ** to the same collation name (using different eTextRep values) then all
5249 ** must give an equivalent answer when invoked with equivalent strings.
5250 ** The collating function must obey the following properties for all
5251 ** strings A, B, and C:
5252 **
5253 ** <ol>
5254 ** <li> If A==B then B==A.
5255 ** <li> If A==B and B==C then A==C.
5256 ** <li> If A&lt;B THEN B&gt;A.
5257 ** <li> If A&lt;B and B&lt;C then A&lt;C.
5258 ** </ol>
5259 **
5260 ** If a collating function fails any of the above constraints and that
5261 ** collating function is registered and used, then the behavior of SQLite
5262 ** is undefined.
5263 **
5264 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5265 ** with the addition that the xDestroy callback is invoked on pArg when
5266 ** the collating function is deleted.
5267 ** ^Collating functions are deleted when they are overridden by later
5268 ** calls to the collation creation functions or when the
5269 ** [database connection] is closed using [sqlite3_close()].
5270 **
5271 ** ^The xDestroy callback is <u>not</u> called if the
5272 ** sqlite3_create_collation_v2() function fails. Applications that invoke
5273 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
5274 ** check the return code and dispose of the application data pointer
5275 ** themselves rather than expecting SQLite to deal with it for them.
5276 ** This is different from every other SQLite interface. The inconsistency
5277 ** is unfortunate but cannot be changed without breaking backwards
5278 ** compatibility.
5279 **
5280 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5281 */
5282 SQLITE_API int sqlite3_create_collation(
5283  sqlite3*,
5284  const char *zName,
5285  int eTextRep,
5286  void *pArg,
5287  int(*xCompare)(void*,int,const void*,int,const void*)
5288 );
5289 SQLITE_API int sqlite3_create_collation_v2(
5290  sqlite3*,
5291  const char *zName,
5292  int eTextRep,
5293  void *pArg,
5294  int(*xCompare)(void*,int,const void*,int,const void*),
5295  void(*xDestroy)(void*)
5296 );
5297 SQLITE_API int sqlite3_create_collation16(
5298  sqlite3*,
5299  const void *zName,
5300  int eTextRep,
5301  void *pArg,
5302  int(*xCompare)(void*,int,const void*,int,const void*)
5303 );
5304 
5305 /*
5306 ** CAPI3REF: Collation Needed Callbacks
5307 ** METHOD: sqlite3
5308 **
5309 ** ^To avoid having to register all collation sequences before a database
5310 ** can be used, a single callback function may be registered with the
5311 ** [database connection] to be invoked whenever an undefined collation
5312 ** sequence is required.
5313 **
5314 ** ^If the function is registered using the sqlite3_collation_needed() API,
5315 ** then it is passed the names of undefined collation sequences as strings
5316 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5317 ** the names are passed as UTF-16 in machine native byte order.
5318 ** ^A call to either function replaces the existing collation-needed callback.
5319 **
5320 ** ^(When the callback is invoked, the first argument passed is a copy
5321 ** of the second argument to sqlite3_collation_needed() or
5322 ** sqlite3_collation_needed16(). The second argument is the database
5323 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5324 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5325 ** sequence function required. The fourth parameter is the name of the
5326 ** required collation sequence.)^
5327 **
5328 ** The callback function should register the desired collation using
5329 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5330 ** [sqlite3_create_collation_v2()].
5331 */
5332 SQLITE_API int sqlite3_collation_needed(
5333  sqlite3*,
5334  void*,
5335  void(*)(void*,sqlite3*,int eTextRep,const char*)
5336 );
5337 SQLITE_API int sqlite3_collation_needed16(
5338  sqlite3*,
5339  void*,
5340  void(*)(void*,sqlite3*,int eTextRep,const void*)
5341 );
5342 
5343 #ifdef SQLITE_HAS_CODEC
5344 /*
5345 ** Specify the key for an encrypted database. This routine should be
5346 ** called right after sqlite3_open().
5347 **
5348 ** The code to implement this API is not available in the public release
5349 ** of SQLite.
5350 */
5351 SQLITE_API int sqlite3_key(
5352  sqlite3 *db, /* Database to be rekeyed */
5353  const void *pKey, int nKey /* The key */
5354 );
5355 SQLITE_API int sqlite3_key_v2(
5356  sqlite3 *db, /* Database to be rekeyed */
5357  const char *zDbName, /* Name of the database */
5358  const void *pKey, int nKey /* The key */
5359 );
5360 
5361 /*
5362 ** Change the key on an open database. If the current database is not
5363 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
5364 ** database is decrypted.
5365 **
5366 ** The code to implement this API is not available in the public release
5367 ** of SQLite.
5368 */
5369 SQLITE_API int sqlite3_rekey(
5370  sqlite3 *db, /* Database to be rekeyed */
5371  const void *pKey, int nKey /* The new key */
5372 );
5373 SQLITE_API int sqlite3_rekey_v2(
5374  sqlite3 *db, /* Database to be rekeyed */
5375  const char *zDbName, /* Name of the database */
5376  const void *pKey, int nKey /* The new key */
5377 );
5378 
5379 /*
5380 ** Specify the activation key for a SEE database. Unless
5381 ** activated, none of the SEE routines will work.
5382 */
5383 SQLITE_API void sqlite3_activate_see(
5384  const char *zPassPhrase /* Activation phrase */
5385 );
5386 #endif
5387 
5388 #ifdef SQLITE_ENABLE_CEROD
5389 /*
5390 ** Specify the activation key for a CEROD database. Unless
5391 ** activated, none of the CEROD routines will work.
5392 */
5393 SQLITE_API void sqlite3_activate_cerod(
5394  const char *zPassPhrase /* Activation phrase */
5395 );
5396 #endif
5397 
5398 /*
5399 ** CAPI3REF: Suspend Execution For A Short Time
5400 **
5401 ** The sqlite3_sleep() function causes the current thread to suspend execution
5402 ** for at least a number of milliseconds specified in its parameter.
5403 **
5404 ** If the operating system does not support sleep requests with
5405 ** millisecond time resolution, then the time will be rounded up to
5406 ** the nearest second. The number of milliseconds of sleep actually
5407 ** requested from the operating system is returned.
5408 **
5409 ** ^SQLite implements this interface by calling the xSleep()
5410 ** method of the default [sqlite3_vfs] object. If the xSleep() method
5411 ** of the default VFS is not implemented correctly, or not implemented at
5412 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5413 ** in the previous paragraphs.
5414 */
5415 SQLITE_API int sqlite3_sleep(int);
5416 
5417 /*
5418 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5419 **
5420 ** ^(If this global variable is made to point to a string which is
5421 ** the name of a folder (a.k.a. directory), then all temporary files
5422 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5423 ** will be placed in that directory.)^ ^If this variable
5424 ** is a NULL pointer, then SQLite performs a search for an appropriate
5425 ** temporary file directory.
5426 **
5427 ** Applications are strongly discouraged from using this global variable.
5428 ** It is required to set a temporary folder on Windows Runtime (WinRT).
5429 ** But for all other platforms, it is highly recommended that applications
5430 ** neither read nor write this variable. This global variable is a relic
5431 ** that exists for backwards compatibility of legacy applications and should
5432 ** be avoided in new projects.
5433 **
5434 ** It is not safe to read or modify this variable in more than one
5435 ** thread at a time. It is not safe to read or modify this variable
5436 ** if a [database connection] is being used at the same time in a separate
5437 ** thread.
5438 ** It is intended that this variable be set once
5439 ** as part of process initialization and before any SQLite interface
5440 ** routines have been called and that this variable remain unchanged
5441 ** thereafter.
5442 **
5443 ** ^The [temp_store_directory pragma] may modify this variable and cause
5444 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5445 ** the [temp_store_directory pragma] always assumes that any string
5446 ** that this variable points to is held in memory obtained from
5447 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5448 ** using [sqlite3_free].
5449 ** Hence, if this variable is modified directly, either it should be
5450 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5451 ** or else the use of the [temp_store_directory pragma] should be avoided.
5452 ** Except when requested by the [temp_store_directory pragma], SQLite
5453 ** does not free the memory that sqlite3_temp_directory points to. If
5454 ** the application wants that memory to be freed, it must do
5455 ** so itself, taking care to only do so after all [database connection]
5456 ** objects have been destroyed.
5457 **
5458 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
5459 ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
5460 ** features that require the use of temporary files may fail. Here is an
5461 ** example of how to do this using C++ with the Windows Runtime:
5462 **
5463 ** <blockquote><pre>
5464 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5465 ** &nbsp; TemporaryFolder->Path->Data();
5466 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5467 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5468 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5469 ** &nbsp; NULL, NULL);
5470 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5471 ** </pre></blockquote>
5472 */
5473 SQLITE_API char *sqlite3_temp_directory;
5474 
5475 /*
5476 ** CAPI3REF: Name Of The Folder Holding Database Files
5477 **
5478 ** ^(If this global variable is made to point to a string which is
5479 ** the name of a folder (a.k.a. directory), then all database files
5480 ** specified with a relative pathname and created or accessed by
5481 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5482 ** to be relative to that directory.)^ ^If this variable is a NULL
5483 ** pointer, then SQLite assumes that all database files specified
5484 ** with a relative pathname are relative to the current directory
5485 ** for the process. Only the windows VFS makes use of this global
5486 ** variable; it is ignored by the unix VFS.
5487 **
5488 ** Changing the value of this variable while a database connection is
5489 ** open can result in a corrupt database.
5490 **
5491 ** It is not safe to read or modify this variable in more than one
5492 ** thread at a time. It is not safe to read or modify this variable
5493 ** if a [database connection] is being used at the same time in a separate
5494 ** thread.
5495 ** It is intended that this variable be set once
5496 ** as part of process initialization and before any SQLite interface
5497 ** routines have been called and that this variable remain unchanged
5498 ** thereafter.
5499 **
5500 ** ^The [data_store_directory pragma] may modify this variable and cause
5501 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5502 ** the [data_store_directory pragma] always assumes that any string
5503 ** that this variable points to is held in memory obtained from
5504 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5505 ** using [sqlite3_free].
5506 ** Hence, if this variable is modified directly, either it should be
5507 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5508 ** or else the use of the [data_store_directory pragma] should be avoided.
5509 */
5510 SQLITE_API char *sqlite3_data_directory;
5511 
5512 /*
5513 ** CAPI3REF: Test For Auto-Commit Mode
5514 ** KEYWORDS: {autocommit mode}
5515 ** METHOD: sqlite3
5516 **
5517 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5518 ** zero if the given database connection is or is not in autocommit mode,
5519 ** respectively. ^Autocommit mode is on by default.
5520 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5521 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5522 **
5523 ** If certain kinds of errors occur on a statement within a multi-statement
5524 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5525 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5526 ** transaction might be rolled back automatically. The only way to
5527 ** find out whether SQLite automatically rolled back the transaction after
5528 ** an error is to use this function.
5529 **
5530 ** If another thread changes the autocommit status of the database
5531 ** connection while this routine is running, then the return value
5532 ** is undefined.
5533 */
5534 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5535 
5536 /*
5537 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5538 ** METHOD: sqlite3_stmt
5539 **
5540 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5541 ** to which a [prepared statement] belongs. ^The [database connection]
5542 ** returned by sqlite3_db_handle is the same [database connection]
5543 ** that was the first argument
5544 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5545 ** create the statement in the first place.
5546 */
5547 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5548 
5549 /*
5550 ** CAPI3REF: Return The Filename For A Database Connection
5551 ** METHOD: sqlite3
5552 **
5553 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5554 ** associated with database N of connection D. ^The main database file
5555 ** has the name "main". If there is no attached database N on the database
5556 ** connection D, or if database N is a temporary or in-memory database, then
5557 ** a NULL pointer is returned.
5558 **
5559 ** ^The filename returned by this function is the output of the
5560 ** xFullPathname method of the [VFS]. ^In other words, the filename
5561 ** will be an absolute pathname, even if the filename used
5562 ** to open the database originally was a URI or relative pathname.
5563 */
5564 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5565 
5566 /*
5567 ** CAPI3REF: Determine if a database is read-only
5568 ** METHOD: sqlite3
5569 **
5570 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5571 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5572 ** the name of a database on connection D.
5573 */
5574 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5575 
5576 /*
5577 ** CAPI3REF: Find the next prepared statement
5578 ** METHOD: sqlite3
5579 **
5580 ** ^This interface returns a pointer to the next [prepared statement] after
5581 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
5582 ** then this interface returns a pointer to the first prepared statement
5583 ** associated with the database connection pDb. ^If no prepared statement
5584 ** satisfies the conditions of this routine, it returns NULL.
5585 **
5586 ** The [database connection] pointer D in a call to
5587 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5588 ** connection and in particular must not be a NULL pointer.
5589 */
5590 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5591 
5592 /*
5593 ** CAPI3REF: Commit And Rollback Notification Callbacks
5594 ** METHOD: sqlite3
5595 **
5596 ** ^The sqlite3_commit_hook() interface registers a callback
5597 ** function to be invoked whenever a transaction is [COMMIT | committed].
5598 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5599 ** for the same database connection is overridden.
5600 ** ^The sqlite3_rollback_hook() interface registers a callback
5601 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5602 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5603 ** for the same database connection is overridden.
5604 ** ^The pArg argument is passed through to the callback.
5605 ** ^If the callback on a commit hook function returns non-zero,
5606 ** then the commit is converted into a rollback.
5607 **
5608 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5609 ** return the P argument from the previous call of the same function
5610 ** on the same [database connection] D, or NULL for
5611 ** the first call for each function on D.
5612 **
5613 ** The commit and rollback hook callbacks are not reentrant.
5614 ** The callback implementation must not do anything that will modify
5615 ** the database connection that invoked the callback. Any actions
5616 ** to modify the database connection must be deferred until after the
5617 ** completion of the [sqlite3_step()] call that triggered the commit
5618 ** or rollback hook in the first place.
5619 ** Note that running any other SQL statements, including SELECT statements,
5620 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5621 ** the database connections for the meaning of "modify" in this paragraph.
5622 **
5623 ** ^Registering a NULL function disables the callback.
5624 **
5625 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5626 ** operation is allowed to continue normally. ^If the commit hook
5627 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5628 ** ^The rollback hook is invoked on a rollback that results from a commit
5629 ** hook returning non-zero, just as it would be with any other rollback.
5630 **
5631 ** ^For the purposes of this API, a transaction is said to have been
5632 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5633 ** an error or constraint causes an implicit rollback to occur.
5634 ** ^The rollback callback is not invoked if a transaction is
5635 ** automatically rolled back because the database connection is closed.
5636 **
5637 ** See also the [sqlite3_update_hook()] interface.
5638 */
5639 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5640 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5641 
5642 /*
5643 ** CAPI3REF: Data Change Notification Callbacks
5644 ** METHOD: sqlite3
5645 **
5646 ** ^The sqlite3_update_hook() interface registers a callback function
5647 ** with the [database connection] identified by the first argument
5648 ** to be invoked whenever a row is updated, inserted or deleted in
5649 ** a [rowid table].
5650 ** ^Any callback set by a previous call to this function
5651 ** for the same database connection is overridden.
5652 **
5653 ** ^The second argument is a pointer to the function to invoke when a
5654 ** row is updated, inserted or deleted in a rowid table.
5655 ** ^The first argument to the callback is a copy of the third argument
5656 ** to sqlite3_update_hook().
5657 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5658 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5659 ** to be invoked.
5660 ** ^The third and fourth arguments to the callback contain pointers to the
5661 ** database and table name containing the affected row.
5662 ** ^The final callback parameter is the [rowid] of the row.
5663 ** ^In the case of an update, this is the [rowid] after the update takes place.
5664 **
5665 ** ^(The update hook is not invoked when internal system tables are
5666 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5667 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5668 **
5669 ** ^In the current implementation, the update hook
5670 ** is not invoked when duplication rows are deleted because of an
5671 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
5672 ** invoked when rows are deleted using the [truncate optimization].
5673 ** The exceptions defined in this paragraph might change in a future
5674 ** release of SQLite.
5675 **
5676 ** The update hook implementation must not do anything that will modify
5677 ** the database connection that invoked the update hook. Any actions
5678 ** to modify the database connection must be deferred until after the
5679 ** completion of the [sqlite3_step()] call that triggered the update hook.
5680 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5681 ** database connections for the meaning of "modify" in this paragraph.
5682 **
5683 ** ^The sqlite3_update_hook(D,C,P) function
5684 ** returns the P argument from the previous call
5685 ** on the same [database connection] D, or NULL for
5686 ** the first call on D.
5687 **
5688 ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5689 ** and [sqlite3_preupdate_hook()] interfaces.
5690 */
5691 SQLITE_API void *sqlite3_update_hook(
5692  sqlite3*,
5693  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5694  void*
5695 );
5696 
5697 /*
5698 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5699 **
5700 ** ^(This routine enables or disables the sharing of the database cache
5701 ** and schema data structures between [database connection | connections]
5702 ** to the same database. Sharing is enabled if the argument is true
5703 ** and disabled if the argument is false.)^
5704 **
5705 ** ^Cache sharing is enabled and disabled for an entire process.
5706 ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
5707 ** In prior versions of SQLite,
5708 ** sharing was enabled or disabled for each thread separately.
5709 **
5710 ** ^(The cache sharing mode set by this interface effects all subsequent
5711 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5712 ** Existing database connections continue use the sharing mode
5713 ** that was in effect at the time they were opened.)^
5714 **
5715 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5716 ** successfully. An [error code] is returned otherwise.)^
5717 **
5718 ** ^Shared cache is disabled by default. But this might change in
5719 ** future releases of SQLite. Applications that care about shared
5720 ** cache setting should set it explicitly.
5721 **
5722 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5723 ** and will always return SQLITE_MISUSE. On those systems,
5724 ** shared cache mode should be enabled per-database connection via
5725 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5726 **
5727 ** This interface is threadsafe on processors where writing a
5728 ** 32-bit integer is atomic.
5729 **
5730 ** See Also: [SQLite Shared-Cache Mode]
5731 */
5732 SQLITE_API int sqlite3_enable_shared_cache(int);
5733 
5734 /*
5735 ** CAPI3REF: Attempt To Free Heap Memory
5736 **
5737 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5738 ** of heap memory by deallocating non-essential memory allocations
5739 ** held by the database library. Memory used to cache database
5740 ** pages to improve performance is an example of non-essential memory.
5741 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5742 ** which might be more or less than the amount requested.
5743 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5744 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5745 **
5746 ** See also: [sqlite3_db_release_memory()]
5747 */
5748 SQLITE_API int sqlite3_release_memory(int);
5749 
5750 /*
5751 ** CAPI3REF: Free Memory Used By A Database Connection
5752 ** METHOD: sqlite3
5753 **
5754 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5755 ** memory as possible from database connection D. Unlike the
5756 ** [sqlite3_release_memory()] interface, this interface is in effect even
5757 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5758 ** omitted.
5759 **
5760 ** See also: [sqlite3_release_memory()]
5761 */
5762 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5763 
5764 /*
5765 ** CAPI3REF: Impose A Limit On Heap Size
5766 **
5767 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5768 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5769 ** ^SQLite strives to keep heap memory utilization below the soft heap
5770 ** limit by reducing the number of pages held in the page cache
5771 ** as heap memory usages approaches the limit.
5772 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5773 ** below the limit, it will exceed the limit rather than generate
5774 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
5775 ** is advisory only.
5776 **
5777 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5778 ** the soft heap limit prior to the call, or negative in the case of an
5779 ** error. ^If the argument N is negative
5780 ** then no change is made to the soft heap limit. Hence, the current
5781 ** size of the soft heap limit can be determined by invoking
5782 ** sqlite3_soft_heap_limit64() with a negative argument.
5783 **
5784 ** ^If the argument N is zero then the soft heap limit is disabled.
5785 **
5786 ** ^(The soft heap limit is not enforced in the current implementation
5787 ** if one or more of following conditions are true:
5788 **
5789 ** <ul>
5790 ** <li> The soft heap limit is set to zero.
5791 ** <li> Memory accounting is disabled using a combination of the
5792 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5793 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5794 ** <li> An alternative page cache implementation is specified using
5795 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5796 ** <li> The page cache allocates from its own memory pool supplied
5797 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5798 ** from the heap.
5799 ** </ul>)^
5800 **
5801 ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
5802 ** the soft heap limit is enforced
5803 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5804 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5805 ** the soft heap limit is enforced on every memory allocation. Without
5806 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5807 ** when memory is allocated by the page cache. Testing suggests that because
5808 ** the page cache is the predominate memory user in SQLite, most
5809 ** applications will achieve adequate soft heap limit enforcement without
5810 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5811 **
5812 ** The circumstances under which SQLite will enforce the soft heap limit may
5813 ** changes in future releases of SQLite.
5814 */
5815 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5816 
5817 /*
5818 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5819 ** DEPRECATED
5820 **
5821 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5822 ** interface. This routine is provided for historical compatibility
5823 ** only. All new applications should use the
5824 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5825 */
5826 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5827 
5828 
5829 /*
5830 ** CAPI3REF: Extract Metadata About A Column Of A Table
5831 ** METHOD: sqlite3
5832 **
5833 ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5834 ** information about column C of table T in database D
5835 ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
5836 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
5837 ** the final five arguments with appropriate values if the specified
5838 ** column exists. ^The sqlite3_table_column_metadata() interface returns
5839 ** SQLITE_ERROR and if the specified column does not exist.
5840 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5841 ** NULL pointer, then this routine simply checks for the existence of the
5842 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5843 ** does not.
5844 **
5845 ** ^The column is identified by the second, third and fourth parameters to
5846 ** this function. ^(The second parameter is either the name of the database
5847 ** (i.e. "main", "temp", or an attached database) containing the specified
5848 ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5849 ** for the table using the same algorithm used by the database engine to
5850 ** resolve unqualified table references.
5851 **
5852 ** ^The third and fourth parameters to this function are the table and column
5853 ** name of the desired column, respectively.
5854 **
5855 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5856 ** and subsequent parameters to this function. ^Any of these arguments may be
5857 ** NULL, in which case the corresponding element of metadata is omitted.
5858 **
5859 ** ^(<blockquote>
5860 ** <table border="1">
5861 ** <tr><th> Parameter <th> Output<br>Type <th> Description
5862 **
5863 ** <tr><td> 5th <td> const char* <td> Data type
5864 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5865 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
5866 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
5867 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
5868 ** </table>
5869 ** </blockquote>)^
5870 **
5871 ** ^The memory pointed to by the character pointers returned for the
5872 ** declaration type and collation sequence is valid until the next
5873 ** call to any SQLite API function.
5874 **
5875 ** ^If the specified table is actually a view, an [error code] is returned.
5876 **
5877 ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
5878 ** is not a [WITHOUT ROWID] table and an
5879 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5880 ** parameters are set for the explicitly declared column. ^(If there is no
5881 ** [INTEGER PRIMARY KEY] column, then the outputs
5882 ** for the [rowid] are set as follows:
5883 **
5884 ** <pre>
5885 ** data type: "INTEGER"
5886 ** collation sequence: "BINARY"
5887 ** not null: 0
5888 ** primary key: 1
5889 ** auto increment: 0
5890 ** </pre>)^
5891 **
5892 ** ^This function causes all database schemas to be read from disk and
5893 ** parsed, if that has not already been done, and returns an error if
5894 ** any errors are encountered while loading the schema.
5895 */
5896 SQLITE_API int sqlite3_table_column_metadata(
5897  sqlite3 *db, /* Connection handle */
5898  const char *zDbName, /* Database name or NULL */
5899  const char *zTableName, /* Table name */
5900  const char *zColumnName, /* Column name */
5901  char const **pzDataType, /* OUTPUT: Declared data type */
5902  char const **pzCollSeq, /* OUTPUT: Collation sequence name */
5903  int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
5904  int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5905  int *pAutoinc /* OUTPUT: True if column is auto-increment */
5906 );
5907 
5908 /*
5909 ** CAPI3REF: Load An Extension
5910 ** METHOD: sqlite3
5911 **
5912 ** ^This interface loads an SQLite extension library from the named file.
5913 **
5914 ** ^The sqlite3_load_extension() interface attempts to load an
5915 ** [SQLite extension] library contained in the file zFile. If
5916 ** the file cannot be loaded directly, attempts are made to load
5917 ** with various operating-system specific extensions added.
5918 ** So for example, if "samplelib" cannot be loaded, then names like
5919 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5920 ** be tried also.
5921 **
5922 ** ^The entry point is zProc.
5923 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5924 ** entry point name on its own. It first tries "sqlite3_extension_init".
5925 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5926 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5927 ** characters in the filename from the last "/" to the first following
5928 ** "." and omitting any initial "lib".)^
5929 ** ^The sqlite3_load_extension() interface returns
5930 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5931 ** ^If an error occurs and pzErrMsg is not 0, then the
5932 ** [sqlite3_load_extension()] interface shall attempt to
5933 ** fill *pzErrMsg with error message text stored in memory
5934 ** obtained from [sqlite3_malloc()]. The calling function
5935 ** should free this memory by calling [sqlite3_free()].
5936 **
5937 ** ^Extension loading must be enabled using
5938 ** [sqlite3_enable_load_extension()] or
5939 ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5940 ** prior to calling this API,
5941 ** otherwise an error will be returned.
5942 **
5943 ** <b>Security warning:</b> It is recommended that the
5944 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5945 ** interface. The use of the [sqlite3_enable_load_extension()] interface
5946 ** should be avoided. This will keep the SQL function [load_extension()]
5947 ** disabled and prevent SQL injections from giving attackers
5948 ** access to extension loading capabilities.
5949 **
5950 ** See also the [load_extension() SQL function].
5951 */
5952 SQLITE_API int sqlite3_load_extension(
5953  sqlite3 *db, /* Load the extension into this database connection */
5954  const char *zFile, /* Name of the shared library containing extension */
5955  const char *zProc, /* Entry point. Derived from zFile if 0 */
5956  char **pzErrMsg /* Put error message here if not 0 */
5957 );
5958 
5959 /*
5960 ** CAPI3REF: Enable Or Disable Extension Loading
5961 ** METHOD: sqlite3
5962 **
5963 ** ^So as not to open security holes in older applications that are
5964 ** unprepared to deal with [extension loading], and as a means of disabling
5965 ** [extension loading] while evaluating user-entered SQL, the following API
5966 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5967 **
5968 ** ^Extension loading is off by default.
5969 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5970 ** to turn extension loading on and call it with onoff==0 to turn
5971 ** it back off again.
5972 **
5973 ** ^This interface enables or disables both the C-API
5974 ** [sqlite3_load_extension()] and the SQL function [load_extension()].
5975 ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
5976 ** to enable or disable only the C-API.)^
5977 **
5978 ** <b>Security warning:</b> It is recommended that extension loading
5979 ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
5980 ** rather than this interface, so the [load_extension()] SQL function
5981 ** remains disabled. This will prevent SQL injections from giving attackers
5982 ** access to extension loading capabilities.
5983 */
5984 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5985 
5986 /*
5987 ** CAPI3REF: Automatically Load Statically Linked Extensions
5988 **
5989 ** ^This interface causes the xEntryPoint() function to be invoked for
5990 ** each new [database connection] that is created. The idea here is that
5991 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5992 ** that is to be automatically loaded into all new database connections.
5993 **
5994 ** ^(Even though the function prototype shows that xEntryPoint() takes
5995 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5996 ** arguments and expects an integer result as if the signature of the
5997 ** entry point where as follows:
5998 **
5999 ** <blockquote><pre>
6000 ** &nbsp; int xEntryPoint(
6001 ** &nbsp; sqlite3 *db,
6002 ** &nbsp; const char **pzErrMsg,
6003 ** &nbsp; const struct sqlite3_api_routines *pThunk
6004 ** &nbsp; );
6005 ** </pre></blockquote>)^
6006 **
6007 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
6008 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
6009 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
6010 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
6011 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
6012 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
6013 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
6014 **
6015 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
6016 ** on the list of automatic extensions is a harmless no-op. ^No entry point
6017 ** will be called more than once for each database connection that is opened.
6018 **
6019 ** See also: [sqlite3_reset_auto_extension()]
6020 ** and [sqlite3_cancel_auto_extension()]
6021 */
6022 SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
6023 
6024 /*
6025 ** CAPI3REF: Cancel Automatic Extension Loading
6026 **
6027 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
6028 ** initialization routine X that was registered using a prior call to
6029 ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
6030 ** routine returns 1 if initialization routine X was successfully
6031 ** unregistered and it returns 0 if X was not on the list of initialization
6032 ** routines.
6033 */
6034 SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
6035 
6036 /*
6037 ** CAPI3REF: Reset Automatic Extension Loading
6038 **
6039 ** ^This interface disables all automatic extensions previously
6040 ** registered using [sqlite3_auto_extension()].
6041 */
6042 SQLITE_API void sqlite3_reset_auto_extension(void);
6043 
6044 /*
6045 ** The interface to the virtual-table mechanism is currently considered
6046 ** to be experimental. The interface might change in incompatible ways.
6047 ** If this is a problem for you, do not use the interface at this time.
6048 **
6049 ** When the virtual-table mechanism stabilizes, we will declare the
6050 ** interface fixed, support it indefinitely, and remove this comment.
6051 */
6052 
6053 /*
6054 ** Structures used by the virtual table interface
6055 */
6056 typedef struct sqlite3_vtab sqlite3_vtab;
6057 typedef struct sqlite3_index_info sqlite3_index_info;
6058 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
6059 typedef struct sqlite3_module sqlite3_module;
6060 
6061 /*
6062 ** CAPI3REF: Virtual Table Object
6063 ** KEYWORDS: sqlite3_module {virtual table module}
6064 **
6065 ** This structure, sometimes called a "virtual table module",
6066 ** defines the implementation of a [virtual tables].
6067 ** This structure consists mostly of methods for the module.
6068 **
6069 ** ^A virtual table module is created by filling in a persistent
6070 ** instance of this structure and passing a pointer to that instance
6071 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
6072 ** ^The registration remains valid until it is replaced by a different
6073 ** module or until the [database connection] closes. The content
6074 ** of this structure must not change while it is registered with
6075 ** any database connection.
6076 */
6077 struct sqlite3_module {
6078  int iVersion;
6079  int (*xCreate)(sqlite3*, void *pAux,
6080  int argc, const char *const*argv,
6081  sqlite3_vtab **ppVTab, char**);
6082  int (*xConnect)(sqlite3*, void *pAux,
6083  int argc, const char *const*argv,
6084  sqlite3_vtab **ppVTab, char**);
6085  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
6086  int (*xDisconnect)(sqlite3_vtab *pVTab);
6087  int (*xDestroy)(sqlite3_vtab *pVTab);
6088  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
6089  int (*xClose)(sqlite3_vtab_cursor*);
6090  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
6091  int argc, sqlite3_value **argv);
6092  int (*xNext)(sqlite3_vtab_cursor*);
6093  int (*xEof)(sqlite3_vtab_cursor*);
6094  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
6095  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
6096  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
6097  int (*xBegin)(sqlite3_vtab *pVTab);
6098  int (*xSync)(sqlite3_vtab *pVTab);
6099  int (*xCommit)(sqlite3_vtab *pVTab);
6100  int (*xRollback)(sqlite3_vtab *pVTab);
6101  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
6102  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
6103  void **ppArg);
6104  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
6105  /* The methods above are in version 1 of the sqlite_module object. Those
6106  ** below are for version 2 and greater. */
6107  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
6108  int (*xRelease)(sqlite3_vtab *pVTab, int);
6109  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
6110 };
6111 
6112 /*
6113 ** CAPI3REF: Virtual Table Indexing Information
6114 ** KEYWORDS: sqlite3_index_info
6115 **
6116 ** The sqlite3_index_info structure and its substructures is used as part
6117 ** of the [virtual table] interface to
6118 ** pass information into and receive the reply from the [xBestIndex]
6119 ** method of a [virtual table module]. The fields under **Inputs** are the
6120 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
6121 ** results into the **Outputs** fields.
6122 **
6123 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
6124 **
6125 ** <blockquote>column OP expr</blockquote>
6126 **
6127 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
6128 ** stored in aConstraint[].op using one of the
6129 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
6130 ** ^(The index of the column is stored in
6131 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
6132 ** expr on the right-hand side can be evaluated (and thus the constraint
6133 ** is usable) and false if it cannot.)^
6134 **
6135 ** ^The optimizer automatically inverts terms of the form "expr OP column"
6136 ** and makes other simplifications to the WHERE clause in an attempt to
6137 ** get as many WHERE clause terms into the form shown above as possible.
6138 ** ^The aConstraint[] array only reports WHERE clause terms that are
6139 ** relevant to the particular virtual table being queried.
6140 **
6141 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
6142 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
6143 **
6144 ** The colUsed field indicates which columns of the virtual table may be
6145 ** required by the current scan. Virtual table columns are numbered from
6146 ** zero in the order in which they appear within the CREATE TABLE statement
6147 ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
6148 ** the corresponding bit is set within the colUsed mask if the column may be
6149 ** required by SQLite. If the table has at least 64 columns and any column
6150 ** to the right of the first 63 is required, then bit 63 of colUsed is also
6151 ** set. In other words, column iCol may be required if the expression
6152 ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
6153 ** non-zero.
6154 **
6155 ** The [xBestIndex] method must fill aConstraintUsage[] with information
6156 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
6157 ** the right-hand side of the corresponding aConstraint[] is evaluated
6158 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
6159 ** is true, then the constraint is assumed to be fully handled by the
6160 ** virtual table and is not checked again by SQLite.)^
6161 **
6162 ** ^The idxNum and idxPtr values are recorded and passed into the
6163 ** [xFilter] method.
6164 ** ^[sqlite3_free()] is used to free idxPtr if and only if
6165 ** needToFreeIdxPtr is true.
6166 **
6167 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
6168 ** the correct order to satisfy the ORDER BY clause so that no separate
6169 ** sorting step is required.
6170 **
6171 ** ^The estimatedCost value is an estimate of the cost of a particular
6172 ** strategy. A cost of N indicates that the cost of the strategy is similar
6173 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
6174 ** indicates that the expense of the operation is similar to that of a
6175 ** binary search on a unique indexed field of an SQLite table with N rows.
6176 **
6177 ** ^The estimatedRows value is an estimate of the number of rows that
6178 ** will be returned by the strategy.
6179 **
6180 ** The xBestIndex method may optionally populate the idxFlags field with a
6181 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
6182 ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
6183 ** assumes that the strategy may visit at most one row.
6184 **
6185 ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
6186 ** SQLite also assumes that if a call to the xUpdate() method is made as
6187 ** part of the same statement to delete or update a virtual table row and the
6188 ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
6189 ** any database changes. In other words, if the xUpdate() returns
6190 ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
6191 ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
6192 ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
6193 ** the xUpdate method are automatically rolled back by SQLite.
6194 **
6195 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
6196 ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
6197 ** If a virtual table extension is
6198 ** used with an SQLite version earlier than 3.8.2, the results of attempting
6199 ** to read or write the estimatedRows field are undefined (but are likely
6200 ** to included crashing the application). The estimatedRows field should
6201 ** therefore only be used if [sqlite3_libversion_number()] returns a
6202 ** value greater than or equal to 3008002. Similarly, the idxFlags field
6203 ** was added for [version 3.9.0] ([dateof:3.9.0]).
6204 ** It may therefore only be used if
6205 ** sqlite3_libversion_number() returns a value greater than or equal to
6206 ** 3009000.
6207 */
6208 struct sqlite3_index_info {
6209  /* Inputs */
6210  int nConstraint; /* Number of entries in aConstraint */
6212  int iColumn; /* Column constrained. -1 for ROWID */
6213  unsigned char op; /* Constraint operator */
6214  unsigned char usable; /* True if this constraint is usable */
6215  int iTermOffset; /* Used internally - xBestIndex should ignore */
6216  } *aConstraint; /* Table of WHERE clause constraints */
6217  int nOrderBy; /* Number of terms in the ORDER BY clause */
6219  int iColumn; /* Column number */
6220  unsigned char desc; /* True for DESC. False for ASC. */
6221  } *aOrderBy; /* The ORDER BY clause */
6222  /* Outputs */
6224  int argvIndex; /* if >0, constraint is part of argv to xFilter */
6225  unsigned char omit; /* Do not code a test for this constraint */
6226  } *aConstraintUsage;
6227  int idxNum; /* Number used to identify the index */
6228  char *idxStr; /* String, possibly obtained from sqlite3_malloc */
6229  int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
6230  int orderByConsumed; /* True if output is already ordered */
6231  double estimatedCost; /* Estimated cost of using this index */
6232  /* Fields below are only available in SQLite 3.8.2 and later */
6233  sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
6234  /* Fields below are only available in SQLite 3.9.0 and later */
6235  int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
6236  /* Fields below are only available in SQLite 3.10.0 and later */
6237  sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
6238 };
6239 
6240 /*
6241 ** CAPI3REF: Virtual Table Scan Flags
6242 */
6243 #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
6244 
6245 /*
6246 ** CAPI3REF: Virtual Table Constraint Operator Codes
6247 **
6248 ** These macros defined the allowed values for the
6249 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
6250 ** an operator that is part of a constraint term in the wHERE clause of
6251 ** a query that uses a [virtual table].
6252 */
6253 #define SQLITE_INDEX_CONSTRAINT_EQ 2
6254 #define SQLITE_INDEX_CONSTRAINT_GT 4
6255 #define SQLITE_INDEX_CONSTRAINT_LE 8
6256 #define SQLITE_INDEX_CONSTRAINT_LT 16
6257 #define SQLITE_INDEX_CONSTRAINT_GE 32
6258 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
6259 #define SQLITE_INDEX_CONSTRAINT_LIKE 65
6260 #define SQLITE_INDEX_CONSTRAINT_GLOB 66
6261 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
6262 
6263 /*
6264 ** CAPI3REF: Register A Virtual Table Implementation
6265 ** METHOD: sqlite3
6266 **
6267 ** ^These routines are used to register a new [virtual table module] name.
6268 ** ^Module names must be registered before
6269 ** creating a new [virtual table] using the module and before using a
6270 ** preexisting [virtual table] for the module.
6271 **
6272 ** ^The module name is registered on the [database connection] specified
6273 ** by the first parameter. ^The name of the module is given by the
6274 ** second parameter. ^The third parameter is a pointer to
6275 ** the implementation of the [virtual table module]. ^The fourth
6276 ** parameter is an arbitrary client data pointer that is passed through
6277 ** into the [xCreate] and [xConnect] methods of the virtual table module
6278 ** when a new virtual table is be being created or reinitialized.
6279 **
6280 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
6281 ** is a pointer to a destructor for the pClientData. ^SQLite will
6282 ** invoke the destructor function (if it is not NULL) when SQLite
6283 ** no longer needs the pClientData pointer. ^The destructor will also
6284 ** be invoked if the call to sqlite3_create_module_v2() fails.
6285 ** ^The sqlite3_create_module()
6286 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
6287 ** destructor.
6288 */
6289 SQLITE_API int sqlite3_create_module(
6290  sqlite3 *db, /* SQLite connection to register module with */
6291  const char *zName, /* Name of the module */
6292  const sqlite3_module *p, /* Methods for the module */
6293  void *pClientData /* Client data for xCreate/xConnect */
6294 );
6295 SQLITE_API int sqlite3_create_module_v2(
6296  sqlite3 *db, /* SQLite connection to register module with */
6297  const char *zName, /* Name of the module */
6298  const sqlite3_module *p, /* Methods for the module */
6299  void *pClientData, /* Client data for xCreate/xConnect */
6300  void(*xDestroy)(void*) /* Module destructor function */
6301 );
6302 
6303 /*
6304 ** CAPI3REF: Virtual Table Instance Object
6305 ** KEYWORDS: sqlite3_vtab
6306 **
6307 ** Every [virtual table module] implementation uses a subclass
6308 ** of this object to describe a particular instance
6309 ** of the [virtual table]. Each subclass will
6310 ** be tailored to the specific needs of the module implementation.
6311 ** The purpose of this superclass is to define certain fields that are
6312 ** common to all module implementations.
6313 **
6314 ** ^Virtual tables methods can set an error message by assigning a
6315 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
6316 ** take care that any prior string is freed by a call to [sqlite3_free()]
6317 ** prior to assigning a new string to zErrMsg. ^After the error message
6318 ** is delivered up to the client application, the string will be automatically
6319 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
6320 */
6321 struct sqlite3_vtab {
6322  const sqlite3_module *pModule; /* The module for this virtual table */
6323  int nRef; /* Number of open cursors */
6324  char *zErrMsg; /* Error message from sqlite3_mprintf() */
6325  /* Virtual table implementations will typically add additional fields */
6326 };
6327 
6328 /*
6329 ** CAPI3REF: Virtual Table Cursor Object
6330 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
6331 **
6332 ** Every [virtual table module] implementation uses a subclass of the
6333 ** following structure to describe cursors that point into the
6334 ** [virtual table] and are used
6335 ** to loop through the virtual table. Cursors are created using the
6336 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
6337 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
6338 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
6339 ** of the module. Each module implementation will define
6340 ** the content of a cursor structure to suit its own needs.
6341 **
6342 ** This superclass exists in order to define fields of the cursor that
6343 ** are common to all implementations.
6344 */
6345 struct sqlite3_vtab_cursor {
6346  sqlite3_vtab *pVtab; /* Virtual table of this cursor */
6347  /* Virtual table implementations will typically add additional fields */
6348 };
6349 
6350 /*
6351 ** CAPI3REF: Declare The Schema Of A Virtual Table
6352 **
6353 ** ^The [xCreate] and [xConnect] methods of a
6354 ** [virtual table module] call this interface
6355 ** to declare the format (the names and datatypes of the columns) of
6356 ** the virtual tables they implement.
6357 */
6358 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
6359 
6360 /*
6361 ** CAPI3REF: Overload A Function For A Virtual Table
6362 ** METHOD: sqlite3
6363 **
6364 ** ^(Virtual tables can provide alternative implementations of functions
6365 ** using the [xFindFunction] method of the [virtual table module].
6366 ** But global versions of those functions
6367 ** must exist in order to be overloaded.)^
6368 **
6369 ** ^(This API makes sure a global version of a function with a particular
6370 ** name and number of parameters exists. If no such function exists
6371 ** before this API is called, a new function is created.)^ ^The implementation
6372 ** of the new function always causes an exception to be thrown. So
6373 ** the new function is not good for anything by itself. Its only
6374 ** purpose is to be a placeholder function that can be overloaded
6375 ** by a [virtual table].
6376 */
6377 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6378 
6379 /*
6380 ** The interface to the virtual-table mechanism defined above (back up
6381 ** to a comment remarkably similar to this one) is currently considered
6382 ** to be experimental. The interface might change in incompatible ways.
6383 ** If this is a problem for you, do not use the interface at this time.
6384 **
6385 ** When the virtual-table mechanism stabilizes, we will declare the
6386 ** interface fixed, support it indefinitely, and remove this comment.
6387 */
6388 
6389 /*
6390 ** CAPI3REF: A Handle To An Open BLOB
6391 ** KEYWORDS: {BLOB handle} {BLOB handles}
6392 **
6393 ** An instance of this object represents an open BLOB on which
6394 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6395 ** ^Objects of this type are created by [sqlite3_blob_open()]
6396 ** and destroyed by [sqlite3_blob_close()].
6397 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6398 ** can be used to read or write small subsections of the BLOB.
6399 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6400 */
6401 typedef struct sqlite3_blob sqlite3_blob;
6402 
6403 /*
6404 ** CAPI3REF: Open A BLOB For Incremental I/O
6405 ** METHOD: sqlite3
6406 ** CONSTRUCTOR: sqlite3_blob
6407 **
6408 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6409 ** in row iRow, column zColumn, table zTable in database zDb;
6410 ** in other words, the same BLOB that would be selected by:
6411 **
6412 ** <pre>
6413 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6414 ** </pre>)^
6415 **
6416 ** ^(Parameter zDb is not the filename that contains the database, but
6417 ** rather the symbolic name of the database. For attached databases, this is
6418 ** the name that appears after the AS keyword in the [ATTACH] statement.
6419 ** For the main database file, the database name is "main". For TEMP
6420 ** tables, the database name is "temp".)^
6421 **
6422 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
6423 ** and write access. ^If the flags parameter is zero, the BLOB is opened for
6424 ** read-only access.
6425 **
6426 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
6427 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
6428 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
6429 ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
6430 ** on *ppBlob after this function it returns.
6431 **
6432 ** This function fails with SQLITE_ERROR if any of the following are true:
6433 ** <ul>
6434 ** <li> ^(Database zDb does not exist)^,
6435 ** <li> ^(Table zTable does not exist within database zDb)^,
6436 ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
6437 ** <li> ^(Column zColumn does not exist)^,
6438 ** <li> ^(Row iRow is not present in the table)^,
6439 ** <li> ^(The specified column of row iRow contains a value that is not
6440 ** a TEXT or BLOB value)^,
6441 ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
6442 ** constraint and the blob is being opened for read/write access)^,
6443 ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
6444 ** column zColumn is part of a [child key] definition and the blob is
6445 ** being opened for read/write access)^.
6446 ** </ul>
6447 **
6448 ** ^Unless it returns SQLITE_MISUSE, this function sets the
6449 ** [database connection] error code and message accessible via
6450 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6451 **
6452 **
6453 ** ^(If the row that a BLOB handle points to is modified by an
6454 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6455 ** then the BLOB handle is marked as "expired".
6456 ** This is true if any column of the row is changed, even a column
6457 ** other than the one the BLOB handle is open on.)^
6458 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6459 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6460 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
6461 ** rolled back by the expiration of the BLOB. Such changes will eventually
6462 ** commit if the transaction continues to completion.)^
6463 **
6464 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6465 ** the opened blob. ^The size of a blob may not be changed by this
6466 ** interface. Use the [UPDATE] SQL command to change the size of a
6467 ** blob.
6468 **
6469 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6470 ** and the built-in [zeroblob] SQL function may be used to create a
6471 ** zero-filled blob to read or write using the incremental-blob interface.
6472 **
6473 ** To avoid a resource leak, every open [BLOB handle] should eventually
6474 ** be released by a call to [sqlite3_blob_close()].
6475 */
6476 SQLITE_API int sqlite3_blob_open(
6477  sqlite3*,
6478  const char *zDb,
6479  const char *zTable,
6480  const char *zColumn,
6481  sqlite3_int64 iRow,
6482  int flags,
6483  sqlite3_blob **ppBlob
6484 );
6485 
6486 /*
6487 ** CAPI3REF: Move a BLOB Handle to a New Row
6488 ** METHOD: sqlite3_blob
6489 **
6490 ** ^This function is used to move an existing blob handle so that it points
6491 ** to a different row of the same database table. ^The new row is identified
6492 ** by the rowid value passed as the second argument. Only the row can be
6493 ** changed. ^The database, table and column on which the blob handle is open
6494 ** remain the same. Moving an existing blob handle to a new row can be
6495 ** faster than closing the existing handle and opening a new one.
6496 **
6497 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6498 ** it must exist and there must be either a blob or text value stored in
6499 ** the nominated column.)^ ^If the new row is not present in the table, or if
6500 ** it does not contain a blob or text value, or if another error occurs, an
6501 ** SQLite error code is returned and the blob handle is considered aborted.
6502 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6503 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6504 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6505 ** always returns zero.
6506 **
6507 ** ^This function sets the database handle error code and message.
6508 */
6509 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6510 
6511 /*
6512 ** CAPI3REF: Close A BLOB Handle
6513 ** DESTRUCTOR: sqlite3_blob
6514 **
6515 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6516 ** unconditionally. Even if this routine returns an error code, the
6517 ** handle is still closed.)^
6518 **
6519 ** ^If the blob handle being closed was opened for read-write access, and if
6520 ** the database is in auto-commit mode and there are no other open read-write
6521 ** blob handles or active write statements, the current transaction is
6522 ** committed. ^If an error occurs while committing the transaction, an error
6523 ** code is returned and the transaction rolled back.
6524 **
6525 ** Calling this function with an argument that is not a NULL pointer or an
6526 ** open blob handle results in undefined behaviour. ^Calling this routine
6527 ** with a null pointer (such as would be returned by a failed call to
6528 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6529 ** is passed a valid open blob handle, the values returned by the
6530 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6531 */
6532 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6533 
6534 /*
6535 ** CAPI3REF: Return The Size Of An Open BLOB
6536 ** METHOD: sqlite3_blob
6537 **
6538 ** ^Returns the size in bytes of the BLOB accessible via the
6539 ** successfully opened [BLOB handle] in its only argument. ^The
6540 ** incremental blob I/O routines can only read or overwriting existing
6541 ** blob content; they cannot change the size of a blob.
6542 **
6543 ** This routine only works on a [BLOB handle] which has been created
6544 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6545 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6546 ** to this routine results in undefined and probably undesirable behavior.
6547 */
6548 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6549 
6550 /*
6551 ** CAPI3REF: Read Data From A BLOB Incrementally
6552 ** METHOD: sqlite3_blob
6553 **
6554 ** ^(This function is used to read data from an open [BLOB handle] into a
6555 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6556 ** from the open BLOB, starting at offset iOffset.)^
6557 **
6558 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6559 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
6560 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6561 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6562 ** can be determined using the [sqlite3_blob_bytes()] interface.
6563 **
6564 ** ^An attempt to read from an expired [BLOB handle] fails with an
6565 ** error code of [SQLITE_ABORT].
6566 **
6567 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6568 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6569 **
6570 ** This routine only works on a [BLOB handle] which has been created
6571 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6572 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6573 ** to this routine results in undefined and probably undesirable behavior.
6574 **
6575 ** See also: [sqlite3_blob_write()].
6576 */
6577 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6578 
6579 /*
6580 ** CAPI3REF: Write Data Into A BLOB Incrementally
6581 ** METHOD: sqlite3_blob
6582 **
6583 ** ^(This function is used to write data into an open [BLOB handle] from a
6584 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6585 ** into the open BLOB, starting at offset iOffset.)^
6586 **
6587 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6588 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6589 ** ^Unless SQLITE_MISUSE is returned, this function sets the
6590 ** [database connection] error code and message accessible via
6591 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6592 **
6593 ** ^If the [BLOB handle] passed as the first argument was not opened for
6594 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6595 ** this function returns [SQLITE_READONLY].
6596 **
6597 ** This function may only modify the contents of the BLOB; it is
6598 ** not possible to increase the size of a BLOB using this API.
6599 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6600 ** [SQLITE_ERROR] is returned and no data is written. The size of the
6601 ** BLOB (and hence the maximum value of N+iOffset) can be determined
6602 ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
6603 ** than zero [SQLITE_ERROR] is returned and no data is written.
6604 **
6605 ** ^An attempt to write to an expired [BLOB handle] fails with an
6606 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
6607 ** before the [BLOB handle] expired are not rolled back by the
6608 ** expiration of the handle, though of course those changes might
6609 ** have been overwritten by the statement that expired the BLOB handle
6610 ** or by other independent statements.
6611 **
6612 ** This routine only works on a [BLOB handle] which has been created
6613 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6614 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6615 ** to this routine results in undefined and probably undesirable behavior.
6616 **
6617 ** See also: [sqlite3_blob_read()].
6618 */
6619 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6620 
6621 /*
6622 ** CAPI3REF: Virtual File System Objects
6623 **
6624 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6625 ** that SQLite uses to interact
6626 ** with the underlying operating system. Most SQLite builds come with a
6627 ** single default VFS that is appropriate for the host computer.
6628 ** New VFSes can be registered and existing VFSes can be unregistered.
6629 ** The following interfaces are provided.
6630 **
6631 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6632 ** ^Names are case sensitive.
6633 ** ^Names are zero-terminated UTF-8 strings.
6634 ** ^If there is no match, a NULL pointer is returned.
6635 ** ^If zVfsName is NULL then the default VFS is returned.
6636 **
6637 ** ^New VFSes are registered with sqlite3_vfs_register().
6638 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6639 ** ^The same VFS can be registered multiple times without injury.
6640 ** ^To make an existing VFS into the default VFS, register it again
6641 ** with the makeDflt flag set. If two different VFSes with the
6642 ** same name are registered, the behavior is undefined. If a
6643 ** VFS is registered with a name that is NULL or an empty string,
6644 ** then the behavior is undefined.
6645 **
6646 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6647 ** ^(If the default VFS is unregistered, another VFS is chosen as
6648 ** the default. The choice for the new VFS is arbitrary.)^
6649 */
6650 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6651 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6652 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6653 
6654 /*
6655 ** CAPI3REF: Mutexes
6656 **
6657 ** The SQLite core uses these routines for thread
6658 ** synchronization. Though they are intended for internal
6659 ** use by SQLite, code that links against SQLite is
6660 ** permitted to use any of these routines.
6661 **
6662 ** The SQLite source code contains multiple implementations
6663 ** of these mutex routines. An appropriate implementation
6664 ** is selected automatically at compile-time. The following
6665 ** implementations are available in the SQLite core:
6666 **
6667 ** <ul>
6668 ** <li> SQLITE_MUTEX_PTHREADS
6669 ** <li> SQLITE_MUTEX_W32
6670 ** <li> SQLITE_MUTEX_NOOP
6671 ** </ul>
6672 **
6673 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6674 ** that does no real locking and is appropriate for use in
6675 ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
6676 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6677 ** and Windows.
6678 **
6679 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6680 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6681 ** implementation is included with the library. In this case the
6682 ** application must supply a custom mutex implementation using the
6683 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6684 ** before calling sqlite3_initialize() or any other public sqlite3_
6685 ** function that calls sqlite3_initialize().
6686 **
6687 ** ^The sqlite3_mutex_alloc() routine allocates a new
6688 ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6689 ** routine returns NULL if it is unable to allocate the requested
6690 ** mutex. The argument to sqlite3_mutex_alloc() must one of these
6691 ** integer constants:
6692 **
6693 ** <ul>
6694 ** <li> SQLITE_MUTEX_FAST
6695 ** <li> SQLITE_MUTEX_RECURSIVE
6696 ** <li> SQLITE_MUTEX_STATIC_MASTER
6697 ** <li> SQLITE_MUTEX_STATIC_MEM
6698 ** <li> SQLITE_MUTEX_STATIC_OPEN
6699 ** <li> SQLITE_MUTEX_STATIC_PRNG
6700 ** <li> SQLITE_MUTEX_STATIC_LRU
6701 ** <li> SQLITE_MUTEX_STATIC_PMEM
6702 ** <li> SQLITE_MUTEX_STATIC_APP1
6703 ** <li> SQLITE_MUTEX_STATIC_APP2
6704 ** <li> SQLITE_MUTEX_STATIC_APP3
6705 ** <li> SQLITE_MUTEX_STATIC_VFS1
6706 ** <li> SQLITE_MUTEX_STATIC_VFS2
6707 ** <li> SQLITE_MUTEX_STATIC_VFS3
6708 ** </ul>
6709 **
6710 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6711 ** cause sqlite3_mutex_alloc() to create
6712 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6713 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6714 ** The mutex implementation does not need to make a distinction
6715 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6716 ** not want to. SQLite will only request a recursive mutex in
6717 ** cases where it really needs one. If a faster non-recursive mutex
6718 ** implementation is available on the host platform, the mutex subsystem
6719 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6720 **
6721 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6722 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6723 ** a pointer to a static preexisting mutex. ^Nine static mutexes are
6724 ** used by the current version of SQLite. Future versions of SQLite
6725 ** may add additional static mutexes. Static mutexes are for internal
6726 ** use by SQLite only. Applications that use SQLite mutexes should
6727 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6728 ** SQLITE_MUTEX_RECURSIVE.
6729 **
6730 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6731 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6732 ** returns a different mutex on every call. ^For the static
6733 ** mutex types, the same mutex is returned on every call that has
6734 ** the same type number.
6735 **
6736 ** ^The sqlite3_mutex_free() routine deallocates a previously
6737 ** allocated dynamic mutex. Attempting to deallocate a static
6738 ** mutex results in undefined behavior.
6739 **
6740 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6741 ** to enter a mutex. ^If another thread is already within the mutex,
6742 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6743 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6744 ** upon successful entry. ^(Mutexes created using
6745 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6746 ** In such cases, the
6747 ** mutex must be exited an equal number of times before another thread
6748 ** can enter.)^ If the same thread tries to enter any mutex other
6749 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6750 **
6751 ** ^(Some systems (for example, Windows 95) do not support the operation
6752 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
6753 ** will always return SQLITE_BUSY. The SQLite core only ever uses
6754 ** sqlite3_mutex_try() as an optimization so this is acceptable
6755 ** behavior.)^
6756 **
6757 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6758 ** previously entered by the same thread. The behavior
6759 ** is undefined if the mutex is not currently entered by the
6760 ** calling thread or is not currently allocated.
6761 **
6762 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6763 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6764 ** behave as no-ops.
6765 **
6766 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6767 */
6768 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6769 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6770 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6771 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6772 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6773 
6774 /*
6775 ** CAPI3REF: Mutex Methods Object
6776 **
6777 ** An instance of this structure defines the low-level routines
6778 ** used to allocate and use mutexes.
6779 **
6780 ** Usually, the default mutex implementations provided by SQLite are
6781 ** sufficient, however the application has the option of substituting a custom
6782 ** implementation for specialized deployments or systems for which SQLite
6783 ** does not provide a suitable implementation. In this case, the application
6784 ** creates and populates an instance of this structure to pass
6785 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6786 ** Additionally, an instance of this structure can be used as an
6787 ** output variable when querying the system for the current mutex
6788 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6789 **
6790 ** ^The xMutexInit method defined by this structure is invoked as
6791 ** part of system initialization by the sqlite3_initialize() function.
6792 ** ^The xMutexInit routine is called by SQLite exactly once for each
6793 ** effective call to [sqlite3_initialize()].
6794 **
6795 ** ^The xMutexEnd method defined by this structure is invoked as
6796 ** part of system shutdown by the sqlite3_shutdown() function. The
6797 ** implementation of this method is expected to release all outstanding
6798 ** resources obtained by the mutex methods implementation, especially
6799 ** those obtained by the xMutexInit method. ^The xMutexEnd()
6800 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6801 **
6802 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6803 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6804 ** xMutexNotheld) implement the following interfaces (respectively):
6805 **
6806 ** <ul>
6807 ** <li> [sqlite3_mutex_alloc()] </li>
6808 ** <li> [sqlite3_mutex_free()] </li>
6809 ** <li> [sqlite3_mutex_enter()] </li>
6810 ** <li> [sqlite3_mutex_try()] </li>
6811 ** <li> [sqlite3_mutex_leave()] </li>
6812 ** <li> [sqlite3_mutex_held()] </li>
6813 ** <li> [sqlite3_mutex_notheld()] </li>
6814 ** </ul>)^
6815 **
6816 ** The only difference is that the public sqlite3_XXX functions enumerated
6817 ** above silently ignore any invocations that pass a NULL pointer instead
6818 ** of a valid mutex handle. The implementations of the methods defined
6819 ** by this structure are not required to handle this case, the results
6820 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6821 ** (i.e. it is acceptable to provide an implementation that segfaults if
6822 ** it is passed a NULL pointer).
6823 **
6824 ** The xMutexInit() method must be threadsafe. It must be harmless to
6825 ** invoke xMutexInit() multiple times within the same process and without
6826 ** intervening calls to xMutexEnd(). Second and subsequent calls to
6827 ** xMutexInit() must be no-ops.
6828 **
6829 ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6830 ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
6831 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
6832 ** memory allocation for a fast or recursive mutex.
6833 **
6834 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6835 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6836 ** If xMutexInit fails in any way, it is expected to clean up after itself
6837 ** prior to returning.
6838 */
6839 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6840 struct sqlite3_mutex_methods {
6841  int (*xMutexInit)(void);
6842  int (*xMutexEnd)(void);
6843  sqlite3_mutex *(*xMutexAlloc)(int);
6844  void (*xMutexFree)(sqlite3_mutex *);
6845  void (*xMutexEnter)(sqlite3_mutex *);
6846  int (*xMutexTry)(sqlite3_mutex *);
6847  void (*xMutexLeave)(sqlite3_mutex *);
6848  int (*xMutexHeld)(sqlite3_mutex *);
6849  int (*xMutexNotheld)(sqlite3_mutex *);
6850 };
6851 
6852 /*
6853 ** CAPI3REF: Mutex Verification Routines
6854 **
6855 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6856 ** are intended for use inside assert() statements. The SQLite core
6857 ** never uses these routines except inside an assert() and applications
6858 ** are advised to follow the lead of the core. The SQLite core only
6859 ** provides implementations for these routines when it is compiled
6860 ** with the SQLITE_DEBUG flag. External mutex implementations
6861 ** are only required to provide these routines if SQLITE_DEBUG is
6862 ** defined and if NDEBUG is not defined.
6863 **
6864 ** These routines should return true if the mutex in their argument
6865 ** is held or not held, respectively, by the calling thread.
6866 **
6867 ** The implementation is not required to provide versions of these
6868 ** routines that actually work. If the implementation does not provide working
6869 ** versions of these routines, it should at least provide stubs that always
6870 ** return true so that one does not get spurious assertion failures.
6871 **
6872 ** If the argument to sqlite3_mutex_held() is a NULL pointer then
6873 ** the routine should return 1. This seems counter-intuitive since
6874 ** clearly the mutex cannot be held if it does not exist. But
6875 ** the reason the mutex does not exist is because the build is not
6876 ** using mutexes. And we do not want the assert() containing the
6877 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6878 ** the appropriate thing to do. The sqlite3_mutex_notheld()
6879 ** interface should also return 1 when given a NULL pointer.
6880 */
6881 #ifndef NDEBUG
6882 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6883 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6884 #endif
6885 
6886 /*
6887 ** CAPI3REF: Mutex Types
6888 **
6889 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6890 ** which is one of these integer constants.
6891 **
6892 ** The set of static mutexes may change from one SQLite release to the
6893 ** next. Applications that override the built-in mutex logic must be
6894 ** prepared to accommodate additional static mutexes.
6895 */
6896 #define SQLITE_MUTEX_FAST 0
6897 #define SQLITE_MUTEX_RECURSIVE 1
6898 #define SQLITE_MUTEX_STATIC_MASTER 2
6899 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
6900 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
6901 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
6902 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
6903 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
6904 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
6905 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
6906 #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
6907 #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
6908 #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
6909 #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
6910 #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
6911 #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
6912 
6913 /*
6914 ** CAPI3REF: Retrieve the mutex for a database connection
6915 ** METHOD: sqlite3
6916 **
6917 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6918 ** serializes access to the [database connection] given in the argument
6919 ** when the [threading mode] is Serialized.
6920 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6921 ** routine returns a NULL pointer.
6922 */
6923 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6924 
6925 /*
6926 ** CAPI3REF: Low-Level Control Of Database Files
6927 ** METHOD: sqlite3
6928 **
6929 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6930 ** xFileControl method for the [sqlite3_io_methods] object associated
6931 ** with a particular database identified by the second argument. ^The
6932 ** name of the database is "main" for the main database or "temp" for the
6933 ** TEMP database, or the name that appears after the AS keyword for
6934 ** databases that are added using the [ATTACH] SQL command.
6935 ** ^A NULL pointer can be used in place of "main" to refer to the
6936 ** main database file.
6937 ** ^The third and fourth parameters to this routine
6938 ** are passed directly through to the second and third parameters of
6939 ** the xFileControl method. ^The return value of the xFileControl
6940 ** method becomes the return value of this routine.
6941 **
6942 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6943 ** a pointer to the underlying [sqlite3_file] object to be written into
6944 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
6945 ** case is a short-circuit path which does not actually invoke the
6946 ** underlying sqlite3_io_methods.xFileControl method.
6947 **
6948 ** ^If the second parameter (zDbName) does not match the name of any
6949 ** open database file, then SQLITE_ERROR is returned. ^This error
6950 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6951 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
6952 ** also return SQLITE_ERROR. There is no way to distinguish between
6953 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6954 ** xFileControl method.
6955 **
6956 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6957 */
6958 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6959 
6960 /*
6961 ** CAPI3REF: Testing Interface
6962 **
6963 ** ^The sqlite3_test_control() interface is used to read out internal
6964 ** state of SQLite and to inject faults into SQLite for testing
6965 ** purposes. ^The first parameter is an operation code that determines
6966 ** the number, meaning, and operation of all subsequent parameters.
6967 **
6968 ** This interface is not for use by applications. It exists solely
6969 ** for verifying the correct operation of the SQLite library. Depending
6970 ** on how the SQLite library is compiled, this interface might not exist.
6971 **
6972 ** The details of the operation codes, their meanings, the parameters
6973 ** they take, and what they do are all subject to change without notice.
6974 ** Unlike most of the SQLite API, this function is not guaranteed to
6975 ** operate consistently from one release to the next.
6976 */
6977 SQLITE_API int sqlite3_test_control(int op, ...);
6978 
6979 /*
6980 ** CAPI3REF: Testing Interface Operation Codes
6981 **
6982 ** These constants are the valid operation code parameters used
6983 ** as the first argument to [sqlite3_test_control()].
6984 **
6985 ** These parameters and their meanings are subject to change
6986 ** without notice. These values are for testing purposes only.
6987 ** Applications should not use any of these parameters or the
6988 ** [sqlite3_test_control()] interface.
6989 */
6990 #define SQLITE_TESTCTRL_FIRST 5
6991 #define SQLITE_TESTCTRL_PRNG_SAVE 5
6992 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
6993 #define SQLITE_TESTCTRL_PRNG_RESET 7
6994 #define SQLITE_TESTCTRL_BITVEC_TEST 8
6995 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
6996 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
6997 #define SQLITE_TESTCTRL_PENDING_BYTE 11
6998 #define SQLITE_TESTCTRL_ASSERT 12
6999 #define SQLITE_TESTCTRL_ALWAYS 13
7000 #define SQLITE_TESTCTRL_RESERVE 14
7001 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
7002 #define SQLITE_TESTCTRL_ISKEYWORD 16
7003 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
7004 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
7005 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
7006 #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
7007 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
7008 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
7009 #define SQLITE_TESTCTRL_BYTEORDER 22
7010 #define SQLITE_TESTCTRL_ISINIT 23
7011 #define SQLITE_TESTCTRL_SORTER_MMAP 24
7012 #define SQLITE_TESTCTRL_IMPOSTER 25
7013 #define SQLITE_TESTCTRL_LAST 25
7014 
7015 /*
7016 ** CAPI3REF: SQLite Runtime Status
7017 **
7018 ** ^These interfaces are used to retrieve runtime status information
7019 ** about the performance of SQLite, and optionally to reset various
7020 ** highwater marks. ^The first argument is an integer code for
7021 ** the specific parameter to measure. ^(Recognized integer codes
7022 ** are of the form [status parameters | SQLITE_STATUS_...].)^
7023 ** ^The current value of the parameter is returned into *pCurrent.
7024 ** ^The highest recorded value is returned in *pHighwater. ^If the
7025 ** resetFlag is true, then the highest record value is reset after
7026 ** *pHighwater is written. ^(Some parameters do not record the highest
7027 ** value. For those parameters
7028 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
7029 ** ^(Other parameters record only the highwater mark and not the current
7030 ** value. For these latter parameters nothing is written into *pCurrent.)^
7031 **
7032 ** ^The sqlite3_status() and sqlite3_status64() routines return
7033 ** SQLITE_OK on success and a non-zero [error code] on failure.
7034 **
7035 ** If either the current value or the highwater mark is too large to
7036 ** be represented by a 32-bit integer, then the values returned by
7037 ** sqlite3_status() are undefined.
7038 **
7039 ** See also: [sqlite3_db_status()]
7040 */
7041 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
7042 SQLITE_API int sqlite3_status64(
7043  int op,
7044  sqlite3_int64 *pCurrent,
7045  sqlite3_int64 *pHighwater,
7046  int resetFlag
7047 );
7048 
7049 
7050 /*
7051 ** CAPI3REF: Status Parameters
7052 ** KEYWORDS: {status parameters}
7053 **
7054 ** These integer constants designate various run-time status parameters
7055 ** that can be returned by [sqlite3_status()].
7056 **
7057 ** <dl>
7058 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
7059 ** <dd>This parameter is the current amount of memory checked out
7060 ** using [sqlite3_malloc()], either directly or indirectly. The
7061 ** figure includes calls made to [sqlite3_malloc()] by the application
7062 ** and internal memory usage by the SQLite library. Scratch memory
7063 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
7064 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
7065 ** this parameter. The amount returned is the sum of the allocation
7066 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
7067 **
7068 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
7069 ** <dd>This parameter records the largest memory allocation request
7070 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
7071 ** internal equivalents). Only the value returned in the
7072 ** *pHighwater parameter to [sqlite3_status()] is of interest.
7073 ** The value written into the *pCurrent parameter is undefined.</dd>)^
7074 **
7075 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
7076 ** <dd>This parameter records the number of separate memory allocations
7077 ** currently checked out.</dd>)^
7078 **
7079 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
7080 ** <dd>This parameter returns the number of pages used out of the
7081 ** [pagecache memory allocator] that was configured using
7082 ** [SQLITE_CONFIG_PAGECACHE]. The
7083 ** value returned is in pages, not in bytes.</dd>)^
7084 **
7085 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
7086 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
7087 ** <dd>This parameter returns the number of bytes of page cache
7088 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
7089 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
7090 ** returned value includes allocations that overflowed because they
7091 ** where too large (they were larger than the "sz" parameter to
7092 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
7093 ** no space was left in the page cache.</dd>)^
7094 **
7095 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
7096 ** <dd>This parameter records the largest memory allocation request
7097 ** handed to [pagecache memory allocator]. Only the value returned in the
7098 ** *pHighwater parameter to [sqlite3_status()] is of interest.
7099 ** The value written into the *pCurrent parameter is undefined.</dd>)^
7100 **
7101 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
7102 ** <dd>This parameter returns the number of allocations used out of the
7103 ** [scratch memory allocator] configured using
7104 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
7105 ** in bytes. Since a single thread may only have one scratch allocation
7106 ** outstanding at time, this parameter also reports the number of threads
7107 ** using scratch memory at the same time.</dd>)^
7108 **
7109 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
7110 ** <dd>This parameter returns the number of bytes of scratch memory
7111 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
7112 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
7113 ** returned include overflows because the requested allocation was too
7114 ** larger (that is, because the requested allocation was larger than the
7115 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
7116 ** slots were available.
7117 ** </dd>)^
7118 **
7119 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
7120 ** <dd>This parameter records the largest memory allocation request
7121 ** handed to [scratch memory allocator]. Only the value returned in the
7122 ** *pHighwater parameter to [sqlite3_status()] is of interest.
7123 ** The value written into the *pCurrent parameter is undefined.</dd>)^
7124 **
7125 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
7126 ** <dd>The *pHighwater parameter records the deepest parser stack.
7127 ** The *pCurrent value is undefined. The *pHighwater value is only
7128 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
7129 ** </dl>
7130 **
7131 ** New status parameters may be added from time to time.
7132 */
7133 #define SQLITE_STATUS_MEMORY_USED 0
7134 #define SQLITE_STATUS_PAGECACHE_USED 1
7135 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
7136 #define SQLITE_STATUS_SCRATCH_USED 3
7137 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
7138 #define SQLITE_STATUS_MALLOC_SIZE 5
7139 #define SQLITE_STATUS_PARSER_STACK 6
7140 #define SQLITE_STATUS_PAGECACHE_SIZE 7
7141 #define SQLITE_STATUS_SCRATCH_SIZE 8
7142 #define SQLITE_STATUS_MALLOC_COUNT 9
7143 
7144 /*
7145 ** CAPI3REF: Database Connection Status
7146 ** METHOD: sqlite3
7147 **
7148 ** ^This interface is used to retrieve runtime status information
7149 ** about a single [database connection]. ^The first argument is the
7150 ** database connection object to be interrogated. ^The second argument
7151 ** is an integer constant, taken from the set of
7152 ** [SQLITE_DBSTATUS options], that
7153 ** determines the parameter to interrogate. The set of
7154 ** [SQLITE_DBSTATUS options] is likely
7155 ** to grow in future releases of SQLite.
7156 **
7157 ** ^The current value of the requested parameter is written into *pCur
7158 ** and the highest instantaneous value is written into *pHiwtr. ^If
7159 ** the resetFlg is true, then the highest instantaneous value is
7160 ** reset back down to the current value.
7161 **
7162 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
7163 ** non-zero [error code] on failure.
7164 **
7165 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
7166 */
7167 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
7168 
7169 /*
7170 ** CAPI3REF: Status Parameters for database connections
7171 ** KEYWORDS: {SQLITE_DBSTATUS options}
7172 **
7173 ** These constants are the available integer "verbs" that can be passed as
7174 ** the second argument to the [sqlite3_db_status()] interface.
7175 **
7176 ** New verbs may be added in future releases of SQLite. Existing verbs
7177 ** might be discontinued. Applications should check the return code from
7178 ** [sqlite3_db_status()] to make sure that the call worked.
7179 ** The [sqlite3_db_status()] interface will return a non-zero error code
7180 ** if a discontinued or unsupported verb is invoked.
7181 **
7182 ** <dl>
7183 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
7184 ** <dd>This parameter returns the number of lookaside memory slots currently
7185 ** checked out.</dd>)^
7186 **
7187 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
7188 ** <dd>This parameter returns the number malloc attempts that were
7189 ** satisfied using lookaside memory. Only the high-water value is meaningful;
7190 ** the current value is always zero.)^
7191 **
7192 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
7193 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
7194 ** <dd>This parameter returns the number malloc attempts that might have
7195 ** been satisfied using lookaside memory but failed due to the amount of
7196 ** memory requested being larger than the lookaside slot size.
7197 ** Only the high-water value is meaningful;
7198 ** the current value is always zero.)^
7199 **
7200 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
7201 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
7202 ** <dd>This parameter returns the number malloc attempts that might have
7203 ** been satisfied using lookaside memory but failed due to all lookaside
7204 ** memory already being in use.
7205 ** Only the high-water value is meaningful;
7206 ** the current value is always zero.)^
7207 **
7208 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
7209 ** <dd>This parameter returns the approximate number of bytes of heap
7210 ** memory used by all pager caches associated with the database connection.)^
7211 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
7212 **
7213 ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
7214 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
7215 ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
7216 ** pager cache is shared between two or more connections the bytes of heap
7217 ** memory used by that pager cache is divided evenly between the attached
7218 ** connections.)^ In other words, if none of the pager caches associated
7219 ** with the database connection are shared, this request returns the same
7220 ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
7221 ** shared, the value returned by this call will be smaller than that returned
7222 ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
7223 ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
7224 **
7225 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
7226 ** <dd>This parameter returns the approximate number of bytes of heap
7227 ** memory used to store the schema for all databases associated
7228 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
7229 ** ^The full amount of memory used by the schemas is reported, even if the
7230 ** schema memory is shared with other database connections due to
7231 ** [shared cache mode] being enabled.
7232 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
7233 **
7234 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
7235 ** <dd>This parameter returns the approximate number of bytes of heap
7236 ** and lookaside memory used by all prepared statements associated with
7237 ** the database connection.)^
7238 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
7239 ** </dd>
7240 **
7241 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
7242 ** <dd>This parameter returns the number of pager cache hits that have
7243 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
7244 ** is always 0.
7245 ** </dd>
7246 **
7247 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
7248 ** <dd>This parameter returns the number of pager cache misses that have
7249 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
7250 ** is always 0.
7251 ** </dd>
7252 **
7253 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
7254 ** <dd>This parameter returns the number of dirty cache entries that have
7255 ** been written to disk. Specifically, the number of pages written to the
7256 ** wal file in wal mode databases, or the number of pages written to the
7257 ** database file in rollback mode databases. Any pages written as part of
7258 ** transaction rollback or database recovery operations are not included.
7259 ** If an IO or other error occurs while writing a page to disk, the effect
7260 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
7261 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
7262 ** </dd>
7263 **
7264 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
7265 ** <dd>This parameter returns zero for the current value if and only if
7266 ** all foreign key constraints (deferred or immediate) have been
7267 ** resolved.)^ ^The highwater mark is always 0.
7268 ** </dd>
7269 ** </dl>
7270 */
7271 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
7272 #define SQLITE_DBSTATUS_CACHE_USED 1
7273 #define SQLITE_DBSTATUS_SCHEMA_USED 2
7274 #define SQLITE_DBSTATUS_STMT_USED 3
7275 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
7276 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
7277 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
7278 #define SQLITE_DBSTATUS_CACHE_HIT 7
7279 #define SQLITE_DBSTATUS_CACHE_MISS 8
7280 #define SQLITE_DBSTATUS_CACHE_WRITE 9
7281 #define SQLITE_DBSTATUS_DEFERRED_FKS 10
7282 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
7283 #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */
7284 
7285 
7286 /*
7287 ** CAPI3REF: Prepared Statement Status
7288 ** METHOD: sqlite3_stmt
7289 **
7290 ** ^(Each prepared statement maintains various
7291 ** [SQLITE_STMTSTATUS counters] that measure the number
7292 ** of times it has performed specific operations.)^ These counters can
7293 ** be used to monitor the performance characteristics of the prepared
7294 ** statements. For example, if the number of table steps greatly exceeds
7295 ** the number of table searches or result rows, that would tend to indicate
7296 ** that the prepared statement is using a full table scan rather than
7297 ** an index.
7298 **
7299 ** ^(This interface is used to retrieve and reset counter values from
7300 ** a [prepared statement]. The first argument is the prepared statement
7301 ** object to be interrogated. The second argument
7302 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
7303 ** to be interrogated.)^
7304 ** ^The current value of the requested counter is returned.
7305 ** ^If the resetFlg is true, then the counter is reset to zero after this
7306 ** interface call returns.
7307 **
7308 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
7309 */
7310 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
7311 
7312 /*
7313 ** CAPI3REF: Status Parameters for prepared statements
7314 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
7315 **
7316 ** These preprocessor macros define integer codes that name counter
7317 ** values associated with the [sqlite3_stmt_status()] interface.
7318 ** The meanings of the various counters are as follows:
7319 **
7320 ** <dl>
7321 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
7322 ** <dd>^This is the number of times that SQLite has stepped forward in
7323 ** a table as part of a full table scan. Large numbers for this counter
7324 ** may indicate opportunities for performance improvement through
7325 ** careful use of indices.</dd>
7326 **
7327 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
7328 ** <dd>^This is the number of sort operations that have occurred.
7329 ** A non-zero value in this counter may indicate an opportunity to
7330 ** improvement performance through careful use of indices.</dd>
7331 **
7332 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
7333 ** <dd>^This is the number of rows inserted into transient indices that
7334 ** were created automatically in order to help joins run faster.
7335 ** A non-zero value in this counter may indicate an opportunity to
7336 ** improvement performance by adding permanent indices that do not
7337 ** need to be reinitialized each time the statement is run.</dd>
7338 **
7339 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
7340 ** <dd>^This is the number of virtual machine operations executed
7341 ** by the prepared statement if that number is less than or equal
7342 ** to 2147483647. The number of virtual machine operations can be
7343 ** used as a proxy for the total work done by the prepared statement.
7344 ** If the number of virtual machine operations exceeds 2147483647
7345 ** then the value returned by this statement status code is undefined.
7346 ** </dd>
7347 ** </dl>
7348 */
7349 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
7350 #define SQLITE_STMTSTATUS_SORT 2
7351 #define SQLITE_STMTSTATUS_AUTOINDEX 3
7352 #define SQLITE_STMTSTATUS_VM_STEP 4
7353 
7354 /*
7355 ** CAPI3REF: Custom Page Cache Object
7356 **
7357 ** The sqlite3_pcache type is opaque. It is implemented by
7358 ** the pluggable module. The SQLite core has no knowledge of
7359 ** its size or internal structure and never deals with the
7360 ** sqlite3_pcache object except by holding and passing pointers
7361 ** to the object.
7362 **
7363 ** See [sqlite3_pcache_methods2] for additional information.
7364 */
7365 typedef struct sqlite3_pcache sqlite3_pcache;
7366 
7367 /*
7368 ** CAPI3REF: Custom Page Cache Object
7369 **
7370 ** The sqlite3_pcache_page object represents a single page in the
7371 ** page cache. The page cache will allocate instances of this
7372 ** object. Various methods of the page cache use pointers to instances
7373 ** of this object as parameters or as their return value.
7374 **
7375 ** See [sqlite3_pcache_methods2] for additional information.
7376 */
7377 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
7378 struct sqlite3_pcache_page {
7379  void *pBuf; /* The content of the page */
7380  void *pExtra; /* Extra information associated with the page */
7381 };
7382 
7383 /*
7384 ** CAPI3REF: Application Defined Page Cache.
7385 ** KEYWORDS: {page cache}
7386 **
7387 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
7388 ** register an alternative page cache implementation by passing in an
7389 ** instance of the sqlite3_pcache_methods2 structure.)^
7390 ** In many applications, most of the heap memory allocated by
7391 ** SQLite is used for the page cache.
7392 ** By implementing a
7393 ** custom page cache using this API, an application can better control
7394 ** the amount of memory consumed by SQLite, the way in which
7395 ** that memory is allocated and released, and the policies used to
7396 ** determine exactly which parts of a database file are cached and for
7397 ** how long.
7398 **
7399 ** The alternative page cache mechanism is an
7400 ** extreme measure that is only needed by the most demanding applications.
7401 ** The built-in page cache is recommended for most uses.
7402 **
7403 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
7404 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
7405 ** the application may discard the parameter after the call to
7406 ** [sqlite3_config()] returns.)^
7407 **
7408 ** [[the xInit() page cache method]]
7409 ** ^(The xInit() method is called once for each effective
7410 ** call to [sqlite3_initialize()])^
7411 ** (usually only once during the lifetime of the process). ^(The xInit()
7412 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
7413 ** The intent of the xInit() method is to set up global data structures
7414 ** required by the custom page cache implementation.
7415 ** ^(If the xInit() method is NULL, then the
7416 ** built-in default page cache is used instead of the application defined
7417 ** page cache.)^
7418 **
7419 ** [[the xShutdown() page cache method]]
7420 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
7421 ** It can be used to clean up
7422 ** any outstanding resources before process shutdown, if required.
7423 ** ^The xShutdown() method may be NULL.
7424 **
7425 ** ^SQLite automatically serializes calls to the xInit method,
7426 ** so the xInit method need not be threadsafe. ^The
7427 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
7428 ** not need to be threadsafe either. All other methods must be threadsafe
7429 ** in multithreaded applications.
7430 **
7431 ** ^SQLite will never invoke xInit() more than once without an intervening
7432 ** call to xShutdown().
7433 **
7434 ** [[the xCreate() page cache methods]]
7435 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
7436 ** SQLite will typically create one cache instance for each open database file,
7437 ** though this is not guaranteed. ^The
7438 ** first parameter, szPage, is the size in bytes of the pages that must
7439 ** be allocated by the cache. ^szPage will always a power of two. ^The
7440 ** second parameter szExtra is a number of bytes of extra storage
7441 ** associated with each page cache entry. ^The szExtra parameter will
7442 ** a number less than 250. SQLite will use the
7443 ** extra szExtra bytes on each page to store metadata about the underlying
7444 ** database page on disk. The value passed into szExtra depends
7445 ** on the SQLite version, the target platform, and how SQLite was compiled.
7446 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
7447 ** created will be used to cache database pages of a file stored on disk, or
7448 ** false if it is used for an in-memory database. The cache implementation
7449 ** does not have to do anything special based with the value of bPurgeable;
7450 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
7451 ** never invoke xUnpin() except to deliberately delete a page.
7452 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7453 ** false will always have the "discard" flag set to true.
7454 ** ^Hence, a cache created with bPurgeable false will
7455 ** never contain any unpinned pages.
7456 **
7457 ** [[the xCachesize() page cache method]]
7458 ** ^(The xCachesize() method may be called at any time by SQLite to set the
7459 ** suggested maximum cache-size (number of pages stored by) the cache
7460 ** instance passed as the first argument. This is the value configured using
7461 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
7462 ** parameter, the implementation is not required to do anything with this
7463 ** value; it is advisory only.
7464 **
7465 ** [[the xPagecount() page cache methods]]
7466 ** The xPagecount() method must return the number of pages currently
7467 ** stored in the cache, both pinned and unpinned.
7468 **
7469 ** [[the xFetch() page cache methods]]
7470 ** The xFetch() method locates a page in the cache and returns a pointer to
7471 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7472 ** The pBuf element of the returned sqlite3_pcache_page object will be a
7473 ** pointer to a buffer of szPage bytes used to store the content of a
7474 ** single database page. The pExtra element of sqlite3_pcache_page will be
7475 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
7476 ** for each entry in the page cache.
7477 **
7478 ** The page to be fetched is determined by the key. ^The minimum key value
7479 ** is 1. After it has been retrieved using xFetch, the page is considered
7480 ** to be "pinned".
7481 **
7482 ** If the requested page is already in the page cache, then the page cache
7483 ** implementation must return a pointer to the page buffer with its content
7484 ** intact. If the requested page is not already in the cache, then the
7485 ** cache implementation should use the value of the createFlag
7486 ** parameter to help it determined what action to take:
7487 **
7488 ** <table border=1 width=85% align=center>
7489 ** <tr><th> createFlag <th> Behavior when page is not already in cache
7490 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
7491 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7492 ** Otherwise return NULL.
7493 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
7494 ** NULL if allocating a new page is effectively impossible.
7495 ** </table>
7496 **
7497 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
7498 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
7499 ** failed.)^ In between the to xFetch() calls, SQLite may
7500 ** attempt to unpin one or more cache pages by spilling the content of
7501 ** pinned pages to disk and synching the operating system disk cache.
7502 **
7503 ** [[the xUnpin() page cache method]]
7504 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7505 ** as its second argument. If the third parameter, discard, is non-zero,
7506 ** then the page must be evicted from the cache.
7507 ** ^If the discard parameter is
7508 ** zero, then the page may be discarded or retained at the discretion of
7509 ** page cache implementation. ^The page cache implementation
7510 ** may choose to evict unpinned pages at any time.
7511 **
7512 ** The cache must not perform any reference counting. A single
7513 ** call to xUnpin() unpins the page regardless of the number of prior calls
7514 ** to xFetch().
7515 **
7516 ** [[the xRekey() page cache methods]]
7517 ** The xRekey() method is used to change the key value associated with the
7518 ** page passed as the second argument. If the cache
7519 ** previously contains an entry associated with newKey, it must be
7520 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7521 ** to be pinned.
7522 **
7523 ** When SQLite calls the xTruncate() method, the cache must discard all
7524 ** existing cache entries with page numbers (keys) greater than or equal
7525 ** to the value of the iLimit parameter passed to xTruncate(). If any
7526 ** of these pages are pinned, they are implicitly unpinned, meaning that
7527 ** they can be safely discarded.
7528 **
7529 ** [[the xDestroy() page cache method]]
7530 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7531 ** All resources associated with the specified cache should be freed. ^After
7532 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7533 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7534 ** functions.
7535 **
7536 ** [[the xShrink() page cache method]]
7537 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7538 ** free up as much of heap memory as possible. The page cache implementation
7539 ** is not obligated to free any memory, but well-behaved implementations should
7540 ** do their best.
7541 */
7542 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7543 struct sqlite3_pcache_methods2 {
7544  int iVersion;
7545  void *pArg;
7546  int (*xInit)(void*);
7547  void (*xShutdown)(void*);
7548  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7549  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7550  int (*xPagecount)(sqlite3_pcache*);
7551  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7552  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7553  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7554  unsigned oldKey, unsigned newKey);
7555  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7556  void (*xDestroy)(sqlite3_pcache*);
7557  void (*xShrink)(sqlite3_pcache*);
7558 };
7559 
7560 /*
7561 ** This is the obsolete pcache_methods object that has now been replaced
7562 ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
7563 ** retained in the header file for backwards compatibility only.
7564 */
7565 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7566 struct sqlite3_pcache_methods {
7567  void *pArg;
7568  int (*xInit)(void*);
7569  void (*xShutdown)(void*);
7570  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7571  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7572  int (*xPagecount)(sqlite3_pcache*);
7573  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7574  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7575  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7576  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7577  void (*xDestroy)(sqlite3_pcache*);
7578 };
7579 
7580 
7581 /*
7582 ** CAPI3REF: Online Backup Object
7583 **
7584 ** The sqlite3_backup object records state information about an ongoing
7585 ** online backup operation. ^The sqlite3_backup object is created by
7586 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7587 ** [sqlite3_backup_finish()].
7588 **
7589 ** See Also: [Using the SQLite Online Backup API]
7590 */
7591 typedef struct sqlite3_backup sqlite3_backup;
7592 
7593 /*
7594 ** CAPI3REF: Online Backup API.
7595 **
7596 ** The backup API copies the content of one database into another.
7597 ** It is useful either for creating backups of databases or
7598 ** for copying in-memory databases to or from persistent files.
7599 **
7600 ** See Also: [Using the SQLite Online Backup API]
7601 **
7602 ** ^SQLite holds a write transaction open on the destination database file
7603 ** for the duration of the backup operation.
7604 ** ^The source database is read-locked only while it is being read;
7605 ** it is not locked continuously for the entire backup operation.
7606 ** ^Thus, the backup may be performed on a live source database without
7607 ** preventing other database connections from
7608 ** reading or writing to the source database while the backup is underway.
7609 **
7610 ** ^(To perform a backup operation:
7611 ** <ol>
7612 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
7613 ** backup,
7614 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7615 ** the data between the two databases, and finally
7616 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
7617 ** associated with the backup operation.
7618 ** </ol>)^
7619 ** There should be exactly one call to sqlite3_backup_finish() for each
7620 ** successful call to sqlite3_backup_init().
7621 **
7622 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7623 **
7624 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7625 ** [database connection] associated with the destination database
7626 ** and the database name, respectively.
7627 ** ^The database name is "main" for the main database, "temp" for the
7628 ** temporary database, or the name specified after the AS keyword in
7629 ** an [ATTACH] statement for an attached database.
7630 ** ^The S and M arguments passed to
7631 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7632 ** and database name of the source database, respectively.
7633 ** ^The source and destination [database connections] (parameters S and D)
7634 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7635 ** an error.
7636 **
7637 ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
7638 ** there is already a read or read-write transaction open on the
7639 ** destination database.
7640 **
7641 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7642 ** returned and an error code and error message are stored in the
7643 ** destination [database connection] D.
7644 ** ^The error code and message for the failed call to sqlite3_backup_init()
7645 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7646 ** [sqlite3_errmsg16()] functions.
7647 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7648 ** [sqlite3_backup] object.
7649 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7650 ** sqlite3_backup_finish() functions to perform the specified backup
7651 ** operation.
7652 **
7653 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7654 **
7655 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7656 ** the source and destination databases specified by [sqlite3_backup] object B.
7657 ** ^If N is negative, all remaining source pages are copied.
7658 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7659 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7660 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7661 ** from source to destination, then it returns [SQLITE_DONE].
7662 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7663 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7664 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7665 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7666 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7667 **
7668 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7669 ** <ol>
7670 ** <li> the destination database was opened read-only, or
7671 ** <li> the destination database is using write-ahead-log journaling
7672 ** and the destination and source page sizes differ, or
7673 ** <li> the destination database is an in-memory database and the
7674 ** destination and source page sizes differ.
7675 ** </ol>)^
7676 **
7677 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7678 ** the [sqlite3_busy_handler | busy-handler function]
7679 ** is invoked (if one is specified). ^If the
7680 ** busy-handler returns non-zero before the lock is available, then
7681 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7682 ** sqlite3_backup_step() can be retried later. ^If the source
7683 ** [database connection]
7684 ** is being used to write to the source database when sqlite3_backup_step()
7685 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7686 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7687 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7688 ** [SQLITE_READONLY] is returned, then
7689 ** there is no point in retrying the call to sqlite3_backup_step(). These
7690 ** errors are considered fatal.)^ The application must accept
7691 ** that the backup operation has failed and pass the backup operation handle
7692 ** to the sqlite3_backup_finish() to release associated resources.
7693 **
7694 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7695 ** on the destination file. ^The exclusive lock is not released until either
7696 ** sqlite3_backup_finish() is called or the backup operation is complete
7697 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
7698 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7699 ** lasts for the duration of the sqlite3_backup_step() call.
7700 ** ^Because the source database is not locked between calls to
7701 ** sqlite3_backup_step(), the source database may be modified mid-way
7702 ** through the backup process. ^If the source database is modified by an
7703 ** external process or via a database connection other than the one being
7704 ** used by the backup operation, then the backup will be automatically
7705 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7706 ** database is modified by the using the same database connection as is used
7707 ** by the backup operation, then the backup database is automatically
7708 ** updated at the same time.
7709 **
7710 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7711 **
7712 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7713 ** application wishes to abandon the backup operation, the application
7714 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7715 ** ^The sqlite3_backup_finish() interfaces releases all
7716 ** resources associated with the [sqlite3_backup] object.
7717 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7718 ** active write-transaction on the destination database is rolled back.
7719 ** The [sqlite3_backup] object is invalid
7720 ** and may not be used following a call to sqlite3_backup_finish().
7721 **
7722 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7723 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7724 ** sqlite3_backup_step() completed.
7725 ** ^If an out-of-memory condition or IO error occurred during any prior
7726 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7727 ** sqlite3_backup_finish() returns the corresponding [error code].
7728 **
7729 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7730 ** is not a permanent error and does not affect the return value of
7731 ** sqlite3_backup_finish().
7732 **
7733 ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7734 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7735 **
7736 ** ^The sqlite3_backup_remaining() routine returns the number of pages still
7737 ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7738 ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7739 ** in the source database at the conclusion of the most recent
7740 ** sqlite3_backup_step().
7741 ** ^(The values returned by these functions are only updated by
7742 ** sqlite3_backup_step(). If the source database is modified in a way that
7743 ** changes the size of the source database or the number of pages remaining,
7744 ** those changes are not reflected in the output of sqlite3_backup_pagecount()
7745 ** and sqlite3_backup_remaining() until after the next
7746 ** sqlite3_backup_step().)^
7747 **
7748 ** <b>Concurrent Usage of Database Handles</b>
7749 **
7750 ** ^The source [database connection] may be used by the application for other
7751 ** purposes while a backup operation is underway or being initialized.
7752 ** ^If SQLite is compiled and configured to support threadsafe database
7753 ** connections, then the source database connection may be used concurrently
7754 ** from within other threads.
7755 **
7756 ** However, the application must guarantee that the destination
7757 ** [database connection] is not passed to any other API (by any thread) after
7758 ** sqlite3_backup_init() is called and before the corresponding call to
7759 ** sqlite3_backup_finish(). SQLite does not currently check to see
7760 ** if the application incorrectly accesses the destination [database connection]
7761 ** and so no error code is reported, but the operations may malfunction
7762 ** nevertheless. Use of the destination database connection while a
7763 ** backup is in progress might also also cause a mutex deadlock.
7764 **
7765 ** If running in [shared cache mode], the application must
7766 ** guarantee that the shared cache used by the destination database
7767 ** is not accessed while the backup is running. In practice this means
7768 ** that the application must guarantee that the disk file being
7769 ** backed up to is not accessed by any connection within the process,
7770 ** not just the specific connection that was passed to sqlite3_backup_init().
7771 **
7772 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7773 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7774 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7775 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7776 ** same time as another thread is invoking sqlite3_backup_step() it is
7777 ** possible that they return invalid values.
7778 */
7779 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7780  sqlite3 *pDest, /* Destination database handle */
7781  const char *zDestName, /* Destination database name */
7782  sqlite3 *pSource, /* Source database handle */
7783  const char *zSourceName /* Source database name */
7784 );
7785 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7786 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7787 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7788 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7789 
7790 /*
7791 ** CAPI3REF: Unlock Notification
7792 ** METHOD: sqlite3
7793 **
7794 ** ^When running in shared-cache mode, a database operation may fail with
7795 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7796 ** individual tables within the shared-cache cannot be obtained. See
7797 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7798 ** ^This API may be used to register a callback that SQLite will invoke
7799 ** when the connection currently holding the required lock relinquishes it.
7800 ** ^This API is only available if the library was compiled with the
7801 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7802 **
7803 ** See Also: [Using the SQLite Unlock Notification Feature].
7804 **
7805 ** ^Shared-cache locks are released when a database connection concludes
7806 ** its current transaction, either by committing it or rolling it back.
7807 **
7808 ** ^When a connection (known as the blocked connection) fails to obtain a
7809 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7810 ** identity of the database connection (the blocking connection) that
7811 ** has locked the required resource is stored internally. ^After an
7812 ** application receives an SQLITE_LOCKED error, it may call the
7813 ** sqlite3_unlock_notify() method with the blocked connection handle as
7814 ** the first argument to register for a callback that will be invoked
7815 ** when the blocking connections current transaction is concluded. ^The
7816 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7817 ** call that concludes the blocking connections transaction.
7818 **
7819 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7820 ** there is a chance that the blocking connection will have already
7821 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7822 ** If this happens, then the specified callback is invoked immediately,
7823 ** from within the call to sqlite3_unlock_notify().)^
7824 **
7825 ** ^If the blocked connection is attempting to obtain a write-lock on a
7826 ** shared-cache table, and more than one other connection currently holds
7827 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7828 ** the other connections to use as the blocking connection.
7829 **
7830 ** ^(There may be at most one unlock-notify callback registered by a
7831 ** blocked connection. If sqlite3_unlock_notify() is called when the
7832 ** blocked connection already has a registered unlock-notify callback,
7833 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7834 ** called with a NULL pointer as its second argument, then any existing
7835 ** unlock-notify callback is canceled. ^The blocked connections
7836 ** unlock-notify callback may also be canceled by closing the blocked
7837 ** connection using [sqlite3_close()].
7838 **
7839 ** The unlock-notify callback is not reentrant. If an application invokes
7840 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7841 ** crash or deadlock may be the result.
7842 **
7843 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7844 ** returns SQLITE_OK.
7845 **
7846 ** <b>Callback Invocation Details</b>
7847 **
7848 ** When an unlock-notify callback is registered, the application provides a
7849 ** single void* pointer that is passed to the callback when it is invoked.
7850 ** However, the signature of the callback function allows SQLite to pass
7851 ** it an array of void* context pointers. The first argument passed to
7852 ** an unlock-notify callback is a pointer to an array of void* pointers,
7853 ** and the second is the number of entries in the array.
7854 **
7855 ** When a blocking connections transaction is concluded, there may be
7856 ** more than one blocked connection that has registered for an unlock-notify
7857 ** callback. ^If two or more such blocked connections have specified the
7858 ** same callback function, then instead of invoking the callback function
7859 ** multiple times, it is invoked once with the set of void* context pointers
7860 ** specified by the blocked connections bundled together into an array.
7861 ** This gives the application an opportunity to prioritize any actions
7862 ** related to the set of unblocked database connections.
7863 **
7864 ** <b>Deadlock Detection</b>
7865 **
7866 ** Assuming that after registering for an unlock-notify callback a
7867 ** database waits for the callback to be issued before taking any further
7868 ** action (a reasonable assumption), then using this API may cause the
7869 ** application to deadlock. For example, if connection X is waiting for
7870 ** connection Y's transaction to be concluded, and similarly connection
7871 ** Y is waiting on connection X's transaction, then neither connection
7872 ** will proceed and the system may remain deadlocked indefinitely.
7873 **
7874 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7875 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7876 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7877 ** unlock-notify callback is registered. The system is said to be in
7878 ** a deadlocked state if connection A has registered for an unlock-notify
7879 ** callback on the conclusion of connection B's transaction, and connection
7880 ** B has itself registered for an unlock-notify callback when connection
7881 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7882 ** the system is also considered to be deadlocked if connection B has
7883 ** registered for an unlock-notify callback on the conclusion of connection
7884 ** C's transaction, where connection C is waiting on connection A. ^Any
7885 ** number of levels of indirection are allowed.
7886 **
7887 ** <b>The "DROP TABLE" Exception</b>
7888 **
7889 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7890 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7891 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7892 ** SQLite checks if there are any currently executing SELECT statements
7893 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7894 ** returned. In this case there is no "blocking connection", so invoking
7895 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7896 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7897 ** or "DROP INDEX" query, an infinite loop might be the result.
7898 **
7899 ** One way around this problem is to check the extended error code returned
7900 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7901 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7902 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7903 ** SQLITE_LOCKED.)^
7904 */
7905 SQLITE_API int sqlite3_unlock_notify(
7906  sqlite3 *pBlocked, /* Waiting connection */
7907  void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
7908  void *pNotifyArg /* Argument to pass to xNotify */
7909 );
7910 
7911 
7912 /*
7913 ** CAPI3REF: String Comparison
7914 **
7915 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7916 ** and extensions to compare the contents of two buffers containing UTF-8
7917 ** strings in a case-independent fashion, using the same definition of "case
7918 ** independence" that SQLite uses internally when comparing identifiers.
7919 */
7920 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7921 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7922 
7923 /*
7924 ** CAPI3REF: String Globbing
7925 *
7926 ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
7927 ** string X matches the [GLOB] pattern P.
7928 ** ^The definition of [GLOB] pattern matching used in
7929 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7930 ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
7931 ** is case sensitive.
7932 **
7933 ** Note that this routine returns zero on a match and non-zero if the strings
7934 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7935 **
7936 ** See also: [sqlite3_strlike()].
7937 */
7938 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7939 
7940 /*
7941 ** CAPI3REF: String LIKE Matching
7942 *
7943 ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
7944 ** string X matches the [LIKE] pattern P with escape character E.
7945 ** ^The definition of [LIKE] pattern matching used in
7946 ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
7947 ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
7948 ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
7949 ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
7950 ** insensitive - equivalent upper and lower case ASCII characters match
7951 ** one another.
7952 **
7953 ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
7954 ** only ASCII characters are case folded.
7955 **
7956 ** Note that this routine returns zero on a match and non-zero if the strings
7957 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7958 **
7959 ** See also: [sqlite3_strglob()].
7960 */
7961 SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
7962 
7963 /*
7964 ** CAPI3REF: Error Logging Interface
7965 **
7966 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7967 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7968 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7969 ** used with [sqlite3_snprintf()] to generate the final output string.
7970 **
7971 ** The sqlite3_log() interface is intended for use by extensions such as
7972 ** virtual tables, collating functions, and SQL functions. While there is
7973 ** nothing to prevent an application from calling sqlite3_log(), doing so
7974 ** is considered bad form.
7975 **
7976 ** The zFormat string must not be NULL.
7977 **
7978 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7979 ** will not use dynamically allocated memory. The log message is stored in
7980 ** a fixed-length buffer on the stack. If the log message is longer than
7981 ** a few hundred characters, it will be truncated to the length of the
7982 ** buffer.
7983 */
7984 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7985 
7986 /*
7987 ** CAPI3REF: Write-Ahead Log Commit Hook
7988 ** METHOD: sqlite3
7989 **
7990 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7991 ** is invoked each time data is committed to a database in wal mode.
7992 **
7993 ** ^(The callback is invoked by SQLite after the commit has taken place and
7994 ** the associated write-lock on the database released)^, so the implementation
7995 ** may read, write or [checkpoint] the database as required.
7996 **
7997 ** ^The first parameter passed to the callback function when it is invoked
7998 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7999 ** registering the callback. ^The second is a copy of the database handle.
8000 ** ^The third parameter is the name of the database that was written to -
8001 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
8002 ** is the number of pages currently in the write-ahead log file,
8003 ** including those that were just committed.
8004 **
8005 ** The callback function should normally return [SQLITE_OK]. ^If an error
8006 ** code is returned, that error will propagate back up through the
8007 ** SQLite code base to cause the statement that provoked the callback
8008 ** to report an error, though the commit will have still occurred. If the
8009 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
8010 ** that does not correspond to any valid SQLite error code, the results
8011 ** are undefined.
8012 **
8013 ** A single database handle may have at most a single write-ahead log callback
8014 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
8015 ** previously registered write-ahead log callback. ^Note that the
8016 ** [sqlite3_wal_autocheckpoint()] interface and the
8017 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
8018 ** overwrite any prior [sqlite3_wal_hook()] settings.
8019 */
8020 SQLITE_API void *sqlite3_wal_hook(
8021  sqlite3*,
8022  int(*)(void *,sqlite3*,const char*,int),
8023  void*
8024 );
8025 
8026 /*
8027 ** CAPI3REF: Configure an auto-checkpoint
8028 ** METHOD: sqlite3
8029 **
8030 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
8031 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
8032 ** to automatically [checkpoint]
8033 ** after committing a transaction if there are N or
8034 ** more frames in the [write-ahead log] file. ^Passing zero or
8035 ** a negative value as the nFrame parameter disables automatic
8036 ** checkpoints entirely.
8037 **
8038 ** ^The callback registered by this function replaces any existing callback
8039 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
8040 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
8041 ** configured by this function.
8042 **
8043 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
8044 ** from SQL.
8045 **
8046 ** ^Checkpoints initiated by this mechanism are
8047 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
8048 **
8049 ** ^Every new [database connection] defaults to having the auto-checkpoint
8050 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
8051 ** pages. The use of this interface
8052 ** is only necessary if the default setting is found to be suboptimal
8053 ** for a particular application.
8054 */
8055 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
8056 
8057 /*
8058 ** CAPI3REF: Checkpoint a database
8059 ** METHOD: sqlite3
8060 **
8061 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
8062 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
8063 **
8064 ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
8065 ** [write-ahead log] for database X on [database connection] D to be
8066 ** transferred into the database file and for the write-ahead log to
8067 ** be reset. See the [checkpointing] documentation for addition
8068 ** information.
8069 **
8070 ** This interface used to be the only way to cause a checkpoint to
8071 ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
8072 ** interface was added. This interface is retained for backwards
8073 ** compatibility and as a convenience for applications that need to manually
8074 ** start a callback but which do not need the full power (and corresponding
8075 ** complication) of [sqlite3_wal_checkpoint_v2()].
8076 */
8077 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
8078 
8079 /*
8080 ** CAPI3REF: Checkpoint a database
8081 ** METHOD: sqlite3
8082 **
8083 ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
8084 ** operation on database X of [database connection] D in mode M. Status
8085 ** information is written back into integers pointed to by L and C.)^
8086 ** ^(The M parameter must be a valid [checkpoint mode]:)^
8087 **
8088 ** <dl>
8089 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
8090 ** ^Checkpoint as many frames as possible without waiting for any database
8091 ** readers or writers to finish, then sync the database file if all frames
8092 ** in the log were checkpointed. ^The [busy-handler callback]
8093 ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
8094 ** ^On the other hand, passive mode might leave the checkpoint unfinished
8095 ** if there are concurrent readers or writers.
8096 **
8097 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
8098 ** ^This mode blocks (it invokes the
8099 ** [sqlite3_busy_handler|busy-handler callback]) until there is no
8100 ** database writer and all readers are reading from the most recent database
8101 ** snapshot. ^It then checkpoints all frames in the log file and syncs the
8102 ** database file. ^This mode blocks new database writers while it is pending,
8103 ** but new database readers are allowed to continue unimpeded.
8104 **
8105 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
8106 ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
8107 ** that after checkpointing the log file it blocks (calls the
8108 ** [busy-handler callback])
8109 ** until all readers are reading from the database file only. ^This ensures
8110 ** that the next writer will restart the log file from the beginning.
8111 ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
8112 ** database writer attempts while it is pending, but does not impede readers.
8113 **
8114 ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
8115 ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
8116 ** addition that it also truncates the log file to zero bytes just prior
8117 ** to a successful return.
8118 ** </dl>
8119 **
8120 ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
8121 ** the log file or to -1 if the checkpoint could not run because
8122 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
8123 ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
8124 ** log file (including any that were already checkpointed before the function
8125 ** was called) or to -1 if the checkpoint could not run due to an error or
8126 ** because the database is not in WAL mode. ^Note that upon successful
8127 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
8128 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
8129 **
8130 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
8131 ** any other process is running a checkpoint operation at the same time, the
8132 ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
8133 ** busy-handler configured, it will not be invoked in this case.
8134 **
8135 ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
8136 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
8137 ** obtained immediately, and a busy-handler is configured, it is invoked and
8138 ** the writer lock retried until either the busy-handler returns 0 or the lock
8139 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
8140 ** database readers as described above. ^If the busy-handler returns 0 before
8141 ** the writer lock is obtained or while waiting for database readers, the
8142 ** checkpoint operation proceeds from that point in the same way as
8143 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
8144 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
8145 **
8146 ** ^If parameter zDb is NULL or points to a zero length string, then the
8147 ** specified operation is attempted on all WAL databases [attached] to
8148 ** [database connection] db. In this case the
8149 ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
8150 ** an SQLITE_BUSY error is encountered when processing one or more of the
8151 ** attached WAL databases, the operation is still attempted on any remaining
8152 ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
8153 ** error occurs while processing an attached database, processing is abandoned
8154 ** and the error code is returned to the caller immediately. ^If no error
8155 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
8156 ** databases, SQLITE_OK is returned.
8157 **
8158 ** ^If database zDb is the name of an attached database that is not in WAL
8159 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
8160 ** zDb is not NULL (or a zero length string) and is not the name of any
8161 ** attached database, SQLITE_ERROR is returned to the caller.
8162 **
8163 ** ^Unless it returns SQLITE_MISUSE,
8164 ** the sqlite3_wal_checkpoint_v2() interface
8165 ** sets the error information that is queried by
8166 ** [sqlite3_errcode()] and [sqlite3_errmsg()].
8167 **
8168 ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
8169 ** from SQL.
8170 */
8171 SQLITE_API int sqlite3_wal_checkpoint_v2(
8172  sqlite3 *db, /* Database handle */
8173  const char *zDb, /* Name of attached database (or NULL) */
8174  int eMode, /* SQLITE_CHECKPOINT_* value */
8175  int *pnLog, /* OUT: Size of WAL log in frames */
8176  int *pnCkpt /* OUT: Total number of frames checkpointed */
8177 );
8178 
8179 /*
8180 ** CAPI3REF: Checkpoint Mode Values
8181 ** KEYWORDS: {checkpoint mode}
8182 **
8183 ** These constants define all valid values for the "checkpoint mode" passed
8184 ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
8185 ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
8186 ** meaning of each of these checkpoint modes.
8187 */
8188 #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
8189 #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
8190 #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
8191 #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
8192 
8193 /*
8194 ** CAPI3REF: Virtual Table Interface Configuration
8195 **
8196 ** This function may be called by either the [xConnect] or [xCreate] method
8197 ** of a [virtual table] implementation to configure
8198 ** various facets of the virtual table interface.
8199 **
8200 ** If this interface is invoked outside the context of an xConnect or
8201 ** xCreate virtual table method then the behavior is undefined.
8202 **
8203 ** At present, there is only one option that may be configured using
8204 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
8205 ** may be added in the future.
8206 */
8207 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
8208 
8209 /*
8210 ** CAPI3REF: Virtual Table Configuration Options
8211 **
8212 ** These macros define the various options to the
8213 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
8214 ** can use to customize and optimize their behavior.
8215 **
8216 ** <dl>
8217 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
8218 ** <dd>Calls of the form
8219 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
8220 ** where X is an integer. If X is zero, then the [virtual table] whose
8221 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
8222 ** support constraints. In this configuration (which is the default) if
8223 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
8224 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
8225 ** specified as part of the users SQL statement, regardless of the actual
8226 ** ON CONFLICT mode specified.
8227 **
8228 ** If X is non-zero, then the virtual table implementation guarantees
8229 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
8230 ** any modifications to internal or persistent data structures have been made.
8231 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
8232 ** is able to roll back a statement or database transaction, and abandon
8233 ** or continue processing the current SQL statement as appropriate.
8234 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
8235 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
8236 ** had been ABORT.
8237 **
8238 ** Virtual table implementations that are required to handle OR REPLACE
8239 ** must do so within the [xUpdate] method. If a call to the
8240 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
8241 ** CONFLICT policy is REPLACE, the virtual table implementation should
8242 ** silently replace the appropriate rows within the xUpdate callback and
8243 ** return SQLITE_OK. Or, if this is not possible, it may return
8244 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
8245 ** constraint handling.
8246 ** </dl>
8247 */
8248 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
8249 
8250 /*
8251 ** CAPI3REF: Determine The Virtual Table Conflict Policy
8252 **
8253 ** This function may only be called from within a call to the [xUpdate] method
8254 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
8255 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
8256 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
8257 ** of the SQL statement that triggered the call to the [xUpdate] method of the
8258 ** [virtual table].
8259 */
8260 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
8261 
8262 /*
8263 ** CAPI3REF: Conflict resolution modes
8264 ** KEYWORDS: {conflict resolution mode}
8265 **
8266 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
8267 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
8268 ** is for the SQL statement being evaluated.
8269 **
8270 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
8271 ** return value from the [sqlite3_set_authorizer()] callback and that
8272 ** [SQLITE_ABORT] is also a [result code].
8273 */
8274 #define SQLITE_ROLLBACK 1
8275 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
8276 #define SQLITE_FAIL 3
8277 /* #define SQLITE_ABORT 4 // Also an error code */
8278 #define SQLITE_REPLACE 5
8279 
8280 /*
8281 ** CAPI3REF: Prepared Statement Scan Status Opcodes
8282 ** KEYWORDS: {scanstatus options}
8283 **
8284 ** The following constants can be used for the T parameter to the
8285 ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
8286 ** different metric for sqlite3_stmt_scanstatus() to return.
8287 **
8288 ** When the value returned to V is a string, space to hold that string is
8289 ** managed by the prepared statement S and will be automatically freed when
8290 ** S is finalized.
8291 **
8292 ** <dl>
8293 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
8294 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
8295 ** set to the total number of times that the X-th loop has run.</dd>
8296 **
8297 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
8298 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
8299 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
8300 **
8301 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
8302 ** <dd>^The "double" variable pointed to by the T parameter will be set to the
8303 ** query planner's estimate for the average number of rows output from each
8304 ** iteration of the X-th loop. If the query planner's estimates was accurate,
8305 ** then this value will approximate the quotient NVISIT/NLOOP and the
8306 ** product of this value for all prior loops with the same SELECTID will
8307 ** be the NLOOP value for the current loop.
8308 **
8309 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
8310 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8311 ** to a zero-terminated UTF-8 string containing the name of the index or table
8312 ** used for the X-th loop.
8313 **
8314 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
8315 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8316 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
8317 ** description for the X-th loop.
8318 **
8319 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
8320 ** <dd>^The "int" variable pointed to by the T parameter will be set to the
8321 ** "select-id" for the X-th loop. The select-id identifies which query or
8322 ** subquery the loop is part of. The main query has a select-id of zero.
8323 ** The select-id is the same value as is output in the first column
8324 ** of an [EXPLAIN QUERY PLAN] query.
8325 ** </dl>
8326 */
8327 #define SQLITE_SCANSTAT_NLOOP 0
8328 #define SQLITE_SCANSTAT_NVISIT 1
8329 #define SQLITE_SCANSTAT_EST 2
8330 #define SQLITE_SCANSTAT_NAME 3
8331 #define SQLITE_SCANSTAT_EXPLAIN 4
8332 #define SQLITE_SCANSTAT_SELECTID 5
8333 
8334 /*
8335 ** CAPI3REF: Prepared Statement Scan Status
8336 ** METHOD: sqlite3_stmt
8337 **
8338 ** This interface returns information about the predicted and measured
8339 ** performance for pStmt. Advanced applications can use this
8340 ** interface to compare the predicted and the measured performance and
8341 ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
8342 **
8343 ** Since this interface is expected to be rarely used, it is only
8344 ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
8345 ** compile-time option.
8346 **
8347 ** The "iScanStatusOp" parameter determines which status information to return.
8348 ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
8349 ** of this interface is undefined.
8350 ** ^The requested measurement is written into a variable pointed to by
8351 ** the "pOut" parameter.
8352 ** Parameter "idx" identifies the specific loop to retrieve statistics for.
8353 ** Loops are numbered starting from zero. ^If idx is out of range - less than
8354 ** zero or greater than or equal to the total number of loops used to implement
8355 ** the statement - a non-zero value is returned and the variable that pOut
8356 ** points to is unchanged.
8357 **
8358 ** ^Statistics might not be available for all loops in all statements. ^In cases
8359 ** where there exist loops with no available statistics, this function behaves
8360 ** as if the loop did not exist - it returns non-zero and leave the variable
8361 ** that pOut points to unchanged.
8362 **
8363 ** See also: [sqlite3_stmt_scanstatus_reset()]
8364 */
8365 SQLITE_API int sqlite3_stmt_scanstatus(
8366  sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
8367  int idx, /* Index of loop to report on */
8368  int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
8369  void *pOut /* Result written here */
8370 );
8371 
8372 /*
8373 ** CAPI3REF: Zero Scan-Status Counters
8374 ** METHOD: sqlite3_stmt
8375 **
8376 ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
8377 **
8378 ** This API is only available if the library is built with pre-processor
8379 ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
8380 */
8381 SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
8382 
8383 /*
8384 ** CAPI3REF: Flush caches to disk mid-transaction
8385 **
8386 ** ^If a write-transaction is open on [database connection] D when the
8387 ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
8388 ** pages in the pager-cache that are not currently in use are written out
8389 ** to disk. A dirty page may be in use if a database cursor created by an
8390 ** active SQL statement is reading from it, or if it is page 1 of a database
8391 ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
8392 ** interface flushes caches for all schemas - "main", "temp", and
8393 ** any [attached] databases.
8394 **
8395 ** ^If this function needs to obtain extra database locks before dirty pages
8396 ** can be flushed to disk, it does so. ^If those locks cannot be obtained
8397 ** immediately and there is a busy-handler callback configured, it is invoked
8398 ** in the usual manner. ^If the required lock still cannot be obtained, then
8399 ** the database is skipped and an attempt made to flush any dirty pages
8400 ** belonging to the next (if any) database. ^If any databases are skipped
8401 ** because locks cannot be obtained, but no other error occurs, this
8402 ** function returns SQLITE_BUSY.
8403 **
8404 ** ^If any other error occurs while flushing dirty pages to disk (for
8405 ** example an IO error or out-of-memory condition), then processing is
8406 ** abandoned and an SQLite [error code] is returned to the caller immediately.
8407 **
8408 ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
8409 **
8410 ** ^This function does not set the database handle error code or message
8411 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
8412 */
8413 SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
8414 
8415 /*
8416 ** CAPI3REF: The pre-update hook.
8417 **
8418 ** ^These interfaces are only available if SQLite is compiled using the
8419 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
8420 **
8421 ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
8422 ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
8423 ** on a [rowid table].
8424 ** ^At most one preupdate hook may be registered at a time on a single
8425 ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
8426 ** the previous setting.
8427 ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
8428 ** with a NULL pointer as the second parameter.
8429 ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
8430 ** the first parameter to callbacks.
8431 **
8432 ** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
8433 ** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
8434 ** tables.
8435 **
8436 ** ^The second parameter to the preupdate callback is a pointer to
8437 ** the [database connection] that registered the preupdate hook.
8438 ** ^The third parameter to the preupdate callback is one of the constants
8439 ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
8440 ** kind of update operation that is about to occur.
8441 ** ^(The fourth parameter to the preupdate callback is the name of the
8442 ** database within the database connection that is being modified. This
8443 ** will be "main" for the main database or "temp" for TEMP tables or
8444 ** the name given after the AS keyword in the [ATTACH] statement for attached
8445 ** databases.)^
8446 ** ^The fifth parameter to the preupdate callback is the name of the
8447 ** table that is being modified.
8448 ** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
8449 ** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
8450 ** undefined for SQLITE_INSERT changes.
8451 ** ^The seventh parameter to the preupdate callback is the final [rowid] of
8452 ** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
8453 ** undefined for SQLITE_DELETE changes.
8454 **
8455 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
8456 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
8457 ** provide additional information about a preupdate event. These routines
8458 ** may only be called from within a preupdate callback. Invoking any of
8459 ** these routines from outside of a preupdate callback or with a
8460 ** [database connection] pointer that is different from the one supplied
8461 ** to the preupdate callback results in undefined and probably undesirable
8462 ** behavior.
8463 **
8464 ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8465 ** in the row that is being inserted, updated, or deleted.
8466 **
8467 ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8468 ** a [protected sqlite3_value] that contains the value of the Nth column of
8469 ** the table row before it is updated. The N parameter must be between 0
8470 ** and one less than the number of columns or the behavior will be
8471 ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8472 ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8473 ** behavior is undefined. The [sqlite3_value] that P points to
8474 ** will be destroyed when the preupdate callback returns.
8475 **
8476 ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8477 ** a [protected sqlite3_value] that contains the value of the Nth column of
8478 ** the table row after it is updated. The N parameter must be between 0
8479 ** and one less than the number of columns or the behavior will be
8480 ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8481 ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8482 ** behavior is undefined. The [sqlite3_value] that P points to
8483 ** will be destroyed when the preupdate callback returns.
8484 **
8485 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8486 ** callback was invoked as a result of a direct insert, update, or delete
8487 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
8488 ** triggers; or 2 for changes resulting from triggers called by top-level
8489 ** triggers; and so forth.
8490 **
8491 ** See also: [sqlite3_update_hook()]
8492 */
8493 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_preupdate_hook(
8494  sqlite3 *db,
8495  void(*xPreUpdate)(
8496  void *pCtx, /* Copy of third arg to preupdate_hook() */
8497  sqlite3 *db, /* Database handle */
8498  int op, /* SQLITE_UPDATE, DELETE or INSERT */
8499  char const *zDb, /* Database name */
8500  char const *zName, /* Table name */
8501  sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
8502  sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
8503  ),
8504  void*
8505 );
8506 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
8507 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_count(sqlite3 *);
8508 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_depth(sqlite3 *);
8509 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
8510 
8511 /*
8512 ** CAPI3REF: Low-level system error code
8513 **
8514 ** ^Attempt to return the underlying operating system error code or error
8515 ** number that caused the most recent I/O error or failure to open a file.
8516 ** The return value is OS-dependent. For example, on unix systems, after
8517 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
8518 ** called to get back the underlying "errno" that caused the problem, such
8519 ** as ENOSPC, EAUTH, EISDIR, and so forth.
8520 */
8521 SQLITE_API int sqlite3_system_errno(sqlite3*);
8522 
8523 /*
8524 ** CAPI3REF: Database Snapshot
8525 ** KEYWORDS: {snapshot}
8526 ** EXPERIMENTAL
8527 **
8528 ** An instance of the snapshot object records the state of a [WAL mode]
8529 ** database for some specific point in history.
8530 **
8531 ** In [WAL mode], multiple [database connections] that are open on the
8532 ** same database file can each be reading a different historical version
8533 ** of the database file. When a [database connection] begins a read
8534 ** transaction, that connection sees an unchanging copy of the database
8535 ** as it existed for the point in time when the transaction first started.
8536 ** Subsequent changes to the database from other connections are not seen
8537 ** by the reader until a new read transaction is started.
8538 **
8539 ** The sqlite3_snapshot object records state information about an historical
8540 ** version of the database file so that it is possible to later open a new read
8541 ** transaction that sees that historical version of the database rather than
8542 ** the most recent version.
8543 **
8544 ** The constructor for this object is [sqlite3_snapshot_get()]. The
8545 ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
8546 ** to an historical snapshot (if possible). The destructor for
8547 ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
8548 */
8549 typedef struct sqlite3_snapshot sqlite3_snapshot;
8550 
8551 /*
8552 ** CAPI3REF: Record A Database Snapshot
8553 ** EXPERIMENTAL
8554 **
8555 ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
8556 ** new [sqlite3_snapshot] object that records the current state of
8557 ** schema S in database connection D. ^On success, the
8558 ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
8559 ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
8560 ** ^If schema S of [database connection] D is not a [WAL mode] database
8561 ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)]
8562 ** leaves the *P value unchanged and returns an appropriate [error code].
8563 **
8564 ** The [sqlite3_snapshot] object returned from a successful call to
8565 ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
8566 ** to avoid a memory leak.
8567 **
8568 ** The [sqlite3_snapshot_get()] interface is only available when the
8569 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8570 */
8571 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
8572  sqlite3 *db,
8573  const char *zSchema,
8574  sqlite3_snapshot **ppSnapshot
8575 );
8576 
8577 /*
8578 ** CAPI3REF: Start a read transaction on an historical snapshot
8579 ** EXPERIMENTAL
8580 **
8581 ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8582 ** read transaction for schema S of
8583 ** [database connection] D such that the read transaction
8584 ** refers to historical [snapshot] P, rather than the most
8585 ** recent change to the database.
8586 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8587 ** or an appropriate [error code] if it fails.
8588 **
8589 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8590 ** the first operation following the [BEGIN] that takes the schema S
8591 ** out of [autocommit mode].
8592 ** ^In other words, schema S must not currently be in
8593 ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8594 ** database connection D must be out of [autocommit mode].
8595 ** ^A [snapshot] will fail to open if it has been overwritten by a
8596 ** [checkpoint].
8597 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8598 ** database connection D does not know that the database file for
8599 ** schema S is in [WAL mode]. A database connection might not know
8600 ** that the database file is in [WAL mode] if there has been no prior
8601 ** I/O on that database connection, or if the database entered [WAL mode]
8602 ** after the most recent I/O on the database connection.)^
8603 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
8604 ** database connection in order to make it ready to use snapshots.)
8605 **
8606 ** The [sqlite3_snapshot_open()] interface is only available when the
8607 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8608 */
8609 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
8610  sqlite3 *db,
8611  const char *zSchema,
8612  sqlite3_snapshot *pSnapshot
8613 );
8614 
8615 /*
8616 ** CAPI3REF: Destroy a snapshot
8617 ** EXPERIMENTAL
8618 **
8619 ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
8620 ** The application must eventually free every [sqlite3_snapshot] object
8621 ** using this routine to avoid a memory leak.
8622 **
8623 ** The [sqlite3_snapshot_free()] interface is only available when the
8624 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8625 */
8626 SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
8627 
8628 /*
8629 ** CAPI3REF: Compare the ages of two snapshot handles.
8630 ** EXPERIMENTAL
8631 **
8632 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8633 ** of two valid snapshot handles.
8634 **
8635 ** If the two snapshot handles are not associated with the same database
8636 ** file, the result of the comparison is undefined.
8637 **
8638 ** Additionally, the result of the comparison is only valid if both of the
8639 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8640 ** last time the wal file was deleted. The wal file is deleted when the
8641 ** database is changed back to rollback mode or when the number of database
8642 ** clients drops to zero. If either snapshot handle was obtained before the
8643 ** wal file was last deleted, the value returned by this function
8644 ** is undefined.
8645 **
8646 ** Otherwise, this API returns a negative value if P1 refers to an older
8647 ** snapshot than P2, zero if the two handles refer to the same database
8648 ** snapshot, and a positive value if P1 is a newer snapshot than P2.
8649 */
8650 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
8651  sqlite3_snapshot *p1,
8652  sqlite3_snapshot *p2
8653 );
8654 
8655 /*
8656 ** Undo the hack that converts floating point types to integer for
8657 ** builds on processors without floating point support.
8658 */
8659 #ifdef SQLITE_OMIT_FLOATING_POINT
8660 # undef double
8661 #endif
8662 
8663 #if 0
8664 } /* End of the 'extern "C"' block */
8665 #endif
8666 #endif /* SQLITE3_H */
8667 
8668 /******** Begin file sqlite3rtree.h *********/
8669 /*
8670 ** 2010 August 30
8671 **
8672 ** The author disclaims copyright to this source code. In place of
8673 ** a legal notice, here is a blessing:
8674 **
8675 ** May you do good and not evil.
8676 ** May you find forgiveness for yourself and forgive others.
8677 ** May you share freely, never taking more than you give.
8678 **
8679 *************************************************************************
8680 */
8681 
8682 #ifndef _SQLITE3RTREE_H_
8683 #define _SQLITE3RTREE_H_
8684 
8685 
8686 #if 0
8687 extern "C" {
8688 #endif
8689 
8690 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
8691 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
8692 
8693 /* The double-precision datatype used by RTree depends on the
8694 ** SQLITE_RTREE_INT_ONLY compile-time option.
8695 */
8696 #ifdef SQLITE_RTREE_INT_ONLY
8697  typedef sqlite3_int64 sqlite3_rtree_dbl;
8698 #else
8699  typedef double sqlite3_rtree_dbl;
8700 #endif
8701 
8702 /*
8703 ** Register a geometry callback named zGeom that can be used as part of an
8704 ** R-Tree geometry query as follows:
8705 **
8706 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
8707 */
8708 SQLITE_API int sqlite3_rtree_geometry_callback(
8709  sqlite3 *db,
8710  const char *zGeom,
8711  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
8712  void *pContext
8713 );
8714 
8715 
8716 /*
8717 ** A pointer to a structure of the following type is passed as the first
8718 ** argument to callbacks registered using rtree_geometry_callback().
8719 */
8720 struct sqlite3_rtree_geometry {
8721  void *pContext; /* Copy of pContext passed to s_r_g_c() */
8722  int nParam; /* Size of array aParam[] */
8723  sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
8724  void *pUser; /* Callback implementation user data */
8725  void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
8726 };
8727 
8728 /*
8729 ** Register a 2nd-generation geometry callback named zScore that can be
8730 ** used as part of an R-Tree geometry query as follows:
8731 **
8732 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
8733 */
8734 SQLITE_API int sqlite3_rtree_query_callback(
8735  sqlite3 *db,
8736  const char *zQueryFunc,
8737  int (*xQueryFunc)(sqlite3_rtree_query_info*),
8738  void *pContext,
8739  void (*xDestructor)(void*)
8740 );
8741 
8742 
8743 /*
8744 ** A pointer to a structure of the following type is passed as the
8745 ** argument to scored geometry callback registered using
8746 ** sqlite3_rtree_query_callback().
8747 **
8748 ** Note that the first 5 fields of this structure are identical to
8749 ** sqlite3_rtree_geometry. This structure is a subclass of
8750 ** sqlite3_rtree_geometry.
8751 */
8752 struct sqlite3_rtree_query_info {
8753  void *pContext; /* pContext from when function registered */
8754  int nParam; /* Number of function parameters */
8755  sqlite3_rtree_dbl *aParam; /* value of function parameters */
8756  void *pUser; /* callback can use this, if desired */
8757  void (*xDelUser)(void*); /* function to free pUser */
8758  sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
8759  unsigned int *anQueue; /* Number of pending entries in the queue */
8760  int nCoord; /* Number of coordinates */
8761  int iLevel; /* Level of current node or entry */
8762  int mxLevel; /* The largest iLevel value in the tree */
8763  sqlite3_int64 iRowid; /* Rowid for current entry */
8764  sqlite3_rtree_dbl rParentScore; /* Score of parent node */
8765  int eParentWithin; /* Visibility of parent node */
8766  int eWithin; /* OUT: Visiblity */
8767  sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
8768  /* The following fields are only available in 3.8.11 and later */
8769  sqlite3_value **apSqlParam; /* Original SQL values of parameters */
8770 };
8771 
8772 /*
8773 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
8774 */
8775 #define NOT_WITHIN 0 /* Object completely outside of query region */
8776 #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
8777 #define FULLY_WITHIN 2 /* Object fully contained within query region */
8778 
8779 
8780 #if 0
8781 } /* end of the 'extern "C"' block */
8782 #endif
8783 
8784 #endif /* ifndef _SQLITE3RTREE_H_ */
8785 
8786 /******** End of sqlite3rtree.h *********/
8787 /******** Begin file sqlite3session.h *********/
8788 
8789 #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8790 #define __SQLITESESSION_H_ 1
8791 
8792 /*
8793 ** Make sure we can call this stuff from C++.
8794 */
8795 #if 0
8796 extern "C" {
8797 #endif
8798 
8799 
8800 /*
8801 ** CAPI3REF: Session Object Handle
8802 */
8803 typedef struct sqlite3_session sqlite3_session;
8804 
8805 /*
8806 ** CAPI3REF: Changeset Iterator Handle
8807 */
8808 typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8809 
8810 /*
8811 ** CAPI3REF: Create A New Session Object
8812 **
8813 ** Create a new session object attached to database handle db. If successful,
8814 ** a pointer to the new object is written to *ppSession and SQLITE_OK is
8815 ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8816 ** error code (e.g. SQLITE_NOMEM) is returned.
8817 **
8818 ** It is possible to create multiple session objects attached to a single
8819 ** database handle.
8820 **
8821 ** Session objects created using this function should be deleted using the
8822 ** [sqlite3session_delete()] function before the database handle that they
8823 ** are attached to is itself closed. If the database handle is closed before
8824 ** the session object is deleted, then the results of calling any session
8825 ** module function, including [sqlite3session_delete()] on the session object
8826 ** are undefined.
8827 **
8828 ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8829 ** is not possible for an application to register a pre-update hook on a
8830 ** database handle that has one or more session objects attached. Nor is
8831 ** it possible to create a session object attached to a database handle for
8832 ** which a pre-update hook is already defined. The results of attempting
8833 ** either of these things are undefined.
8834 **
8835 ** The session object will be used to create changesets for tables in
8836 ** database zDb, where zDb is either "main", or "temp", or the name of an
8837 ** attached database. It is not an error if database zDb is not attached
8838 ** to the database when the session object is created.
8839 */
8840 int sqlite3session_create(
8841  sqlite3 *db, /* Database handle */
8842  const char *zDb, /* Name of db (e.g. "main") */
8843  sqlite3_session **ppSession /* OUT: New session object */
8844 );
8845 
8846 /*
8847 ** CAPI3REF: Delete A Session Object
8848 **
8849 ** Delete a session object previously allocated using
8850 ** [sqlite3session_create()]. Once a session object has been deleted, the
8851 ** results of attempting to use pSession with any other session module
8852 ** function are undefined.
8853 **
8854 ** Session objects must be deleted before the database handle to which they
8855 ** are attached is closed. Refer to the documentation for
8856 ** [sqlite3session_create()] for details.
8857 */
8858 void sqlite3session_delete(sqlite3_session *pSession);
8859 
8860 
8861 /*
8862 ** CAPI3REF: Enable Or Disable A Session Object
8863 **
8864 ** Enable or disable the recording of changes by a session object. When
8865 ** enabled, a session object records changes made to the database. When
8866 ** disabled - it does not. A newly created session object is enabled.
8867 ** Refer to the documentation for [sqlite3session_changeset()] for further
8868 ** details regarding how enabling and disabling a session object affects
8869 ** the eventual changesets.
8870 **
8871 ** Passing zero to this function disables the session. Passing a value
8872 ** greater than zero enables it. Passing a value less than zero is a
8873 ** no-op, and may be used to query the current state of the session.
8874 **
8875 ** The return value indicates the final state of the session object: 0 if
8876 ** the session is disabled, or 1 if it is enabled.
8877 */
8878 int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8879 
8880 /*
8881 ** CAPI3REF: Set Or Clear the Indirect Change Flag
8882 **
8883 ** Each change recorded by a session object is marked as either direct or
8884 ** indirect. A change is marked as indirect if either:
8885 **
8886 ** <ul>
8887 ** <li> The session object "indirect" flag is set when the change is
8888 ** made, or
8889 ** <li> The change is made by an SQL trigger or foreign key action
8890 ** instead of directly as a result of a users SQL statement.
8891 ** </ul>
8892 **
8893 ** If a single row is affected by more than one operation within a session,
8894 ** then the change is considered indirect if all operations meet the criteria
8895 ** for an indirect change above, or direct otherwise.
8896 **
8897 ** This function is used to set, clear or query the session object indirect
8898 ** flag. If the second argument passed to this function is zero, then the
8899 ** indirect flag is cleared. If it is greater than zero, the indirect flag
8900 ** is set. Passing a value less than zero does not modify the current value
8901 ** of the indirect flag, and may be used to query the current state of the
8902 ** indirect flag for the specified session object.
8903 **
8904 ** The return value indicates the final state of the indirect flag: 0 if
8905 ** it is clear, or 1 if it is set.
8906 */
8907 int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
8908 
8909 /*
8910 ** CAPI3REF: Attach A Table To A Session Object
8911 **
8912 ** If argument zTab is not NULL, then it is the name of a table to attach
8913 ** to the session object passed as the first argument. All subsequent changes
8914 ** made to the table while the session object is enabled will be recorded. See
8915 ** documentation for [sqlite3session_changeset()] for further details.
8916 **
8917 ** Or, if argument zTab is NULL, then changes are recorded for all tables
8918 ** in the database. If additional tables are added to the database (by
8919 ** executing "CREATE TABLE" statements) after this call is made, changes for
8920 ** the new tables are also recorded.
8921 **
8922 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
8923 ** defined as part of their CREATE TABLE statement. It does not matter if the
8924 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
8925 ** KEY may consist of a single column, or may be a composite key.
8926 **
8927 ** It is not an error if the named table does not exist in the database. Nor
8928 ** is it an error if the named table does not have a PRIMARY KEY. However,
8929 ** no changes will be recorded in either of these scenarios.
8930 **
8931 ** Changes are not recorded for individual rows that have NULL values stored
8932 ** in one or more of their PRIMARY KEY columns.
8933 **
8934 ** SQLITE_OK is returned if the call completes without error. Or, if an error
8935 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
8936 */
8937 int sqlite3session_attach(
8938  sqlite3_session *pSession, /* Session object */
8939  const char *zTab /* Table name */
8940 );
8941 
8942 /*
8943 ** CAPI3REF: Set a table filter on a Session Object.
8944 **
8945 ** The second argument (xFilter) is the "filter callback". For changes to rows
8946 ** in tables that are not attached to the Session object, the filter is called
8947 ** to determine whether changes to the table's rows should be tracked or not.
8948 ** If xFilter returns 0, changes is not tracked. Note that once a table is
8949 ** attached, xFilter will not be called again.
8950 */
8951 void sqlite3session_table_filter(
8952  sqlite3_session *pSession, /* Session object */
8953  int(*xFilter)(
8954  void *pCtx, /* Copy of third arg to _filter_table() */
8955  const char *zTab /* Table name */
8956  ),
8957  void *pCtx /* First argument passed to xFilter */
8958 );
8959 
8960 /*
8961 ** CAPI3REF: Generate A Changeset From A Session Object
8962 **
8963 ** Obtain a changeset containing changes to the tables attached to the
8964 ** session object passed as the first argument. If successful,
8965 ** set *ppChangeset to point to a buffer containing the changeset
8966 ** and *pnChangeset to the size of the changeset in bytes before returning
8967 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
8968 ** zero and return an SQLite error code.
8969 **
8970 ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
8971 ** each representing a change to a single row of an attached table. An INSERT
8972 ** change contains the values of each field of a new database row. A DELETE
8973 ** contains the original values of each field of a deleted database row. An
8974 ** UPDATE change contains the original values of each field of an updated
8975 ** database row along with the updated values for each updated non-primary-key
8976 ** column. It is not possible for an UPDATE change to represent a change that
8977 ** modifies the values of primary key columns. If such a change is made, it
8978 ** is represented in a changeset as a DELETE followed by an INSERT.
8979 **
8980 ** Changes are not recorded for rows that have NULL values stored in one or
8981 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
8982 ** no corresponding change is present in the changesets returned by this
8983 ** function. If an existing row with one or more NULL values stored in
8984 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
8985 ** only an INSERT is appears in the changeset. Similarly, if an existing row
8986 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
8987 ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
8988 ** DELETE change only.
8989 **
8990 ** The contents of a changeset may be traversed using an iterator created
8991 ** using the [sqlite3changeset_start()] API. A changeset may be applied to
8992 ** a database with a compatible schema using the [sqlite3changeset_apply()]
8993 ** API.
8994 **
8995 ** Within a changeset generated by this function, all changes related to a
8996 ** single table are grouped together. In other words, when iterating through
8997 ** a changeset or when applying a changeset to a database, all changes related
8998 ** to a single table are processed before moving on to the next table. Tables
8999 ** are sorted in the same order in which they were attached (or auto-attached)
9000 ** to the sqlite3_session object. The order in which the changes related to
9001 ** a single table are stored is undefined.
9002 **
9003 ** Following a successful call to this function, it is the responsibility of
9004 ** the caller to eventually free the buffer that *ppChangeset points to using
9005 ** [sqlite3_free()].
9006 **
9007 ** <h3>Changeset Generation</h3>
9008 **
9009 ** Once a table has been attached to a session object, the session object
9010 ** records the primary key values of all new rows inserted into the table.
9011 ** It also records the original primary key and other column values of any
9012 ** deleted or updated rows. For each unique primary key value, data is only
9013 ** recorded once - the first time a row with said primary key is inserted,
9014 ** updated or deleted in the lifetime of the session.
9015 **
9016 ** There is one exception to the previous paragraph: when a row is inserted,
9017 ** updated or deleted, if one or more of its primary key columns contain a
9018 ** NULL value, no record of the change is made.
9019 **
9020 ** The session object therefore accumulates two types of records - those
9021 ** that consist of primary key values only (created when the user inserts
9022 ** a new record) and those that consist of the primary key values and the
9023 ** original values of other table columns (created when the users deletes
9024 ** or updates a record).
9025 **
9026 ** When this function is called, the requested changeset is created using
9027 ** both the accumulated records and the current contents of the database
9028 ** file. Specifically:
9029 **
9030 ** <ul>
9031 ** <li> For each record generated by an insert, the database is queried
9032 ** for a row with a matching primary key. If one is found, an INSERT
9033 ** change is added to the changeset. If no such row is found, no change
9034 ** is added to the changeset.
9035 **
9036 ** <li> For each record generated by an update or delete, the database is
9037 ** queried for a row with a matching primary key. If such a row is
9038 ** found and one or more of the non-primary key fields have been
9039 ** modified from their original values, an UPDATE change is added to
9040 ** the changeset. Or, if no such row is found in the table, a DELETE
9041 ** change is added to the changeset. If there is a row with a matching
9042 ** primary key in the database, but all fields contain their original
9043 ** values, no change is added to the changeset.
9044 ** </ul>
9045 **
9046 ** This means, amongst other things, that if a row is inserted and then later
9047 ** deleted while a session object is active, neither the insert nor the delete
9048 ** will be present in the changeset. Or if a row is deleted and then later a
9049 ** row with the same primary key values inserted while a session object is
9050 ** active, the resulting changeset will contain an UPDATE change instead of
9051 ** a DELETE and an INSERT.
9052 **
9053 ** When a session object is disabled (see the [sqlite3session_enable()] API),
9054 ** it does not accumulate records when rows are inserted, updated or deleted.
9055 ** This may appear to have some counter-intuitive effects if a single row
9056 ** is written to more than once during a session. For example, if a row
9057 ** is inserted while a session object is enabled, then later deleted while
9058 ** the same session object is disabled, no INSERT record will appear in the
9059 ** changeset, even though the delete took place while the session was disabled.
9060 ** Or, if one field of a row is updated while a session is disabled, and
9061 ** another field of the same row is updated while the session is enabled, the
9062 ** resulting changeset will contain an UPDATE change that updates both fields.
9063 */
9064 int sqlite3session_changeset(
9065  sqlite3_session *pSession, /* Session object */
9066  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
9067  void **ppChangeset /* OUT: Buffer containing changeset */
9068 );
9069 
9070 /*
9071 ** CAPI3REF: Load The Difference Between Tables Into A Session
9072 **
9073 ** If it is not already attached to the session object passed as the first
9074 ** argument, this function attaches table zTbl in the same manner as the
9075 ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
9076 ** does not have a primary key, this function is a no-op (but does not return
9077 ** an error).
9078 **
9079 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
9080 ** attached to the same database handle as the session object that contains
9081 ** a table compatible with the table attached to the session by this function.
9082 ** A table is considered compatible if it:
9083 **
9084 ** <ul>
9085 ** <li> Has the same name,
9086 ** <li> Has the same set of columns declared in the same order, and
9087 ** <li> Has the same PRIMARY KEY definition.
9088 ** </ul>
9089 **
9090 ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
9091 ** are compatible but do not have any PRIMARY KEY columns, it is not an error
9092 ** but no changes are added to the session object. As with other session
9093 ** APIs, tables without PRIMARY KEYs are simply ignored.
9094 **
9095 ** This function adds a set of changes to the session object that could be
9096 ** used to update the table in database zFrom (call this the "from-table")
9097 ** so that its content is the same as the table attached to the session
9098 ** object (call this the "to-table"). Specifically:
9099 **
9100 ** <ul>
9101 ** <li> For each row (primary key) that exists in the to-table but not in
9102 ** the from-table, an INSERT record is added to the session object.
9103 **
9104 ** <li> For each row (primary key) that exists in the to-table but not in
9105 ** the from-table, a DELETE record is added to the session object.
9106 **
9107 ** <li> For each row (primary key) that exists in both tables, but features
9108 ** different in each, an UPDATE record is added to the session.
9109 ** </ul>
9110 **
9111 ** To clarify, if this function is called and then a changeset constructed
9112 ** using [sqlite3session_changeset()], then after applying that changeset to
9113 ** database zFrom the contents of the two compatible tables would be
9114 ** identical.
9115 **
9116 ** It an error if database zFrom does not exist or does not contain the
9117 ** required compatible table.
9118 **
9119 ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
9120 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
9121 ** may be set to point to a buffer containing an English language error
9122 ** message. It is the responsibility of the caller to free this buffer using
9123 ** sqlite3_free().
9124 */
9125 int sqlite3session_diff(
9126  sqlite3_session *pSession,
9127  const char *zFromDb,
9128  const char *zTbl,
9129  char **pzErrMsg
9130 );
9131 
9132 
9133 /*
9134 ** CAPI3REF: Generate A Patchset From A Session Object
9135 **
9136 ** The differences between a patchset and a changeset are that:
9137 **
9138 ** <ul>
9139 ** <li> DELETE records consist of the primary key fields only. The
9140 ** original values of other fields are omitted.
9141 ** <li> The original values of any modified fields are omitted from
9142 ** UPDATE records.
9143 ** </ul>
9144 **
9145 ** A patchset blob may be used with up to date versions of all
9146 ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
9147 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
9148 ** attempting to use a patchset blob with old versions of the
9149 ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
9150 **
9151 ** Because the non-primary key "old.*" fields are omitted, no
9152 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
9153 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
9154 ** in the same way as for changesets.
9155 **
9156 ** Changes within a patchset are ordered in the same way as for changesets
9157 ** generated by the sqlite3session_changeset() function (i.e. all changes for
9158 ** a single table are grouped together, tables appear in the order in which
9159 ** they were attached to the session object).
9160 */
9161 int sqlite3session_patchset(
9162  sqlite3_session *pSession, /* Session object */
9163  int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
9164  void **ppPatchset /* OUT: Buffer containing changeset */
9165 );
9166 
9167 /*
9168 ** CAPI3REF: Test if a changeset has recorded any changes.
9169 **
9170 ** Return non-zero if no changes to attached tables have been recorded by
9171 ** the session object passed as the first argument. Otherwise, if one or
9172 ** more changes have been recorded, return zero.
9173 **
9174 ** Even if this function returns zero, it is possible that calling
9175 ** [sqlite3session_changeset()] on the session handle may still return a
9176 ** changeset that contains no changes. This can happen when a row in
9177 ** an attached table is modified and then later on the original values
9178 ** are restored. However, if this function returns non-zero, then it is
9179 ** guaranteed that a call to sqlite3session_changeset() will return a
9180 ** changeset containing zero changes.
9181 */
9182 int sqlite3session_isempty(sqlite3_session *pSession);
9183 
9184 /*
9185 ** CAPI3REF: Create An Iterator To Traverse A Changeset
9186 **
9187 ** Create an iterator used to iterate through the contents of a changeset.
9188 ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
9189 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
9190 ** SQLite error code is returned.
9191 **
9192 ** The following functions can be used to advance and query a changeset
9193 ** iterator created by this function:
9194 **
9195 ** <ul>
9196 ** <li> [sqlite3changeset_next()]
9197 ** <li> [sqlite3changeset_op()]
9198 ** <li> [sqlite3changeset_new()]
9199 ** <li> [sqlite3changeset_old()]
9200 ** </ul>
9201 **
9202 ** It is the responsibility of the caller to eventually destroy the iterator
9203 ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
9204 ** changeset (pChangeset) must remain valid until after the iterator is
9205 ** destroyed.
9206 **
9207 ** Assuming the changeset blob was created by one of the
9208 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
9209 ** [sqlite3changeset_invert()] functions, all changes within the changeset
9210 ** that apply to a single table are grouped together. This means that when
9211 ** an application iterates through a changeset using an iterator created by
9212 ** this function, all changes that relate to a single table are visited
9213 ** consecutively. There is no chance that the iterator will visit a change
9214 ** the applies to table X, then one for table Y, and then later on visit
9215 ** another change for table X.
9216 */
9217 int sqlite3changeset_start(
9218  sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
9219  int nChangeset, /* Size of changeset blob in bytes */
9220  void *pChangeset /* Pointer to blob containing changeset */
9221 );
9222 
9223 
9224 /*
9225 ** CAPI3REF: Advance A Changeset Iterator
9226 **
9227 ** This function may only be used with iterators created by function
9228 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
9229 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
9230 ** is returned and the call has no effect.
9231 **
9232 ** Immediately after an iterator is created by sqlite3changeset_start(), it
9233 ** does not point to any change in the changeset. Assuming the changeset
9234 ** is not empty, the first call to this function advances the iterator to
9235 ** point to the first change in the changeset. Each subsequent call advances
9236 ** the iterator to point to the next change in the changeset (if any). If
9237 ** no error occurs and the iterator points to a valid change after a call
9238 ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
9239 ** Otherwise, if all changes in the changeset have already been visited,
9240 ** SQLITE_DONE is returned.
9241 **
9242 ** If an error occurs, an SQLite error code is returned. Possible error
9243 ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
9244 ** SQLITE_NOMEM.
9245 */
9246 int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
9247 
9248 /*
9249 ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
9250 **
9251 ** The pIter argument passed to this function may either be an iterator
9252 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9253 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9254 ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
9255 ** is not the case, this function returns [SQLITE_MISUSE].
9256 **
9257 ** If argument pzTab is not NULL, then *pzTab is set to point to a
9258 ** nul-terminated utf-8 encoded string containing the name of the table
9259 ** affected by the current change. The buffer remains valid until either
9260 ** sqlite3changeset_next() is called on the iterator or until the
9261 ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
9262 ** set to the number of columns in the table affected by the change. If
9263 ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
9264 ** is an indirect change, or false (0) otherwise. See the documentation for
9265 ** [sqlite3session_indirect()] for a description of direct and indirect
9266 ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
9267 ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
9268 ** type of change that the iterator currently points to.
9269 **
9270 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
9271 ** SQLite error code is returned. The values of the output variables may not
9272 ** be trusted in this case.
9273 */
9274 int sqlite3changeset_op(
9275  sqlite3_changeset_iter *pIter, /* Iterator object */
9276  const char **pzTab, /* OUT: Pointer to table name */
9277  int *pnCol, /* OUT: Number of columns in table */
9278  int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
9279  int *pbIndirect /* OUT: True for an 'indirect' change */
9280 );
9281 
9282 /*
9283 ** CAPI3REF: Obtain The Primary Key Definition Of A Table
9284 **
9285 ** For each modified table, a changeset includes the following:
9286 **
9287 ** <ul>
9288 ** <li> The number of columns in the table, and
9289 ** <li> Which of those columns make up the tables PRIMARY KEY.
9290 ** </ul>
9291 **
9292 ** This function is used to find which columns comprise the PRIMARY KEY of
9293 ** the table modified by the change that iterator pIter currently points to.
9294 ** If successful, *pabPK is set to point to an array of nCol entries, where
9295 ** nCol is the number of columns in the table. Elements of *pabPK are set to
9296 ** 0x01 if the corresponding column is part of the tables primary key, or
9297 ** 0x00 if it is not.
9298 **
9299 ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
9300 ** in the table.
9301 **
9302 ** If this function is called when the iterator does not point to a valid
9303 ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
9304 ** SQLITE_OK is returned and the output variables populated as described
9305 ** above.
9306 */
9307 int sqlite3changeset_pk(
9308  sqlite3_changeset_iter *pIter, /* Iterator object */
9309  unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
9310  int *pnCol /* OUT: Number of entries in output array */
9311 );
9312 
9313 /*
9314 ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
9315 **
9316 ** The pIter argument passed to this function may either be an iterator
9317 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9318 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9319 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9320 ** Furthermore, it may only be called if the type of change that the iterator
9321 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
9322 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9323 **
9324 ** Argument iVal must be greater than or equal to 0, and less than the number
9325 ** of columns in the table affected by the current change. Otherwise,
9326 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9327 **
9328 ** If successful, this function sets *ppValue to point to a protected
9329 ** sqlite3_value object containing the iVal'th value from the vector of
9330 ** original row values stored as part of the UPDATE or DELETE change and
9331 ** returns SQLITE_OK. The name of the function comes from the fact that this
9332 ** is similar to the "old.*" columns available to update or delete triggers.
9333 **
9334 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9335 ** is returned and *ppValue is set to NULL.
9336 */
9337 int sqlite3changeset_old(
9338  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9339  int iVal, /* Column number */
9340  sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
9341 );
9342 
9343 /*
9344 ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
9345 **
9346 ** The pIter argument passed to this function may either be an iterator
9347 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9348 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9349 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9350 ** Furthermore, it may only be called if the type of change that the iterator
9351 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
9352 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9353 **
9354 ** Argument iVal must be greater than or equal to 0, and less than the number
9355 ** of columns in the table affected by the current change. Otherwise,
9356 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9357 **
9358 ** If successful, this function sets *ppValue to point to a protected
9359 ** sqlite3_value object containing the iVal'th value from the vector of
9360 ** new row values stored as part of the UPDATE or INSERT change and
9361 ** returns SQLITE_OK. If the change is an UPDATE and does not include
9362 ** a new value for the requested column, *ppValue is set to NULL and
9363 ** SQLITE_OK returned. The name of the function comes from the fact that
9364 ** this is similar to the "new.*" columns available to update or delete
9365 ** triggers.
9366 **
9367 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9368 ** is returned and *ppValue is set to NULL.
9369 */
9370 int sqlite3changeset_new(
9371  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9372  int iVal, /* Column number */
9373  sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
9374 );
9375 
9376 /*
9377 ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
9378 **
9379 ** This function should only be used with iterator objects passed to a
9380 ** conflict-handler callback by [sqlite3changeset_apply()] with either
9381 ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
9382 ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
9383 ** is set to NULL.
9384 **
9385 ** Argument iVal must be greater than or equal to 0, and less than the number
9386 ** of columns in the table affected by the current change. Otherwise,
9387 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9388 **
9389 ** If successful, this function sets *ppValue to point to a protected
9390 ** sqlite3_value object containing the iVal'th value from the
9391 ** "conflicting row" associated with the current conflict-handler callback
9392 ** and returns SQLITE_OK.
9393 **
9394 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9395 ** is returned and *ppValue is set to NULL.
9396 */
9397 int sqlite3changeset_conflict(
9398  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9399  int iVal, /* Column number */
9400  sqlite3_value **ppValue /* OUT: Value from conflicting row */
9401 );
9402 
9403 /*
9404 ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
9405 **
9406 ** This function may only be called with an iterator passed to an
9407 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
9408 ** it sets the output variable to the total number of known foreign key
9409 ** violations in the destination database and returns SQLITE_OK.
9410 **
9411 ** In all other cases this function returns SQLITE_MISUSE.
9412 */
9413 int sqlite3changeset_fk_conflicts(
9414  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9415  int *pnOut /* OUT: Number of FK violations */
9416 );
9417 
9418 
9419 /*
9420 ** CAPI3REF: Finalize A Changeset Iterator
9421 **
9422 ** This function is used to finalize an iterator allocated with
9423 ** [sqlite3changeset_start()].
9424 **
9425 ** This function should only be called on iterators created using the
9426 ** [sqlite3changeset_start()] function. If an application calls this
9427 ** function with an iterator passed to a conflict-handler by
9428 ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
9429 ** call has no effect.
9430 **
9431 ** If an error was encountered within a call to an sqlite3changeset_xxx()
9432 ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
9433 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
9434 ** to that error is returned by this function. Otherwise, SQLITE_OK is
9435 ** returned. This is to allow the following pattern (pseudo-code):
9436 **
9437 ** sqlite3changeset_start();
9438 ** while( SQLITE_ROW==sqlite3changeset_next() ){
9439 ** // Do something with change.
9440 ** }
9441 ** rc = sqlite3changeset_finalize();
9442 ** if( rc!=SQLITE_OK ){
9443 ** // An error has occurred
9444 ** }
9445 */
9446 int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
9447 
9448 /*
9449 ** CAPI3REF: Invert A Changeset
9450 **
9451 ** This function is used to "invert" a changeset object. Applying an inverted
9452 ** changeset to a database reverses the effects of applying the uninverted
9453 ** changeset. Specifically:
9454 **
9455 ** <ul>
9456 ** <li> Each DELETE change is changed to an INSERT, and
9457 ** <li> Each INSERT change is changed to a DELETE, and
9458 ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
9459 ** </ul>
9460 **
9461 ** This function does not change the order in which changes appear within
9462 ** the changeset. It merely reverses the sense of each individual change.
9463 **
9464 ** If successful, a pointer to a buffer containing the inverted changeset
9465 ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9466 ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9467 ** zeroed and an SQLite error code returned.
9468 **
9469 ** It is the responsibility of the caller to eventually call sqlite3_free()
9470 ** on the *ppOut pointer to free the buffer allocation following a successful
9471 ** call to this function.
9472 **
9473 ** WARNING/TODO: This function currently assumes that the input is a valid
9474 ** changeset. If it is not, the results are undefined.
9475 */
9476 int sqlite3changeset_invert(
9477  int nIn, const void *pIn, /* Input changeset */
9478  int *pnOut, void **ppOut /* OUT: Inverse of input */
9479 );
9480 
9481 /*
9482 ** CAPI3REF: Concatenate Two Changeset Objects
9483 **
9484 ** This function is used to concatenate two changesets, A and B, into a
9485 ** single changeset. The result is a changeset equivalent to applying
9486 ** changeset A followed by changeset B.
9487 **
9488 ** This function combines the two input changesets using an
9489 ** sqlite3_changegroup object. Calling it produces similar results as the
9490 ** following code fragment:
9491 **
9492 ** sqlite3_changegroup *pGrp;
9493 ** rc = sqlite3_changegroup_new(&pGrp);
9494 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9495 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9496 ** if( rc==SQLITE_OK ){
9497 ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9498 ** }else{
9499 ** *ppOut = 0;
9500 ** *pnOut = 0;
9501 ** }
9502 **
9503 ** Refer to the sqlite3_changegroup documentation below for details.
9504 */
9505 int sqlite3changeset_concat(
9506  int nA, /* Number of bytes in buffer pA */
9507  void *pA, /* Pointer to buffer containing changeset A */
9508  int nB, /* Number of bytes in buffer pB */
9509  void *pB, /* Pointer to buffer containing changeset B */
9510  int *pnOut, /* OUT: Number of bytes in output changeset */
9511  void **ppOut /* OUT: Buffer containing output changeset */
9512 );
9513 
9514 
9515 /*
9516 ** CAPI3REF: Changegroup Handle
9517 */
9518 typedef struct sqlite3_changegroup sqlite3_changegroup;
9519 
9520 /*
9521 ** CAPI3REF: Create A New Changegroup Object
9522 **
9523 ** An sqlite3_changegroup object is used to combine two or more changesets
9524 ** (or patchsets) into a single changeset (or patchset). A single changegroup
9525 ** object may combine changesets or patchsets, but not both. The output is
9526 ** always in the same format as the input.
9527 **
9528 ** If successful, this function returns SQLITE_OK and populates (*pp) with
9529 ** a pointer to a new sqlite3_changegroup object before returning. The caller
9530 ** should eventually free the returned object using a call to
9531 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9532 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9533 **
9534 ** The usual usage pattern for an sqlite3_changegroup object is as follows:
9535 **
9536 ** <ul>
9537 ** <li> It is created using a call to sqlite3changegroup_new().
9538 **
9539 ** <li> Zero or more changesets (or patchsets) are added to the object
9540 ** by calling sqlite3changegroup_add().
9541 **
9542 ** <li> The result of combining all input changesets together is obtained
9543 ** by the application via a call to sqlite3changegroup_output().
9544 **
9545 ** <li> The object is deleted using a call to sqlite3changegroup_delete().
9546 ** </ul>
9547 **
9548 ** Any number of calls to add() and output() may be made between the calls to
9549 ** new() and delete(), and in any order.
9550 **
9551 ** As well as the regular sqlite3changegroup_add() and
9552 ** sqlite3changegroup_output() functions, also available are the streaming
9553 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9554 */
9555 int sqlite3changegroup_new(sqlite3_changegroup **pp);
9556 
9557 /*
9558 ** CAPI3REF: Add A Changeset To A Changegroup
9559 **
9560 ** Add all changes within the changeset (or patchset) in buffer pData (size
9561 ** nData bytes) to the changegroup.
9562 **
9563 ** If the buffer contains a patchset, then all prior calls to this function
9564 ** on the same changegroup object must also have specified patchsets. Or, if
9565 ** the buffer contains a changeset, so must have the earlier calls to this
9566 ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9567 ** to the changegroup.
9568 **
9569 ** Rows within the changeset and changegroup are identified by the values in
9570 ** their PRIMARY KEY columns. A change in the changeset is considered to
9571 ** apply to the same row as a change already present in the changegroup if
9572 ** the two rows have the same primary key.
9573 **
9574 ** Changes to rows that do not already appear in the changegroup are
9575 ** simply copied into it. Or, if both the new changeset and the changegroup
9576 ** contain changes that apply to a single row, the final contents of the
9577 ** changegroup depends on the type of each change, as follows:
9578 **
9579 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9580 ** <tr><th style="white-space:pre">Existing Change </th>
9581 ** <th style="white-space:pre">New Change </th>
9582 ** <th>Output Change
9583 ** <tr><td>INSERT <td>INSERT <td>
9584 ** The new change is ignored. This case does not occur if the new
9585 ** changeset was recorded immediately after the changesets already
9586 ** added to the changegroup.
9587 ** <tr><td>INSERT <td>UPDATE <td>
9588 ** The INSERT change remains in the changegroup. The values in the
9589 ** INSERT change are modified as if the row was inserted by the
9590 ** existing change and then updated according to the new change.
9591 ** <tr><td>INSERT <td>DELETE <td>
9592 ** The existing INSERT is removed from the changegroup. The DELETE is
9593 ** not added.
9594 ** <tr><td>UPDATE <td>INSERT <td>
9595 ** The new change is ignored. This case does not occur if the new
9596 ** changeset was recorded immediately after the changesets already
9597 ** added to the changegroup.
9598 ** <tr><td>UPDATE <td>UPDATE <td>
9599 ** The existing UPDATE remains within the changegroup. It is amended
9600 ** so that the accompanying values are as if the row was updated once
9601 ** by the existing change and then again by the new change.
9602 ** <tr><td>UPDATE <td>DELETE <td>
9603 ** The existing UPDATE is replaced by the new DELETE within the
9604 ** changegroup.
9605 ** <tr><td>DELETE <td>INSERT <td>
9606 ** If one or more of the column values in the row inserted by the
9607 ** new change differ from those in the row deleted by the existing
9608 ** change, the existing DELETE is replaced by an UPDATE within the
9609 ** changegroup. Otherwise, if the inserted row is exactly the same
9610 ** as the deleted row, the existing DELETE is simply discarded.
9611 ** <tr><td>DELETE <td>UPDATE <td>
9612 ** The new change is ignored. This case does not occur if the new
9613 ** changeset was recorded immediately after the changesets already
9614 ** added to the changegroup.
9615 ** <tr><td>DELETE <td>DELETE <td>
9616 ** The new change is ignored. This case does not occur if the new
9617 ** changeset was recorded immediately after the changesets already
9618 ** added to the changegroup.
9619 ** </table>
9620 **
9621 ** If the new changeset contains changes to a table that is already present
9622 ** in the changegroup, then the number of columns and the position of the
9623 ** primary key columns for the table must be consistent. If this is not the
9624 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
9625 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9626 ** returned. Or, if an out-of-memory condition occurs during processing, this
9627 ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9628 ** final contents of the changegroup is undefined.
9629 **
9630 ** If no error occurs, SQLITE_OK is returned.
9631 */
9632 int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9633 
9634 /*
9635 ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
9636 **
9637 ** Obtain a buffer containing a changeset (or patchset) representing the
9638 ** current contents of the changegroup. If the inputs to the changegroup
9639 ** were themselves changesets, the output is a changeset. Or, if the
9640 ** inputs were patchsets, the output is also a patchset.
9641 **
9642 ** As with the output of the sqlite3session_changeset() and
9643 ** sqlite3session_patchset() functions, all changes related to a single
9644 ** table are grouped together in the output of this function. Tables appear
9645 ** in the same order as for the very first changeset added to the changegroup.
9646 ** If the second or subsequent changesets added to the changegroup contain
9647 ** changes for tables that do not appear in the first changeset, they are
9648 ** appended onto the end of the output changeset, again in the order in
9649 ** which they are first encountered.
9650 **
9651 ** If an error occurs, an SQLite error code is returned and the output
9652 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9653 ** is returned and the output variables are set to the size of and a
9654 ** pointer to the output buffer, respectively. In this case it is the
9655 ** responsibility of the caller to eventually free the buffer using a
9656 ** call to sqlite3_free().
9657 */
9658 int sqlite3changegroup_output(
9659  sqlite3_changegroup*,
9660  int *pnData, /* OUT: Size of output buffer in bytes */
9661  void **ppData /* OUT: Pointer to output buffer */
9662 );
9663 
9664 /*
9665 ** CAPI3REF: Delete A Changegroup Object
9666 */
9667 void sqlite3changegroup_delete(sqlite3_changegroup*);
9668 
9669 /*
9670 ** CAPI3REF: Apply A Changeset To A Database
9671 **
9672 ** Apply a changeset to a database. This function attempts to update the
9673 ** "main" database attached to handle db with the changes found in the
9674 ** changeset passed via the second and third arguments.
9675 **
9676 ** The fourth argument (xFilter) passed to this function is the "filter
9677 ** callback". If it is not NULL, then for each table affected by at least one
9678 ** change in the changeset, the filter callback is invoked with
9679 ** the table name as the second argument, and a copy of the context pointer
9680 ** passed as the sixth argument to this function as the first. If the "filter
9681 ** callback" returns zero, then no attempt is made to apply any changes to
9682 ** the table. Otherwise, if the return value is non-zero or the xFilter
9683 ** argument to this function is NULL, all changes related to the table are
9684 ** attempted.
9685 **
9686 ** For each table that is not excluded by the filter callback, this function
9687 ** tests that the target database contains a compatible table. A table is
9688 ** considered compatible if all of the following are true:
9689 **
9690 ** <ul>
9691 ** <li> The table has the same name as the name recorded in the
9692 ** changeset, and
9693 ** <li> The table has the same number of columns as recorded in the
9694 ** changeset, and
9695 ** <li> The table has primary key columns in the same position as
9696 ** recorded in the changeset.
9697 ** </ul>
9698 **
9699 ** If there is no compatible table, it is not an error, but none of the
9700 ** changes associated with the table are applied. A warning message is issued
9701 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9702 ** one such warning is issued for each table in the changeset.
9703 **
9704 ** For each change for which there is a compatible table, an attempt is made
9705 ** to modify the table contents according to the UPDATE, INSERT or DELETE
9706 ** change. If a change cannot be applied cleanly, the conflict handler
9707 ** function passed as the fifth argument to sqlite3changeset_apply() may be
9708 ** invoked. A description of exactly when the conflict handler is invoked for
9709 ** each type of change is below.
9710 **
9711 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9712 ** of passing anything other than a valid function pointer as the xConflict
9713 ** argument are undefined.
9714 **
9715 ** Each time the conflict handler function is invoked, it must return one
9716 ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9717 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9718 ** if the second argument passed to the conflict handler is either
9719 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9720 ** returns an illegal value, any changes already made are rolled back and
9721 ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9722 ** actions are taken by sqlite3changeset_apply() depending on the value
9723 ** returned by each invocation of the conflict-handler function. Refer to
9724 ** the documentation for the three
9725 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
9726 **
9727 ** <dl>
9728 ** <dt>DELETE Changes<dd>
9729 ** For each DELETE change, this function checks if the target database
9730 ** contains a row with the same primary key value (or values) as the
9731 ** original row values stored in the changeset. If it does, and the values
9732 ** stored in all non-primary key columns also match the values stored in
9733 ** the changeset the row is deleted from the target database.
9734 **
9735 ** If a row with matching primary key values is found, but one or more of
9736 ** the non-primary key fields contains a value different from the original
9737 ** row value stored in the changeset, the conflict-handler function is
9738 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument.
9739 **
9740 ** If no row with matching primary key values is found in the database,
9741 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9742 ** passed as the second argument.
9743 **
9744 ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9745 ** (which can only happen if a foreign key constraint is violated), the
9746 ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9747 ** passed as the second argument. This includes the case where the DELETE
9748 ** operation is attempted because an earlier call to the conflict handler
9749 ** function returned [SQLITE_CHANGESET_REPLACE].
9750 **
9751 ** <dt>INSERT Changes<dd>
9752 ** For each INSERT change, an attempt is made to insert the new row into
9753 ** the database.
9754 **
9755 ** If the attempt to insert the row fails because the database already
9756 ** contains a row with the same primary key values, the conflict handler
9757 ** function is invoked with the second argument set to
9758 ** [SQLITE_CHANGESET_CONFLICT].
9759 **
9760 ** If the attempt to insert the row fails because of some other constraint
9761 ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9762 ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9763 ** This includes the case where the INSERT operation is re-attempted because
9764 ** an earlier call to the conflict handler function returned
9765 ** [SQLITE_CHANGESET_REPLACE].
9766 **
9767 ** <dt>UPDATE Changes<dd>
9768 ** For each UPDATE change, this function checks if the target database
9769 ** contains a row with the same primary key value (or values) as the
9770 ** original row values stored in the changeset. If it does, and the values
9771 ** stored in all non-primary key columns also match the values stored in
9772 ** the changeset the row is updated within the target database.
9773 **
9774 ** If a row with matching primary key values is found, but one or more of
9775 ** the non-primary key fields contains a value different from an original
9776 ** row value stored in the changeset, the conflict-handler function is
9777 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9778 ** UPDATE changes only contain values for non-primary key fields that are
9779 ** to be modified, only those fields need to match the original values to
9780 ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9781 **
9782 ** If no row with matching primary key values is found in the database,
9783 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9784 ** passed as the second argument.
9785 **
9786 ** If the UPDATE operation is attempted, but SQLite returns
9787 ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9788 ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9789 ** This includes the case where the UPDATE operation is attempted after
9790 ** an earlier call to the conflict handler function returned
9791 ** [SQLITE_CHANGESET_REPLACE].
9792 ** </dl>
9793 **
9794 ** It is safe to execute SQL statements, including those that write to the
9795 ** table that the callback related to, from within the xConflict callback.
9796 ** This can be used to further customize the applications conflict
9797 ** resolution strategy.
9798 **
9799 ** All changes made by this function are enclosed in a savepoint transaction.
9800 ** If any other error (aside from a constraint failure when attempting to
9801 ** write to the target database) occurs, then the savepoint transaction is
9802 ** rolled back, restoring the target database to its original state, and an
9803 ** SQLite error code returned.
9804 */
9805 int sqlite3changeset_apply(
9806  sqlite3 *db, /* Apply change to "main" db of this handle */
9807  int nChangeset, /* Size of changeset in bytes */
9808  void *pChangeset, /* Changeset blob */
9809  int(*xFilter)(
9810  void *pCtx, /* Copy of sixth arg to _apply() */
9811  const char *zTab /* Table name */
9812  ),
9813  int(*xConflict)(
9814  void *pCtx, /* Copy of sixth arg to _apply() */
9815  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9816  sqlite3_changeset_iter *p /* Handle describing change and conflict */
9817  ),
9818  void *pCtx /* First argument passed to xConflict */
9819 );
9820 
9821 /*
9822 ** CAPI3REF: Constants Passed To The Conflict Handler
9823 **
9824 ** Values that may be passed as the second argument to a conflict-handler.
9825 **
9826 ** <dl>
9827 ** <dt>SQLITE_CHANGESET_DATA<dd>
9828 ** The conflict handler is invoked with CHANGESET_DATA as the second argument
9829 ** when processing a DELETE or UPDATE change if a row with the required
9830 ** PRIMARY KEY fields is present in the database, but one or more other
9831 ** (non primary-key) fields modified by the update do not contain the
9832 ** expected "before" values.
9833 **
9834 ** The conflicting row, in this case, is the database row with the matching
9835 ** primary key.
9836 **
9837 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9838 ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9839 ** argument when processing a DELETE or UPDATE change if a row with the
9840 ** required PRIMARY KEY fields is not present in the database.
9841 **
9842 ** There is no conflicting row in this case. The results of invoking the
9843 ** sqlite3changeset_conflict() API are undefined.
9844 **
9845 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9846 ** CHANGESET_CONFLICT is passed as the second argument to the conflict
9847 ** handler while processing an INSERT change if the operation would result
9848 ** in duplicate primary key values.
9849 **
9850 ** The conflicting row in this case is the database row with the matching
9851 ** primary key.
9852 **
9853 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9854 ** If foreign key handling is enabled, and applying a changeset leaves the
9855 ** database in a state containing foreign key violations, the conflict
9856 ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9857 ** exactly once before the changeset is committed. If the conflict handler
9858 ** returns CHANGESET_OMIT, the changes, including those that caused the
9859 ** foreign key constraint violation, are committed. Or, if it returns
9860 ** CHANGESET_ABORT, the changeset is rolled back.
9861 **
9862 ** No current or conflicting row information is provided. The only function
9863 ** it is possible to call on the supplied sqlite3_changeset_iter handle
9864 ** is sqlite3changeset_fk_conflicts().
9865 **
9866 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9867 ** If any other constraint violation occurs while applying a change (i.e.
9868 ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9869 ** invoked with CHANGESET_CONSTRAINT as the second argument.
9870 **
9871 ** There is no conflicting row in this case. The results of invoking the
9872 ** sqlite3changeset_conflict() API are undefined.
9873 **
9874 ** </dl>
9875 */
9876 #define SQLITE_CHANGESET_DATA 1
9877 #define SQLITE_CHANGESET_NOTFOUND 2
9878 #define SQLITE_CHANGESET_CONFLICT 3
9879 #define SQLITE_CHANGESET_CONSTRAINT 4
9880 #define SQLITE_CHANGESET_FOREIGN_KEY 5
9881 
9882 /*
9883 ** CAPI3REF: Constants Returned By The Conflict Handler
9884 **
9885 ** A conflict handler callback must return one of the following three values.
9886 **
9887 ** <dl>
9888 ** <dt>SQLITE_CHANGESET_OMIT<dd>
9889 ** If a conflict handler returns this value no special action is taken. The
9890 ** change that caused the conflict is not applied. The session module
9891 ** continues to the next change in the changeset.
9892 **
9893 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
9894 ** This value may only be returned if the second argument to the conflict
9895 ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
9896 ** is not the case, any changes applied so far are rolled back and the
9897 ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
9898 **
9899 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
9900 ** handler, then the conflicting row is either updated or deleted, depending
9901 ** on the type of change.
9902 **
9903 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
9904 ** handler, then the conflicting row is removed from the database and a
9905 ** second attempt to apply the change is made. If this second attempt fails,
9906 ** the original row is restored to the database before continuing.
9907 **
9908 ** <dt>SQLITE_CHANGESET_ABORT<dd>
9909 ** If this value is returned, any changes applied so far are rolled back
9910 ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
9911 ** </dl>
9912 */
9913 #define SQLITE_CHANGESET_OMIT 0
9914 #define SQLITE_CHANGESET_REPLACE 1
9915 #define SQLITE_CHANGESET_ABORT 2
9916 
9917 /*
9918 ** CAPI3REF: Streaming Versions of API functions.
9919 **
9920 ** The six streaming API xxx_strm() functions serve similar purposes to the
9921 ** corresponding non-streaming API functions:
9922 **
9923 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9924 ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
9925 ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
9926 ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
9927 ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
9928 ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
9929 ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
9930 ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
9931 ** </table>
9932 **
9933 ** Non-streaming functions that accept changesets (or patchsets) as input
9934 ** require that the entire changeset be stored in a single buffer in memory.
9935 ** Similarly, those that return a changeset or patchset do so by returning
9936 ** a pointer to a single large buffer allocated using sqlite3_malloc().
9937 ** Normally this is convenient. However, if an application running in a
9938 ** low-memory environment is required to handle very large changesets, the
9939 ** large contiguous memory allocations required can become onerous.
9940 **
9941 ** In order to avoid this problem, instead of a single large buffer, input
9942 ** is passed to a streaming API functions by way of a callback function that
9943 ** the sessions module invokes to incrementally request input data as it is
9944 ** required. In all cases, a pair of API function parameters such as
9945 **
9946 ** <pre>
9947 ** &nbsp; int nChangeset,
9948 ** &nbsp; void *pChangeset,
9949 ** </pre>
9950 **
9951 ** Is replaced by:
9952 **
9953 ** <pre>
9954 ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
9955 ** &nbsp; void *pIn,
9956 ** </pre>
9957 **
9958 ** Each time the xInput callback is invoked by the sessions module, the first
9959 ** argument passed is a copy of the supplied pIn context pointer. The second
9960 ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
9961 ** error occurs the xInput method should copy up to (*pnData) bytes of data
9962 ** into the buffer and set (*pnData) to the actual number of bytes copied
9963 ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
9964 ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
9965 ** error code should be returned. In all cases, if an xInput callback returns
9966 ** an error, all processing is abandoned and the streaming API function
9967 ** returns a copy of the error code to the caller.
9968 **
9969 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
9970 ** invoked by the sessions module at any point during the lifetime of the
9971 ** iterator. If such an xInput callback returns an error, the iterator enters
9972 ** an error state, whereby all subsequent calls to iterator functions
9973 ** immediately fail with the same error code as returned by xInput.
9974 **
9975 ** Similarly, streaming API functions that return changesets (or patchsets)
9976 ** return them in chunks by way of a callback function instead of via a
9977 ** pointer to a single large buffer. In this case, a pair of parameters such
9978 ** as:
9979 **
9980 ** <pre>
9981 ** &nbsp; int *pnChangeset,
9982 ** &nbsp; void **ppChangeset,
9983 ** </pre>
9984 **
9985 ** Is replaced by:
9986 **
9987 ** <pre>
9988 ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
9989 ** &nbsp; void *pOut
9990 ** </pre>
9991 **
9992 ** The xOutput callback is invoked zero or more times to return data to
9993 ** the application. The first parameter passed to each call is a copy of the
9994 ** pOut pointer supplied by the application. The second parameter, pData,
9995 ** points to a buffer nData bytes in size containing the chunk of output
9996 ** data being returned. If the xOutput callback successfully processes the
9997 ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
9998 ** it should return some other SQLite error code. In this case processing
9999 ** is immediately abandoned and the streaming API function returns a copy
10000 ** of the xOutput error code to the application.
10001 **
10002 ** The sessions module never invokes an xOutput callback with the third
10003 ** parameter set to a value less than or equal to zero. Other than this,
10004 ** no guarantees are made as to the size of the chunks of data returned.
10005 */
10006 int sqlite3changeset_apply_strm(
10007  sqlite3 *db, /* Apply change to "main" db of this handle */
10008  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
10009  void *pIn, /* First arg for xInput */
10010  int(*xFilter)(
10011  void *pCtx, /* Copy of sixth arg to _apply() */
10012  const char *zTab /* Table name */
10013  ),
10014  int(*xConflict)(
10015  void *pCtx, /* Copy of sixth arg to _apply() */
10016  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
10017  sqlite3_changeset_iter *p /* Handle describing change and conflict */
10018  ),
10019  void *pCtx /* First argument passed to xConflict */
10020 );
10021 int sqlite3changeset_concat_strm(
10022  int (*xInputA)(void *pIn, void *pData, int *pnData),
10023  void *pInA,
10024  int (*xInputB)(void *pIn, void *pData, int *pnData),
10025  void *pInB,
10026  int (*xOutput)(void *pOut, const void *pData, int nData),
10027  void *pOut
10028 );
10029 int sqlite3changeset_invert_strm(
10030  int (*xInput)(void *pIn, void *pData, int *pnData),
10031  void *pIn,
10032  int (*xOutput)(void *pOut, const void *pData, int nData),
10033  void *pOut
10034 );
10035 int sqlite3changeset_start_strm(
10036  sqlite3_changeset_iter **pp,
10037  int (*xInput)(void *pIn, void *pData, int *pnData),
10038  void *pIn
10039 );
10040 int sqlite3session_changeset_strm(
10041  sqlite3_session *pSession,
10042  int (*xOutput)(void *pOut, const void *pData, int nData),
10043  void *pOut
10044 );
10045 int sqlite3session_patchset_strm(
10046  sqlite3_session *pSession,
10047  int (*xOutput)(void *pOut, const void *pData, int nData),
10048  void *pOut
10049 );
10050 int sqlite3changegroup_add_strm(sqlite3_changegroup*,
10051  int (*xInput)(void *pIn, void *pData, int *pnData),
10052  void *pIn
10053 );
10054 int sqlite3changegroup_output_strm(sqlite3_changegroup*,
10055  int (*xOutput)(void *pOut, const void *pData, int nData),
10056  void *pOut
10057 );
10058 
10059 
10060 /*
10061 ** Make sure we can call this stuff from C++.
10062 */
10063 #if 0
10064 }
10065 #endif
10066 
10067 #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
10068 
10069 /******** End of sqlite3session.h *********/
10070 /******** Begin file fts5.h *********/
10071 /*
10072 ** 2014 May 31
10073 **
10074 ** The author disclaims copyright to this source code. In place of
10075 ** a legal notice, here is a blessing:
10076 **
10077 ** May you do good and not evil.
10078 ** May you find forgiveness for yourself and forgive others.
10079 ** May you share freely, never taking more than you give.
10080 **
10081 ******************************************************************************
10082 **
10083 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
10084 ** FTS5 may be extended with:
10085 **
10086 ** * custom tokenizers, and
10087 ** * custom auxiliary functions.
10088 */
10089 
10090 
10091 #ifndef _FTS5_H
10092 #define _FTS5_H
10093 
10094 
10095 #if 0
10096 extern "C" {
10097 #endif
10098 
10099 /*************************************************************************
10100 ** CUSTOM AUXILIARY FUNCTIONS
10101 **
10102 ** Virtual table implementations may overload SQL functions by implementing
10103 ** the sqlite3_module.xFindFunction() method.
10104 */
10105 
10106 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
10107 typedef struct Fts5Context Fts5Context;
10108 typedef struct Fts5PhraseIter Fts5PhraseIter;
10109 
10110 typedef void (*fts5_extension_function)(
10111  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
10112  Fts5Context *pFts, /* First arg to pass to pApi functions */
10113  sqlite3_context *pCtx, /* Context for returning result/error */
10114  int nVal, /* Number of values in apVal[] array */
10115  sqlite3_value **apVal /* Array of trailing arguments */
10116 );
10117 
10118 struct Fts5PhraseIter {
10119  const unsigned char *a;
10120  const unsigned char *b;
10121 };
10122 
10123 /*
10124 ** EXTENSION API FUNCTIONS
10125 **
10126 ** xUserData(pFts):
10127 ** Return a copy of the context pointer the extension function was
10128 ** registered with.
10129 **
10130 ** xColumnTotalSize(pFts, iCol, pnToken):
10131 ** If parameter iCol is less than zero, set output variable *pnToken
10132 ** to the total number of tokens in the FTS5 table. Or, if iCol is
10133 ** non-negative but less than the number of columns in the table, return
10134 ** the total number of tokens in column iCol, considering all rows in
10135 ** the FTS5 table.
10136 **
10137 ** If parameter iCol is greater than or equal to the number of columns
10138 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10139 ** an OOM condition or IO error), an appropriate SQLite error code is
10140 ** returned.
10141 **
10142 ** xColumnCount(pFts):
10143 ** Return the number of columns in the table.
10144 **
10145 ** xColumnSize(pFts, iCol, pnToken):
10146 ** If parameter iCol is less than zero, set output variable *pnToken
10147 ** to the total number of tokens in the current row. Or, if iCol is
10148 ** non-negative but less than the number of columns in the table, set
10149 ** *pnToken to the number of tokens in column iCol of the current row.
10150 **
10151 ** If parameter iCol is greater than or equal to the number of columns
10152 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10153 ** an OOM condition or IO error), an appropriate SQLite error code is
10154 ** returned.
10155 **
10156 ** This function may be quite inefficient if used with an FTS5 table
10157 ** created with the "columnsize=0" option.
10158 **
10159 ** xColumnText:
10160 ** This function attempts to retrieve the text of column iCol of the
10161 ** current document. If successful, (*pz) is set to point to a buffer
10162 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
10163 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
10164 ** if an error occurs, an SQLite error code is returned and the final values
10165 ** of (*pz) and (*pn) are undefined.
10166 **
10167 ** xPhraseCount:
10168 ** Returns the number of phrases in the current query expression.
10169 **
10170 ** xPhraseSize:
10171 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
10172 ** are numbered starting from zero.
10173 **
10174 ** xInstCount:
10175 ** Set *pnInst to the total number of occurrences of all phrases within
10176 ** the query within the current row. Return SQLITE_OK if successful, or
10177 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
10178 **
10179 ** This API can be quite slow if used with an FTS5 table created with the
10180 ** "detail=none" or "detail=column" option. If the FTS5 table is created
10181 ** with either "detail=none" or "detail=column" and "content=" option
10182 ** (i.e. if it is a contentless table), then this API always returns 0.
10183 **
10184 ** xInst:
10185 ** Query for the details of phrase match iIdx within the current row.
10186 ** Phrase matches are numbered starting from zero, so the iIdx argument
10187 ** should be greater than or equal to zero and smaller than the value
10188 ** output by xInstCount().
10189 **
10190 ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
10191 ** to the column in which it occurs and *piOff the token offset of the
10192 ** first token of the phrase. The exception is if the table was created
10193 ** with the offsets=0 option specified. In this case *piOff is always
10194 ** set to -1.
10195 **
10196 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
10197 ** if an error occurs.
10198 **
10199 ** This API can be quite slow if used with an FTS5 table created with the
10200 ** "detail=none" or "detail=column" option.
10201 **
10202 ** xRowid:
10203 ** Returns the rowid of the current row.
10204 **
10205 ** xTokenize:
10206 ** Tokenize text using the tokenizer belonging to the FTS5 table.
10207 **
10208 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
10209 ** This API function is used to query the FTS table for phrase iPhrase
10210 ** of the current query. Specifically, a query equivalent to:
10211 **
10212 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
10213 **
10214 ** with $p set to a phrase equivalent to the phrase iPhrase of the
10215 ** current query is executed. Any column filter that applies to
10216 ** phrase iPhrase of the current query is included in $p. For each
10217 ** row visited, the callback function passed as the fourth argument
10218 ** is invoked. The context and API objects passed to the callback
10219 ** function may be used to access the properties of each matched row.
10220 ** Invoking Api.xUserData() returns a copy of the pointer passed as
10221 ** the third argument to pUserData.
10222 **
10223 ** If the callback function returns any value other than SQLITE_OK, the
10224 ** query is abandoned and the xQueryPhrase function returns immediately.
10225 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
10226 ** Otherwise, the error code is propagated upwards.
10227 **
10228 ** If the query runs to completion without incident, SQLITE_OK is returned.
10229 ** Or, if some error occurs before the query completes or is aborted by
10230 ** the callback, an SQLite error code is returned.
10231 **
10232 **
10233 ** xSetAuxdata(pFts5, pAux, xDelete)
10234 **
10235 ** Save the pointer passed as the second argument as the extension functions
10236 ** "auxiliary data". The pointer may then be retrieved by the current or any
10237 ** future invocation of the same fts5 extension function made as part of
10238 ** of the same MATCH query using the xGetAuxdata() API.
10239 **
10240 ** Each extension function is allocated a single auxiliary data slot for
10241 ** each FTS query (MATCH expression). If the extension function is invoked
10242 ** more than once for a single FTS query, then all invocations share a
10243 ** single auxiliary data context.
10244 **
10245 ** If there is already an auxiliary data pointer when this function is
10246 ** invoked, then it is replaced by the new pointer. If an xDelete callback
10247 ** was specified along with the original pointer, it is invoked at this
10248 ** point.
10249 **
10250 ** The xDelete callback, if one is specified, is also invoked on the
10251 ** auxiliary data pointer after the FTS5 query has finished.
10252 **
10253 ** If an error (e.g. an OOM condition) occurs within this function, an
10254 ** the auxiliary data is set to NULL and an error code returned. If the
10255 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
10256 ** pointer before returning.
10257 **
10258 **
10259 ** xGetAuxdata(pFts5, bClear)
10260 **
10261 ** Returns the current auxiliary data pointer for the fts5 extension
10262 ** function. See the xSetAuxdata() method for details.
10263 **
10264 ** If the bClear argument is non-zero, then the auxiliary data is cleared
10265 ** (set to NULL) before this function returns. In this case the xDelete,
10266 ** if any, is not invoked.
10267 **
10268 **
10269 ** xRowCount(pFts5, pnRow)
10270 **
10271 ** This function is used to retrieve the total number of rows in the table.
10272 ** In other words, the same value that would be returned by:
10273 **
10274 ** SELECT count(*) FROM ftstable;
10275 **
10276 ** xPhraseFirst()
10277 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
10278 ** method, to iterate through all instances of a single query phrase within
10279 ** the current row. This is the same information as is accessible via the
10280 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
10281 ** to use, this API may be faster under some circumstances. To iterate
10282 ** through instances of phrase iPhrase, use the following code:
10283 **
10284 ** Fts5PhraseIter iter;
10285 ** int iCol, iOff;
10286 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
10287 ** iCol>=0;
10288 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
10289 ** ){
10290 ** // An instance of phrase iPhrase at offset iOff of column iCol
10291 ** }
10292 **
10293 ** The Fts5PhraseIter structure is defined above. Applications should not
10294 ** modify this structure directly - it should only be used as shown above
10295 ** with the xPhraseFirst() and xPhraseNext() API methods (and by
10296 ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
10297 **
10298 ** This API can be quite slow if used with an FTS5 table created with the
10299 ** "detail=none" or "detail=column" option. If the FTS5 table is created
10300 ** with either "detail=none" or "detail=column" and "content=" option
10301 ** (i.e. if it is a contentless table), then this API always iterates
10302 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
10303 **
10304 ** xPhraseNext()
10305 ** See xPhraseFirst above.
10306 **
10307 ** xPhraseFirstColumn()
10308 ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
10309 ** and xPhraseNext() APIs described above. The difference is that instead
10310 ** of iterating through all instances of a phrase in the current row, these
10311 ** APIs are used to iterate through the set of columns in the current row
10312 ** that contain one or more instances of a specified phrase. For example:
10313 **
10314 ** Fts5PhraseIter iter;
10315 ** int iCol;
10316 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
10317 ** iCol>=0;
10318 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
10319 ** ){
10320 ** // Column iCol contains at least one instance of phrase iPhrase
10321 ** }
10322 **
10323 ** This API can be quite slow if used with an FTS5 table created with the
10324 ** "detail=none" option. If the FTS5 table is created with either
10325 ** "detail=none" "content=" option (i.e. if it is a contentless table),
10326 ** then this API always iterates through an empty set (all calls to
10327 ** xPhraseFirstColumn() set iCol to -1).
10328 **
10329 ** The information accessed using this API and its companion
10330 ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
10331 ** (or xInst/xInstCount). The chief advantage of this API is that it is
10332 ** significantly more efficient than those alternatives when used with
10333 ** "detail=column" tables.
10334 **
10335 ** xPhraseNextColumn()
10336 ** See xPhraseFirstColumn above.
10337 */
10338 struct Fts5ExtensionApi {
10339  int iVersion; /* Currently always set to 3 */
10340 
10341  void *(*xUserData)(Fts5Context*);
10342 
10343  int (*xColumnCount)(Fts5Context*);
10344  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
10345  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
10346 
10347  int (*xTokenize)(Fts5Context*,
10348  const char *pText, int nText, /* Text to tokenize */
10349  void *pCtx, /* Context passed to xToken() */
10350  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
10351  );
10352 
10353  int (*xPhraseCount)(Fts5Context*);
10354  int (*xPhraseSize)(Fts5Context*, int iPhrase);
10355 
10356  int (*xInstCount)(Fts5Context*, int *pnInst);
10357  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
10358 
10359  sqlite3_int64 (*xRowid)(Fts5Context*);
10360  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
10361  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
10362 
10363  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
10364  int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
10365  );
10366  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
10367  void *(*xGetAuxdata)(Fts5Context*, int bClear);
10368 
10369  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
10370  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
10371 
10372  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
10373  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
10374 };
10375 
10376 /*
10377 ** CUSTOM AUXILIARY FUNCTIONS
10378 *************************************************************************/
10379 
10380 /*************************************************************************
10381 ** CUSTOM TOKENIZERS
10382 **
10383 ** Applications may also register custom tokenizer types. A tokenizer
10384 ** is registered by providing fts5 with a populated instance of the
10385 ** following structure. All structure methods must be defined, setting
10386 ** any member of the fts5_tokenizer struct to NULL leads to undefined
10387 ** behaviour. The structure methods are expected to function as follows:
10388 **
10389 ** xCreate:
10390 ** This function is used to allocate and initialize a tokenizer instance.
10391 ** A tokenizer instance is required to actually tokenize text.
10392 **
10393 ** The first argument passed to this function is a copy of the (void*)
10394 ** pointer provided by the application when the fts5_tokenizer object
10395 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
10396 ** The second and third arguments are an array of nul-terminated strings
10397 ** containing the tokenizer arguments, if any, specified following the
10398 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
10399 ** to create the FTS5 table.
10400 **
10401 ** The final argument is an output variable. If successful, (*ppOut)
10402 ** should be set to point to the new tokenizer handle and SQLITE_OK
10403 ** returned. If an error occurs, some value other than SQLITE_OK should
10404 ** be returned. In this case, fts5 assumes that the final value of *ppOut
10405 ** is undefined.
10406 **
10407 ** xDelete:
10408 ** This function is invoked to delete a tokenizer handle previously
10409 ** allocated using xCreate(). Fts5 guarantees that this function will
10410 ** be invoked exactly once for each successful call to xCreate().
10411 **
10412 ** xTokenize:
10413 ** This function is expected to tokenize the nText byte string indicated
10414 ** by argument pText. pText may or may not be nul-terminated. The first
10415 ** argument passed to this function is a pointer to an Fts5Tokenizer object
10416 ** returned by an earlier call to xCreate().
10417 **
10418 ** The second argument indicates the reason that FTS5 is requesting
10419 ** tokenization of the supplied text. This is always one of the following
10420 ** four values:
10421 **
10422 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
10423 ** or removed from the FTS table. The tokenizer is being invoked to
10424 ** determine the set of tokens to add to (or delete from) the
10425 ** FTS index.
10426 **
10427 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
10428 ** against the FTS index. The tokenizer is being called to tokenize
10429 ** a bareword or quoted string specified as part of the query.
10430 **
10431 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
10432 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
10433 ** followed by a "*" character, indicating that the last token
10434 ** returned by the tokenizer will be treated as a token prefix.
10435 **
10436 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
10437 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
10438 ** function. Or an fts5_api.xColumnSize() request made by the same
10439 ** on a columnsize=0 database.
10440 ** </ul>
10441 **
10442 ** For each token in the input string, the supplied callback xToken() must
10443 ** be invoked. The first argument to it should be a copy of the pointer
10444 ** passed as the second argument to xTokenize(). The third and fourth
10445 ** arguments are a pointer to a buffer containing the token text, and the
10446 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
10447 ** of the first byte of and first byte immediately following the text from
10448 ** which the token is derived within the input.
10449 **
10450 ** The second argument passed to the xToken() callback ("tflags") should
10451 ** normally be set to 0. The exception is if the tokenizer supports
10452 ** synonyms. In this case see the discussion below for details.
10453 **
10454 ** FTS5 assumes the xToken() callback is invoked for each token in the
10455 ** order that they occur within the input text.
10456 **
10457 ** If an xToken() callback returns any value other than SQLITE_OK, then
10458 ** the tokenization should be abandoned and the xTokenize() method should
10459 ** immediately return a copy of the xToken() return value. Or, if the
10460 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
10461 ** if an error occurs with the xTokenize() implementation itself, it
10462 ** may abandon the tokenization and return any error code other than
10463 ** SQLITE_OK or SQLITE_DONE.
10464 **
10465 ** SYNONYM SUPPORT
10466 **
10467 ** Custom tokenizers may also support synonyms. Consider a case in which a
10468 ** user wishes to query for a phrase such as "first place". Using the
10469 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
10470 ** of "first place" within the document set, but not alternative forms
10471 ** such as "1st place". In some applications, it would be better to match
10472 ** all instances of "first place" or "1st place" regardless of which form
10473 ** the user specified in the MATCH query text.
10474 **
10475 ** There are several ways to approach this in FTS5:
10476 **
10477 ** <ol><li> By mapping all synonyms to a single token. In this case, the
10478 ** In the above example, this means that the tokenizer returns the
10479 ** same token for inputs "first" and "1st". Say that token is in
10480 ** fact "first", so that when the user inserts the document "I won
10481 ** 1st place" entries are added to the index for tokens "i", "won",
10482 ** "first" and "place". If the user then queries for '1st + place',
10483 ** the tokenizer substitutes "first" for "1st" and the query works
10484 ** as expected.
10485 **
10486 ** <li> By adding multiple synonyms for a single term to the FTS index.
10487 ** In this case, when tokenizing query text, the tokenizer may
10488 ** provide multiple synonyms for a single term within the document.
10489 ** FTS5 then queries the index for each synonym individually. For
10490 ** example, faced with the query:
10491 **
10492 ** <codeblock>
10493 ** ... MATCH 'first place'</codeblock>
10494 **
10495 ** the tokenizer offers both "1st" and "first" as synonyms for the
10496 ** first token in the MATCH query and FTS5 effectively runs a query
10497 ** similar to:
10498 **
10499 ** <codeblock>
10500 ** ... MATCH '(first OR 1st) place'</codeblock>
10501 **
10502 ** except that, for the purposes of auxiliary functions, the query
10503 ** still appears to contain just two phrases - "(first OR 1st)"
10504 ** being treated as a single phrase.
10505 **
10506 ** <li> By adding multiple synonyms for a single term to the FTS index.
10507 ** Using this method, when tokenizing document text, the tokenizer
10508 ** provides multiple synonyms for each token. So that when a
10509 ** document such as "I won first place" is tokenized, entries are
10510 ** added to the FTS index for "i", "won", "first", "1st" and
10511 ** "place".
10512 **
10513 ** This way, even if the tokenizer does not provide synonyms
10514 ** when tokenizing query text (it should not - to do would be
10515 ** inefficient), it doesn't matter if the user queries for
10516 ** 'first + place' or '1st + place', as there are entires in the
10517 ** FTS index corresponding to both forms of the first token.
10518 ** </ol>
10519 **
10520 ** Whether it is parsing document or query text, any call to xToken that
10521 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
10522 ** is considered to supply a synonym for the previous token. For example,
10523 ** when parsing the document "I won first place", a tokenizer that supports
10524 ** synonyms would call xToken() 5 times, as follows:
10525 **
10526 ** <codeblock>
10527 ** xToken(pCtx, 0, "i", 1, 0, 1);
10528 ** xToken(pCtx, 0, "won", 3, 2, 5);
10529 ** xToken(pCtx, 0, "first", 5, 6, 11);
10530 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
10531 ** xToken(pCtx, 0, "place", 5, 12, 17);
10532 **</codeblock>
10533 **
10534 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
10535 ** xToken() is called. Multiple synonyms may be specified for a single token
10536 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
10537 ** There is no limit to the number of synonyms that may be provided for a
10538 ** single token.
10539 **
10540 ** In many cases, method (1) above is the best approach. It does not add
10541 ** extra data to the FTS index or require FTS5 to query for multiple terms,
10542 ** so it is efficient in terms of disk space and query speed. However, it
10543 ** does not support prefix queries very well. If, as suggested above, the
10544 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
10545 **
10546 ** <codeblock>
10547 ** ... MATCH '1s*'</codeblock>
10548 **
10549 ** will not match documents that contain the token "1st" (as the tokenizer
10550 ** will probably not map "1s" to any prefix of "first").
10551 **
10552 ** For full prefix support, method (3) may be preferred. In this case,
10553 ** because the index contains entries for both "first" and "1st", prefix
10554 ** queries such as 'fi*' or '1s*' will match correctly. However, because
10555 ** extra entries are added to the FTS index, this method uses more space
10556 ** within the database.
10557 **
10558 ** Method (2) offers a midpoint between (1) and (3). Using this method,
10559 ** a query such as '1s*' will match documents that contain the literal
10560 ** token "1st", but not "first" (assuming the tokenizer is not able to
10561 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
10562 ** will match against "1st" and "first". This method does not require
10563 ** extra disk space, as no extra entries are added to the FTS index.
10564 ** On the other hand, it may require more CPU cycles to run MATCH queries,
10565 ** as separate queries of the FTS index are required for each synonym.
10566 **
10567 ** When using methods (2) or (3), it is important that the tokenizer only
10568 ** provide synonyms when tokenizing document text (method (2)) or query
10569 ** text (method (3)), not both. Doing so will not cause any errors, but is
10570 ** inefficient.
10571 */
10572 typedef struct Fts5Tokenizer Fts5Tokenizer;
10573 typedef struct fts5_tokenizer fts5_tokenizer;
10574 struct fts5_tokenizer {
10575  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
10576  void (*xDelete)(Fts5Tokenizer*);
10577  int (*xTokenize)(Fts5Tokenizer*,
10578  void *pCtx,
10579  int flags, /* Mask of FTS5_TOKENIZE_* flags */
10580  const char *pText, int nText,
10581  int (*xToken)(
10582  void *pCtx, /* Copy of 2nd argument to xTokenize() */
10583  int tflags, /* Mask of FTS5_TOKEN_* flags */
10584  const char *pToken, /* Pointer to buffer containing token */
10585  int nToken, /* Size of token in bytes */
10586  int iStart, /* Byte offset of token within input text */
10587  int iEnd /* Byte offset of end of token within input text */
10588  )
10589  );
10590 };
10591 
10592 /* Flags that may be passed as the third argument to xTokenize() */
10593 #define FTS5_TOKENIZE_QUERY 0x0001
10594 #define FTS5_TOKENIZE_PREFIX 0x0002
10595 #define FTS5_TOKENIZE_DOCUMENT 0x0004
10596 #define FTS5_TOKENIZE_AUX 0x0008
10597 
10598 /* Flags that may be passed by the tokenizer implementation back to FTS5
10599 ** as the third argument to the supplied xToken callback. */
10600 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
10601 
10602 /*
10603 ** END OF CUSTOM TOKENIZERS
10604 *************************************************************************/
10605 
10606 /*************************************************************************
10607 ** FTS5 EXTENSION REGISTRATION API
10608 */
10609 typedef struct fts5_api fts5_api;
10610 struct fts5_api {
10611  int iVersion; /* Currently always set to 2 */
10612 
10613  /* Create a new tokenizer */
10614  int (*xCreateTokenizer)(
10615  fts5_api *pApi,
10616  const char *zName,
10617  void *pContext,
10618  fts5_tokenizer *pTokenizer,
10619  void (*xDestroy)(void*)
10620  );
10621 
10622  /* Find an existing tokenizer */
10623  int (*xFindTokenizer)(
10624  fts5_api *pApi,
10625  const char *zName,
10626  void **ppContext,
10627  fts5_tokenizer *pTokenizer
10628  );
10629 
10630  /* Create a new auxiliary function */
10631  int (*xCreateFunction)(
10632  fts5_api *pApi,
10633  const char *zName,
10634  void *pContext,
10635  fts5_extension_function xFunction,
10636  void (*xDestroy)(void*)
10637  );
10638 };
10639 
10640 /*
10641 ** END OF REGISTRATION API
10642 *************************************************************************/
10643 
10644 #if 0
10645 } /* end of the 'extern "C"' block */
10646 #endif
10647 
10648 #endif /* _FTS5_H */
10649 
10650 /******** End of fts5.h *********/
10651 
10652 /************** End of sqlite3.h *********************************************/
10653 /************** Continuing where we left off in sqliteInt.h ******************/
10654 
10655 /*
10656 ** Include the configuration header output by 'configure' if we're using the
10657 ** autoconf-based build
10658 */
10659 #ifdef _HAVE_SQLITE_CONFIG_H
10660 #include "config.h"
10661 #endif
10662 
10663 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
10664 /************** Begin file sqliteLimit.h *************************************/
10665 /*
10666 ** 2007 May 7
10667 **
10668 ** The author disclaims copyright to this source code. In place of
10669 ** a legal notice, here is a blessing:
10670 **
10671 ** May you do good and not evil.
10672 ** May you find forgiveness for yourself and forgive others.
10673 ** May you share freely, never taking more than you give.
10674 **
10675 *************************************************************************
10676 **
10677 ** This file defines various limits of what SQLite can process.
10678 */
10679 
10680 /*
10681 ** The maximum length of a TEXT or BLOB in bytes. This also
10682 ** limits the size of a row in a table or index.
10683 **
10684 ** The hard limit is the ability of a 32-bit signed integer
10685 ** to count the size: 2^31-1 or 2147483647.
10686 */
10687 #ifndef SQLITE_MAX_LENGTH
10688 # define SQLITE_MAX_LENGTH 1000000000
10689 #endif
10690 
10691 /*
10692 ** This is the maximum number of
10693 **
10694 ** * Columns in a table
10695 ** * Columns in an index
10696 ** * Columns in a view
10697 ** * Terms in the SET clause of an UPDATE statement
10698 ** * Terms in the result set of a SELECT statement
10699 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
10700 ** * Terms in the VALUES clause of an INSERT statement
10701 **
10702 ** The hard upper limit here is 32676. Most database people will
10703 ** tell you that in a well-normalized database, you usually should
10704 ** not have more than a dozen or so columns in any table. And if
10705 ** that is the case, there is no point in having more than a few
10706 ** dozen values in any of the other situations described above.
10707 */
10708 #ifndef SQLITE_MAX_COLUMN
10709 # define SQLITE_MAX_COLUMN 2000
10710 #endif
10711 
10712 /*
10713 ** The maximum length of a single SQL statement in bytes.
10714 **
10715 ** It used to be the case that setting this value to zero would
10716 ** turn the limit off. That is no longer true. It is not possible
10717 ** to turn this limit off.
10718 */
10719 #ifndef SQLITE_MAX_SQL_LENGTH
10720 # define SQLITE_MAX_SQL_LENGTH 1000000000
10721 #endif
10722 
10723 /*
10724 ** The maximum depth of an expression tree. This is limited to
10725 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
10726 ** want to place more severe limits on the complexity of an
10727 ** expression.
10728 **
10729 ** A value of 0 used to mean that the limit was not enforced.
10730 ** But that is no longer true. The limit is now strictly enforced
10731 ** at all times.
10732 */
10733 #ifndef SQLITE_MAX_EXPR_DEPTH
10734 # define SQLITE_MAX_EXPR_DEPTH 1000
10735 #endif
10736 
10737 /*
10738 ** The maximum number of terms in a compound SELECT statement.
10739 ** The code generator for compound SELECT statements does one
10740 ** level of recursion for each term. A stack overflow can result
10741 ** if the number of terms is too large. In practice, most SQL
10742 ** never has more than 3 or 4 terms. Use a value of 0 to disable
10743 ** any limit on the number of terms in a compount SELECT.
10744 */
10745 #ifndef SQLITE_MAX_COMPOUND_SELECT
10746 # define SQLITE_MAX_COMPOUND_SELECT 500
10747 #endif
10748 
10749 /*
10750 ** The maximum number of opcodes in a VDBE program.
10751 ** Not currently enforced.
10752 */
10753 #ifndef SQLITE_MAX_VDBE_OP
10754 # define SQLITE_MAX_VDBE_OP 25000
10755 #endif
10756 
10757 /*
10758 ** The maximum number of arguments to an SQL function.
10759 */
10760 #ifndef SQLITE_MAX_FUNCTION_ARG
10761 # define SQLITE_MAX_FUNCTION_ARG 127
10762 #endif
10763 
10764 /*
10765 ** The suggested maximum number of in-memory pages to use for
10766 ** the main database table and for temporary tables.
10767 **
10768 ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
10769 ** which means the cache size is limited to 2048000 bytes of memory.
10770 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
10771 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
10772 */
10773 #ifndef SQLITE_DEFAULT_CACHE_SIZE
10774 # define SQLITE_DEFAULT_CACHE_SIZE -2000
10775 #endif
10776 
10777 /*
10778 ** The default number of frames to accumulate in the log file before
10779 ** checkpointing the database in WAL mode.
10780 */
10781 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
10782 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
10783 #endif
10784 
10785 /*
10786 ** The maximum number of attached databases. This must be between 0
10787 ** and 125. The upper bound of 125 is because the attached databases are
10788 ** counted using a signed 8-bit integer which has a maximum value of 127
10789 ** and we have to allow 2 extra counts for the "main" and "temp" databases.
10790 */
10791 #ifndef SQLITE_MAX_ATTACHED
10792 # define SQLITE_MAX_ATTACHED 10
10793 #endif
10794 
10795 
10796 /*
10797 ** The maximum value of a ?nnn wildcard that the parser will accept.
10798 */
10799 #ifndef SQLITE_MAX_VARIABLE_NUMBER
10800 # define SQLITE_MAX_VARIABLE_NUMBER 999
10801 #endif
10802 
10803 /* Maximum page size. The upper bound on this value is 65536. This a limit
10804 ** imposed by the use of 16-bit offsets within each page.
10805 **
10806 ** Earlier versions of SQLite allowed the user to change this value at
10807 ** compile time. This is no longer permitted, on the grounds that it creates
10808 ** a library that is technically incompatible with an SQLite library
10809 ** compiled with a different limit. If a process operating on a database
10810 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
10811 ** compiled with the default page-size limit will not be able to rollback
10812 ** the aborted transaction. This could lead to database corruption.
10813 */
10814 #ifdef SQLITE_MAX_PAGE_SIZE
10815 # undef SQLITE_MAX_PAGE_SIZE
10816 #endif
10817 #define SQLITE_MAX_PAGE_SIZE 65536
10818 
10819 
10820 /*
10821 ** The default size of a database page.
10822 */
10823 #ifndef SQLITE_DEFAULT_PAGE_SIZE
10824 # define SQLITE_DEFAULT_PAGE_SIZE 4096
10825 #endif
10826 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10827 # undef SQLITE_DEFAULT_PAGE_SIZE
10828 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10829 #endif
10830 
10831 /*
10832 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
10833 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
10834 ** device characteristics (sector-size and atomic write() support),
10835 ** SQLite may choose a larger value. This constant is the maximum value
10836 ** SQLite will choose on its own.
10837 */
10838 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
10839 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
10840 #endif
10841 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10842 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
10843 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10844 #endif
10845 
10846 
10847 /*
10848 ** Maximum number of pages in one database file.
10849 **
10850 ** This is really just the default value for the max_page_count pragma.
10851 ** This value can be lowered (or raised) at run-time using that the
10852 ** max_page_count macro.
10853 */
10854 #ifndef SQLITE_MAX_PAGE_COUNT
10855 # define SQLITE_MAX_PAGE_COUNT 1073741823
10856 #endif
10857 
10858 /*
10859 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
10860 ** operator.
10861 */
10862 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
10863 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
10864 #endif
10865 
10866 /*
10867 ** Maximum depth of recursion for triggers.
10868 **
10869 ** A value of 1 means that a trigger program will not be able to itself
10870 ** fire any triggers. A value of 0 means that no trigger programs at all
10871 ** may be executed.
10872 */
10873 #ifndef SQLITE_MAX_TRIGGER_DEPTH
10874 # define SQLITE_MAX_TRIGGER_DEPTH 1000
10875 #endif
10876 
10877 /************** End of sqliteLimit.h *****************************************/
10878 /************** Continuing where we left off in sqliteInt.h ******************/
10879 
10880 /* Disable nuisance warnings on Borland compilers */
10881 #if defined(__BORLANDC__)
10882 #pragma warn -rch /* unreachable code */
10883 #pragma warn -ccc /* Condition is always true or false */
10884 #pragma warn -aus /* Assigned value is never used */
10885 #pragma warn -csu /* Comparing signed and unsigned */
10886 #pragma warn -spa /* Suspicious pointer arithmetic */
10887 #endif
10888 
10889 /*
10890 ** Include standard header files as necessary
10891 */
10892 #ifdef HAVE_STDINT_H
10893 #include <stdint.h>
10894 #endif
10895 #ifdef HAVE_INTTYPES_H
10896 #include <inttypes.h>
10897 #endif
10898 
10899 /*
10900 ** The following macros are used to cast pointers to integers and
10901 ** integers to pointers. The way you do this varies from one compiler
10902 ** to the next, so we have developed the following set of #if statements
10903 ** to generate appropriate macros for a wide range of compilers.
10904 **
10905 ** The correct "ANSI" way to do this is to use the intptr_t type.
10906 ** Unfortunately, that typedef is not available on all compilers, or
10907 ** if it is available, it requires an #include of specific headers
10908 ** that vary from one machine to the next.
10909 **
10910 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
10911 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
10912 ** So we have to define the macros in different ways depending on the
10913 ** compiler.
10914 */
10915 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
10916 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
10917 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
10918 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
10919 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
10920 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
10921 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
10922 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
10923 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
10924 #else /* Generates a warning - but it always works */
10925 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
10926 # define SQLITE_PTR_TO_INT(X) ((int)(X))
10927 #endif
10928 
10929 /*
10930 ** A macro to hint to the compiler that a function should not be
10931 ** inlined.
10932 */
10933 #if defined(__GNUC__)
10934 # define SQLITE_NOINLINE __attribute__((noinline))
10935 #elif defined(_MSC_VER) && _MSC_VER>=1310
10936 # define SQLITE_NOINLINE __declspec(noinline)
10937 #else
10938 # define SQLITE_NOINLINE
10939 #endif
10940 
10941 /*
10942 ** Make sure that the compiler intrinsics we desire are enabled when
10943 ** compiling with an appropriate version of MSVC unless prevented by
10944 ** the SQLITE_DISABLE_INTRINSIC define.
10945 */
10946 #if !defined(SQLITE_DISABLE_INTRINSIC)
10947 # if defined(_MSC_VER) && _MSC_VER>=1400
10948 # if !defined(_WIN32_WCE)
10949 # include <intrin.h>
10950 # pragma intrinsic(_byteswap_ushort)
10951 # pragma intrinsic(_byteswap_ulong)
10952 # pragma intrinsic(_ReadWriteBarrier)
10953 # else
10954 # include <cmnintrin.h>
10955 # endif
10956 # endif
10957 #endif
10958 
10959 /*
10960 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
10961 ** 0 means mutexes are permanently disable and the library is never
10962 ** threadsafe. 1 means the library is serialized which is the highest
10963 ** level of threadsafety. 2 means the library is multithreaded - multiple
10964 ** threads can use SQLite as long as no two threads try to use the same
10965 ** database connection at the same time.
10966 **
10967 ** Older versions of SQLite used an optional THREADSAFE macro.
10968 ** We support that for legacy.
10969 */
10970 #if !defined(SQLITE_THREADSAFE)
10971 # if defined(THREADSAFE)
10972 # define SQLITE_THREADSAFE THREADSAFE
10973 # else
10974 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
10975 # endif
10976 #endif
10977 
10978 /*
10979 ** Powersafe overwrite is on by default. But can be turned off using
10980 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
10981 */
10982 #ifndef SQLITE_POWERSAFE_OVERWRITE
10983 # define SQLITE_POWERSAFE_OVERWRITE 1
10984 #endif
10985 
10986 /*
10987 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
10988 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
10989 ** which case memory allocation statistics are disabled by default.
10990 */
10991 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
10992 # define SQLITE_DEFAULT_MEMSTATUS 1
10993 #endif
10994 
10995 /*
10996 ** Exactly one of the following macros must be defined in order to
10997 ** specify which memory allocation subsystem to use.
10998 **
10999 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
11000 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
11001 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
11002 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
11003 **
11004 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
11005 ** assert() macro is enabled, each call into the Win32 native heap subsystem
11006 ** will cause HeapValidate to be called. If heap validation should fail, an
11007 ** assertion will be triggered.
11008 **
11009 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
11010 ** the default.
11011 */
11012 #if defined(SQLITE_SYSTEM_MALLOC) \
11013  + defined(SQLITE_WIN32_MALLOC) \
11014  + defined(SQLITE_ZERO_MALLOC) \
11015  + defined(SQLITE_MEMDEBUG)>1
11016 # error "Two or more of the following compile-time configuration options\
11017  are defined but at most one is allowed:\
11018  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
11019  SQLITE_ZERO_MALLOC"
11020 #endif
11021 #if defined(SQLITE_SYSTEM_MALLOC) \
11022  + defined(SQLITE_WIN32_MALLOC) \
11023  + defined(SQLITE_ZERO_MALLOC) \
11024  + defined(SQLITE_MEMDEBUG)==0
11025 # define SQLITE_SYSTEM_MALLOC 1
11026 #endif
11027 
11028 /*
11029 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
11030 ** sizes of memory allocations below this value where possible.
11031 */
11032 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
11033 # define SQLITE_MALLOC_SOFT_LIMIT 1024
11034 #endif
11035 
11036 /*
11037 ** We need to define _XOPEN_SOURCE as follows in order to enable
11038 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
11039 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
11040 ** it.
11041 */
11042 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
11043 # define _XOPEN_SOURCE 600
11044 #endif
11045 
11046 /*
11047 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
11048 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
11049 ** make it true by defining or undefining NDEBUG.
11050 **
11051 ** Setting NDEBUG makes the code smaller and faster by disabling the
11052 ** assert() statements in the code. So we want the default action
11053 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
11054 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
11055 ** feature.
11056 */
11057 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
11058 # define NDEBUG 1
11059 #endif
11060 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
11061 # undef NDEBUG
11062 #endif
11063 
11064 /*
11065 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
11066 */
11067 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
11068 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
11069 #endif
11070 
11071 /*
11072 ** The testcase() macro is used to aid in coverage testing. When
11073 ** doing coverage testing, the condition inside the argument to
11074 ** testcase() must be evaluated both true and false in order to
11075 ** get full branch coverage. The testcase() macro is inserted
11076 ** to help ensure adequate test coverage in places where simple
11077 ** condition/decision coverage is inadequate. For example, testcase()
11078 ** can be used to make sure boundary values are tested. For
11079 ** bitmask tests, testcase() can be used to make sure each bit
11080 ** is significant and used at least once. On switch statements
11081 ** where multiple cases go to the same block of code, testcase()
11082 ** can insure that all cases are evaluated.
11083 **
11084 */
11085 #ifdef SQLITE_COVERAGE_TEST
11086 SQLITE_PRIVATE void sqlite3Coverage(int);
11087 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
11088 #else
11089 # define testcase(X)
11090 #endif
11091 
11092 /*
11093 ** The TESTONLY macro is used to enclose variable declarations or
11094 ** other bits of code that are needed to support the arguments
11095 ** within testcase() and assert() macros.
11096 */
11097 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
11098 # define TESTONLY(X) X
11099 #else
11100 # define TESTONLY(X)
11101 #endif
11102 
11103 /*
11104 ** Sometimes we need a small amount of code such as a variable initialization
11105 ** to setup for a later assert() statement. We do not want this code to
11106 ** appear when assert() is disabled. The following macro is therefore
11107 ** used to contain that setup code. The "VVA" acronym stands for
11108 ** "Verification, Validation, and Accreditation". In other words, the
11109 ** code within VVA_ONLY() will only run during verification processes.
11110 */
11111 #ifndef NDEBUG
11112 # define VVA_ONLY(X) X
11113 #else
11114 # define VVA_ONLY(X)
11115 #endif
11116 
11117 /*
11118 ** The ALWAYS and NEVER macros surround boolean expressions which
11119 ** are intended to always be true or false, respectively. Such
11120 ** expressions could be omitted from the code completely. But they
11121 ** are included in a few cases in order to enhance the resilience
11122 ** of SQLite to unexpected behavior - to make the code "self-healing"
11123 ** or "ductile" rather than being "brittle" and crashing at the first
11124 ** hint of unplanned behavior.
11125 **
11126 ** In other words, ALWAYS and NEVER are added for defensive code.
11127 **
11128 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
11129 ** be true and false so that the unreachable code they specify will
11130 ** not be counted as untested code.
11131 */
11132 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11133 # define ALWAYS(X) (1)
11134 # define NEVER(X) (0)
11135 #elif !defined(NDEBUG)
11136 # define ALWAYS(X) ((X)?1:(assert(0),0))
11137 # define NEVER(X) ((X)?(assert(0),1):0)
11138 #else
11139 # define ALWAYS(X) (X)
11140 # define NEVER(X) (X)
11141 #endif
11142 
11143 /*
11144 ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
11145 ** defined. We need to defend against those failures when testing with
11146 ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
11147 ** during a normal build. The following macro can be used to disable tests
11148 ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
11149 */
11150 #if defined(SQLITE_TEST_REALLOC_STRESS)
11151 # define ONLY_IF_REALLOC_STRESS(X) (X)
11152 #elif !defined(NDEBUG)
11153 # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
11154 #else
11155 # define ONLY_IF_REALLOC_STRESS(X) (0)
11156 #endif
11157 
11158 /*
11159 ** Declarations used for tracing the operating system interfaces.
11160 */
11161 #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
11162  (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11163  extern int sqlite3OSTrace;
11164 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
11165 # define SQLITE_HAVE_OS_TRACE
11166 #else
11167 # define OSTRACE(X)
11168 # undef SQLITE_HAVE_OS_TRACE
11169 #endif
11170 
11171 /*
11172 ** Is the sqlite3ErrName() function needed in the build? Currently,
11173 ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
11174 ** OSTRACE is enabled), and by several "test*.c" files (which are
11175 ** compiled using SQLITE_TEST).
11176 */
11177 #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
11178  (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11179 # define SQLITE_NEED_ERR_NAME
11180 #else
11181 # undef SQLITE_NEED_ERR_NAME
11182 #endif
11183 
11184 /*
11185 ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
11186 */
11187 #ifdef SQLITE_OMIT_EXPLAIN
11188 # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
11189 #endif
11190 
11191 /*
11192 ** Return true (non-zero) if the input is an integer that is too large
11193 ** to fit in 32-bits. This macro is used inside of various testcase()
11194 ** macros to verify that we have tested SQLite for large-file support.
11195 */
11196 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
11197 
11198 /*
11199 ** The macro unlikely() is a hint that surrounds a boolean
11200 ** expression that is usually false. Macro likely() surrounds
11201 ** a boolean expression that is usually true. These hints could,
11202 ** in theory, be used by the compiler to generate better code, but
11203 ** currently they are just comments for human readers.
11204 */
11205 #define likely(X) (X)
11206 #define unlikely(X) (X)
11207 
11208 /************** Include hash.h in the middle of sqliteInt.h ******************/
11209 /************** Begin file hash.h ********************************************/
11210 /*
11211 ** 2001 September 22
11212 **
11213 ** The author disclaims copyright to this source code. In place of
11214 ** a legal notice, here is a blessing:
11215 **
11216 ** May you do good and not evil.
11217 ** May you find forgiveness for yourself and forgive others.
11218 ** May you share freely, never taking more than you give.
11219 **
11220 *************************************************************************
11221 ** This is the header file for the generic hash-table implementation
11222 ** used in SQLite.
11223 */
11224 #ifndef SQLITE_HASH_H
11225 #define SQLITE_HASH_H
11226 
11227 /* Forward declarations of structures. */
11228 typedef struct Hash Hash;
11229 typedef struct HashElem HashElem;
11230 
11231 /* A complete hash table is an instance of the following structure.
11232 ** The internals of this structure are intended to be opaque -- client
11233 ** code should not attempt to access or modify the fields of this structure
11234 ** directly. Change this structure only by using the routines below.
11235 ** However, some of the "procedures" and "functions" for modifying and
11236 ** accessing this structure are really macros, so we can't really make
11237 ** this structure opaque.
11238 **
11239 ** All elements of the hash table are on a single doubly-linked list.
11240 ** Hash.first points to the head of this list.
11241 **
11242 ** There are Hash.htsize buckets. Each bucket points to a spot in
11243 ** the global doubly-linked list. The contents of the bucket are the
11244 ** element pointed to plus the next _ht.count-1 elements in the list.
11245 **
11246 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
11247 ** by a linear search of the global list. For small tables, the
11248 ** Hash.ht table is never allocated because if there are few elements
11249 ** in the table, it is faster to do a linear search than to manage
11250 ** the hash table.
11251 */
11252 struct Hash {
11253  unsigned int htsize; /* Number of buckets in the hash table */
11254  unsigned int count; /* Number of entries in this table */
11255  HashElem *first; /* The first element of the array */
11256  struct _ht { /* the hash table */
11257  int count; /* Number of entries with this hash */
11258  HashElem *chain; /* Pointer to first entry with this hash */
11259  } *ht;
11260 };
11261 
11262 /* Each element in the hash table is an instance of the following
11263 ** structure. All elements are stored on a single doubly-linked list.
11264 **
11265 ** Again, this structure is intended to be opaque, but it can't really
11266 ** be opaque because it is used by macros.
11267 */
11268 struct HashElem {
11269  HashElem *next, *prev; /* Next and previous elements in the table */
11270  void *data; /* Data associated with this element */
11271  const char *pKey; /* Key associated with this element */
11272 };
11273 
11274 /*
11275 ** Access routines. To delete, insert a NULL pointer.
11276 */
11277 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
11278 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
11279 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
11280 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
11281 
11282 /*
11283 ** Macros for looping over all elements of a hash table. The idiom is
11284 ** like this:
11285 **
11286 ** Hash h;
11287 ** HashElem *p;
11288 ** ...
11289 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
11290 ** SomeStructure *pData = sqliteHashData(p);
11291 ** // do something with pData
11292 ** }
11293 */
11294 #define sqliteHashFirst(H) ((H)->first)
11295 #define sqliteHashNext(E) ((E)->next)
11296 #define sqliteHashData(E) ((E)->data)
11297 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
11298 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
11299 
11300 /*
11301 ** Number of entries in a hash table
11302 */
11303 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
11304 
11305 #endif /* SQLITE_HASH_H */
11306 
11307 /************** End of hash.h ************************************************/
11308 /************** Continuing where we left off in sqliteInt.h ******************/
11309 /************** Include parse.h in the middle of sqliteInt.h *****************/
11310 /************** Begin file parse.h *******************************************/
11311 #define TK_SEMI 1
11312 #define TK_EXPLAIN 2
11313 #define TK_QUERY 3
11314 #define TK_PLAN 4
11315 #define TK_BEGIN 5
11316 #define TK_TRANSACTION 6
11317 #define TK_DEFERRED 7
11318 #define TK_IMMEDIATE 8
11319 #define TK_EXCLUSIVE 9
11320 #define TK_COMMIT 10
11321 #define TK_END 11
11322 #define TK_ROLLBACK 12
11323 #define TK_SAVEPOINT 13
11324 #define TK_RELEASE 14
11325 #define TK_TO 15
11326 #define TK_TABLE 16
11327 #define TK_CREATE 17
11328 #define TK_IF 18
11329 #define TK_NOT 19
11330 #define TK_EXISTS 20
11331 #define TK_TEMP 21
11332 #define TK_LP 22
11333 #define TK_RP 23
11334 #define TK_AS 24
11335 #define TK_WITHOUT 25
11336 #define TK_COMMA 26
11337 #define TK_OR 27
11338 #define TK_AND 28
11339 #define TK_IS 29
11340 #define TK_MATCH 30
11341 #define TK_LIKE_KW 31
11342 #define TK_BETWEEN 32
11343 #define TK_IN 33
11344 #define TK_ISNULL 34
11345 #define TK_NOTNULL 35
11346 #define TK_NE 36
11347 #define TK_EQ 37
11348 #define TK_GT 38
11349 #define TK_LE 39
11350 #define TK_LT 40
11351 #define TK_GE 41
11352 #define TK_ESCAPE 42
11353 #define TK_BITAND 43
11354 #define TK_BITOR 44
11355 #define TK_LSHIFT 45
11356 #define TK_RSHIFT 46
11357 #define TK_PLUS 47
11358 #define TK_MINUS 48
11359 #define TK_STAR 49
11360 #define TK_SLASH 50
11361 #define TK_REM 51
11362 #define TK_CONCAT 52
11363 #define TK_COLLATE 53
11364 #define TK_BITNOT 54
11365 #define TK_ID 55
11366 #define TK_INDEXED 56
11367 #define TK_ABORT 57
11368 #define TK_ACTION 58
11369 #define TK_AFTER 59
11370 #define TK_ANALYZE 60
11371 #define TK_ASC 61
11372 #define TK_ATTACH 62
11373 #define TK_BEFORE 63
11374 #define TK_BY 64
11375 #define TK_CASCADE 65
11376 #define TK_CAST 66
11377 #define TK_COLUMNKW 67
11378 #define TK_CONFLICT 68
11379 #define TK_DATABASE 69
11380 #define TK_DESC 70
11381 #define TK_DETACH 71
11382 #define TK_EACH 72
11383 #define TK_FAIL 73
11384 #define TK_FOR 74
11385 #define TK_IGNORE 75
11386 #define TK_INITIALLY 76
11387 #define TK_INSTEAD 77
11388 #define TK_NO 78
11389 #define TK_KEY 79
11390 #define TK_OF 80
11391 #define TK_OFFSET 81
11392 #define TK_PRAGMA 82
11393 #define TK_RAISE 83
11394 #define TK_RECURSIVE 84
11395 #define TK_REPLACE 85
11396 #define TK_RESTRICT 86
11397 #define TK_ROW 87
11398 #define TK_TRIGGER 88
11399 #define TK_VACUUM 89
11400 #define TK_VIEW 90
11401 #define TK_VIRTUAL 91
11402 #define TK_WITH 92
11403 #define TK_REINDEX 93
11404 #define TK_RENAME 94
11405 #define TK_CTIME_KW 95
11406 #define TK_ANY 96
11407 #define TK_STRING 97
11408 #define TK_JOIN_KW 98
11409 #define TK_CONSTRAINT 99
11410 #define TK_DEFAULT 100
11411 #define TK_NULL 101
11412 #define TK_PRIMARY 102
11413 #define TK_UNIQUE 103
11414 #define TK_CHECK 104
11415 #define TK_REFERENCES 105
11416 #define TK_AUTOINCR 106
11417 #define TK_ON 107
11418 #define TK_INSERT 108
11419 #define TK_DELETE 109
11420 #define TK_UPDATE 110
11421 #define TK_SET 111
11422 #define TK_DEFERRABLE 112
11423 #define TK_FOREIGN 113
11424 #define TK_DROP 114
11425 #define TK_UNION 115
11426 #define TK_ALL 116
11427 #define TK_EXCEPT 117
11428 #define TK_INTERSECT 118
11429 #define TK_SELECT 119
11430 #define TK_VALUES 120
11431 #define TK_DISTINCT 121
11432 #define TK_DOT 122
11433 #define TK_FROM 123
11434 #define TK_JOIN 124
11435 #define TK_USING 125
11436 #define TK_ORDER 126
11437 #define TK_GROUP 127
11438 #define TK_HAVING 128
11439 #define TK_LIMIT 129
11440 #define TK_WHERE 130
11441 #define TK_INTO 131
11442 #define TK_FLOAT 132
11443 #define TK_BLOB 133
11444 #define TK_INTEGER 134
11445 #define TK_VARIABLE 135
11446 #define TK_CASE 136
11447 #define TK_WHEN 137
11448 #define TK_THEN 138
11449 #define TK_ELSE 139
11450 #define TK_INDEX 140
11451 #define TK_ALTER 141
11452 #define TK_ADD 142
11453 #define TK_TO_TEXT 143
11454 #define TK_TO_BLOB 144
11455 #define TK_TO_NUMERIC 145
11456 #define TK_TO_INT 146
11457 #define TK_TO_REAL 147
11458 #define TK_ISNOT 148
11459 #define TK_END_OF_FILE 149
11460 #define TK_UNCLOSED_STRING 150
11461 #define TK_FUNCTION 151
11462 #define TK_COLUMN 152
11463 #define TK_AGG_FUNCTION 153
11464 #define TK_AGG_COLUMN 154
11465 #define TK_UMINUS 155
11466 #define TK_UPLUS 156
11467 #define TK_REGISTER 157
11468 #define TK_VECTOR 158
11469 #define TK_SELECT_COLUMN 159
11470 #define TK_ASTERISK 160
11471 #define TK_SPAN 161
11472 #define TK_SPACE 162
11473 #define TK_ILLEGAL 163
11474 
11475 /* The token codes above must all fit in 8 bits */
11476 #define TKFLG_MASK 0xff
11477 
11478 /* Flags that can be added to a token code when it is not
11479 ** being stored in a u8: */
11480 #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
11481 
11482 /************** End of parse.h ***********************************************/
11483 /************** Continuing where we left off in sqliteInt.h ******************/
11484 #include <stdio.h>
11485 #include <stdlib.h>
11486 #include <string.h>
11487 #include <assert.h>
11488 #include <stddef.h>
11489 
11490 /*
11491 ** If compiling for a processor that lacks floating point support,
11492 ** substitute integer for floating-point
11493 */
11494 #ifdef SQLITE_OMIT_FLOATING_POINT
11495 # define double sqlite_int64
11496 # define float sqlite_int64
11497 # define LONGDOUBLE_TYPE sqlite_int64
11498 # ifndef SQLITE_BIG_DBL
11499 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
11500 # endif
11501 # define SQLITE_OMIT_DATETIME_FUNCS 1
11502 # define SQLITE_OMIT_TRACE 1
11503 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11504 # undef SQLITE_HAVE_ISNAN
11505 #endif
11506 #ifndef SQLITE_BIG_DBL
11507 # define SQLITE_BIG_DBL (1e99)
11508 #endif
11509 
11510 /*
11511 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
11512 ** afterward. Having this macro allows us to cause the C compiler
11513 ** to omit code used by TEMP tables without messy #ifndef statements.
11514 */
11515 #ifdef SQLITE_OMIT_TEMPDB
11516 #define OMIT_TEMPDB 1
11517 #else
11518 #define OMIT_TEMPDB 0
11519 #endif
11520 
11521 /*
11522 ** The "file format" number is an integer that is incremented whenever
11523 ** the VDBE-level file format changes. The following macros define the
11524 ** the default file format for new databases and the maximum file format
11525 ** that the library can read.
11526 */
11527 #define SQLITE_MAX_FILE_FORMAT 4
11528 #ifndef SQLITE_DEFAULT_FILE_FORMAT
11529 # define SQLITE_DEFAULT_FILE_FORMAT 4
11530 #endif
11531 
11532 /*
11533 ** Determine whether triggers are recursive by default. This can be
11534 ** changed at run-time using a pragma.
11535 */
11536 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
11537 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
11538 #endif
11539 
11540 /*
11541 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
11542 ** on the command-line
11543 */
11544 #ifndef SQLITE_TEMP_STORE
11545 # define SQLITE_TEMP_STORE 1
11546 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
11547 #endif
11548 
11549 /*
11550 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
11551 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
11552 ** to zero.
11553 */
11554 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
11555 # undef SQLITE_MAX_WORKER_THREADS
11556 # define SQLITE_MAX_WORKER_THREADS 0
11557 #endif
11558 #ifndef SQLITE_MAX_WORKER_THREADS
11559 # define SQLITE_MAX_WORKER_THREADS 8
11560 #endif
11561 #ifndef SQLITE_DEFAULT_WORKER_THREADS
11562 # define SQLITE_DEFAULT_WORKER_THREADS 0
11563 #endif
11564 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
11565 # undef SQLITE_MAX_WORKER_THREADS
11566 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
11567 #endif
11568 
11569 /*
11570 ** The default initial allocation for the pagecache when using separate
11571 ** pagecaches for each database connection. A positive number is the
11572 ** number of pages. A negative number N translations means that a buffer
11573 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
11574 */
11575 #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
11576 # define SQLITE_DEFAULT_PCACHE_INITSZ 100
11577 #endif
11578 
11579 /*
11580 ** GCC does not define the offsetof() macro so we'll have to do it
11581 ** ourselves.
11582 */
11583 #ifndef offsetof
11584 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
11585 #endif
11586 
11587 /*
11588 ** Macros to compute minimum and maximum of two numbers.
11589 */
11590 #ifndef MIN
11591 # define MIN(A,B) ((A)<(B)?(A):(B))
11592 #endif
11593 #ifndef MAX
11594 # define MAX(A,B) ((A)>(B)?(A):(B))
11595 #endif
11596 
11597 /*
11598 ** Swap two objects of type TYPE.
11599 */
11600 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
11601 
11602 /*
11603 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
11604 ** not, there are still machines out there that use EBCDIC.)
11605 */
11606 #if 'A' == '\301'
11607 # define SQLITE_EBCDIC 1
11608 #else
11609 # define SQLITE_ASCII 1
11610 #endif
11611 
11612 /*
11613 ** Integers of known sizes. These typedefs might change for architectures
11614 ** where the sizes very. Preprocessor macros are available so that the
11615 ** types can be conveniently redefined at compile-type. Like this:
11616 **
11617 ** cc '-DUINTPTR_TYPE=long long int' ...
11618 */
11619 #ifndef UINT32_TYPE
11620 # ifdef HAVE_UINT32_T
11621 # define UINT32_TYPE uint32_t
11622 # else
11623 # define UINT32_TYPE unsigned int
11624 # endif
11625 #endif
11626 #ifndef UINT16_TYPE
11627 # ifdef HAVE_UINT16_T
11628 # define UINT16_TYPE uint16_t
11629 # else
11630 # define UINT16_TYPE unsigned short int
11631 # endif
11632 #endif
11633 #ifndef INT16_TYPE
11634 # ifdef HAVE_INT16_T
11635 # define INT16_TYPE int16_t
11636 # else
11637 # define INT16_TYPE short int
11638 # endif
11639 #endif
11640 #ifndef UINT8_TYPE
11641 # ifdef HAVE_UINT8_T
11642 # define UINT8_TYPE uint8_t
11643 # else
11644 # define UINT8_TYPE unsigned char
11645 # endif
11646 #endif
11647 #ifndef INT8_TYPE
11648 # ifdef HAVE_INT8_T
11649 # define INT8_TYPE int8_t
11650 # else
11651 # define INT8_TYPE signed char
11652 # endif
11653 #endif
11654 #ifndef LONGDOUBLE_TYPE
11655 # define LONGDOUBLE_TYPE long double
11656 #endif
11657 typedef sqlite_int64 i64; /* 8-byte signed integer */
11658 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
11659 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
11660 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
11661 typedef INT16_TYPE i16; /* 2-byte signed integer */
11662 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
11663 typedef INT8_TYPE i8; /* 1-byte signed integer */
11664 
11665 /*
11666 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
11667 ** that can be stored in a u32 without loss of data. The value
11668 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
11669 ** have to specify the value in the less intuitive manner shown:
11670 */
11671 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
11672 
11673 /*
11674 ** The datatype used to store estimates of the number of rows in a
11675 ** table or index. This is an unsigned integer type. For 99.9% of
11676 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
11677 ** can be used at compile-time if desired.
11678 */
11679 #ifdef SQLITE_64BIT_STATS
11680  typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
11681 #else
11682  typedef u32 tRowcnt; /* 32-bit is the default */
11683 #endif
11684 
11685 /*
11686 ** Estimated quantities used for query planning are stored as 16-bit
11687 ** logarithms. For quantity X, the value stored is 10*log2(X). This
11688 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
11689 ** But the allowed values are "grainy". Not every value is representable.
11690 ** For example, quantities 16 and 17 are both represented by a LogEst
11691 ** of 40. However, since LogEst quantities are suppose to be estimates,
11692 ** not exact values, this imprecision is not a problem.
11693 **
11694 ** "LogEst" is short for "Logarithmic Estimate".
11695 **
11696 ** Examples:
11697 ** 1 -> 0 20 -> 43 10000 -> 132
11698 ** 2 -> 10 25 -> 46 25000 -> 146
11699 ** 3 -> 16 100 -> 66 1000000 -> 199
11700 ** 4 -> 20 1000 -> 99 1048576 -> 200
11701 ** 10 -> 33 1024 -> 100 4294967296 -> 320
11702 **
11703 ** The LogEst can be negative to indicate fractional values.
11704 ** Examples:
11705 **
11706 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
11707 */
11708 typedef INT16_TYPE LogEst;
11709 
11710 /*
11711 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
11712 */
11713 #ifndef SQLITE_PTRSIZE
11714 # if defined(__SIZEOF_POINTER__)
11715 # define SQLITE_PTRSIZE __SIZEOF_POINTER__
11716 # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
11717  defined(_M_ARM) || defined(__arm__) || defined(__x86)
11718 # define SQLITE_PTRSIZE 4
11719 # else
11720 # define SQLITE_PTRSIZE 8
11721 # endif
11722 #endif
11723 
11724 /* The uptr type is an unsigned integer large enough to hold a pointer
11725 */
11726 #if defined(HAVE_STDINT_H)
11727  typedef uintptr_t uptr;
11728 #elif SQLITE_PTRSIZE==4
11729  typedef u32 uptr;
11730 #else
11731  typedef u64 uptr;
11732 #endif
11733 
11734 /*
11735 ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
11736 ** something between S (inclusive) and E (exclusive).
11737 **
11738 ** In other words, S is a buffer and E is a pointer to the first byte after
11739 ** the end of buffer S. This macro returns true if P points to something
11740 ** contained within the buffer S.
11741 */
11742 #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
11743 
11744 
11745 /*
11746 ** Macros to determine whether the machine is big or little endian,
11747 ** and whether or not that determination is run-time or compile-time.
11748 **
11749 ** For best performance, an attempt is made to guess at the byte-order
11750 ** using C-preprocessor macros. If that is unsuccessful, or if
11751 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
11752 ** at run-time.
11753 */
11754 #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
11755  defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
11756  defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
11757  defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
11758 # define SQLITE_BYTEORDER 1234
11759 # define SQLITE_BIGENDIAN 0
11760 # define SQLITE_LITTLEENDIAN 1
11761 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
11762 #endif
11763 #if (defined(sparc) || defined(__ppc__)) \
11764  && !defined(SQLITE_RUNTIME_BYTEORDER)
11765 # define SQLITE_BYTEORDER 4321
11766 # define SQLITE_BIGENDIAN 1
11767 # define SQLITE_LITTLEENDIAN 0
11768 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
11769 #endif
11770 #if !defined(SQLITE_BYTEORDER)
11771 # ifdef SQLITE_AMALGAMATION
11772  const int sqlite3one = 1;
11773 # else
11774  extern const int sqlite3one;
11775 # endif
11776 # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
11777 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
11778 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
11779 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
11780 #endif
11781 
11782 /*
11783 ** Constants for the largest and smallest possible 64-bit signed integers.
11784 ** These macros are designed to work correctly on both 32-bit and 64-bit
11785 ** compilers.
11786 */
11787 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
11788 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
11789 
11790 /*
11791 ** Round up a number to the next larger multiple of 8. This is used
11792 ** to force 8-byte alignment on 64-bit architectures.
11793 */
11794 #define ROUND8(x) (((x)+7)&~7)
11795 
11796 /*
11797 ** Round down to the nearest multiple of 8
11798 */
11799 #define ROUNDDOWN8(x) ((x)&~7)
11800 
11801 /*
11802 ** Assert that the pointer X is aligned to an 8-byte boundary. This
11803 ** macro is used only within assert() to verify that the code gets
11804 ** all alignment restrictions correct.
11805 **
11806 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
11807 ** underlying malloc() implementation might return us 4-byte aligned
11808 ** pointers. In that case, only verify 4-byte alignment.
11809 */
11810 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11811 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
11812 #else
11813 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
11814 #endif
11815 
11816 /*
11817 ** Disable MMAP on platforms where it is known to not work
11818 */
11819 #if defined(__OpenBSD__) || defined(__QNXNTO__)
11820 # undef SQLITE_MAX_MMAP_SIZE
11821 # define SQLITE_MAX_MMAP_SIZE 0
11822 #endif
11823 
11824 /*
11825 ** Default maximum size of memory used by memory-mapped I/O in the VFS
11826 */
11827 #ifdef __APPLE__
11828 # include <TargetConditionals.h>
11829 #endif
11830 #ifndef SQLITE_MAX_MMAP_SIZE
11831 # if defined(__linux__) \
11832  || defined(_WIN32) \
11833  || (defined(__APPLE__) && defined(__MACH__)) \
11834  || defined(__sun) \
11835  || defined(__FreeBSD__) \
11836  || defined(__DragonFly__)
11837 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
11838 # else
11839 # define SQLITE_MAX_MMAP_SIZE 0
11840 # endif
11841 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
11842 #endif
11843 
11844 /*
11845 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
11846 ** default MMAP_SIZE is specified at compile-time, make sure that it does
11847 ** not exceed the maximum mmap size.
11848 */
11849 #ifndef SQLITE_DEFAULT_MMAP_SIZE
11850 # define SQLITE_DEFAULT_MMAP_SIZE 0
11851 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
11852 #endif
11853 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
11854 # undef SQLITE_DEFAULT_MMAP_SIZE
11855 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
11856 #endif
11857 
11858 /*
11859 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
11860 ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
11861 ** define SQLITE_ENABLE_STAT3_OR_STAT4
11862 */
11863 #ifdef SQLITE_ENABLE_STAT4
11864 # undef SQLITE_ENABLE_STAT3
11865 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11866 #elif SQLITE_ENABLE_STAT3
11867 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11868 #elif SQLITE_ENABLE_STAT3_OR_STAT4
11869 # undef SQLITE_ENABLE_STAT3_OR_STAT4
11870 #endif
11871 
11872 /*
11873 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
11874 ** the Select query generator tracing logic is turned on.
11875 */
11876 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
11877 # define SELECTTRACE_ENABLED 1
11878 #else
11879 # define SELECTTRACE_ENABLED 0
11880 #endif
11881 
11882 /*
11883 ** An instance of the following structure is used to store the busy-handler
11884 ** callback for a given sqlite handle.
11885 **
11886 ** The sqlite.busyHandler member of the sqlite struct contains the busy
11887 ** callback for the database handle. Each pager opened via the sqlite
11888 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
11889 ** callback is currently invoked only from within pager.c.
11890 */
11891 typedef struct BusyHandler BusyHandler;
11892 struct BusyHandler {
11893  int (*xFunc)(void *,int); /* The busy callback */
11894  void *pArg; /* First arg to busy callback */
11895  int nBusy; /* Incremented with each busy call */
11896 };
11897 
11898 /*
11899 ** Name of the master database table. The master database table
11900 ** is a special table that holds the names and attributes of all
11901 ** user tables and indices.
11902 */
11903 #define MASTER_NAME "sqlite_master"
11904 #define TEMP_MASTER_NAME "sqlite_temp_master"
11905 
11906 /*
11907 ** The root-page of the master database table.
11908 */
11909 #define MASTER_ROOT 1
11910 
11911 /*
11912 ** The name of the schema table.
11913 */
11914 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
11915 
11916 /*
11917 ** A convenience macro that returns the number of elements in
11918 ** an array.
11919 */
11920 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
11921 
11922 /*
11923 ** Determine if the argument is a power of two
11924 */
11925 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
11926 
11927 /*
11928 ** The following value as a destructor means to use sqlite3DbFree().
11929 ** The sqlite3DbFree() routine requires two parameters instead of the
11930 ** one parameter that destructors normally want. So we have to introduce
11931 ** this magic value that the code knows to handle differently. Any
11932 ** pointer will work here as long as it is distinct from SQLITE_STATIC
11933 ** and SQLITE_TRANSIENT.
11934 */
11935 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
11936 
11937 /*
11938 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
11939 ** not support Writable Static Data (WSD) such as global and static variables.
11940 ** All variables must either be on the stack or dynamically allocated from
11941 ** the heap. When WSD is unsupported, the variable declarations scattered
11942 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
11943 ** macro is used for this purpose. And instead of referencing the variable
11944 ** directly, we use its constant as a key to lookup the run-time allocated
11945 ** buffer that holds real variable. The constant is also the initializer
11946 ** for the run-time allocated buffer.
11947 **
11948 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
11949 ** macros become no-ops and have zero performance impact.
11950 */
11951 #ifdef SQLITE_OMIT_WSD
11952  #define SQLITE_WSD const
11953  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
11954  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
11955 SQLITE_API int sqlite3_wsd_init(int N, int J);
11956 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
11957 #else
11958  #define SQLITE_WSD
11959  #define GLOBAL(t,v) v
11960  #define sqlite3GlobalConfig sqlite3Config
11961 #endif
11962 
11963 /*
11964 ** The following macros are used to suppress compiler warnings and to
11965 ** make it clear to human readers when a function parameter is deliberately
11966 ** left unused within the body of a function. This usually happens when
11967 ** a function is called via a function pointer. For example the
11968 ** implementation of an SQL aggregate step callback may not use the
11969 ** parameter indicating the number of arguments passed to the aggregate,
11970 ** if it knows that this is enforced elsewhere.
11971 **
11972 ** When a function parameter is not used at all within the body of a function,
11973 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
11974 ** However, these macros may also be used to suppress warnings related to
11975 ** parameters that may or may not be used depending on compilation options.
11976 ** For example those parameters only used in assert() statements. In these
11977 ** cases the parameters are named as per the usual conventions.
11978 */
11979 #define UNUSED_PARAMETER(x) (void)(x)
11980 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
11981 
11982 /*
11983 ** Forward references to structures
11984 */
11985 typedef struct AggInfo AggInfo;
11986 typedef struct AuthContext AuthContext;
11987 typedef struct AutoincInfo AutoincInfo;
11988 typedef struct Bitvec Bitvec;
11989 typedef struct CollSeq CollSeq;
11990 typedef struct Column Column;
11991 typedef struct Db Db;
11992 typedef struct Schema Schema;
11993 typedef struct Expr Expr;
11994 typedef struct ExprList ExprList;
11995 typedef struct ExprSpan ExprSpan;
11996 typedef struct FKey FKey;
11997 typedef struct FuncDestructor FuncDestructor;
11998 typedef struct FuncDef FuncDef;
11999 typedef struct FuncDefHash FuncDefHash;
12000 typedef struct IdList IdList;
12001 typedef struct Index Index;
12002 typedef struct IndexSample IndexSample;
12003 typedef struct KeyClass KeyClass;
12004 typedef struct KeyInfo KeyInfo;
12005 typedef struct Lookaside Lookaside;
12006 typedef struct LookasideSlot LookasideSlot;
12007 typedef struct Module Module;
12008 typedef struct NameContext NameContext;
12009 typedef struct Parse Parse;
12010 typedef struct PreUpdate PreUpdate;
12011 typedef struct PrintfArguments PrintfArguments;
12012 typedef struct RowSet RowSet;
12013 typedef struct Savepoint Savepoint;
12014 typedef struct Select Select;
12015 typedef struct SQLiteThread SQLiteThread;
12016 typedef struct SelectDest SelectDest;
12017 typedef struct SrcList SrcList;
12018 typedef struct StrAccum StrAccum;
12019 typedef struct Table Table;
12020 typedef struct TableLock TableLock;
12021 typedef struct Token Token;
12022 typedef struct TreeView TreeView;
12023 typedef struct Trigger Trigger;
12024 typedef struct TriggerPrg TriggerPrg;
12025 typedef struct TriggerStep TriggerStep;
12026 typedef struct UnpackedRecord UnpackedRecord;
12027 typedef struct VTable VTable;
12028 typedef struct VtabCtx VtabCtx;
12029 typedef struct Walker Walker;
12030 typedef struct WhereInfo WhereInfo;
12031 typedef struct With With;
12032 
12033 /*
12034 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
12035 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
12036 ** pointer types (i.e. FuncDef) defined above.
12037 */
12038 /************** Include btree.h in the middle of sqliteInt.h *****************/
12039 /************** Begin file btree.h *******************************************/
12040 /*
12041 ** 2001 September 15
12042 **
12043 ** The author disclaims copyright to this source code. In place of
12044 ** a legal notice, here is a blessing:
12045 **
12046 ** May you do good and not evil.
12047 ** May you find forgiveness for yourself and forgive others.
12048 ** May you share freely, never taking more than you give.
12049 **
12050 *************************************************************************
12051 ** This header file defines the interface that the sqlite B-Tree file
12052 ** subsystem. See comments in the source code for a detailed description
12053 ** of what each interface routine does.
12054 */
12055 #ifndef SQLITE_BTREE_H
12056 #define SQLITE_BTREE_H
12057 
12058 /* TODO: This definition is just included so other modules compile. It
12059 ** needs to be revisited.
12060 */
12061 #define SQLITE_N_BTREE_META 16
12062 
12063 /*
12064 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
12065 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
12066 */
12067 #ifndef SQLITE_DEFAULT_AUTOVACUUM
12068  #define SQLITE_DEFAULT_AUTOVACUUM 0
12069 #endif
12070 
12071 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
12072 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
12073 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
12074 
12075 /*
12076 ** Forward declarations of structure
12077 */
12078 typedef struct Btree Btree;
12079 typedef struct BtCursor BtCursor;
12080 typedef struct BtShared BtShared;
12081 typedef struct BtreePayload BtreePayload;
12082 
12083 
12084 SQLITE_PRIVATE int sqlite3BtreeOpen(
12085  sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
12086  const char *zFilename, /* Name of database file to open */
12087  sqlite3 *db, /* Associated database connection */
12088  Btree **ppBtree, /* Return open Btree* here */
12089  int flags, /* Flags */
12090  int vfsFlags /* Flags passed through to VFS open */
12091 );
12092 
12093 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
12094 ** following values.
12095 **
12096 ** NOTE: These values must match the corresponding PAGER_ values in
12097 ** pager.h.
12098 */
12099 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
12100 #define BTREE_MEMORY 2 /* This is an in-memory DB */
12101 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
12102 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
12103 
12104 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
12105 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
12106 SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
12107 #if SQLITE_MAX_MMAP_SIZE>0
12108 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
12109 #endif
12110 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
12111 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
12112 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
12113 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
12114 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
12115 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
12116 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
12117 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
12118 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
12119 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
12120 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
12121 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
12122 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
12123 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
12124 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
12125 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
12126 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
12127 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
12128 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
12129 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
12130 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
12131 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
12132 #ifndef SQLITE_OMIT_SHARED_CACHE
12133 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
12134 #endif
12135 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
12136 
12137 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
12138 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
12139 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
12140 
12141 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
12142 
12143 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
12144 ** of the flags shown below.
12145 **
12146 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
12147 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
12148 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
12149 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
12150 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
12151 ** indices.)
12152 */
12153 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
12154 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
12155 
12156 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
12157 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
12158 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
12159 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
12160 
12161 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
12162 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
12163 
12164 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
12165 
12166 /*
12167 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
12168 ** should be one of the following values. The integer values are assigned
12169 ** to constants so that the offset of the corresponding field in an
12170 ** SQLite database header may be found using the following formula:
12171 **
12172 ** offset = 36 + (idx * 4)
12173 **
12174 ** For example, the free-page-count field is located at byte offset 36 of
12175 ** the database file header. The incr-vacuum-flag field is located at
12176 ** byte offset 64 (== 36+4*7).
12177 **
12178 ** The BTREE_DATA_VERSION value is not really a value stored in the header.
12179 ** It is a read-only number computed by the pager. But we merge it with
12180 ** the header value access routines since its access pattern is the same.
12181 ** Call it a "virtual meta value".
12182 */
12183 #define BTREE_FREE_PAGE_COUNT 0
12184 #define BTREE_SCHEMA_VERSION 1
12185 #define BTREE_FILE_FORMAT 2
12186 #define BTREE_DEFAULT_CACHE_SIZE 3
12187 #define BTREE_LARGEST_ROOT_PAGE 4
12188 #define BTREE_TEXT_ENCODING 5
12189 #define BTREE_USER_VERSION 6
12190 #define BTREE_INCR_VACUUM 7
12191 #define BTREE_APPLICATION_ID 8
12192 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
12193 
12194 /*
12195 ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
12196 ** interface.
12197 **
12198 ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
12199 **
12200 ** The first argument is an Expr* (which is guaranteed to be constant for
12201 ** the lifetime of the cursor) that defines constraints on which rows
12202 ** might be fetched with this cursor. The Expr* tree may contain
12203 ** TK_REGISTER nodes that refer to values stored in the array of registers
12204 ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
12205 ** then the value of the node is the value in Mem[pExpr.iTable]. Any
12206 ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
12207 ** column of the b-tree of the cursor. The Expr tree will not contain
12208 ** any function calls nor subqueries nor references to b-trees other than
12209 ** the cursor being hinted.
12210 **
12211 ** The design of the _RANGE hint is aid b-tree implementations that try
12212 ** to prefetch content from remote machines - to provide those
12213 ** implementations with limits on what needs to be prefetched and thereby
12214 ** reduce network bandwidth.
12215 **
12216 ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
12217 ** standard SQLite. The other hints are provided for extentions that use
12218 ** the SQLite parser and code generator but substitute their own storage
12219 ** engine.
12220 */
12221 #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
12222 
12223 /*
12224 ** Values that may be OR'd together to form the argument to the
12225 ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
12226 **
12227 ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
12228 ** to be filled with content that is already in sorted order.
12229 **
12230 ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
12231 ** OP_SeekLE opcodes for a range search, but where the range of entries
12232 ** selected will all have the same key. In other words, the cursor will
12233 ** be used only for equality key searches.
12234 **
12235 */
12236 #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
12237 #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
12238 
12239 /*
12240 ** Flags passed as the third argument to sqlite3BtreeCursor().
12241 **
12242 ** For read-only cursors the wrFlag argument is always zero. For read-write
12243 ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
12244 ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
12245 ** only be used by SQLite for the following:
12246 **
12247 ** * to seek to and then delete specific entries, and/or
12248 **
12249 ** * to read values that will be used to create keys that other
12250 ** BTREE_FORDELETE cursors will seek to and delete.
12251 **
12252 ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
12253 ** by this, the native b-tree engine of SQLite, but it is available to
12254 ** alternative storage engines that might be substituted in place of this
12255 ** b-tree system. For alternative storage engines in which a delete of
12256 ** the main table row automatically deletes corresponding index rows,
12257 ** the FORDELETE flag hint allows those alternative storage engines to
12258 ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
12259 ** and DELETE operations as no-ops, and any READ operation against a
12260 ** FORDELETE cursor may return a null row: 0x01 0x00.
12261 */
12262 #define BTREE_WRCSR 0x00000004 /* read-write cursor */
12263 #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
12264 
12265 SQLITE_PRIVATE int sqlite3BtreeCursor(
12266  Btree*, /* BTree containing table to open */
12267  int iTable, /* Index of root page */
12268  int wrFlag, /* 1 for writing. 0 for read-only */
12269  struct KeyInfo*, /* First argument to compare function */
12270  BtCursor *pCursor /* Space to write cursor structure */
12271 );
12272 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
12273 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
12274 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
12275 #ifdef SQLITE_ENABLE_CURSOR_HINTS
12276 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
12277 #endif
12278 
12279 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
12280 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
12281  BtCursor*,
12282  UnpackedRecord *pUnKey,
12283  i64 intKey,
12284  int bias,
12285  int *pRes
12286 );
12287 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
12288 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
12289 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
12290 
12291 /* Allowed flags for the 2nd argument to sqlite3BtreeDelete() */
12292 #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
12293 #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
12294 
12295 /* An instance of the BtreePayload object describes the content of a single
12296 ** entry in either an index or table btree.
12297 **
12298 ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
12299 ** an arbitrary key and no data. These btrees have pKey,nKey set to their
12300 ** key and pData,nData,nZero set to zero.
12301 **
12302 ** Table btrees (used for rowid tables) contain an integer rowid used as
12303 ** the key and passed in the nKey field. The pKey field is zero.
12304 ** pData,nData hold the content of the new entry. nZero extra zero bytes
12305 ** are appended to the end of the content when constructing the entry.
12306 **
12307 ** This object is used to pass information into sqlite3BtreeInsert(). The
12308 ** same information used to be passed as five separate parameters. But placing
12309 ** the information into this object helps to keep the interface more
12310 ** organized and understandable, and it also helps the resulting code to
12311 ** run a little faster by using fewer registers for parameter passing.
12312 */
12313 struct BtreePayload {
12314  const void *pKey; /* Key content for indexes. NULL for tables */
12315  sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
12316  const void *pData; /* Data for tables. NULL for indexes */
12317  int nData; /* Size of pData. 0 if none. */
12318  int nZero; /* Extra zero data appended after pData,nData */
12319 };
12320 
12321 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
12322  int bias, int seekResult);
12323 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
12324 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
12325 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
12326 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
12327 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
12328 SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
12329 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
12330 SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
12331 SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
12332 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
12333 
12334 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
12335 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
12336 
12337 #ifndef SQLITE_OMIT_INCRBLOB
12338 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
12339 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
12340 #endif
12341 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
12342 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
12343 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
12344 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
12345 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
12346 
12347 #ifndef NDEBUG
12348 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
12349 #endif
12350 
12351 #ifndef SQLITE_OMIT_BTREECOUNT
12352 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
12353 #endif
12354 
12355 #ifdef SQLITE_TEST
12356 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
12357 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
12358 #endif
12359 
12360 #ifndef SQLITE_OMIT_WAL
12361 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
12362 #endif
12363 
12364 /*
12365 ** If we are not using shared cache, then there is no need to
12366 ** use mutexes to access the BtShared structures. So make the
12367 ** Enter and Leave procedures no-ops.
12368 */
12369 #ifndef SQLITE_OMIT_SHARED_CACHE
12370 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
12371 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
12372 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
12373 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
12374 SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
12375 #else
12376 # define sqlite3BtreeEnter(X)
12377 # define sqlite3BtreeEnterAll(X)
12378 # define sqlite3BtreeSharable(X) 0
12379 # define sqlite3BtreeEnterCursor(X)
12380 # define sqlite3BtreeConnectionCount(X) 1
12381 #endif
12382 
12383 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
12384 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
12385 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
12386 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
12387 #ifndef NDEBUG
12388  /* These routines are used inside assert() statements only. */
12389 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
12390 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
12391 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
12392 #endif
12393 #else
12394 
12395 # define sqlite3BtreeLeave(X)
12396 # define sqlite3BtreeLeaveCursor(X)
12397 # define sqlite3BtreeLeaveAll(X)
12398 
12399 # define sqlite3BtreeHoldsMutex(X) 1
12400 # define sqlite3BtreeHoldsAllMutexes(X) 1
12401 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
12402 #endif
12403 
12404 
12405 #endif /* SQLITE_BTREE_H */
12406 
12407 /************** End of btree.h ***********************************************/
12408 /************** Continuing where we left off in sqliteInt.h ******************/
12409 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
12410 /************** Begin file vdbe.h ********************************************/
12411 /*
12412 ** 2001 September 15
12413 **
12414 ** The author disclaims copyright to this source code. In place of
12415 ** a legal notice, here is a blessing:
12416 **
12417 ** May you do good and not evil.
12418 ** May you find forgiveness for yourself and forgive others.
12419 ** May you share freely, never taking more than you give.
12420 **
12421 *************************************************************************
12422 ** Header file for the Virtual DataBase Engine (VDBE)
12423 **
12424 ** This header defines the interface to the virtual database engine
12425 ** or VDBE. The VDBE implements an abstract machine that runs a
12426 ** simple program to access and modify the underlying database.
12427 */
12428 #ifndef SQLITE_VDBE_H
12429 #define SQLITE_VDBE_H
12430 /* #include <stdio.h> */
12431 
12432 /*
12433 ** A single VDBE is an opaque structure named "Vdbe". Only routines
12434 ** in the source file sqliteVdbe.c are allowed to see the insides
12435 ** of this structure.
12436 */
12437 typedef struct Vdbe Vdbe;
12438 
12439 /*
12440 ** The names of the following types declared in vdbeInt.h are required
12441 ** for the VdbeOp definition.
12442 */
12443 typedef struct Mem Mem;
12444 typedef struct SubProgram SubProgram;
12445 
12446 /*
12447 ** A single instruction of the virtual machine has an opcode
12448 ** and as many as three operands. The instruction is recorded
12449 ** as an instance of the following structure:
12450 */
12451 struct VdbeOp {
12452  u8 opcode; /* What operation to perform */
12453  signed char p4type; /* One of the P4_xxx constants for p4 */
12454  u8 notUsed1;
12455  u8 p5; /* Fifth parameter is an unsigned character */
12456  int p1; /* First operand */
12457  int p2; /* Second parameter (often the jump destination) */
12458  int p3; /* The third parameter */
12459  union p4union { /* fourth parameter */
12460  int i; /* Integer value if p4type==P4_INT32 */
12461  void *p; /* Generic pointer */
12462  char *z; /* Pointer to data for string (char array) types */
12463  i64 *pI64; /* Used when p4type is P4_INT64 */
12464  double *pReal; /* Used when p4type is P4_REAL */
12465  FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
12466  sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
12467  CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
12468  Mem *pMem; /* Used when p4type is P4_MEM */
12469  VTable *pVtab; /* Used when p4type is P4_VTAB */
12470  KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
12471  int *ai; /* Used when p4type is P4_INTARRAY */
12472  SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
12473  Table *pTab; /* Used when p4type is P4_TABLE */
12474 #ifdef SQLITE_ENABLE_CURSOR_HINTS
12475  Expr *pExpr; /* Used when p4type is P4_EXPR */
12476 #endif
12477  int (*xAdvance)(BtCursor *, int *);
12478  } p4;
12479 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12480  char *zComment; /* Comment to improve readability */
12481 #endif
12482 #ifdef VDBE_PROFILE
12483  u32 cnt; /* Number of times this instruction was executed */
12484  u64 cycles; /* Total time spent executing this instruction */
12485 #endif
12486 #ifdef SQLITE_VDBE_COVERAGE
12487  int iSrcLine; /* Source-code line that generated this opcode */
12488 #endif
12489 };
12490 typedef struct VdbeOp VdbeOp;
12491 
12492 
12493 /*
12494 ** A sub-routine used to implement a trigger program.
12495 */
12496 struct SubProgram {
12497  VdbeOp *aOp; /* Array of opcodes for sub-program */
12498  int nOp; /* Elements in aOp[] */
12499  int nMem; /* Number of memory cells required */
12500  int nCsr; /* Number of cursors required */
12501  void *token; /* id that may be used to recursive triggers */
12502  SubProgram *pNext; /* Next sub-program already visited */
12503 };
12504 
12505 /*
12506 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
12507 ** it takes up less space.
12508 */
12509 struct VdbeOpList {
12510  u8 opcode; /* What operation to perform */
12511  signed char p1; /* First operand */
12512  signed char p2; /* Second parameter (often the jump destination) */
12513  signed char p3; /* Third parameter */
12514 };
12515 typedef struct VdbeOpList VdbeOpList;
12516 
12517 /*
12518 ** Allowed values of VdbeOp.p4type
12519 */
12520 #define P4_NOTUSED 0 /* The P4 parameter is not used */
12521 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
12522 #define P4_STATIC (-2) /* Pointer to a static string */
12523 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
12524 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
12525 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
12526 #define P4_EXPR (-7) /* P4 is a pointer to an Expr tree */
12527 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
12528 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
12529 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
12530 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
12531 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
12532 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
12533 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
12534 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
12535 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
12536 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
12537 #define P4_TABLE (-20) /* P4 is a pointer to a Table structure */
12538 #define P4_FUNCCTX (-21) /* P4 is a pointer to an sqlite3_context object */
12539 
12540 /* Error message codes for OP_Halt */
12541 #define P5_ConstraintNotNull 1
12542 #define P5_ConstraintUnique 2
12543 #define P5_ConstraintCheck 3
12544 #define P5_ConstraintFK 4
12545 
12546 /*
12547 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
12548 ** number of columns of data returned by the statement.
12549 */
12550 #define COLNAME_NAME 0
12551 #define COLNAME_DECLTYPE 1
12552 #define COLNAME_DATABASE 2
12553 #define COLNAME_TABLE 3
12554 #define COLNAME_COLUMN 4
12555 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12556 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
12557 #else
12558 # ifdef SQLITE_OMIT_DECLTYPE
12559 # define COLNAME_N 1 /* Store only the name */
12560 # else
12561 # define COLNAME_N 2 /* Store the name and decltype */
12562 # endif
12563 #endif
12564 
12565 /*
12566 ** The following macro converts a relative address in the p2 field
12567 ** of a VdbeOp structure into a negative number so that
12568 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
12569 ** the macro again restores the address.
12570 */
12571 #define ADDR(X) (-1-(X))
12572 
12573 /*
12574 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
12575 ** header file that defines a number for each opcode used by the VDBE.
12576 */
12577 /************** Include opcodes.h in the middle of vdbe.h ********************/
12578 /************** Begin file opcodes.h *****************************************/
12579 /* Automatically generated. Do not edit */
12580 /* See the tool/mkopcodeh.tcl script for details */
12581 #define OP_Savepoint 0
12582 #define OP_AutoCommit 1
12583 #define OP_Transaction 2
12584 #define OP_SorterNext 3
12585 #define OP_PrevIfOpen 4
12586 #define OP_NextIfOpen 5
12587 #define OP_Prev 6
12588 #define OP_Next 7
12589 #define OP_Checkpoint 8
12590 #define OP_JournalMode 9
12591 #define OP_Vacuum 10
12592 #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
12593 #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
12594 #define OP_Goto 13
12595 #define OP_Gosub 14
12596 #define OP_InitCoroutine 15
12597 #define OP_Yield 16
12598 #define OP_MustBeInt 17
12599 #define OP_Jump 18
12600 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
12601 #define OP_Once 20
12602 #define OP_If 21
12603 #define OP_IfNot 22
12604 #define OP_SeekLT 23 /* synopsis: key=r[P3@P4] */
12605 #define OP_SeekLE 24 /* synopsis: key=r[P3@P4] */
12606 #define OP_SeekGE 25 /* synopsis: key=r[P3@P4] */
12607 #define OP_SeekGT 26 /* synopsis: key=r[P3@P4] */
12608 #define OP_Or 27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
12609 #define OP_And 28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
12610 #define OP_NoConflict 29 /* synopsis: key=r[P3@P4] */
12611 #define OP_NotFound 30 /* synopsis: key=r[P3@P4] */
12612 #define OP_Found 31 /* synopsis: key=r[P3@P4] */
12613 #define OP_SeekRowid 32 /* synopsis: intkey=r[P3] */
12614 #define OP_NotExists 33 /* synopsis: intkey=r[P3] */
12615 #define OP_IsNull 34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
12616 #define OP_NotNull 35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
12617 #define OP_Ne 36 /* same as TK_NE, synopsis: IF r[P3]!=r[P1] */
12618 #define OP_Eq 37 /* same as TK_EQ, synopsis: IF r[P3]==r[P1] */
12619 #define OP_Gt 38 /* same as TK_GT, synopsis: IF r[P3]>r[P1] */
12620 #define OP_Le 39 /* same as TK_LE, synopsis: IF r[P3]<=r[P1] */
12621 #define OP_Lt 40 /* same as TK_LT, synopsis: IF r[P3]<r[P1] */
12622 #define OP_Ge 41 /* same as TK_GE, synopsis: IF r[P3]>=r[P1] */
12623 #define OP_ElseNotEq 42 /* same as TK_ESCAPE */
12624 #define OP_BitAnd 43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
12625 #define OP_BitOr 44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
12626 #define OP_ShiftLeft 45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
12627 #define OP_ShiftRight 46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
12628 #define OP_Add 47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
12629 #define OP_Subtract 48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
12630 #define OP_Multiply 49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
12631 #define OP_Divide 50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
12632 #define OP_Remainder 51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
12633 #define OP_Concat 52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
12634 #define OP_Last 53
12635 #define OP_BitNot 54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12636 #define OP_SorterSort 55
12637 #define OP_Sort 56
12638 #define OP_Rewind 57
12639 #define OP_IdxLE 58 /* synopsis: key=r[P3@P4] */
12640 #define OP_IdxGT 59 /* synopsis: key=r[P3@P4] */
12641 #define OP_IdxLT 60 /* synopsis: key=r[P3@P4] */
12642 #define OP_IdxGE 61 /* synopsis: key=r[P3@P4] */
12643 #define OP_RowSetRead 62 /* synopsis: r[P3]=rowset(P1) */
12644 #define OP_RowSetTest 63 /* synopsis: if r[P3] in rowset(P1) goto P2 */
12645 #define OP_Program 64
12646 #define OP_FkIfZero 65 /* synopsis: if fkctr[P1]==0 goto P2 */
12647 #define OP_IfPos 66 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
12648 #define OP_IfNotZero 67 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
12649 #define OP_DecrJumpZero 68 /* synopsis: if (--r[P1])==0 goto P2 */
12650 #define OP_IncrVacuum 69
12651 #define OP_VNext 70
12652 #define OP_Init 71 /* synopsis: Start at P2 */
12653 #define OP_Return 72
12654 #define OP_EndCoroutine 73
12655 #define OP_HaltIfNull 74 /* synopsis: if r[P3]=null halt */
12656 #define OP_Halt 75
12657 #define OP_Integer 76 /* synopsis: r[P2]=P1 */
12658 #define OP_Int64 77 /* synopsis: r[P2]=P4 */
12659 #define OP_String 78 /* synopsis: r[P2]='P4' (len=P1) */
12660 #define OP_Null 79 /* synopsis: r[P2..P3]=NULL */
12661 #define OP_SoftNull 80 /* synopsis: r[P1]=NULL */
12662 #define OP_Blob 81 /* synopsis: r[P2]=P4 (len=P1) */
12663 #define OP_Variable 82 /* synopsis: r[P2]=parameter(P1,P4) */
12664 #define OP_Move 83 /* synopsis: r[P2@P3]=r[P1@P3] */
12665 #define OP_Copy 84 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
12666 #define OP_SCopy 85 /* synopsis: r[P2]=r[P1] */
12667 #define OP_IntCopy 86 /* synopsis: r[P2]=r[P1] */
12668 #define OP_ResultRow 87 /* synopsis: output=r[P1@P2] */
12669 #define OP_CollSeq 88
12670 #define OP_Function0 89 /* synopsis: r[P3]=func(r[P2@P5]) */
12671 #define OP_Function 90 /* synopsis: r[P3]=func(r[P2@P5]) */
12672 #define OP_AddImm 91 /* synopsis: r[P1]=r[P1]+P2 */
12673 #define OP_RealAffinity 92
12674 #define OP_Cast 93 /* synopsis: affinity(r[P1]) */
12675 #define OP_Permutation 94
12676 #define OP_Compare 95 /* synopsis: r[P1@P3] <-> r[P2@P3] */
12677 #define OP_Column 96 /* synopsis: r[P3]=PX */
12678 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
12679 #define OP_Affinity 98 /* synopsis: affinity(r[P1@P2]) */
12680 #define OP_MakeRecord 99 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
12681 #define OP_Count 100 /* synopsis: r[P2]=count() */
12682 #define OP_ReadCookie 101
12683 #define OP_SetCookie 102
12684 #define OP_ReopenIdx 103 /* synopsis: root=P2 iDb=P3 */
12685 #define OP_OpenRead 104 /* synopsis: root=P2 iDb=P3 */
12686 #define OP_OpenWrite 105 /* synopsis: root=P2 iDb=P3 */
12687 #define OP_OpenAutoindex 106 /* synopsis: nColumn=P2 */
12688 #define OP_OpenEphemeral 107 /* synopsis: nColumn=P2 */
12689 #define OP_SorterOpen 108
12690 #define OP_SequenceTest 109 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
12691 #define OP_OpenPseudo 110 /* synopsis: P3 columns in r[P2] */
12692 #define OP_Close 111
12693 #define OP_ColumnsUsed 112
12694 #define OP_Sequence 113 /* synopsis: r[P2]=cursor[P1].ctr++ */
12695 #define OP_NewRowid 114 /* synopsis: r[P2]=rowid */
12696 #define OP_Insert 115 /* synopsis: intkey=r[P3] data=r[P2] */
12697 #define OP_InsertInt 116 /* synopsis: intkey=P3 data=r[P2] */
12698 #define OP_Delete 117
12699 #define OP_ResetCount 118
12700 #define OP_SorterCompare 119 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
12701 #define OP_SorterData 120 /* synopsis: r[P2]=data */
12702 #define OP_RowKey 121 /* synopsis: r[P2]=key */
12703 #define OP_RowData 122 /* synopsis: r[P2]=data */
12704 #define OP_Rowid 123 /* synopsis: r[P2]=rowid */
12705 #define OP_NullRow 124
12706 #define OP_SorterInsert 125
12707 #define OP_IdxInsert 126 /* synopsis: key=r[P2] */
12708 #define OP_IdxDelete 127 /* synopsis: key=r[P2@P3] */
12709 #define OP_Seek 128 /* synopsis: Move P3 to P1.rowid */
12710 #define OP_IdxRowid 129 /* synopsis: r[P2]=rowid */
12711 #define OP_Destroy 130
12712 #define OP_Clear 131
12713 #define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
12714 #define OP_ResetSorter 133
12715 #define OP_CreateIndex 134 /* synopsis: r[P2]=root iDb=P1 */
12716 #define OP_CreateTable 135 /* synopsis: r[P2]=root iDb=P1 */
12717 #define OP_ParseSchema 136
12718 #define OP_LoadAnalysis 137
12719 #define OP_DropTable 138
12720 #define OP_DropIndex 139
12721 #define OP_DropTrigger 140
12722 #define OP_IntegrityCk 141
12723 #define OP_RowSetAdd 142 /* synopsis: rowset(P1)=r[P2] */
12724 #define OP_Param 143
12725 #define OP_FkCounter 144 /* synopsis: fkctr[P1]+=P2 */
12726 #define OP_MemMax 145 /* synopsis: r[P1]=max(r[P1],r[P2]) */
12727 #define OP_OffsetLimit 146 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
12728 #define OP_AggStep0 147 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12729 #define OP_AggStep 148 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12730 #define OP_AggFinal 149 /* synopsis: accum=r[P1] N=P2 */
12731 #define OP_Expire 150
12732 #define OP_TableLock 151 /* synopsis: iDb=P1 root=P2 write=P3 */
12733 #define OP_VBegin 152
12734 #define OP_VCreate 153
12735 #define OP_VDestroy 154
12736 #define OP_VOpen 155
12737 #define OP_VColumn 156 /* synopsis: r[P3]=vcolumn(P2) */
12738 #define OP_VRename 157
12739 #define OP_Pagecount 158
12740 #define OP_MaxPgcnt 159
12741 #define OP_CursorHint 160
12742 #define OP_Noop 161
12743 #define OP_Explain 162
12744 
12745 /* Properties such as "out2" or "jump" that are specified in
12746 ** comments following the "case" for each opcode in the vdbe.c
12747 ** are encoded into bitvectors as follows:
12748 */
12749 #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
12750 #define OPFLG_IN1 0x02 /* in1: P1 is an input */
12751 #define OPFLG_IN2 0x04 /* in2: P2 is an input */
12752 #define OPFLG_IN3 0x08 /* in3: P3 is an input */
12753 #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
12754 #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
12755 #define OPFLG_INITIALIZER {\
12756 /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
12757 /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
12758 /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\
12759 /* 24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\
12760 /* 32 */ 0x09, 0x09, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
12761 /* 40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\
12762 /* 48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\
12763 /* 56 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b,\
12764 /* 64 */ 0x01, 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x01,\
12765 /* 72 */ 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10,\
12766 /* 80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00,\
12767 /* 88 */ 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
12768 /* 96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
12769 /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12770 /* 112 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
12771 /* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00,\
12772 /* 128 */ 0x00, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10,\
12773 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10,\
12774 /* 144 */ 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00,\
12775 /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
12776 /* 160 */ 0x00, 0x00, 0x00,}
12777 
12778 /* The sqlite3P2Values() routine is able to run faster if it knows
12779 ** the value of the largest JUMP opcode. The smaller the maximum
12780 ** JUMP opcode the better, so the mkopcodeh.tcl script that
12781 ** generated this include file strives to group all JUMP opcodes
12782 ** together near the beginning of the list.
12783 */
12784 #define SQLITE_MX_JUMP_OPCODE 71 /* Maximum JUMP opcode */
12785 
12786 /************** End of opcodes.h *********************************************/
12787 /************** Continuing where we left off in vdbe.h ***********************/
12788 
12789 /*
12790 ** Prototypes for the VDBE interface. See comments on the implementation
12791 ** for a description of what each of these routines does.
12792 */
12793 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
12794 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
12795 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
12796 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
12797 SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
12798 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
12799 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
12800 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
12801 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
12802 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
12803 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
12804 SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
12805 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
12806 SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
12807 #else
12808 # define sqlite3VdbeVerifyNoMallocRequired(A,B)
12809 #endif
12810 SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
12811 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
12812 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
12813 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
12814 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
12815 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
12816 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
12817 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
12818 SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
12819 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
12820 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
12821 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
12822 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
12823 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
12824 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
12825 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
12826 SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
12827 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
12828 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
12829 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
12830 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
12831 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
12832 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
12833 #ifdef SQLITE_DEBUG
12834 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
12835 #endif
12836 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
12837 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
12838 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
12839 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
12840 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
12841 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
12842 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
12843 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
12844 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
12845 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
12846 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
12847 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
12848 #ifndef SQLITE_OMIT_TRACE
12849 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
12850 #endif
12851 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12852 
12853 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
12854 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
12855 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
12856 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
12857 
12858 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
12859 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
12860 
12861 #ifndef SQLITE_OMIT_TRIGGER
12862 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
12863 #endif
12864 
12865 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
12866 ** each VDBE opcode.
12867 **
12868 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
12869 ** comments in VDBE programs that show key decision points in the code
12870 ** generator.
12871 */
12872 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12873 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
12874 # define VdbeComment(X) sqlite3VdbeComment X
12875 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
12876 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
12877 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
12878 # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
12879 # else
12880 # define VdbeModuleComment(X)
12881 # endif
12882 #else
12883 # define VdbeComment(X)
12884 # define VdbeNoopComment(X)
12885 # define VdbeModuleComment(X)
12886 #endif
12887 
12888 /*
12889 ** The VdbeCoverage macros are used to set a coverage testing point
12890 ** for VDBE branch instructions. The coverage testing points are line
12891 ** numbers in the sqlite3.c source file. VDBE branch coverage testing
12892 ** only works with an amalagmation build. That's ok since a VDBE branch
12893 ** coverage build designed for testing the test suite only. No application
12894 ** should ever ship with VDBE branch coverage measuring turned on.
12895 **
12896 ** VdbeCoverage(v) // Mark the previously coded instruction
12897 ** // as a branch
12898 **
12899 ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
12900 **
12901 ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
12902 **
12903 ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
12904 **
12905 ** Every VDBE branch operation must be tagged with one of the macros above.
12906 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
12907 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
12908 ** routine in vdbe.c, alerting the developer to the missed tag.
12909 */
12910 #ifdef SQLITE_VDBE_COVERAGE
12911 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
12912 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
12913 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
12914 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
12915 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
12916 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
12917 #else
12918 # define VdbeCoverage(v)
12919 # define VdbeCoverageIf(v,x)
12920 # define VdbeCoverageAlwaysTaken(v)
12921 # define VdbeCoverageNeverTaken(v)
12922 # define VDBE_OFFSET_LINENO(x) 0
12923 #endif
12924 
12925 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
12926 SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
12927 #else
12928 # define sqlite3VdbeScanStatus(a,b,c,d,e)
12929 #endif
12930 
12931 #endif /* SQLITE_VDBE_H */
12932 
12933 /************** End of vdbe.h ************************************************/
12934 /************** Continuing where we left off in sqliteInt.h ******************/
12935 /************** Include pager.h in the middle of sqliteInt.h *****************/
12936 /************** Begin file pager.h *******************************************/
12937 /*
12938 ** 2001 September 15
12939 **
12940 ** The author disclaims copyright to this source code. In place of
12941 ** a legal notice, here is a blessing:
12942 **
12943 ** May you do good and not evil.
12944 ** May you find forgiveness for yourself and forgive others.
12945 ** May you share freely, never taking more than you give.
12946 **
12947 *************************************************************************
12948 ** This header file defines the interface that the sqlite page cache
12949 ** subsystem. The page cache subsystem reads and writes a file a page
12950 ** at a time and provides a journal for rollback.
12951 */
12952 
12953 #ifndef SQLITE_PAGER_H
12954 #define SQLITE_PAGER_H
12955 
12956 /*
12957 ** Default maximum size for persistent journal files. A negative
12958 ** value means no limit. This value may be overridden using the
12959 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
12960 */
12961 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
12962  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
12963 #endif
12964 
12965 /*
12966 ** The type used to represent a page number. The first page in a file
12967 ** is called page 1. 0 is used to represent "not a page".
12968 */
12969 typedef u32 Pgno;
12970 
12971 /*
12972 ** Each open file is managed by a separate instance of the "Pager" structure.
12973 */
12974 typedef struct Pager Pager;
12975 
12976 /*
12977 ** Handle type for pages.
12978 */
12979 typedef struct PgHdr DbPage;
12980 
12981 /*
12982 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
12983 ** reserved for working around a windows/posix incompatibility). It is
12984 ** used in the journal to signify that the remainder of the journal file
12985 ** is devoted to storing a master journal name - there are no more pages to
12986 ** roll back. See comments for function writeMasterJournal() in pager.c
12987 ** for details.
12988 */
12989 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
12990 
12991 /*
12992 ** Allowed values for the flags parameter to sqlite3PagerOpen().
12993 **
12994 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
12995 */
12996 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
12997 #define PAGER_MEMORY 0x0002 /* In-memory database */
12998 
12999 /*
13000 ** Valid values for the second argument to sqlite3PagerLockingMode().
13001 */
13002 #define PAGER_LOCKINGMODE_QUERY -1
13003 #define PAGER_LOCKINGMODE_NORMAL 0
13004 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
13005 
13006 /*
13007 ** Numeric constants that encode the journalmode.
13008 **
13009 ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
13010 ** are exposed in the API via the "PRAGMA journal_mode" command and
13011 ** therefore cannot be changed without a compatibility break.
13012 */
13013 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
13014 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
13015 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
13016 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
13017 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
13018 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
13019 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
13020 
13021 /*
13022 ** Flags that make up the mask passed to sqlite3PagerGet().
13023 */
13024 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
13025 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
13026 
13027 /*
13028 ** Flags for sqlite3PagerSetFlags()
13029 **
13030 ** Value constraints (enforced via assert()):
13031 ** PAGER_FULLFSYNC == SQLITE_FullFSync
13032 ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
13033 ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
13034 */
13035 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
13036 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
13037 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
13038 #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
13039 #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
13040 #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
13041 #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
13042 #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
13043 #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
13044 
13045 /*
13046 ** The remainder of this file contains the declarations of the functions
13047 ** that make up the Pager sub-system API. See source code comments for
13048 ** a detailed description of each routine.
13049 */
13050 
13051 /* Open and close a Pager connection. */
13052 SQLITE_PRIVATE int sqlite3PagerOpen(
13053  sqlite3_vfs*,
13054  Pager **ppPager,
13055  const char*,
13056  int,
13057  int,
13058  int,
13059  void(*)(DbPage*)
13060 );
13061 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
13062 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
13063 
13064 /* Functions used to configure a Pager object. */
13065 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
13066 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
13067 #ifdef SQLITE_HAS_CODEC
13068 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
13069 #endif
13070 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
13071 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
13072 SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
13073 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
13074 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
13075 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
13076 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
13077 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
13078 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
13079 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
13080 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
13081 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
13082 SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
13083 
13084 /* Functions used to obtain and release page references. */
13085 SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
13086 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
13087 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
13088 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
13089 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
13090 
13091 /* Operations on page references. */
13092 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
13093 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
13094 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
13095 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
13096 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
13097 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
13098 
13099 /* Functions used to manage pager transactions and savepoints. */
13100 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
13101 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
13102 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
13103 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
13104 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
13105 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
13106 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
13107 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
13108 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
13109 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
13110 
13111 #ifndef SQLITE_OMIT_WAL
13112 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
13113 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
13114 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
13115 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
13116 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
13117 SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager);
13118 # ifdef SQLITE_ENABLE_SNAPSHOT
13119 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
13120 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
13121 # endif
13122 #else
13123 # define sqlite3PagerUseWal(x) 0
13124 #endif
13125 
13126 #ifdef SQLITE_ENABLE_ZIPVFS
13127 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
13128 #endif
13129 
13130 /* Functions used to query pager state and configuration. */
13131 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
13132 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
13133 #ifdef SQLITE_DEBUG
13134 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
13135 #endif
13136 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
13137 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
13138 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
13139 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
13140 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
13141 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
13142 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
13143 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
13144 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
13145 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
13146 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
13147 
13148 /* Functions used to truncate the database file. */
13149 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
13150 
13151 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
13152 
13153 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
13154 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
13155 #endif
13156 
13157 /* Functions to support testing and debugging. */
13158 #if !defined(NDEBUG) || defined(SQLITE_TEST)
13159 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
13160 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
13161 #endif
13162 #ifdef SQLITE_TEST
13163 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
13164 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
13165  void disable_simulated_io_errors(void);
13166  void enable_simulated_io_errors(void);
13167 #else
13168 # define disable_simulated_io_errors()
13169 # define enable_simulated_io_errors()
13170 #endif
13171 
13172 #endif /* SQLITE_PAGER_H */
13173 
13174 /************** End of pager.h ***********************************************/
13175 /************** Continuing where we left off in sqliteInt.h ******************/
13176 /************** Include pcache.h in the middle of sqliteInt.h ****************/
13177 /************** Begin file pcache.h ******************************************/
13178 /*
13179 ** 2008 August 05
13180 **
13181 ** The author disclaims copyright to this source code. In place of
13182 ** a legal notice, here is a blessing:
13183 **
13184 ** May you do good and not evil.
13185 ** May you find forgiveness for yourself and forgive others.
13186 ** May you share freely, never taking more than you give.
13187 **
13188 *************************************************************************
13189 ** This header file defines the interface that the sqlite page cache
13190 ** subsystem.
13191 */
13192 
13193 #ifndef _PCACHE_H_
13194 
13195 typedef struct PgHdr PgHdr;
13196 typedef struct PCache PCache;
13197 
13198 /*
13199 ** Every page in the cache is controlled by an instance of the following
13200 ** structure.
13201 */
13202 struct PgHdr {
13203  sqlite3_pcache_page *pPage; /* Pcache object page handle */
13204  void *pData; /* Page data */
13205  void *pExtra; /* Extra content */
13206  PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
13207  Pager *pPager; /* The pager this page is part of */
13208  Pgno pgno; /* Page number for this page */
13209 #ifdef SQLITE_CHECK_PAGES
13210  u32 pageHash; /* Hash of page content */
13211 #endif
13212  u16 flags; /* PGHDR flags defined below */
13213 
13214  /**********************************************************************
13215  ** Elements above are public. All that follows is private to pcache.c
13216  ** and should not be accessed by other modules.
13217  */
13218  i16 nRef; /* Number of users of this page */
13219  PCache *pCache; /* Cache that owns this page */
13220 
13221  PgHdr *pDirtyNext; /* Next element in list of dirty pages */
13222  PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
13223 };
13224 
13225 /* Bit values for PgHdr.flags */
13226 #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
13227 #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
13228 #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
13229 #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
13230  ** writing this page to the database */
13231 #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
13232 #define PGHDR_MMAP 0x020 /* This is an mmap page object */
13233 
13234 #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
13235 
13236 /* Initialize and shutdown the page cache subsystem */
13237 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
13238 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
13239 
13240 /* Page cache buffer management:
13241 ** These routines implement SQLITE_CONFIG_PAGECACHE.
13242 */
13243 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
13244 
13245 /* Create a new pager cache.
13246 ** Under memory stress, invoke xStress to try to make pages clean.
13247 ** Only clean and unpinned pages can be reclaimed.
13248 */
13249 SQLITE_PRIVATE int sqlite3PcacheOpen(
13250  int szPage, /* Size of every page */
13251  int szExtra, /* Extra space associated with each page */
13252  int bPurgeable, /* True if pages are on backing store */
13253  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
13254  void *pStress, /* Argument to xStress */
13255  PCache *pToInit /* Preallocated space for the PCache */
13256 );
13257 
13258 /* Modify the page-size after the cache has been created. */
13259 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
13260 
13261 /* Return the size in bytes of a PCache object. Used to preallocate
13262 ** storage space.
13263 */
13264 SQLITE_PRIVATE int sqlite3PcacheSize(void);
13265 
13266 /* One release per successful fetch. Page is pinned until released.
13267 ** Reference counted.
13268 */
13269 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
13270 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
13271 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
13272 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
13273 
13274 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
13275 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
13276 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
13277 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
13278 SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
13279 
13280 /* Change a page number. Used by incr-vacuum. */
13281 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
13282 
13283 /* Remove all pages with pgno>x. Reset the cache if x==0 */
13284 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
13285 
13286 /* Get a list of all dirty pages in the cache, sorted by page number */
13287 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
13288 
13289 /* Reset and close the cache object */
13290 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
13291 
13292 /* Clear flags from pages of the page cache */
13293 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
13294 
13295 /* Discard the contents of the cache */
13296 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
13297 
13298 /* Return the total number of outstanding page references */
13299 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
13300 
13301 /* Increment the reference count of an existing page */
13302 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
13303 
13304 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
13305 
13306 /* Return the total number of pages stored in the cache */
13307 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
13308 
13309 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
13310 /* Iterate through all dirty pages currently stored in the cache. This
13311 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
13312 ** library is built.
13313 */
13314 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
13315 #endif
13316 
13317 #if defined(SQLITE_DEBUG)
13318 /* Check invariants on a PgHdr object */
13319 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
13320 #endif
13321 
13322 /* Set and get the suggested cache-size for the specified pager-cache.
13323 **
13324 ** If no global maximum is configured, then the system attempts to limit
13325 ** the total number of pages cached by purgeable pager-caches to the sum
13326 ** of the suggested cache-sizes.
13327 */
13328 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
13329 #ifdef SQLITE_TEST
13330 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
13331 #endif
13332 
13333 /* Set or get the suggested spill-size for the specified pager-cache.
13334 **
13335 ** The spill-size is the minimum number of pages in cache before the cache
13336 ** will attempt to spill dirty pages by calling xStress.
13337 */
13338 SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
13339 
13340 /* Free up as much memory as possible from the page cache */
13341 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
13342 
13343 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13344 /* Try to return memory used by the pcache module to the main memory heap */
13345 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
13346 #endif
13347 
13348 #ifdef SQLITE_TEST
13349 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
13350 #endif
13351 
13352 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
13353 
13354 /* Return the header size */
13355 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
13356 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
13357 
13358 /* Number of dirty pages as a percentage of the configured cache size */
13359 SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
13360 
13361 #endif /* _PCACHE_H_ */
13362 
13363 /************** End of pcache.h **********************************************/
13364 /************** Continuing where we left off in sqliteInt.h ******************/
13365 /************** Include os.h in the middle of sqliteInt.h ********************/
13366 /************** Begin file os.h **********************************************/
13367 /*
13368 ** 2001 September 16
13369 **
13370 ** The author disclaims copyright to this source code. In place of
13371 ** a legal notice, here is a blessing:
13372 **
13373 ** May you do good and not evil.
13374 ** May you find forgiveness for yourself and forgive others.
13375 ** May you share freely, never taking more than you give.
13376 **
13377 ******************************************************************************
13378 **
13379 ** This header file (together with is companion C source-code file
13380 ** "os.c") attempt to abstract the underlying operating system so that
13381 ** the SQLite library will work on both POSIX and windows systems.
13382 **
13383 ** This header file is #include-ed by sqliteInt.h and thus ends up
13384 ** being included by every source file.
13385 */
13386 #ifndef _SQLITE_OS_H_
13387 #define _SQLITE_OS_H_
13388 
13389 /*
13390 ** Attempt to automatically detect the operating system and setup the
13391 ** necessary pre-processor macros for it.
13392 */
13393 /************** Include os_setup.h in the middle of os.h *********************/
13394 /************** Begin file os_setup.h ****************************************/
13395 /*
13396 ** 2013 November 25
13397 **
13398 ** The author disclaims copyright to this source code. In place of
13399 ** a legal notice, here is a blessing:
13400 **
13401 ** May you do good and not evil.
13402 ** May you find forgiveness for yourself and forgive others.
13403 ** May you share freely, never taking more than you give.
13404 **
13405 ******************************************************************************
13406 **
13407 ** This file contains pre-processor directives related to operating system
13408 ** detection and/or setup.
13409 */
13410 #ifndef SQLITE_OS_SETUP_H
13411 #define SQLITE_OS_SETUP_H
13412 
13413 /*
13414 ** Figure out if we are dealing with Unix, Windows, or some other operating
13415 ** system.
13416 **
13417 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
13418 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
13419 ** the three will be 1. The other two will be 0.
13420 */
13421 #if defined(SQLITE_OS_OTHER)
13422 # if SQLITE_OS_OTHER==1
13423 # undef SQLITE_OS_UNIX
13424 # define SQLITE_OS_UNIX 0
13425 # undef SQLITE_OS_WIN
13426 # define SQLITE_OS_WIN 0
13427 # else
13428 # undef SQLITE_OS_OTHER
13429 # endif
13430 #endif
13431 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
13432 # define SQLITE_OS_OTHER 0
13433 # ifndef SQLITE_OS_WIN
13434 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
13435  defined(__MINGW32__) || defined(__BORLANDC__)
13436 # define SQLITE_OS_WIN 1
13437 # define SQLITE_OS_UNIX 0
13438 # else
13439 # define SQLITE_OS_WIN 0
13440 # define SQLITE_OS_UNIX 1
13441 # endif
13442 # else
13443 # define SQLITE_OS_UNIX 0
13444 # endif
13445 #else
13446 # ifndef SQLITE_OS_WIN
13447 # define SQLITE_OS_WIN 0
13448 # endif
13449 #endif
13450 
13451 #endif /* SQLITE_OS_SETUP_H */
13452 
13453 /************** End of os_setup.h ********************************************/
13454 /************** Continuing where we left off in os.h *************************/
13455 
13456 /* If the SET_FULLSYNC macro is not defined above, then make it
13457 ** a no-op
13458 */
13459 #ifndef SET_FULLSYNC
13460 # define SET_FULLSYNC(x,y)
13461 #endif
13462 
13463 /*
13464 ** The default size of a disk sector
13465 */
13466 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
13467 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
13468 #endif
13469 
13470 /*
13471 ** Temporary files are named starting with this prefix followed by 16 random
13472 ** alphanumeric characters, and no file extension. They are stored in the
13473 ** OS's standard temporary file directory, and are deleted prior to exit.
13474 ** If sqlite is being embedded in another program, you may wish to change the
13475 ** prefix to reflect your program's name, so that if your program exits
13476 ** prematurely, old temporary files can be easily identified. This can be done
13477 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
13478 **
13479 ** 2006-10-31: The default prefix used to be "sqlite_". But then
13480 ** Mcafee started using SQLite in their anti-virus product and it
13481 ** started putting files with the "sqlite" name in the c:/temp folder.
13482 ** This annoyed many windows users. Those users would then do a
13483 ** Google search for "sqlite", find the telephone numbers of the
13484 ** developers and call to wake them up at night and complain.
13485 ** For this reason, the default name prefix is changed to be "sqlite"
13486 ** spelled backwards. So the temp files are still identified, but
13487 ** anybody smart enough to figure out the code is also likely smart
13488 ** enough to know that calling the developer will not help get rid
13489 ** of the file.
13490 */
13491 #ifndef SQLITE_TEMP_FILE_PREFIX
13492 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
13493 #endif
13494 
13495 /*
13496 ** The following values may be passed as the second argument to
13497 ** sqlite3OsLock(). The various locks exhibit the following semantics:
13498 **
13499 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
13500 ** RESERVED: A single process may hold a RESERVED lock on a file at
13501 ** any time. Other processes may hold and obtain new SHARED locks.
13502 ** PENDING: A single process may hold a PENDING lock on a file at
13503 ** any one time. Existing SHARED locks may persist, but no new
13504 ** SHARED locks may be obtained by other processes.
13505 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
13506 **
13507 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
13508 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
13509 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
13510 ** sqlite3OsLock().
13511 */
13512 #define NO_LOCK 0
13513 #define SHARED_LOCK 1
13514 #define RESERVED_LOCK 2
13515 #define PENDING_LOCK 3
13516 #define EXCLUSIVE_LOCK 4
13517 
13518 /*
13519 ** File Locking Notes: (Mostly about windows but also some info for Unix)
13520 **
13521 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
13522 ** those functions are not available. So we use only LockFile() and
13523 ** UnlockFile().
13524 **
13525 ** LockFile() prevents not just writing but also reading by other processes.
13526 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
13527 ** byte out of a specific range of bytes. The lock byte is obtained at
13528 ** random so two separate readers can probably access the file at the
13529 ** same time, unless they are unlucky and choose the same lock byte.
13530 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
13531 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
13532 ** a single byte of the file that is designated as the reserved lock byte.
13533 ** A PENDING_LOCK is obtained by locking a designated byte different from
13534 ** the RESERVED_LOCK byte.
13535 **
13536 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
13537 ** which means we can use reader/writer locks. When reader/writer locks
13538 ** are used, the lock is placed on the same range of bytes that is used
13539 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
13540 ** will support two or more Win95 readers or two or more WinNT readers.
13541 ** But a single Win95 reader will lock out all WinNT readers and a single
13542 ** WinNT reader will lock out all other Win95 readers.
13543 **
13544 ** The following #defines specify the range of bytes used for locking.
13545 ** SHARED_SIZE is the number of bytes available in the pool from which
13546 ** a random byte is selected for a shared lock. The pool of bytes for
13547 ** shared locks begins at SHARED_FIRST.
13548 **
13549 ** The same locking strategy and
13550 ** byte ranges are used for Unix. This leaves open the possibility of having
13551 ** clients on win95, winNT, and unix all talking to the same shared file
13552 ** and all locking correctly. To do so would require that samba (or whatever
13553 ** tool is being used for file sharing) implements locks correctly between
13554 ** windows and unix. I'm guessing that isn't likely to happen, but by
13555 ** using the same locking range we are at least open to the possibility.
13556 **
13557 ** Locking in windows is manditory. For this reason, we cannot store
13558 ** actual data in the bytes used for locking. The pager never allocates
13559 ** the pages involved in locking therefore. SHARED_SIZE is selected so
13560 ** that all locks will fit on a single page even at the minimum page size.
13561 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
13562 ** is set high so that we don't have to allocate an unused page except
13563 ** for very large databases. But one should test the page skipping logic
13564 ** by setting PENDING_BYTE low and running the entire regression suite.
13565 **
13566 ** Changing the value of PENDING_BYTE results in a subtly incompatible
13567 ** file format. Depending on how it is changed, you might not notice
13568 ** the incompatibility right away, even running a full regression test.
13569 ** The default location of PENDING_BYTE is the first byte past the
13570 ** 1GB boundary.
13571 **
13572 */
13573 #ifdef SQLITE_OMIT_WSD
13574 # define PENDING_BYTE (0x40000000)
13575 #else
13576 # define PENDING_BYTE sqlite3PendingByte
13577 #endif
13578 #define RESERVED_BYTE (PENDING_BYTE+1)
13579 #define SHARED_FIRST (PENDING_BYTE+2)
13580 #define SHARED_SIZE 510
13581 
13582 /*
13583 ** Wrapper around OS specific sqlite3_os_init() function.
13584 */
13585 SQLITE_PRIVATE int sqlite3OsInit(void);
13586 
13587 /*
13588 ** Functions for accessing sqlite3_file methods
13589 */
13590 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
13591 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
13592 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
13593 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
13594 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
13595 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
13596 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
13597 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
13598 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
13599 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
13600 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
13601 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
13602 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
13603 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
13604 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
13605 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
13606 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
13607 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
13608 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
13609 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
13610 
13611 
13612 /*
13613 ** Functions for accessing sqlite3_vfs methods
13614 */
13615 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
13616 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
13617 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
13618 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
13619 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13620 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
13621 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
13622 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
13623 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
13624 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
13625 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
13626 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
13627 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
13628 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
13629 
13630 /*
13631 ** Convenience functions for opening and closing files using
13632 ** sqlite3_malloc() to obtain space for the file-handle structure.
13633 */
13634 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
13635 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
13636 
13637 #endif /* _SQLITE_OS_H_ */
13638 
13639 /************** End of os.h **************************************************/
13640 /************** Continuing where we left off in sqliteInt.h ******************/
13641 /************** Include mutex.h in the middle of sqliteInt.h *****************/
13642 /************** Begin file mutex.h *******************************************/
13643 /*
13644 ** 2007 August 28
13645 **
13646 ** The author disclaims copyright to this source code. In place of
13647 ** a legal notice, here is a blessing:
13648 **
13649 ** May you do good and not evil.
13650 ** May you find forgiveness for yourself and forgive others.
13651 ** May you share freely, never taking more than you give.
13652 **
13653 *************************************************************************
13654 **
13655 ** This file contains the common header for all mutex implementations.
13656 ** The sqliteInt.h header #includes this file so that it is available
13657 ** to all source files. We break it out in an effort to keep the code
13658 ** better organized.
13659 **
13660 ** NOTE: source files should *not* #include this header file directly.
13661 ** Source files should #include the sqliteInt.h file and let that file
13662 ** include this one indirectly.
13663 */
13664 
13665 
13666 /*
13667 ** Figure out what version of the code to use. The choices are
13668 **
13669 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
13670 ** mutexes implementation cannot be overridden
13671 ** at start-time.
13672 **
13673 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
13674 ** mutual exclusion is provided. But this
13675 ** implementation can be overridden at
13676 ** start-time.
13677 **
13678 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
13679 **
13680 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
13681 */
13682 #if !SQLITE_THREADSAFE
13683 # define SQLITE_MUTEX_OMIT
13684 #endif
13685 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
13686 # if SQLITE_OS_UNIX
13687 # define SQLITE_MUTEX_PTHREADS
13688 # elif SQLITE_OS_WIN
13689 # define SQLITE_MUTEX_W32
13690 # else
13691 # define SQLITE_MUTEX_NOOP
13692 # endif
13693 #endif
13694 
13695 #ifdef SQLITE_MUTEX_OMIT
13696 /*
13697 ** If this is a no-op implementation, implement everything as macros.
13698 */
13699 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
13700 #define sqlite3_mutex_free(X)
13701 #define sqlite3_mutex_enter(X)
13702 #define sqlite3_mutex_try(X) SQLITE_OK
13703 #define sqlite3_mutex_leave(X)
13704 #define sqlite3_mutex_held(X) ((void)(X),1)
13705 #define sqlite3_mutex_notheld(X) ((void)(X),1)
13706 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
13707 #define sqlite3MutexInit() SQLITE_OK
13708 #define sqlite3MutexEnd()
13709 #define MUTEX_LOGIC(X)
13710 #else
13711 #define MUTEX_LOGIC(X) X
13712 #endif /* defined(SQLITE_MUTEX_OMIT) */
13713 
13714 /************** End of mutex.h ***********************************************/
13715 /************** Continuing where we left off in sqliteInt.h ******************/
13716 
13717 /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
13718 ** synchronous setting to EXTRA. It is no longer supported.
13719 */
13720 #ifdef SQLITE_EXTRA_DURABLE
13721 # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
13722 # define SQLITE_DEFAULT_SYNCHRONOUS 3
13723 #endif
13724 
13725 /*
13726 ** Default synchronous levels.
13727 **
13728 ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
13729 ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
13730 **
13731 ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
13732 ** OFF 1 0
13733 ** NORMAL 2 1
13734 ** FULL 3 2
13735 ** EXTRA 4 3
13736 **
13737 ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
13738 ** In other words, the zero-based numbers are used for all external interfaces
13739 ** and the one-based values are used internally.
13740 */
13741 #ifndef SQLITE_DEFAULT_SYNCHRONOUS
13742 # define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1)
13743 #endif
13744 #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
13745 # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
13746 #endif
13747 
13748 /*
13749 ** Each database file to be accessed by the system is an instance
13750 ** of the following structure. There are normally two of these structures
13751 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
13752 ** aDb[1] is the database file used to hold temporary tables. Additional
13753 ** databases may be attached.
13754 */
13755 struct Db {
13756  char *zDbSName; /* Name of this database. (schema name, not filename) */
13757  Btree *pBt; /* The B*Tree structure for this database file */
13758  u8 safety_level; /* How aggressive at syncing data to disk */
13759  u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
13760  Schema *pSchema; /* Pointer to database schema (possibly shared) */
13761 };
13762 
13763 /*
13764 ** An instance of the following structure stores a database schema.
13765 **
13766 ** Most Schema objects are associated with a Btree. The exception is
13767 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
13768 ** In shared cache mode, a single Schema object can be shared by multiple
13769 ** Btrees that refer to the same underlying BtShared object.
13770 **
13771 ** Schema objects are automatically deallocated when the last Btree that
13772 ** references them is destroyed. The TEMP Schema is manually freed by
13773 ** sqlite3_close().
13774 *
13775 ** A thread must be holding a mutex on the corresponding Btree in order
13776 ** to access Schema content. This implies that the thread must also be
13777 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
13778 ** For a TEMP Schema, only the connection mutex is required.
13779 */
13780 struct Schema {
13781  int schema_cookie; /* Database schema version number for this file */
13782  int iGeneration; /* Generation counter. Incremented with each change */
13783  Hash tblHash; /* All tables indexed by name */
13784  Hash idxHash; /* All (named) indices indexed by name */
13785  Hash trigHash; /* All triggers indexed by name */
13786  Hash fkeyHash; /* All foreign keys by referenced table name */
13787  Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
13788  u8 file_format; /* Schema format version for this file */
13789  u8 enc; /* Text encoding used by this database */
13790  u16 schemaFlags; /* Flags associated with this schema */
13791  int cache_size; /* Number of pages to use in the cache */
13792 };
13793 
13794 /*
13795 ** These macros can be used to test, set, or clear bits in the
13796 ** Db.pSchema->flags field.
13797 */
13798 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
13799 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
13800 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
13801 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
13802 
13803 /*
13804 ** Allowed values for the DB.pSchema->flags field.
13805 **
13806 ** The DB_SchemaLoaded flag is set after the database schema has been
13807 ** read into internal hash tables.
13808 **
13809 ** DB_UnresetViews means that one or more views have column names that
13810 ** have been filled out. If the schema changes, these column names might
13811 ** changes and so the view will need to be reset.
13812 */
13813 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
13814 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
13815 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
13816 
13817 /*
13818 ** The number of different kinds of things that can be limited
13819 ** using the sqlite3_limit() interface.
13820 */
13821 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
13822 
13823 /*
13824 ** Lookaside malloc is a set of fixed-size buffers that can be used
13825 ** to satisfy small transient memory allocation requests for objects
13826 ** associated with a particular database connection. The use of
13827 ** lookaside malloc provides a significant performance enhancement
13828 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
13829 ** SQL statements.
13830 **
13831 ** The Lookaside structure holds configuration information about the
13832 ** lookaside malloc subsystem. Each available memory allocation in
13833 ** the lookaside subsystem is stored on a linked list of LookasideSlot
13834 ** objects.
13835 **
13836 ** Lookaside allocations are only allowed for objects that are associated
13837 ** with a particular database connection. Hence, schema information cannot
13838 ** be stored in lookaside because in shared cache mode the schema information
13839 ** is shared by multiple database connections. Therefore, while parsing
13840 ** schema information, the Lookaside.bEnabled flag is cleared so that
13841 ** lookaside allocations are not used to construct the schema objects.
13842 */
13843 struct Lookaside {
13844  u32 bDisable; /* Only operate the lookaside when zero */
13845  u16 sz; /* Size of each buffer in bytes */
13846  u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
13847  int nOut; /* Number of buffers currently checked out */
13848  int mxOut; /* Highwater mark for nOut */
13849  int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
13850  LookasideSlot *pFree; /* List of available buffers */
13851  void *pStart; /* First byte of available memory space */
13852  void *pEnd; /* First byte past end of available space */
13853 };
13854 struct LookasideSlot {
13855  LookasideSlot *pNext; /* Next buffer in the list of free buffers */
13856 };
13857 
13858 /*
13859 ** A hash table for built-in function definitions. (Application-defined
13860 ** functions use a regular table table from hash.h.)
13861 **
13862 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
13863 ** Collisions are on the FuncDef.u.pHash chain.
13864 */
13865 #define SQLITE_FUNC_HASH_SZ 23
13866 struct FuncDefHash {
13867  FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
13868 };
13869 
13870 #ifdef SQLITE_USER_AUTHENTICATION
13871 /*
13872 ** Information held in the "sqlite3" database connection object and used
13873 ** to manage user authentication.
13874 */
13875 typedef struct sqlite3_userauth sqlite3_userauth;
13876 struct sqlite3_userauth {
13877  u8 authLevel; /* Current authentication level */
13878  int nAuthPW; /* Size of the zAuthPW in bytes */
13879  char *zAuthPW; /* Password used to authenticate */
13880  char *zAuthUser; /* User name used to authenticate */
13881 };
13882 
13883 /* Allowed values for sqlite3_userauth.authLevel */
13884 #define UAUTH_Unknown 0 /* Authentication not yet checked */
13885 #define UAUTH_Fail 1 /* User authentication failed */
13886 #define UAUTH_User 2 /* Authenticated as a normal user */
13887 #define UAUTH_Admin 3 /* Authenticated as an administrator */
13888 
13889 /* Functions used only by user authorization logic */
13890 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
13891 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
13892 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
13893 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
13894 
13895 #endif /* SQLITE_USER_AUTHENTICATION */
13896 
13897 /*
13898 ** typedef for the authorization callback function.
13899 */
13900 #ifdef SQLITE_USER_AUTHENTICATION
13901  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13902  const char*, const char*);
13903 #else
13904  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13905  const char*);
13906 #endif
13907 
13908 #ifndef SQLITE_OMIT_DEPRECATED
13909 /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
13910 ** in the style of sqlite3_trace()
13911 */
13912 #define SQLITE_TRACE_LEGACY 0x80
13913 #else
13914 #define SQLITE_TRACE_LEGACY 0
13915 #endif /* SQLITE_OMIT_DEPRECATED */
13916 
13917 
13918 /*
13919 ** Each database connection is an instance of the following structure.
13920 */
13921 struct sqlite3 {
13922  sqlite3_vfs *pVfs; /* OS Interface */
13923  struct Vdbe *pVdbe; /* List of active virtual machines */
13924  CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
13925  sqlite3_mutex *mutex; /* Connection mutex */
13926  Db *aDb; /* All backends */
13927  int nDb; /* Number of backends currently in use */
13928  int flags; /* Miscellaneous flags. See below */
13929  i64 lastRowid; /* ROWID of most recent insert (see above) */
13930  i64 szMmap; /* Default mmap_size setting */
13931  unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
13932  int errCode; /* Most recent error code (SQLITE_*) */
13933  int errMask; /* & result codes with this before returning */
13934  int iSysErrno; /* Errno value from last system error */
13935  u16 dbOptFlags; /* Flags to enable/disable optimizations */
13936  u8 enc; /* Text encoding */
13937  u8 autoCommit; /* The auto-commit flag. */
13938  u8 temp_store; /* 1: file 2: memory 0: default */
13939  u8 mallocFailed; /* True if we have seen a malloc failure */
13940  u8 bBenignMalloc; /* Do not require OOMs if true */
13941  u8 dfltLockMode; /* Default locking-mode for attached dbs */
13942  signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
13943  u8 suppressErr; /* Do not issue error messages if true */
13944  u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
13945  u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
13946  u8 mTrace; /* zero or more SQLITE_TRACE flags */
13947  int nextPagesize; /* Pagesize after VACUUM if >0 */
13948  u32 magic; /* Magic number for detect library misuse */
13949  int nChange; /* Value returned by sqlite3_changes() */
13950  int nTotalChange; /* Value returned by sqlite3_total_changes() */
13951  int aLimit[SQLITE_N_LIMIT]; /* Limits */
13952  int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
13953  struct sqlite3InitInfo { /* Information used during initialization */
13954  int newTnum; /* Rootpage of table being initialized */
13955  u8 iDb; /* Which db file is being initialized */
13956  u8 busy; /* TRUE if currently initializing */
13957  u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
13958  u8 imposterTable; /* Building an imposter table */
13959  } init;
13960  int nVdbeActive; /* Number of VDBEs currently running */
13961  int nVdbeRead; /* Number of active VDBEs that read or write */
13962  int nVdbeWrite; /* Number of active VDBEs that read and write */
13963  int nVdbeExec; /* Number of nested calls to VdbeExec() */
13964  int nVDestroy; /* Number of active OP_VDestroy operations */
13965  int nExtension; /* Number of loaded extensions */
13966  void **aExtension; /* Array of shared library handles */
13967  int (*xTrace)(u32,void*,void*,void*); /* Trace function */
13968  void *pTraceArg; /* Argument to the trace function */
13969  void (*xProfile)(void*,const char*,u64); /* Profiling function */
13970  void *pProfileArg; /* Argument to profile function */
13971  void *pCommitArg; /* Argument to xCommitCallback() */
13972  int (*xCommitCallback)(void*); /* Invoked at every commit. */
13973  void *pRollbackArg; /* Argument to xRollbackCallback() */
13974  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
13975  void *pUpdateArg;
13976  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
13977 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
13978  void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
13979  void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
13980  void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
13981  );
13982  PreUpdate *pPreUpdate; /* Context for active pre-update callback */
13983 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
13984 #ifndef SQLITE_OMIT_WAL
13985  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
13986  void *pWalArg;
13987 #endif
13988  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
13989  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
13990  void *pCollNeededArg;
13991  sqlite3_value *pErr; /* Most recent error message */
13992  union {
13993  volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
13994  double notUsed1; /* Spacer */
13995  } u1;
13996  Lookaside lookaside; /* Lookaside malloc configuration */
13997 #ifndef SQLITE_OMIT_AUTHORIZATION
13998  sqlite3_xauth xAuth; /* Access authorization function */
13999  void *pAuthArg; /* 1st argument to the access auth function */
14000 #endif
14001 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
14002  int (*xProgress)(void *); /* The progress callback */
14003  void *pProgressArg; /* Argument to the progress callback */
14004  unsigned nProgressOps; /* Number of opcodes for progress callback */
14005 #endif
14006 #ifndef SQLITE_OMIT_VIRTUALTABLE
14007  int nVTrans; /* Allocated size of aVTrans */
14008  Hash aModule; /* populated by sqlite3_create_module() */
14009  VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
14010  VTable **aVTrans; /* Virtual tables with open transactions */
14011  VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
14012 #endif
14013  Hash aFunc; /* Hash table of connection functions */
14014  Hash aCollSeq; /* All collating sequences */
14015  BusyHandler busyHandler; /* Busy callback */
14016  Db aDbStatic[2]; /* Static space for the 2 default backends */
14017  Savepoint *pSavepoint; /* List of active savepoints */
14018  int busyTimeout; /* Busy handler timeout, in msec */
14019  int nSavepoint; /* Number of non-transaction savepoints */
14020  int nStatement; /* Number of nested statement-transactions */
14021  i64 nDeferredCons; /* Net deferred constraints this transaction. */
14022  i64 nDeferredImmCons; /* Net deferred immediate constraints */
14023  int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
14024 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
14025  /* The following variables are all protected by the STATIC_MASTER
14026  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
14027  **
14028  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
14029  ** unlock so that it can proceed.
14030  **
14031  ** When X.pBlockingConnection==Y, that means that something that X tried
14032  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
14033  ** held by Y.
14034  */
14035  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
14036  sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
14037  void *pUnlockArg; /* Argument to xUnlockNotify */
14038  void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
14039  sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
14040 #endif
14041 #ifdef SQLITE_USER_AUTHENTICATION
14042  sqlite3_userauth auth; /* User authentication information */
14043 #endif
14044 };
14045 
14046 /*
14047 ** A macro to discover the encoding of a database.
14048 */
14049 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
14050 #define ENC(db) ((db)->enc)
14051 
14052 /*
14053 ** Possible values for the sqlite3.flags.
14054 **
14055 ** Value constraints (enforced via assert()):
14056 ** SQLITE_FullFSync == PAGER_FULLFSYNC
14057 ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
14058 ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
14059 */
14060 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
14061 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
14062 #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
14063 #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
14064 #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
14065 #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
14066 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
14067 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
14068  /* DELETE, or UPDATE and return */
14069  /* the count using a callback. */
14070 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
14071  /* result set is empty */
14072 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
14073 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
14074 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
14075 #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
14076 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
14077 #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
14078 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
14079 #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
14080 #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
14081 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
14082 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
14083 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
14084 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
14085 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
14086 #define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */
14087 #define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */
14088 #define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */
14089 #define SQLITE_QueryOnly 0x04000000 /* Disable database changes */
14090 #define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */
14091 #define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */
14092 #define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */
14093 #define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */
14094 
14095 
14096 /*
14097 ** Bits of the sqlite3.dbOptFlags field that are used by the
14098 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
14099 ** selectively disable various optimizations.
14100 */
14101 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
14102 #define SQLITE_ColumnCache 0x0002 /* Column cache */
14103 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
14104 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
14105 /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
14106 #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
14107 #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
14108 #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
14109 #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
14110 #define SQLITE_Transitive 0x0200 /* Transitive constraints */
14111 #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
14112 #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
14113 #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */
14114 #define SQLITE_AllOpts 0xffff /* All optimizations */
14115 
14116 /*
14117 ** Macros for testing whether or not optimizations are enabled or disabled.
14118 */
14119 #ifndef SQLITE_OMIT_BUILTIN_TEST
14120 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
14121 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
14122 #else
14123 #define OptimizationDisabled(db, mask) 0
14124 #define OptimizationEnabled(db, mask) 1
14125 #endif
14126 
14127 /*
14128 ** Return true if it OK to factor constant expressions into the initialization
14129 ** code. The argument is a Parse object for the code generator.
14130 */
14131 #define ConstFactorOk(P) ((P)->okConstFactor)
14132 
14133 /*
14134 ** Possible values for the sqlite.magic field.
14135 ** The numbers are obtained at random and have no special meaning, other
14136 ** than being distinct from one another.
14137 */
14138 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
14139 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
14140 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
14141 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
14142 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
14143 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
14144 
14145 /*
14146 ** Each SQL function is defined by an instance of the following
14147 ** structure. For global built-in functions (ex: substr(), max(), count())
14148 ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
14149 ** For per-connection application-defined functions, a pointer to this
14150 ** structure is held in the db->aHash hash table.
14151 **
14152 ** The u.pHash field is used by the global built-ins. The u.pDestructor
14153 ** field is used by per-connection app-def functions.
14154 */
14155 struct FuncDef {
14156  i8 nArg; /* Number of arguments. -1 means unlimited */
14157  u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
14158  void *pUserData; /* User data parameter */
14159  FuncDef *pNext; /* Next function with same name */
14160  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
14161  void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
14162  const char *zName; /* SQL name of the function. */
14163  union {
14164  FuncDef *pHash; /* Next with a different name but the same hash */
14165  FuncDestructor *pDestructor; /* Reference counted destructor function */
14166  } u;
14167 };
14168 
14169 /*
14170 ** This structure encapsulates a user-function destructor callback (as
14171 ** configured using create_function_v2()) and a reference counter. When
14172 ** create_function_v2() is called to create a function with a destructor,
14173 ** a single object of this type is allocated. FuncDestructor.nRef is set to
14174 ** the number of FuncDef objects created (either 1 or 3, depending on whether
14175 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
14176 ** member of each of the new FuncDef objects is set to point to the allocated
14177 ** FuncDestructor.
14178 **
14179 ** Thereafter, when one of the FuncDef objects is deleted, the reference
14180 ** count on this object is decremented. When it reaches 0, the destructor
14181 ** is invoked and the FuncDestructor structure freed.
14182 */
14183 struct FuncDestructor {
14184  int nRef;
14185  void (*xDestroy)(void *);
14186  void *pUserData;
14187 };
14188 
14189 /*
14190 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
14191 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
14192 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
14193 ** are assert() statements in the code to verify this.
14194 **
14195 ** Value constraints (enforced via assert()):
14196 ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
14197 ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
14198 ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
14199 ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
14200 ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
14201 */
14202 #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
14203 #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
14204 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
14205 #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
14206 #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
14207 #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
14208 #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
14209 #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
14210 #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
14211 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
14212 #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
14213 #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
14214 #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
14215  ** single query - might change over time */
14216 
14217 /*
14218 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
14219 ** used to create the initializers for the FuncDef structures.
14220 **
14221 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
14222 ** Used to create a scalar function definition of a function zName
14223 ** implemented by C function xFunc that accepts nArg arguments. The
14224 ** value passed as iArg is cast to a (void*) and made available
14225 ** as the user-data (sqlite3_user_data()) for the function. If
14226 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
14227 **
14228 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
14229 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
14230 **
14231 ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
14232 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
14233 ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
14234 ** and functions like sqlite_version() that can change, but not during
14235 ** a single query.
14236 **
14237 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
14238 ** Used to create an aggregate function definition implemented by
14239 ** the C functions xStep and xFinal. The first four parameters
14240 ** are interpreted in the same way as the first 4 parameters to
14241 ** FUNCTION().
14242 **
14243 ** LIKEFUNC(zName, nArg, pArg, flags)
14244 ** Used to create a scalar function definition of a function zName
14245 ** that accepts nArg arguments and is implemented by a call to C
14246 ** function likeFunc. Argument pArg is cast to a (void *) and made
14247 ** available as the function user-data (sqlite3_user_data()). The
14248 ** FuncDef.flags variable is set to the value passed as the flags
14249 ** parameter.
14250 */
14251 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
14252  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14253  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14254 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14255  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14256  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14257 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14258  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14259  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14260 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
14261  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
14262  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14263 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
14264  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14265  pArg, 0, xFunc, 0, #zName, }
14266 #define LIKEFUNC(zName, nArg, arg, flags) \
14267  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
14268  (void *)arg, 0, likeFunc, 0, #zName, {0} }
14269 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
14270  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
14271  SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14272 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
14273  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
14274  SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14275 
14276 /*
14277 ** All current savepoints are stored in a linked list starting at
14278 ** sqlite3.pSavepoint. The first element in the list is the most recently
14279 ** opened savepoint. Savepoints are added to the list by the vdbe
14280 ** OP_Savepoint instruction.
14281 */
14282 struct Savepoint {
14283  char *zName; /* Savepoint name (nul-terminated) */
14284  i64 nDeferredCons; /* Number of deferred fk violations */
14285  i64 nDeferredImmCons; /* Number of deferred imm fk. */
14286  Savepoint *pNext; /* Parent savepoint (if any) */
14287 };
14288 
14289 /*
14290 ** The following are used as the second parameter to sqlite3Savepoint(),
14291 ** and as the P1 argument to the OP_Savepoint instruction.
14292 */
14293 #define SAVEPOINT_BEGIN 0
14294 #define SAVEPOINT_RELEASE 1
14295 #define SAVEPOINT_ROLLBACK 2
14296 
14297 
14298 /*
14299 ** Each SQLite module (virtual table definition) is defined by an
14300 ** instance of the following structure, stored in the sqlite3.aModule
14301 ** hash table.
14302 */
14303 struct Module {
14304  const sqlite3_module *pModule; /* Callback pointers */
14305  const char *zName; /* Name passed to create_module() */
14306  void *pAux; /* pAux passed to create_module() */
14307  void (*xDestroy)(void *); /* Module destructor function */
14308  Table *pEpoTab; /* Eponymous table for this module */
14309 };
14310 
14311 /*
14312 ** information about each column of an SQL table is held in an instance
14313 ** of this structure.
14314 */
14315 struct Column {
14316  char *zName; /* Name of this column, \000, then the type */
14317  Expr *pDflt; /* Default value of this column */
14318  char *zColl; /* Collating sequence. If NULL, use the default */
14319  u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
14320  char affinity; /* One of the SQLITE_AFF_... values */
14321  u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
14322  u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
14323 };
14324 
14325 /* Allowed values for Column.colFlags:
14326 */
14327 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
14328 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
14329 #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
14330 
14331 /*
14332 ** A "Collating Sequence" is defined by an instance of the following
14333 ** structure. Conceptually, a collating sequence consists of a name and
14334 ** a comparison routine that defines the order of that sequence.
14335 **
14336 ** If CollSeq.xCmp is NULL, it means that the
14337 ** collating sequence is undefined. Indices built on an undefined
14338 ** collating sequence may not be read or written.
14339 */
14340 struct CollSeq {
14341  char *zName; /* Name of the collating sequence, UTF-8 encoded */
14342  u8 enc; /* Text encoding handled by xCmp() */
14343  void *pUser; /* First argument to xCmp() */
14344  int (*xCmp)(void*,int, const void*, int, const void*);
14345  void (*xDel)(void*); /* Destructor for pUser */
14346 };
14347 
14348 /*
14349 ** A sort order can be either ASC or DESC.
14350 */
14351 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
14352 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
14353 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
14354 
14355 /*
14356 ** Column affinity types.
14357 **
14358 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
14359 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
14360 ** the speed a little by numbering the values consecutively.
14361 **
14362 ** But rather than start with 0 or 1, we begin with 'A'. That way,
14363 ** when multiple affinity types are concatenated into a string and
14364 ** used as the P4 operand, they will be more readable.
14365 **
14366 ** Note also that the numeric types are grouped together so that testing
14367 ** for a numeric type is a single comparison. And the BLOB type is first.
14368 */
14369 #define SQLITE_AFF_BLOB 'A'
14370 #define SQLITE_AFF_TEXT 'B'
14371 #define SQLITE_AFF_NUMERIC 'C'
14372 #define SQLITE_AFF_INTEGER 'D'
14373 #define SQLITE_AFF_REAL 'E'
14374 
14375 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
14376 
14377 /*
14378 ** The SQLITE_AFF_MASK values masks off the significant bits of an
14379 ** affinity value.
14380 */
14381 #define SQLITE_AFF_MASK 0x47
14382 
14383 /*
14384 ** Additional bit values that can be ORed with an affinity without
14385 ** changing the affinity.
14386 **
14387 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
14388 ** It causes an assert() to fire if either operand to a comparison
14389 ** operator is NULL. It is added to certain comparison operators to
14390 ** prove that the operands are always NOT NULL.
14391 */
14392 #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
14393 #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
14394 #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
14395 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
14396 #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
14397 
14398 /*
14399 ** An object of this type is created for each virtual table present in
14400 ** the database schema.
14401 **
14402 ** If the database schema is shared, then there is one instance of this
14403 ** structure for each database connection (sqlite3*) that uses the shared
14404 ** schema. This is because each database connection requires its own unique
14405 ** instance of the sqlite3_vtab* handle used to access the virtual table
14406 ** implementation. sqlite3_vtab* handles can not be shared between
14407 ** database connections, even when the rest of the in-memory database
14408 ** schema is shared, as the implementation often stores the database
14409 ** connection handle passed to it via the xConnect() or xCreate() method
14410 ** during initialization internally. This database connection handle may
14411 ** then be used by the virtual table implementation to access real tables
14412 ** within the database. So that they appear as part of the callers
14413 ** transaction, these accesses need to be made via the same database
14414 ** connection as that used to execute SQL operations on the virtual table.
14415 **
14416 ** All VTable objects that correspond to a single table in a shared
14417 ** database schema are initially stored in a linked-list pointed to by
14418 ** the Table.pVTable member variable of the corresponding Table object.
14419 ** When an sqlite3_prepare() operation is required to access the virtual
14420 ** table, it searches the list for the VTable that corresponds to the
14421 ** database connection doing the preparing so as to use the correct
14422 ** sqlite3_vtab* handle in the compiled query.
14423 **
14424 ** When an in-memory Table object is deleted (for example when the
14425 ** schema is being reloaded for some reason), the VTable objects are not
14426 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
14427 ** immediately. Instead, they are moved from the Table.pVTable list to
14428 ** another linked list headed by the sqlite3.pDisconnect member of the
14429 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
14430 ** next time a statement is prepared using said sqlite3*. This is done
14431 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
14432 ** Refer to comments above function sqlite3VtabUnlockList() for an
14433 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
14434 ** list without holding the corresponding sqlite3.mutex mutex.
14435 **
14436 ** The memory for objects of this type is always allocated by
14437 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
14438 ** the first argument.
14439 */
14440 struct VTable {
14441  sqlite3 *db; /* Database connection associated with this table */
14442  Module *pMod; /* Pointer to module implementation */
14443  sqlite3_vtab *pVtab; /* Pointer to vtab instance */
14444  int nRef; /* Number of pointers to this structure */
14445  u8 bConstraint; /* True if constraints are supported */
14446  int iSavepoint; /* Depth of the SAVEPOINT stack */
14447  VTable *pNext; /* Next in linked list (see above) */
14448 };
14449 
14450 /*
14451 ** The schema for each SQL table and view is represented in memory
14452 ** by an instance of the following structure.
14453 */
14454 struct Table {
14455  char *zName; /* Name of the table or view */
14456  Column *aCol; /* Information about each column */
14457  Index *pIndex; /* List of SQL indexes on this table. */
14458  Select *pSelect; /* NULL for tables. Points to definition if a view. */
14459  FKey *pFKey; /* Linked list of all foreign keys in this table */
14460  char *zColAff; /* String defining the affinity of each column */
14461  ExprList *pCheck; /* All CHECK constraints */
14462  /* ... also used as column name list in a VIEW */
14463  int tnum; /* Root BTree page for this table */
14464  i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
14465  i16 nCol; /* Number of columns in this table */
14466  u16 nRef; /* Number of pointers to this Table */
14467  LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
14468  LogEst szTabRow; /* Estimated size of each table row in bytes */
14469 #ifdef SQLITE_ENABLE_COSTMULT
14470  LogEst costMult; /* Cost multiplier for using this table */
14471 #endif
14472  u8 tabFlags; /* Mask of TF_* values */
14473  u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
14474 #ifndef SQLITE_OMIT_ALTERTABLE
14475  int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
14476 #endif
14477 #ifndef SQLITE_OMIT_VIRTUALTABLE
14478  int nModuleArg; /* Number of arguments to the module */
14479  char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
14480  VTable *pVTable; /* List of VTable objects. */
14481 #endif
14482  Trigger *pTrigger; /* List of triggers stored in pSchema */
14483  Schema *pSchema; /* Schema that contains this table */
14484  Table *pNextZombie; /* Next on the Parse.pZombieTab list */
14485 };
14486 
14487 /*
14488 ** Allowed values for Table.tabFlags.
14489 **
14490 ** TF_OOOHidden applies to tables or view that have hidden columns that are
14491 ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
14492 ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
14493 ** the TF_OOOHidden attribute would apply in this case. Such tables require
14494 ** special handling during INSERT processing.
14495 */
14496 #define TF_Readonly 0x01 /* Read-only system table */
14497 #define TF_Ephemeral 0x02 /* An ephemeral table */
14498 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
14499 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
14500 #define TF_Virtual 0x10 /* Is a virtual table */
14501 #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */
14502 #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */
14503 #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */
14504 
14505 
14506 /*
14507 ** Test to see whether or not a table is a virtual table. This is
14508 ** done as a macro so that it will be optimized out when virtual
14509 ** table support is omitted from the build.
14510 */
14511 #ifndef SQLITE_OMIT_VIRTUALTABLE
14512 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
14513 #else
14514 # define IsVirtual(X) 0
14515 #endif
14516 
14517 /*
14518 ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
14519 ** only works for non-virtual tables (ordinary tables and views) and is
14520 ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
14521 ** IsHiddenColumn() macro is general purpose.
14522 */
14523 #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
14524 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14525 # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14526 #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
14527 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14528 # define IsOrdinaryHiddenColumn(X) 0
14529 #else
14530 # define IsHiddenColumn(X) 0
14531 # define IsOrdinaryHiddenColumn(X) 0
14532 #endif
14533 
14534 
14535 /* Does the table have a rowid */
14536 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
14537 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
14538 
14539 /*
14540 ** Each foreign key constraint is an instance of the following structure.
14541 **
14542 ** A foreign key is associated with two tables. The "from" table is
14543 ** the table that contains the REFERENCES clause that creates the foreign
14544 ** key. The "to" table is the table that is named in the REFERENCES clause.
14545 ** Consider this example:
14546 **
14547 ** CREATE TABLE ex1(
14548 ** a INTEGER PRIMARY KEY,
14549 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
14550 ** );
14551 **
14552 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
14553 ** Equivalent names:
14554 **
14555 ** from-table == child-table
14556 ** to-table == parent-table
14557 **
14558 ** Each REFERENCES clause generates an instance of the following structure
14559 ** which is attached to the from-table. The to-table need not exist when
14560 ** the from-table is created. The existence of the to-table is not checked.
14561 **
14562 ** The list of all parents for child Table X is held at X.pFKey.
14563 **
14564 ** A list of all children for a table named Z (which might not even exist)
14565 ** is held in Schema.fkeyHash with a hash key of Z.
14566 */
14567 struct FKey {
14568  Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
14569  FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
14570  char *zTo; /* Name of table that the key points to (aka: Parent) */
14571  FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
14572  FKey *pPrevTo; /* Previous with the same zTo */
14573  int nCol; /* Number of columns in this key */
14574  /* EV: R-30323-21917 */
14575  u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
14576  u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
14577  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
14578  struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
14579  int iFrom; /* Index of column in pFrom */
14580  char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
14581  } aCol[1]; /* One entry for each of nCol columns */
14582 };
14583 
14584 /*
14585 ** SQLite supports many different ways to resolve a constraint
14586 ** error. ROLLBACK processing means that a constraint violation
14587 ** causes the operation in process to fail and for the current transaction
14588 ** to be rolled back. ABORT processing means the operation in process
14589 ** fails and any prior changes from that one operation are backed out,
14590 ** but the transaction is not rolled back. FAIL processing means that
14591 ** the operation in progress stops and returns an error code. But prior
14592 ** changes due to the same operation are not backed out and no rollback
14593 ** occurs. IGNORE means that the particular row that caused the constraint
14594 ** error is not inserted or updated. Processing continues and no error
14595 ** is returned. REPLACE means that preexisting database rows that caused
14596 ** a UNIQUE constraint violation are removed so that the new insert or
14597 ** update can proceed. Processing continues and no error is reported.
14598 **
14599 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
14600 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
14601 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
14602 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
14603 ** referenced table row is propagated into the row that holds the
14604 ** foreign key.
14605 **
14606 ** The following symbolic values are used to record which type
14607 ** of action to take.
14608 */
14609 #define OE_None 0 /* There is no constraint to check */
14610 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
14611 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
14612 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
14613 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
14614 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
14615 
14616 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
14617 #define OE_SetNull 7 /* Set the foreign key value to NULL */
14618 #define OE_SetDflt 8 /* Set the foreign key value to its default */
14619 #define OE_Cascade 9 /* Cascade the changes */
14620 
14621 #define OE_Default 10 /* Do whatever the default action is */
14622 
14623 
14624 /*
14625 ** An instance of the following structure is passed as the first
14626 ** argument to sqlite3VdbeKeyCompare and is used to control the
14627 ** comparison of the two index keys.
14628 **
14629 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
14630 ** are nField slots for the columns of an index then one extra slot
14631 ** for the rowid at the end.
14632 */
14633 struct KeyInfo {
14634  u32 nRef; /* Number of references to this KeyInfo object */
14635  u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
14636  u16 nField; /* Number of key columns in the index */
14637  u16 nXField; /* Number of columns beyond the key columns */
14638  sqlite3 *db; /* The database connection */
14639  u8 *aSortOrder; /* Sort order for each column. */
14640  CollSeq *aColl[1]; /* Collating sequence for each term of the key */
14641 };
14642 
14643 /*
14644 ** This object holds a record which has been parsed out into individual
14645 ** fields, for the purposes of doing a comparison.
14646 **
14647 ** A record is an object that contains one or more fields of data.
14648 ** Records are used to store the content of a table row and to store
14649 ** the key of an index. A blob encoding of a record is created by
14650 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
14651 ** OP_Column opcode.
14652 **
14653 ** An instance of this object serves as a "key" for doing a search on
14654 ** an index b+tree. The goal of the search is to find the entry that
14655 ** is closed to the key described by this object. This object might hold
14656 ** just a prefix of the key. The number of fields is given by
14657 ** pKeyInfo->nField.
14658 **
14659 ** The r1 and r2 fields are the values to return if this key is less than
14660 ** or greater than a key in the btree, respectively. These are normally
14661 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
14662 ** is in DESC order.
14663 **
14664 ** The key comparison functions actually return default_rc when they find
14665 ** an equals comparison. default_rc can be -1, 0, or +1. If there are
14666 ** multiple entries in the b-tree with the same key (when only looking
14667 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
14668 ** cause the search to find the last match, or +1 to cause the search to
14669 ** find the first match.
14670 **
14671 ** The key comparison functions will set eqSeen to true if they ever
14672 ** get and equal results when comparing this structure to a b-tree record.
14673 ** When default_rc!=0, the search might end up on the record immediately
14674 ** before the first match or immediately after the last match. The
14675 ** eqSeen field will indicate whether or not an exact match exists in the
14676 ** b-tree.
14677 */
14678 struct UnpackedRecord {
14679  KeyInfo *pKeyInfo; /* Collation and sort-order information */
14680  Mem *aMem; /* Values */
14681  u16 nField; /* Number of entries in apMem[] */
14682  i8 default_rc; /* Comparison result if keys are equal */
14683  u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
14684  i8 r1; /* Value to return if (lhs > rhs) */
14685  i8 r2; /* Value to return if (rhs < lhs) */
14686  u8 eqSeen; /* True if an equality comparison has been seen */
14687 };
14688 
14689 
14690 /*
14691 ** Each SQL index is represented in memory by an
14692 ** instance of the following structure.
14693 **
14694 ** The columns of the table that are to be indexed are described
14695 ** by the aiColumn[] field of this structure. For example, suppose
14696 ** we have the following table and index:
14697 **
14698 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
14699 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
14700 **
14701 ** In the Table structure describing Ex1, nCol==3 because there are
14702 ** three columns in the table. In the Index structure describing
14703 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
14704 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
14705 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
14706 ** The second column to be indexed (c1) has an index of 0 in
14707 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
14708 **
14709 ** The Index.onError field determines whether or not the indexed columns
14710 ** must be unique and what to do if they are not. When Index.onError=OE_None,
14711 ** it means this is not a unique index. Otherwise it is a unique index
14712 ** and the value of Index.onError indicate the which conflict resolution
14713 ** algorithm to employ whenever an attempt is made to insert a non-unique
14714 ** element.
14715 **
14716 ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
14717 ** generate VDBE code (as opposed to parsing one read from an sqlite_master
14718 ** table as part of parsing an existing database schema), transient instances
14719 ** of this structure may be created. In this case the Index.tnum variable is
14720 ** used to store the address of a VDBE instruction, not a database page
14721 ** number (it cannot - the database page is not allocated until the VDBE
14722 ** program is executed). See convertToWithoutRowidTable() for details.
14723 */
14724 struct Index {
14725  char *zName; /* Name of this index */
14726  i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
14727  LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
14728  Table *pTable; /* The SQL table being indexed */
14729  char *zColAff; /* String defining the affinity of each column */
14730  Index *pNext; /* The next index associated with the same table */
14731  Schema *pSchema; /* Schema containing this index */
14732  u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
14733  const char **azColl; /* Array of collation sequence names for index */
14734  Expr *pPartIdxWhere; /* WHERE clause for partial indices */
14735  ExprList *aColExpr; /* Column expressions */
14736  int tnum; /* DB Page containing root of this index */
14737  LogEst szIdxRow; /* Estimated average row size in bytes */
14738  u16 nKeyCol; /* Number of columns forming the key */
14739  u16 nColumn; /* Number of columns stored in the index */
14740  u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
14741  unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
14742  unsigned bUnordered:1; /* Use this index for == or IN queries only */
14743  unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
14744  unsigned isResized:1; /* True if resizeIndexObject() has been called */
14745  unsigned isCovering:1; /* True if this is a covering index */
14746  unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
14747 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
14748  int nSample; /* Number of elements in aSample[] */
14749  int nSampleCol; /* Size of IndexSample.anEq[] and so on */
14750  tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
14751  IndexSample *aSample; /* Samples of the left-most key */
14752  tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
14753  tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
14754 #endif
14755 };
14756 
14757 /*
14758 ** Allowed values for Index.idxType
14759 */
14760 #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
14761 #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
14762 #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
14763 
14764 /* Return true if index X is a PRIMARY KEY index */
14765 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
14766 
14767 /* Return true if index X is a UNIQUE index */
14768 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
14769 
14770 /* The Index.aiColumn[] values are normally positive integer. But
14771 ** there are some negative values that have special meaning:
14772 */
14773 #define XN_ROWID (-1) /* Indexed column is the rowid */
14774 #define XN_EXPR (-2) /* Indexed column is an expression */
14775 
14776 /*
14777 ** Each sample stored in the sqlite_stat3 table is represented in memory
14778 ** using a structure of this type. See documentation at the top of the
14779 ** analyze.c source file for additional information.
14780 */
14781 struct IndexSample {
14782  void *p; /* Pointer to sampled record */
14783  int n; /* Size of record in bytes */
14784  tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
14785  tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
14786  tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
14787 };
14788 
14789 /*
14790 ** Each token coming out of the lexer is an instance of
14791 ** this structure. Tokens are also used as part of an expression.
14792 **
14793 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
14794 ** may contain random values. Do not make any assumptions about Token.dyn
14795 ** and Token.n when Token.z==0.
14796 */
14797 struct Token {
14798  const char *z; /* Text of the token. Not NULL-terminated! */
14799  unsigned int n; /* Number of characters in this token */
14800 };
14801 
14802 /*
14803 ** An instance of this structure contains information needed to generate
14804 ** code for a SELECT that contains aggregate functions.
14805 **
14806 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
14807 ** pointer to this structure. The Expr.iColumn field is the index in
14808 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
14809 ** code for that node.
14810 **
14811 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
14812 ** original Select structure that describes the SELECT statement. These
14813 ** fields do not need to be freed when deallocating the AggInfo structure.
14814 */
14815 struct AggInfo {
14816  u8 directMode; /* Direct rendering mode means take data directly
14817  ** from source tables rather than from accumulators */
14818  u8 useSortingIdx; /* In direct mode, reference the sorting index rather
14819  ** than the source table */
14820  int sortingIdx; /* Cursor number of the sorting index */
14821  int sortingIdxPTab; /* Cursor number of pseudo-table */
14822  int nSortingColumn; /* Number of columns in the sorting index */
14823  int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
14824  ExprList *pGroupBy; /* The group by clause */
14825  struct AggInfo_col { /* For each column used in source tables */
14826  Table *pTab; /* Source table */
14827  int iTable; /* Cursor number of the source table */
14828  int iColumn; /* Column number within the source table */
14829  int iSorterColumn; /* Column number in the sorting index */
14830  int iMem; /* Memory location that acts as accumulator */
14831  Expr *pExpr; /* The original expression */
14832  } *aCol;
14833  int nColumn; /* Number of used entries in aCol[] */
14834  int nAccumulator; /* Number of columns that show through to the output.
14835  ** Additional columns are used only as parameters to
14836  ** aggregate functions */
14837  struct AggInfo_func { /* For each aggregate function */
14838  Expr *pExpr; /* Expression encoding the function */
14839  FuncDef *pFunc; /* The aggregate function implementation */
14840  int iMem; /* Memory location that acts as accumulator */
14841  int iDistinct; /* Ephemeral table used to enforce DISTINCT */
14842  } *aFunc;
14843  int nFunc; /* Number of entries in aFunc[] */
14844 };
14845 
14846 /*
14847 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
14848 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
14849 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
14850 ** it uses less memory in the Expr object, which is a big memory user
14851 ** in systems with lots of prepared statements. And few applications
14852 ** need more than about 10 or 20 variables. But some extreme users want
14853 ** to have prepared statements with over 32767 variables, and for them
14854 ** the option is available (at compile-time).
14855 */
14856 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
14857 typedef i16 ynVar;
14858 #else
14859 typedef int ynVar;
14860 #endif
14861 
14862 /*
14863 ** Each node of an expression in the parse tree is an instance
14864 ** of this structure.
14865 **
14866 ** Expr.op is the opcode. The integer parser token codes are reused
14867 ** as opcodes here. For example, the parser defines TK_GE to be an integer
14868 ** code representing the ">=" operator. This same integer code is reused
14869 ** to represent the greater-than-or-equal-to operator in the expression
14870 ** tree.
14871 **
14872 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
14873 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
14874 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
14875 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
14876 ** then Expr.token contains the name of the function.
14877 **
14878 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
14879 ** binary operator. Either or both may be NULL.
14880 **
14881 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
14882 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
14883 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
14884 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
14885 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
14886 ** valid.
14887 **
14888 ** An expression of the form ID or ID.ID refers to a column in a table.
14889 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
14890 ** the integer cursor number of a VDBE cursor pointing to that table and
14891 ** Expr.iColumn is the column number for the specific column. If the
14892 ** expression is used as a result in an aggregate SELECT, then the
14893 ** value is also stored in the Expr.iAgg column in the aggregate so that
14894 ** it can be accessed after all aggregates are computed.
14895 **
14896 ** If the expression is an unbound variable marker (a question mark
14897 ** character '?' in the original SQL) then the Expr.iTable holds the index
14898 ** number for that variable.
14899 **
14900 ** If the expression is a subquery then Expr.iColumn holds an integer
14901 ** register number containing the result of the subquery. If the
14902 ** subquery gives a constant result, then iTable is -1. If the subquery
14903 ** gives a different answer at different times during statement processing
14904 ** then iTable is the address of a subroutine that computes the subquery.
14905 **
14906 ** If the Expr is of type OP_Column, and the table it is selecting from
14907 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
14908 ** corresponding table definition.
14909 **
14910 ** ALLOCATION NOTES:
14911 **
14912 ** Expr objects can use a lot of memory space in database schema. To
14913 ** help reduce memory requirements, sometimes an Expr object will be
14914 ** truncated. And to reduce the number of memory allocations, sometimes
14915 ** two or more Expr objects will be stored in a single memory allocation,
14916 ** together with Expr.zToken strings.
14917 **
14918 ** If the EP_Reduced and EP_TokenOnly flags are set when
14919 ** an Expr object is truncated. When EP_Reduced is set, then all
14920 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
14921 ** are contained within the same memory allocation. Note, however, that
14922 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
14923 ** allocated, regardless of whether or not EP_Reduced is set.
14924 */
14925 struct Expr {
14926  u8 op; /* Operation performed by this node */
14927  char affinity; /* The affinity of the column or 0 if not a column */
14928  u32 flags; /* Various flags. EP_* See below */
14929  union {
14930  char *zToken; /* Token value. Zero terminated and dequoted */
14931  int iValue; /* Non-negative integer value if EP_IntValue */
14932  } u;
14933 
14934  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
14935  ** space is allocated for the fields below this point. An attempt to
14936  ** access them will result in a segfault or malfunction.
14937  *********************************************************************/
14938 
14939  Expr *pLeft; /* Left subnode */
14940  Expr *pRight; /* Right subnode */
14941  union {
14942  ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
14943  Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
14944  } x;
14945 
14946  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
14947  ** space is allocated for the fields below this point. An attempt to
14948  ** access them will result in a segfault or malfunction.
14949  *********************************************************************/
14950 
14951 #if SQLITE_MAX_EXPR_DEPTH>0
14952  int nHeight; /* Height of the tree headed by this node */
14953 #endif
14954  int iTable; /* TK_COLUMN: cursor number of table holding column
14955  ** TK_REGISTER: register number
14956  ** TK_TRIGGER: 1 -> new, 0 -> old
14957  ** EP_Unlikely: 134217728 times likelihood
14958  ** TK_SELECT: 1st register of result vector */
14959  ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
14960  ** TK_VARIABLE: variable number (always >= 1).
14961  ** TK_SELECT_COLUMN: column of the result vector */
14962  i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
14963  i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
14964  u8 op2; /* TK_REGISTER: original value of Expr.op
14965  ** TK_COLUMN: the value of p5 for OP_Column
14966  ** TK_AGG_FUNCTION: nesting depth */
14967  AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
14968  Table *pTab; /* Table for TK_COLUMN expressions. */
14969 };
14970 
14971 /*
14972 ** The following are the meanings of bits in the Expr.flags field.
14973 */
14974 #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
14975 #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
14976 #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
14977 #define EP_Error 0x000008 /* Expression contains one or more errors */
14978 #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
14979 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
14980 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
14981 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
14982 #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
14983 #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
14984 #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
14985 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
14986 #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
14987 #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
14988 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
14989 #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
14990 #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
14991 #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
14992 #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
14993 #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
14994 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
14995 #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
14996 #define EP_Alias 0x400000 /* Is an alias for a result set column */
14997 #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
14998 
14999 /*
15000 ** Combinations of two or more EP_* flags
15001 */
15002 #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
15003 
15004 /*
15005 ** These macros can be used to test, set, or clear bits in the
15006 ** Expr.flags field.
15007 */
15008 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
15009 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
15010 #define ExprSetProperty(E,P) (E)->flags|=(P)
15011 #define ExprClearProperty(E,P) (E)->flags&=~(P)
15012 
15013 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
15014 ** and Accreditation only. It works like ExprSetProperty() during VVA
15015 ** processes but is a no-op for delivery.
15016 */
15017 #ifdef SQLITE_DEBUG
15018 # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
15019 #else
15020 # define ExprSetVVAProperty(E,P)
15021 #endif
15022 
15023 /*
15024 ** Macros to determine the number of bytes required by a normal Expr
15025 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
15026 ** and an Expr struct with the EP_TokenOnly flag set.
15027 */
15028 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
15029 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
15030 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
15031 
15032 /*
15033 ** Flags passed to the sqlite3ExprDup() function. See the header comment
15034 ** above sqlite3ExprDup() for details.
15035 */
15036 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
15037 
15038 /*
15039 ** A list of expressions. Each expression may optionally have a
15040 ** name. An expr/name combination can be used in several ways, such
15041 ** as the list of "expr AS ID" fields following a "SELECT" or in the
15042 ** list of "ID = expr" items in an UPDATE. A list of expressions can
15043 ** also be used as the argument to a function, in which case the a.zName
15044 ** field is not used.
15045 **
15046 ** By default the Expr.zSpan field holds a human-readable description of
15047 ** the expression that is used in the generation of error messages and
15048 ** column labels. In this case, Expr.zSpan is typically the text of a
15049 ** column expression as it exists in a SELECT statement. However, if
15050 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
15051 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
15052 ** form is used for name resolution with nested FROM clauses.
15053 */
15054 struct ExprList {
15055  int nExpr; /* Number of expressions on the list */
15056  struct ExprList_item { /* For each expression in the list */
15057  Expr *pExpr; /* The list of expressions */
15058  char *zName; /* Token associated with this expression */
15059  char *zSpan; /* Original text of the expression */
15060  u8 sortOrder; /* 1 for DESC or 0 for ASC */
15061  unsigned done :1; /* A flag to indicate when processing is finished */
15062  unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
15063  unsigned reusable :1; /* Constant expression is reusable */
15064  union {
15065  struct {
15066  u16 iOrderByCol; /* For ORDER BY, column number in result set */
15067  u16 iAlias; /* Index into Parse.aAlias[] for zName */
15068  } x;
15069  int iConstExprReg; /* Register in which Expr value is cached */
15070  } u;
15071  } *a; /* Alloc a power of two greater or equal to nExpr */
15072 };
15073 
15074 /*
15075 ** An instance of this structure is used by the parser to record both
15076 ** the parse tree for an expression and the span of input text for an
15077 ** expression.
15078 */
15079 struct ExprSpan {
15080  Expr *pExpr; /* The expression parse tree */
15081  const char *zStart; /* First character of input text */
15082  const char *zEnd; /* One character past the end of input text */
15083 };
15084 
15085 /*
15086 ** An instance of this structure can hold a simple list of identifiers,
15087 ** such as the list "a,b,c" in the following statements:
15088 **
15089 ** INSERT INTO t(a,b,c) VALUES ...;
15090 ** CREATE INDEX idx ON t(a,b,c);
15091 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
15092 **
15093 ** The IdList.a.idx field is used when the IdList represents the list of
15094 ** column names after a table name in an INSERT statement. In the statement
15095 **
15096 ** INSERT INTO t(a,b,c) ...
15097 **
15098 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
15099 */
15100 struct IdList {
15101  struct IdList_item {
15102  char *zName; /* Name of the identifier */
15103  int idx; /* Index in some Table.aCol[] of a column named zName */
15104  } *a;
15105  int nId; /* Number of identifiers on the list */
15106 };
15107 
15108 /*
15109 ** The bitmask datatype defined below is used for various optimizations.
15110 **
15111 ** Changing this from a 64-bit to a 32-bit type limits the number of
15112 ** tables in a join to 32 instead of 64. But it also reduces the size
15113 ** of the library by 738 bytes on ix86.
15114 */
15115 #ifdef SQLITE_BITMASK_TYPE
15116  typedef SQLITE_BITMASK_TYPE Bitmask;
15117 #else
15118  typedef u64 Bitmask;
15119 #endif
15120 
15121 /*
15122 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
15123 */
15124 #define BMS ((int)(sizeof(Bitmask)*8))
15125 
15126 /*
15127 ** A bit in a Bitmask
15128 */
15129 #define MASKBIT(n) (((Bitmask)1)<<(n))
15130 #define MASKBIT32(n) (((unsigned int)1)<<(n))
15131 #define ALLBITS ((Bitmask)-1)
15132 
15133 /*
15134 ** The following structure describes the FROM clause of a SELECT statement.
15135 ** Each table or subquery in the FROM clause is a separate element of
15136 ** the SrcList.a[] array.
15137 **
15138 ** With the addition of multiple database support, the following structure
15139 ** can also be used to describe a particular table such as the table that
15140 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
15141 ** such a table must be a simple name: ID. But in SQLite, the table can
15142 ** now be identified by a database name, a dot, then the table name: ID.ID.
15143 **
15144 ** The jointype starts out showing the join type between the current table
15145 ** and the next table on the list. The parser builds the list this way.
15146 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
15147 ** jointype expresses the join between the table and the previous table.
15148 **
15149 ** In the colUsed field, the high-order bit (bit 63) is set if the table
15150 ** contains more than 63 columns and the 64-th or later column is used.
15151 */
15152 struct SrcList {
15153  int nSrc; /* Number of tables or subqueries in the FROM clause */
15154  u32 nAlloc; /* Number of entries allocated in a[] below */
15155  struct SrcList_item {
15156  Schema *pSchema; /* Schema to which this item is fixed */
15157  char *zDatabase; /* Name of database holding this table */
15158  char *zName; /* Name of the table */
15159  char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
15160  Table *pTab; /* An SQL table corresponding to zName */
15161  Select *pSelect; /* A SELECT statement used in place of a table name */
15162  int addrFillSub; /* Address of subroutine to manifest a subquery */
15163  int regReturn; /* Register holding return address of addrFillSub */
15164  int regResult; /* Registers holding results of a co-routine */
15165  struct {
15166  u8 jointype; /* Type of join between this table and the previous */
15167  unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
15168  unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
15169  unsigned isTabFunc :1; /* True if table-valued-function syntax */
15170  unsigned isCorrelated :1; /* True if sub-query is correlated */
15171  unsigned viaCoroutine :1; /* Implemented as a co-routine */
15172  unsigned isRecursive :1; /* True for recursive reference in WITH */
15173  } fg;
15174 #ifndef SQLITE_OMIT_EXPLAIN
15175  u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
15176 #endif
15177  int iCursor; /* The VDBE cursor number used to access this table */
15178  Expr *pOn; /* The ON clause of a join */
15179  IdList *pUsing; /* The USING clause of a join */
15180  Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
15181  union {
15182  char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
15183  ExprList *pFuncArg; /* Arguments to table-valued-function */
15184  } u1;
15185  Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
15186  } a[1]; /* One entry for each identifier on the list */
15187 };
15188 
15189 /*
15190 ** Permitted values of the SrcList.a.jointype field
15191 */
15192 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
15193 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
15194 #define JT_NATURAL 0x0004 /* True for a "natural" join */
15195 #define JT_LEFT 0x0008 /* Left outer join */
15196 #define JT_RIGHT 0x0010 /* Right outer join */
15197 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
15198 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
15199 
15200 
15201 /*
15202 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
15203 ** and the WhereInfo.wctrlFlags member.
15204 **
15205 ** Value constraints (enforced via assert()):
15206 ** WHERE_USE_LIMIT == SF_FixedLimit
15207 */
15208 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
15209 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
15210 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
15211 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
15212 #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
15213 #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
15214 #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
15215  ** the OR optimization */
15216 #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
15217 #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
15218 #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
15219 #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
15220 #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
15221 #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
15222  /* 0x1000 not currently used */
15223  /* 0x2000 not currently used */
15224 #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
15225  /* 0x8000 not currently used */
15226 
15227 /* Allowed return values from sqlite3WhereIsDistinct()
15228 */
15229 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
15230 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
15231 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
15232 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
15233 
15234 /*
15235 ** A NameContext defines a context in which to resolve table and column
15236 ** names. The context consists of a list of tables (the pSrcList) field and
15237 ** a list of named expression (pEList). The named expression list may
15238 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
15239 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
15240 ** pEList corresponds to the result set of a SELECT and is NULL for
15241 ** other statements.
15242 **
15243 ** NameContexts can be nested. When resolving names, the inner-most
15244 ** context is searched first. If no match is found, the next outer
15245 ** context is checked. If there is still no match, the next context
15246 ** is checked. This process continues until either a match is found
15247 ** or all contexts are check. When a match is found, the nRef member of
15248 ** the context containing the match is incremented.
15249 **
15250 ** Each subquery gets a new NameContext. The pNext field points to the
15251 ** NameContext in the parent query. Thus the process of scanning the
15252 ** NameContext list corresponds to searching through successively outer
15253 ** subqueries looking for a match.
15254 */
15255 struct NameContext {
15256  Parse *pParse; /* The parser */
15257  SrcList *pSrcList; /* One or more tables used to resolve names */
15258  ExprList *pEList; /* Optional list of result-set columns */
15259  AggInfo *pAggInfo; /* Information about aggregates at this level */
15260  NameContext *pNext; /* Next outer name context. NULL for outermost */
15261  int nRef; /* Number of names resolved by this context */
15262  int nErr; /* Number of errors encountered while resolving names */
15263  u16 ncFlags; /* Zero or more NC_* flags defined below */
15264 };
15265 
15266 /*
15267 ** Allowed values for the NameContext, ncFlags field.
15268 **
15269 ** Value constraints (all checked via assert()):
15270 ** NC_HasAgg == SF_HasAgg
15271 ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
15272 **
15273 */
15274 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
15275 #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
15276 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
15277 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
15278 #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
15279 #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
15280 #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
15281 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
15282 
15283 /*
15284 ** An instance of the following structure contains all information
15285 ** needed to generate code for a single SELECT statement.
15286 **
15287 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
15288 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
15289 ** limit and nOffset to the value of the offset (or 0 if there is not
15290 ** offset). But later on, nLimit and nOffset become the memory locations
15291 ** in the VDBE that record the limit and offset counters.
15292 **
15293 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
15294 ** These addresses must be stored so that we can go back and fill in
15295 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
15296 ** the number of columns in P2 can be computed at the same time
15297 ** as the OP_OpenEphm instruction is coded because not
15298 ** enough information about the compound query is known at that point.
15299 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
15300 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
15301 ** sequences for the ORDER BY clause.
15302 */
15303 struct Select {
15304  ExprList *pEList; /* The fields of the result */
15305  u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
15306  LogEst nSelectRow; /* Estimated number of result rows */
15307  u32 selFlags; /* Various SF_* values */
15308  int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
15309 #if SELECTTRACE_ENABLED
15310  char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
15311 #endif
15312  int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
15313  SrcList *pSrc; /* The FROM clause */
15314  Expr *pWhere; /* The WHERE clause */
15315  ExprList *pGroupBy; /* The GROUP BY clause */
15316  Expr *pHaving; /* The HAVING clause */
15317  ExprList *pOrderBy; /* The ORDER BY clause */
15318  Select *pPrior; /* Prior select in a compound select statement */
15319  Select *pNext; /* Next select to the left in a compound */
15320  Expr *pLimit; /* LIMIT expression. NULL means not used. */
15321  Expr *pOffset; /* OFFSET expression. NULL means not used. */
15322  With *pWith; /* WITH clause attached to this select. Or NULL. */
15323 };
15324 
15325 /*
15326 ** Allowed values for Select.selFlags. The "SF" prefix stands for
15327 ** "Select Flag".
15328 **
15329 ** Value constraints (all checked via assert())
15330 ** SF_HasAgg == NC_HasAgg
15331 ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
15332 ** SF_FixedLimit == WHERE_USE_LIMIT
15333 */
15334 #define SF_Distinct 0x00001 /* Output should be DISTINCT */
15335 #define SF_All 0x00002 /* Includes the ALL keyword */
15336 #define SF_Resolved 0x00004 /* Identifiers have been resolved */
15337 #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
15338 #define SF_HasAgg 0x00010 /* Contains aggregate functions */
15339 #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
15340 #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
15341 #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
15342 #define SF_Compound 0x00100 /* Part of a compound query */
15343 #define SF_Values 0x00200 /* Synthesized from VALUES clause */
15344 #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
15345 #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
15346 #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
15347 #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
15348 #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
15349 #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
15350 #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
15351 #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
15352 
15353 
15354 /*
15355 ** The results of a SELECT can be distributed in several ways, as defined
15356 ** by one of the following macros. The "SRT" prefix means "SELECT Result
15357 ** Type".
15358 **
15359 ** SRT_Union Store results as a key in a temporary index
15360 ** identified by pDest->iSDParm.
15361 **
15362 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
15363 **
15364 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
15365 ** set is not empty.
15366 **
15367 ** SRT_Discard Throw the results away. This is used by SELECT
15368 ** statements within triggers whose only purpose is
15369 ** the side-effects of functions.
15370 **
15371 ** All of the above are free to ignore their ORDER BY clause. Those that
15372 ** follow must honor the ORDER BY clause.
15373 **
15374 ** SRT_Output Generate a row of output (using the OP_ResultRow
15375 ** opcode) for each row in the result set.
15376 **
15377 ** SRT_Mem Only valid if the result is a single column.
15378 ** Store the first column of the first result row
15379 ** in register pDest->iSDParm then abandon the rest
15380 ** of the query. This destination implies "LIMIT 1".
15381 **
15382 ** SRT_Set The result must be a single column. Store each
15383 ** row of result as the key in table pDest->iSDParm.
15384 ** Apply the affinity pDest->affSdst before storing
15385 ** results. Used to implement "IN (SELECT ...)".
15386 **
15387 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
15388 ** the result there. The cursor is left open after
15389 ** returning. This is like SRT_Table except that
15390 ** this destination uses OP_OpenEphemeral to create
15391 ** the table first.
15392 **
15393 ** SRT_Coroutine Generate a co-routine that returns a new row of
15394 ** results each time it is invoked. The entry point
15395 ** of the co-routine is stored in register pDest->iSDParm
15396 ** and the result row is stored in pDest->nDest registers
15397 ** starting with pDest->iSdst.
15398 **
15399 ** SRT_Table Store results in temporary table pDest->iSDParm.
15400 ** SRT_Fifo This is like SRT_EphemTab except that the table
15401 ** is assumed to already be open. SRT_Fifo has
15402 ** the additional property of being able to ignore
15403 ** the ORDER BY clause.
15404 **
15405 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
15406 ** But also use temporary table pDest->iSDParm+1 as
15407 ** a record of all prior results and ignore any duplicate
15408 ** rows. Name means: "Distinct Fifo".
15409 **
15410 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
15411 ** an index). Append a sequence number so that all entries
15412 ** are distinct.
15413 **
15414 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
15415 ** the same record has never been stored before. The
15416 ** index at pDest->iSDParm+1 hold all prior stores.
15417 */
15418 #define SRT_Union 1 /* Store result as keys in an index */
15419 #define SRT_Except 2 /* Remove result from a UNION index */
15420 #define SRT_Exists 3 /* Store 1 if the result is not empty */
15421 #define SRT_Discard 4 /* Do not save the results anywhere */
15422 #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
15423 #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
15424 #define SRT_Queue 7 /* Store result in an queue */
15425 #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
15426 
15427 /* The ORDER BY clause is ignored for all of the above */
15428 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
15429 
15430 #define SRT_Output 9 /* Output each row of result */
15431 #define SRT_Mem 10 /* Store result in a memory cell */
15432 #define SRT_Set 11 /* Store results as keys in an index */
15433 #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
15434 #define SRT_Coroutine 13 /* Generate a single row of result */
15435 #define SRT_Table 14 /* Store result as data with an automatic rowid */
15436 
15437 /*
15438 ** An instance of this object describes where to put of the results of
15439 ** a SELECT statement.
15440 */
15441 struct SelectDest {
15442  u8 eDest; /* How to dispose of the results. On of SRT_* above. */
15443  char *zAffSdst; /* Affinity used when eDest==SRT_Set */
15444  int iSDParm; /* A parameter used by the eDest disposal method */
15445  int iSdst; /* Base register where results are written */
15446  int nSdst; /* Number of registers allocated */
15447  ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
15448 };
15449 
15450 /*
15451 ** During code generation of statements that do inserts into AUTOINCREMENT
15452 ** tables, the following information is attached to the Table.u.autoInc.p
15453 ** pointer of each autoincrement table to record some side information that
15454 ** the code generator needs. We have to keep per-table autoincrement
15455 ** information in case inserts are done within triggers. Triggers do not
15456 ** normally coordinate their activities, but we do need to coordinate the
15457 ** loading and saving of autoincrement information.
15458 */
15459 struct AutoincInfo {
15460  AutoincInfo *pNext; /* Next info block in a list of them all */
15461  Table *pTab; /* Table this info block refers to */
15462  int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
15463  int regCtr; /* Memory register holding the rowid counter */
15464 };
15465 
15466 /*
15467 ** Size of the column cache
15468 */
15469 #ifndef SQLITE_N_COLCACHE
15470 # define SQLITE_N_COLCACHE 10
15471 #endif
15472 
15473 /*
15474 ** At least one instance of the following structure is created for each
15475 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
15476 ** statement. All such objects are stored in the linked list headed at
15477 ** Parse.pTriggerPrg and deleted once statement compilation has been
15478 ** completed.
15479 **
15480 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
15481 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
15482 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
15483 ** The Parse.pTriggerPrg list never contains two entries with the same
15484 ** values for both pTrigger and orconf.
15485 **
15486 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
15487 ** accessed (or set to 0 for triggers fired as a result of INSERT
15488 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
15489 ** a mask of new.* columns used by the program.
15490 */
15491 struct TriggerPrg {
15492  Trigger *pTrigger; /* Trigger this program was coded from */
15493  TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
15494  SubProgram *pProgram; /* Program implementing pTrigger/orconf */
15495  int orconf; /* Default ON CONFLICT policy */
15496  u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
15497 };
15498 
15499 /*
15500 ** The yDbMask datatype for the bitmask of all attached databases.
15501 */
15502 #if SQLITE_MAX_ATTACHED>30
15503  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
15504 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
15505 # define DbMaskZero(M) memset((M),0,sizeof(M))
15506 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
15507 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
15508 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
15509 #else
15510  typedef unsigned int yDbMask;
15511 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
15512 # define DbMaskZero(M) (M)=0
15513 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
15514 # define DbMaskAllZero(M) (M)==0
15515 # define DbMaskNonZero(M) (M)!=0
15516 #endif
15517 
15518 /*
15519 ** An SQL parser context. A copy of this structure is passed through
15520 ** the parser and down into all the parser action routine in order to
15521 ** carry around information that is global to the entire parse.
15522 **
15523 ** The structure is divided into two parts. When the parser and code
15524 ** generate call themselves recursively, the first part of the structure
15525 ** is constant but the second part is reset at the beginning and end of
15526 ** each recursion.
15527 **
15528 ** The nTableLock and aTableLock variables are only used if the shared-cache
15529 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
15530 ** used to store the set of table-locks required by the statement being
15531 ** compiled. Function sqlite3TableLock() is used to add entries to the
15532 ** list.
15533 */
15534 struct Parse {
15535  sqlite3 *db; /* The main database structure */
15536  char *zErrMsg; /* An error message */
15537  Vdbe *pVdbe; /* An engine for executing database bytecode */
15538  int rc; /* Return code from execution */
15539  u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
15540  u8 checkSchema; /* Causes schema cookie check after an error */
15541  u8 nested; /* Number of nested calls to the parser/code generator */
15542  u8 nTempReg; /* Number of temporary registers in aTempReg[] */
15543  u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
15544  u8 mayAbort; /* True if statement may throw an ABORT exception */
15545  u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
15546  u8 okConstFactor; /* OK to factor out constants */
15547  u8 disableLookaside; /* Number of times lookaside has been disabled */
15548  u8 nColCache; /* Number of entries in aColCache[] */
15549  int nRangeReg; /* Size of the temporary register block */
15550  int iRangeReg; /* First register in temporary register block */
15551  int nErr; /* Number of errors seen */
15552  int nTab; /* Number of previously allocated VDBE cursors */
15553  int nMem; /* Number of memory cells used so far */
15554  int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
15555  int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
15556  int ckBase; /* Base register of data during check constraints */
15557  int iSelfTab; /* Table of an index whose exprs are being coded */
15558  int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
15559  int iCacheCnt; /* Counter used to generate aColCache[].lru values */
15560  int nLabel; /* Number of labels used */
15561  int *aLabel; /* Space to hold the labels */
15562  ExprList *pConstExpr;/* Constant expressions */
15563  Token constraintName;/* Name of the constraint currently being parsed */
15564  yDbMask writeMask; /* Start a write transaction on these databases */
15565  yDbMask cookieMask; /* Bitmask of schema verified databases */
15566  int regRowid; /* Register holding rowid of CREATE TABLE entry */
15567  int regRoot; /* Register holding root page number for new objects */
15568  int nMaxArg; /* Max args passed to user function by sub-program */
15569 #if SELECTTRACE_ENABLED
15570  int nSelect; /* Number of SELECT statements seen */
15571  int nSelectIndent; /* How far to indent SELECTTRACE() output */
15572 #endif
15573 #ifndef SQLITE_OMIT_SHARED_CACHE
15574  int nTableLock; /* Number of locks in aTableLock */
15575  TableLock *aTableLock; /* Required table locks for shared-cache mode */
15576 #endif
15577  AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
15578  Parse *pToplevel; /* Parse structure for main program (or NULL) */
15579  Table *pTriggerTab; /* Table triggers are being coded for */
15580  int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
15581  u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
15582  u32 oldmask; /* Mask of old.* columns referenced */
15583  u32 newmask; /* Mask of new.* columns referenced */
15584  u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
15585  u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
15586  u8 disableTriggers; /* True to disable triggers */
15587 
15588  /**************************************************************************
15589  ** Fields above must be initialized to zero. The fields that follow,
15590  ** down to the beginning of the recursive section, do not need to be
15591  ** initialized as they will be set before being used. The boundary is
15592  ** determined by offsetof(Parse,aColCache).
15593  **************************************************************************/
15594 
15595  struct yColCache {
15596  int iTable; /* Table cursor number */
15597  i16 iColumn; /* Table column number */
15598  u8 tempReg; /* iReg is a temp register that needs to be freed */
15599  int iLevel; /* Nesting level */
15600  int iReg; /* Reg with value of this column. 0 means none. */
15601  int lru; /* Least recently used entry has the smallest value */
15602  } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
15603  int aTempReg[8]; /* Holding area for temporary registers */
15604  Token sNameToken; /* Token with unqualified schema object name */
15605  Token sLastToken; /* The last token parsed */
15606 
15607  /************************************************************************
15608  ** Above is constant between recursions. Below is reset before and after
15609  ** each recursion. The boundary between these two regions is determined
15610  ** using offsetof(Parse,nVar) so the nVar field must be the first field
15611  ** in the recursive region.
15612  ************************************************************************/
15613 
15614  ynVar nVar; /* Number of '?' variables seen in the SQL so far */
15615  int nzVar; /* Number of available slots in azVar[] */
15616  u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
15617  u8 explain; /* True if the EXPLAIN flag is found on the query */
15618 #ifndef SQLITE_OMIT_VIRTUALTABLE
15619  u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
15620  int nVtabLock; /* Number of virtual tables to lock */
15621 #endif
15622  int nHeight; /* Expression tree height of current sub-select */
15623 #ifndef SQLITE_OMIT_EXPLAIN
15624  int iSelectId; /* ID of current select for EXPLAIN output */
15625  int iNextSelectId; /* Next available select ID for EXPLAIN output */
15626 #endif
15627  char **azVar; /* Pointers to names of parameters */
15628  Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
15629  const char *zTail; /* All SQL text past the last semicolon parsed */
15630  Table *pNewTable; /* A table being constructed by CREATE TABLE */
15631  Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
15632  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
15633 #ifndef SQLITE_OMIT_VIRTUALTABLE
15634  Token sArg; /* Complete text of a module argument */
15635  Table **apVtabLock; /* Pointer to virtual tables needing locking */
15636 #endif
15637  Table *pZombieTab; /* List of Table objects to delete after code gen */
15638  TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
15639  With *pWith; /* Current WITH clause, or NULL */
15640  With *pWithToFree; /* Free this WITH object at the end of the parse */
15641 };
15642 
15643 /*
15644 ** Sizes and pointers of various parts of the Parse object.
15645 */
15646 #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
15647 #define PARSE_RECURSE_SZ offsetof(Parse,nVar) /* Recursive part */
15648 #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
15649 #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
15650 
15651 /*
15652 ** Return true if currently inside an sqlite3_declare_vtab() call.
15653 */
15654 #ifdef SQLITE_OMIT_VIRTUALTABLE
15655  #define IN_DECLARE_VTAB 0
15656 #else
15657  #define IN_DECLARE_VTAB (pParse->declareVtab)
15658 #endif
15659 
15660 /*
15661 ** An instance of the following structure can be declared on a stack and used
15662 ** to save the Parse.zAuthContext value so that it can be restored later.
15663 */
15664 struct AuthContext {
15665  const char *zAuthContext; /* Put saved Parse.zAuthContext here */
15666  Parse *pParse; /* The Parse structure */
15667 };
15668 
15669 /*
15670 ** Bitfield flags for P5 value in various opcodes.
15671 **
15672 ** Value constraints (enforced via assert()):
15673 ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
15674 ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
15675 ** OPFLAG_BULKCSR == BTREE_BULKLOAD
15676 ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
15677 ** OPFLAG_FORDELETE == BTREE_FORDELETE
15678 ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
15679 ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
15680 */
15681 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
15682  /* Also used in P2 (not P5) of OP_Delete */
15683 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
15684 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
15685 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
15686 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
15687 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
15688 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15689 #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
15690 #endif
15691 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
15692 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
15693 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
15694 #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
15695 #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
15696 #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
15697 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
15698 #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete: keep cursor position */
15699 #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
15700 
15701 /*
15702  * Each trigger present in the database schema is stored as an instance of
15703  * struct Trigger.
15704  *
15705  * Pointers to instances of struct Trigger are stored in two ways.
15706  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
15707  * database). This allows Trigger structures to be retrieved by name.
15708  * 2. All triggers associated with a single table form a linked list, using the
15709  * pNext member of struct Trigger. A pointer to the first element of the
15710  * linked list is stored as the "pTrigger" member of the associated
15711  * struct Table.
15712  *
15713  * The "step_list" member points to the first element of a linked list
15714  * containing the SQL statements specified as the trigger program.
15715  */
15716 struct Trigger {
15717  char *zName; /* The name of the trigger */
15718  char *table; /* The table or view to which the trigger applies */
15719  u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
15720  u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
15721  Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
15722  IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
15723  the <column-list> is stored here */
15724  Schema *pSchema; /* Schema containing the trigger */
15725  Schema *pTabSchema; /* Schema containing the table */
15726  TriggerStep *step_list; /* Link list of trigger program steps */
15727  Trigger *pNext; /* Next trigger associated with the table */
15728 };
15729 
15730 /*
15731 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
15732 ** determine which.
15733 **
15734 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
15735 ** In that cases, the constants below can be ORed together.
15736 */
15737 #define TRIGGER_BEFORE 1
15738 #define TRIGGER_AFTER 2
15739 
15740 /*
15741  * An instance of struct TriggerStep is used to store a single SQL statement
15742  * that is a part of a trigger-program.
15743  *
15744  * Instances of struct TriggerStep are stored in a singly linked list (linked
15745  * using the "pNext" member) referenced by the "step_list" member of the
15746  * associated struct Trigger instance. The first element of the linked list is
15747  * the first step of the trigger-program.
15748  *
15749  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
15750  * "SELECT" statement. The meanings of the other members is determined by the
15751  * value of "op" as follows:
15752  *
15753  * (op == TK_INSERT)
15754  * orconf -> stores the ON CONFLICT algorithm
15755  * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
15756  * this stores a pointer to the SELECT statement. Otherwise NULL.
15757  * zTarget -> Dequoted name of the table to insert into.
15758  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
15759  * this stores values to be inserted. Otherwise NULL.
15760  * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
15761  * statement, then this stores the column-names to be
15762  * inserted into.
15763  *
15764  * (op == TK_DELETE)
15765  * zTarget -> Dequoted name of the table to delete from.
15766  * pWhere -> The WHERE clause of the DELETE statement if one is specified.
15767  * Otherwise NULL.
15768  *
15769  * (op == TK_UPDATE)
15770  * zTarget -> Dequoted name of the table to update.
15771  * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
15772  * Otherwise NULL.
15773  * pExprList -> A list of the columns to update and the expressions to update
15774  * them to. See sqlite3Update() documentation of "pChanges"
15775  * argument.
15776  *
15777  */
15778 struct TriggerStep {
15779  u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
15780  u8 orconf; /* OE_Rollback etc. */
15781  Trigger *pTrig; /* The trigger that this step is a part of */
15782  Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
15783  char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
15784  Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
15785  ExprList *pExprList; /* SET clause for UPDATE. */
15786  IdList *pIdList; /* Column names for INSERT */
15787  TriggerStep *pNext; /* Next in the link-list */
15788  TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
15789 };
15790 
15791 /*
15792 ** The following structure contains information used by the sqliteFix...
15793 ** routines as they walk the parse tree to make database references
15794 ** explicit.
15795 */
15796 typedef struct DbFixer DbFixer;
15797 struct DbFixer {
15798  Parse *pParse; /* The parsing context. Error messages written here */
15799  Schema *pSchema; /* Fix items to this schema */
15800  int bVarOnly; /* Check for variable references only */
15801  const char *zDb; /* Make sure all objects are contained in this database */
15802  const char *zType; /* Type of the container - used for error messages */
15803  const Token *pName; /* Name of the container - used for error messages */
15804 };
15805 
15806 /*
15807 ** An objected used to accumulate the text of a string where we
15808 ** do not necessarily know how big the string will be in the end.
15809 */
15810 struct StrAccum {
15811  sqlite3 *db; /* Optional database for lookaside. Can be NULL */
15812  char *zBase; /* A base allocation. Not from malloc. */
15813  char *zText; /* The string collected so far */
15814  u32 nChar; /* Length of the string so far */
15815  u32 nAlloc; /* Amount of space allocated in zText */
15816  u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
15817  u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
15818  u8 printfFlags; /* SQLITE_PRINTF flags below */
15819 };
15820 #define STRACCUM_NOMEM 1
15821 #define STRACCUM_TOOBIG 2
15822 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
15823 #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
15824 #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
15825 
15826 #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
15827 
15828 
15829 /*
15830 ** A pointer to this structure is used to communicate information
15831 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
15832 */
15833 typedef struct {
15834  sqlite3 *db; /* The database being initialized */
15835  char **pzErrMsg; /* Error message stored here */
15836  int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
15837  int rc; /* Result code stored here */
15838 } InitData;
15839 
15840 /*
15841 ** Structure containing global configuration data for the SQLite library.
15842 **
15843 ** This structure also contains some state information.
15844 */
15846  int bMemstat; /* True to enable memory status */
15847  int bCoreMutex; /* True to enable core mutexing */
15848  int bFullMutex; /* True to enable full mutexing */
15849  int bOpenUri; /* True to interpret filenames as URIs */
15850  int bUseCis; /* Use covering indices for full-scans */
15851  int mxStrlen; /* Maximum string length */
15852  int neverCorrupt; /* Database is always well-formed */
15853  int szLookaside; /* Default lookaside buffer size */
15854  int nLookaside; /* Default lookaside buffer count */
15855  int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
15856  sqlite3_mem_methods m; /* Low-level memory allocation interface */
15857  sqlite3_mutex_methods mutex; /* Low-level mutex interface */
15858  sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
15859  void *pHeap; /* Heap storage space */
15860  int nHeap; /* Size of pHeap[] */
15861  int mnReq, mxReq; /* Min and max heap requests sizes */
15862  sqlite3_int64 szMmap; /* mmap() space per open file */
15863  sqlite3_int64 mxMmap; /* Maximum value for szMmap */
15864  void *pScratch; /* Scratch memory */
15865  int szScratch; /* Size of each scratch buffer */
15866  int nScratch; /* Number of scratch buffers */
15867  void *pPage; /* Page cache memory */
15868  int szPage; /* Size of each page in pPage[] */
15869  int nPage; /* Number of pages in pPage[] */
15870  int mxParserStack; /* maximum depth of the parser stack */
15871  int sharedCacheEnabled; /* true if shared-cache mode enabled */
15872  u32 szPma; /* Maximum Sorter PMA size */
15873  /* The above might be initialized to non-zero. The following need to always
15874  ** initially be zero, however. */
15875  int isInit; /* True after initialization has finished */
15876  int inProgress; /* True while initialization in progress */
15877  int isMutexInit; /* True after mutexes are initialized */
15878  int isMallocInit; /* True after malloc is initialized */
15879  int isPCacheInit; /* True after malloc is initialized */
15880  int nRefInitMutex; /* Number of users of pInitMutex */
15881  sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
15882  void (*xLog)(void*,int,const char*); /* Function for logging */
15883  void *pLogArg; /* First argument to xLog() */
15884 #ifdef SQLITE_ENABLE_SQLLOG
15885  void(*xSqllog)(void*,sqlite3*,const char*, int);
15886  void *pSqllogArg;
15887 #endif
15888 #ifdef SQLITE_VDBE_COVERAGE
15889  /* The following callback (if not NULL) is invoked on every VDBE branch
15890  ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
15891  */
15892  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
15893  void *pVdbeBranchArg; /* 1st argument */
15894 #endif
15895 #ifndef SQLITE_OMIT_BUILTIN_TEST
15896  int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
15897 #endif
15898  int bLocaltimeFault; /* True to fail localtime() calls */
15899  int iOnceResetThreshold; /* When to reset OP_Once counters */
15900 };
15901 
15902 /*
15903 ** This macro is used inside of assert() statements to indicate that
15904 ** the assert is only valid on a well-formed database. Instead of:
15905 **
15906 ** assert( X );
15907 **
15908 ** One writes:
15909 **
15910 ** assert( X || CORRUPT_DB );
15911 **
15912 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
15913 ** that the database is definitely corrupt, only that it might be corrupt.
15914 ** For most test cases, CORRUPT_DB is set to false using a special
15915 ** sqlite3_test_control(). This enables assert() statements to prove
15916 ** things that are always true for well-formed databases.
15917 */
15918 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
15919 
15920 /*
15921 ** Context pointer passed down through the tree-walk.
15922 */
15923 struct Walker {
15924  Parse *pParse; /* Parser context. */
15925  int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
15926  int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
15927  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
15928  int walkerDepth; /* Number of subqueries */
15929  u8 eCode; /* A small processing code */
15930  union { /* Extra data for callback */
15931  NameContext *pNC; /* Naming context */
15932  int n; /* A counter */
15933  int iCur; /* A cursor number */
15934  SrcList *pSrcList; /* FROM clause */
15935  struct SrcCount *pSrcCount; /* Counting column references */
15936  struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
15937  int *aiCol; /* array of column indexes */
15938  struct IdxCover *pIdxCover; /* Check for index coverage */
15939  } u;
15940 };
15941 
15942 /* Forward declarations */
15943 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
15944 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
15945 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
15946 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
15947 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
15948 SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
15949 
15950 /*
15951 ** Return code from the parse-tree walking primitives and their
15952 ** callbacks.
15953 */
15954 #define WRC_Continue 0 /* Continue down into children */
15955 #define WRC_Prune 1 /* Omit children but continue walking siblings */
15956 #define WRC_Abort 2 /* Abandon the tree walk */
15957 
15958 /*
15959 ** An instance of this structure represents a set of one or more CTEs
15960 ** (common table expressions) created by a single WITH clause.
15961 */
15962 struct With {
15963  int nCte; /* Number of CTEs in the WITH clause */
15964  With *pOuter; /* Containing WITH clause, or NULL */
15965  struct Cte { /* For each CTE in the WITH clause.... */
15966  char *zName; /* Name of this CTE */
15967  ExprList *pCols; /* List of explicit column names, or NULL */
15968  Select *pSelect; /* The definition of this CTE */
15969  const char *zCteErr; /* Error message for circular references */
15970  } a[1];
15971 };
15972 
15973 #ifdef SQLITE_DEBUG
15974 /*
15975 ** An instance of the TreeView object is used for printing the content of
15976 ** data structures on sqlite3DebugPrintf() using a tree-like view.
15977 */
15978 struct TreeView {
15979  int iLevel; /* Which level of the tree we are on */
15980  u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
15981 };
15982 #endif /* SQLITE_DEBUG */
15983 
15984 /*
15985 ** Assuming zIn points to the first byte of a UTF-8 character,
15986 ** advance zIn to point to the first byte of the next UTF-8 character.
15987 */
15988 #define SQLITE_SKIP_UTF8(zIn) { \
15989  if( (*(zIn++))>=0xc0 ){ \
15990  while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
15991  } \
15992 }
15993 
15994 /*
15995 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
15996 ** the same name but without the _BKPT suffix. These macros invoke
15997 ** routines that report the line-number on which the error originated
15998 ** using sqlite3_log(). The routines also provide a convenient place
15999 ** to set a debugger breakpoint.
16000 */
16001 SQLITE_PRIVATE int sqlite3CorruptError(int);
16002 SQLITE_PRIVATE int sqlite3MisuseError(int);
16003 SQLITE_PRIVATE int sqlite3CantopenError(int);
16004 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
16005 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
16006 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
16007 #ifdef SQLITE_DEBUG
16008 SQLITE_PRIVATE int sqlite3NomemError(int);
16009 SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
16010 # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
16011 # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
16012 #else
16013 # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
16014 # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
16015 #endif
16016 
16017 /*
16018 ** FTS3 and FTS4 both require virtual table support
16019 */
16020 #if defined(SQLITE_OMIT_VIRTUALTABLE)
16021 # undef SQLITE_ENABLE_FTS3
16022 # undef SQLITE_ENABLE_FTS4
16023 #endif
16024 
16025 /*
16026 ** FTS4 is really an extension for FTS3. It is enabled using the
16027 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
16028 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
16029 */
16030 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
16031 # define SQLITE_ENABLE_FTS3 1
16032 #endif
16033 
16034 /*
16035 ** The ctype.h header is needed for non-ASCII systems. It is also
16036 ** needed by FTS3 when FTS3 is included in the amalgamation.
16037 */
16038 #if !defined(SQLITE_ASCII) || \
16039  (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
16040 # include <ctype.h>
16041 #endif
16042 
16043 /*
16044 ** The following macros mimic the standard library functions toupper(),
16045 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
16046 ** sqlite versions only work for ASCII characters, regardless of locale.
16047 */
16048 #ifdef SQLITE_ASCII
16049 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
16050 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
16051 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
16052 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
16053 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
16054 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
16055 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
16056 # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
16057 #else
16058 # define sqlite3Toupper(x) toupper((unsigned char)(x))
16059 # define sqlite3Isspace(x) isspace((unsigned char)(x))
16060 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
16061 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
16062 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
16063 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
16064 # define sqlite3Tolower(x) tolower((unsigned char)(x))
16065 # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
16066 #endif
16067 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
16068 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
16069 #endif
16070 
16071 /*
16072 ** Internal function prototypes
16073 */
16074 SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
16075 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
16076 SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
16077 #define sqlite3StrNICmp sqlite3_strnicmp
16078 
16079 SQLITE_PRIVATE int sqlite3MallocInit(void);
16080 SQLITE_PRIVATE void sqlite3MallocEnd(void);
16081 SQLITE_PRIVATE void *sqlite3Malloc(u64);
16082 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
16083 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
16084 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
16085 SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
16086 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
16087 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
16088 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
16089 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
16090 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
16091 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
16092 SQLITE_PRIVATE int sqlite3MallocSize(void*);
16093 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
16094 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
16095 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
16096 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
16097 SQLITE_PRIVATE void sqlite3PageFree(void*);
16098 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
16099 #ifndef SQLITE_OMIT_BUILTIN_TEST
16100 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
16101 #endif
16102 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
16103 
16104 /*
16105 ** On systems with ample stack space and that support alloca(), make
16106 ** use of alloca() to obtain space for large automatic objects. By default,
16107 ** obtain space from malloc().
16108 **
16109 ** The alloca() routine never returns NULL. This will cause code paths
16110 ** that deal with sqlite3StackAlloc() failures to be unreachable.
16111 */
16112 #ifdef SQLITE_USE_ALLOCA
16113 # define sqlite3StackAllocRaw(D,N) alloca(N)
16114 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
16115 # define sqlite3StackFree(D,P)
16116 #else
16117 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
16118 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
16119 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
16120 #endif
16121 
16122 /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
16123 ** are, disable MEMSYS3
16124 */
16125 #ifdef SQLITE_ENABLE_MEMSYS5
16126 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
16127 #undef SQLITE_ENABLE_MEMSYS3
16128 #endif
16129 #ifdef SQLITE_ENABLE_MEMSYS3
16130 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
16131 #endif
16132 
16133 
16134 #ifndef SQLITE_MUTEX_OMIT
16135 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
16136 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
16137 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
16138 SQLITE_PRIVATE int sqlite3MutexInit(void);
16139 SQLITE_PRIVATE int sqlite3MutexEnd(void);
16140 #endif
16141 #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
16142 SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
16143 #else
16144 # define sqlite3MemoryBarrier()
16145 #endif
16146 
16147 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
16148 SQLITE_PRIVATE void sqlite3StatusUp(int, int);
16149 SQLITE_PRIVATE void sqlite3StatusDown(int, int);
16150 SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
16151 
16152 /* Access to mutexes used by sqlite3_status() */
16153 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
16154 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
16155 
16156 #ifndef SQLITE_OMIT_FLOATING_POINT
16157 SQLITE_PRIVATE int sqlite3IsNaN(double);
16158 #else
16159 # define sqlite3IsNaN(X) 0
16160 #endif
16161 
16162 /*
16163 ** An instance of the following structure holds information about SQL
16164 ** functions arguments that are the parameters to the printf() function.
16165 */
16166 struct PrintfArguments {
16167  int nArg; /* Total number of arguments */
16168  int nUsed; /* Number of arguments used so far */
16169  sqlite3_value **apArg; /* The argument values */
16170 };
16171 
16172 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
16173 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
16174 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
16175 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
16176 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
16177 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
16178 #endif
16179 #if defined(SQLITE_TEST)
16180 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
16181 #endif
16182 
16183 #if defined(SQLITE_DEBUG)
16184 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
16185 SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
16186 SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
16187 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
16188 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
16189 #endif
16190 
16191 
16192 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
16193 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
16194 SQLITE_PRIVATE void sqlite3Dequote(char*);
16195 SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
16196 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
16197 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
16198 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
16199 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
16200 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
16201 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
16202 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
16203 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
16204 #ifdef SQLITE_DEBUG
16205 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
16206 #endif
16207 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
16208 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
16209 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
16210 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
16211 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
16212 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
16213 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
16214 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
16215 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
16216 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
16217 SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
16218 SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
16219 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
16220 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
16221 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
16222 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
16223 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
16224 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
16225 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
16226 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
16227 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
16228 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
16229 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
16230 SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
16231 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
16232 SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
16233 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
16234 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
16235 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
16236 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
16237 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
16238 #if SQLITE_ENABLE_HIDDEN_COLUMNS
16239 SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
16240 #else
16241 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
16242 #endif
16243 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
16244 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
16245 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
16246 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
16247 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
16248 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
16249 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
16250 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
16251  sqlite3_vfs**,char**,char **);
16252 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
16253 
16254 #ifdef SQLITE_OMIT_BUILTIN_TEST
16255 # define sqlite3FaultSim(X) SQLITE_OK
16256 #else
16257 SQLITE_PRIVATE int sqlite3FaultSim(int);
16258 #endif
16259 
16260 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
16261 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
16262 SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
16263 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
16264 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
16265 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
16266 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
16267 #ifndef SQLITE_OMIT_BUILTIN_TEST
16268 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
16269 #endif
16270 
16271 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
16272 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
16273 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
16274 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
16275 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
16276 
16277 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
16278 
16279 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
16280 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
16281 #else
16282 # define sqlite3ViewGetColumnNames(A,B) 0
16283 #endif
16284 
16285 #if SQLITE_MAX_ATTACHED>30
16286 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
16287 #endif
16288 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
16289 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
16290 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
16291 #ifndef SQLITE_OMIT_AUTOINCREMENT
16292 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
16293 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
16294 #else
16295 # define sqlite3AutoincrementBegin(X)
16296 # define sqlite3AutoincrementEnd(X)
16297 #endif
16298 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
16299 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
16300 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
16301 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
16302 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
16303 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
16304 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
16305  Token*, Select*, Expr*, IdList*);
16306 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
16307 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
16308 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
16309 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
16310 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
16311 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
16312 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
16313 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
16314 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
16315  Expr*, int, int, u8);
16316 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
16317 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
16318 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
16319  Expr*,ExprList*,u32,Expr*,Expr*);
16320 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
16321 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
16322 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
16323 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
16324 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
16325 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
16326 #endif
16327 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
16328 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
16329 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
16330 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
16331 SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
16332 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
16333 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
16334 SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
16335 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
16336 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
16337 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
16338 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
16339 #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
16340 #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
16341 #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
16342 SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
16343 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
16344 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
16345 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
16346 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
16347 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
16348 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
16349 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
16350 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
16351 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
16352 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
16353 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
16354 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
16355 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
16356 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
16357 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
16358 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
16359 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
16360 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
16361 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
16362 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
16363 #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
16364 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
16365 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
16366 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
16367 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
16368 #define LOCATE_VIEW 0x01
16369 #define LOCATE_NOERR 0x02
16370 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
16371 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
16372 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
16373 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
16374 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
16375 SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
16376 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
16377 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
16378 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
16379 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
16380 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
16381 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
16382 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
16383 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
16384 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
16385 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
16386 #ifndef SQLITE_OMIT_BUILTIN_TEST
16387 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
16388 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
16389 #endif
16390 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
16391 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
16392 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
16393 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
16394 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
16395 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
16396 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
16397 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
16398 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
16399 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
16400 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
16401 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
16402 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
16403 #ifdef SQLITE_ENABLE_CURSOR_HINTS
16404 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
16405 #endif
16406 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
16407 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
16408 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
16409 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
16410 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
16411  Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
16412 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
16413 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
16414 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
16415 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
16416  u8,u8,int,int*,int*);
16417 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
16418 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
16419 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
16420 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
16421 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
16422 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
16423 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
16424 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
16425 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
16426 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
16427 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
16428 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
16429 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
16430 #if SELECTTRACE_ENABLED
16431 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
16432 #else
16433 # define sqlite3SelectSetName(A,B)
16434 #endif
16435 SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
16436 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
16437 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
16438 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
16439 SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
16440 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
16441 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
16442 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
16443 
16444 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
16445 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
16446 #endif
16447 
16448 #ifndef SQLITE_OMIT_TRIGGER
16449 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
16450  Expr*,int, int);
16451 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
16452 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
16453 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
16454 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
16455 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
16456 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
16457  int, int, int);
16458 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
16459  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
16460 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
16461 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
16462 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
16463  Select*,u8);
16464 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
16465 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
16466 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
16467 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
16468 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
16469 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
16470 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
16471 #else
16472 # define sqlite3TriggersExist(B,C,D,E,F) 0
16473 # define sqlite3DeleteTrigger(A,B)
16474 # define sqlite3DropTriggerPtr(A,B)
16475 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
16476 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
16477 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
16478 # define sqlite3TriggerList(X, Y) 0
16479 # define sqlite3ParseToplevel(p) p
16480 # define sqlite3IsToplevel(p) 1
16481 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
16482 #endif
16483 
16484 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
16485 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
16486 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
16487 #ifndef SQLITE_OMIT_AUTHORIZATION
16488 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
16489 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
16490 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
16491 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
16492 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
16493 #else
16494 # define sqlite3AuthRead(a,b,c,d)
16495 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
16496 # define sqlite3AuthContextPush(a,b,c)
16497 # define sqlite3AuthContextPop(a) ((void)(a))
16498 #endif
16499 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
16500 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
16501 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
16502 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
16503 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
16504 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
16505 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
16506 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
16507 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
16508 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
16509 SQLITE_PRIVATE int sqlite3Atoi(const char*);
16510 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
16511 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
16512 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
16513 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
16514 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
16515 #ifndef SQLITE_OMIT_VIRTUALTABLE
16516 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
16517 #endif
16518 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
16519  defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
16520  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
16521 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
16522 #endif
16523 
16524 /*
16525 ** Routines to read and write variable-length integers. These used to
16526 ** be defined locally, but now we use the varint routines in the util.c
16527 ** file.
16528 */
16529 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
16530 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
16531 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
16532 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
16533 
16534 /*
16535 ** The common case is for a varint to be a single byte. They following
16536 ** macros handle the common case without a procedure call, but then call
16537 ** the procedure for larger varints.
16538 */
16539 #define getVarint32(A,B) \
16540  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
16541 #define putVarint32(A,B) \
16542  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
16543  sqlite3PutVarint((A),(B)))
16544 #define getVarint sqlite3GetVarint
16545 #define putVarint sqlite3PutVarint
16546 
16547 
16548 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
16549 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
16550 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
16551 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
16552 SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
16553 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
16554 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
16555 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
16556 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
16557 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
16558 SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
16559 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
16560 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
16561 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
16562 
16563 #if defined(SQLITE_NEED_ERR_NAME)
16564 SQLITE_PRIVATE const char *sqlite3ErrName(int);
16565 #endif
16566 
16567 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
16568 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
16569 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
16570 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
16571 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
16572 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
16573 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
16574 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
16575 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
16576 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
16577 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
16578 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
16579 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
16580 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
16581 SQLITE_PRIVATE int sqlite3AbsInt32(int);
16582 #ifdef SQLITE_ENABLE_8_3_NAMES
16583 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
16584 #else
16585 # define sqlite3FileSuffix3(X,Y)
16586 #endif
16587 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
16588 
16589 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
16590 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
16591 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
16592  void(*)(void*));
16593 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
16594 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
16595 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
16596 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
16597 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
16598 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
16599 #ifndef SQLITE_AMALGAMATION
16600 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
16601 SQLITE_PRIVATE const char sqlite3StrBINARY[];
16602 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
16603 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
16604 SQLITE_PRIVATE const Token sqlite3IntTokens[];
16605 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
16606 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
16607 #ifndef SQLITE_OMIT_WSD
16608 SQLITE_PRIVATE int sqlite3PendingByte;
16609 #endif
16610 #endif
16611 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
16612 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
16613 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
16614 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
16615 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
16616 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
16617 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
16618 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
16619 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
16620 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
16621 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
16622 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
16623 SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
16624 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
16625 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
16626 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
16627 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
16628 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
16629 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
16630 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
16631 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
16632 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
16633 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
16634 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
16635 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
16636 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
16637 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
16638 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
16639 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
16640 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
16641 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
16642 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
16643 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
16644 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
16645 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
16646 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
16647 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
16648 #ifdef SQLITE_DEBUG
16649 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
16650 #endif
16651 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
16652  void (*)(sqlite3_context*,int,sqlite3_value **),
16653  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
16654  FuncDestructor *pDestructor
16655 );
16656 SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
16657 SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
16658 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
16659 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
16660 
16661 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
16662 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
16663 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
16664 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
16665 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
16666 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
16667 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
16668 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
16669 
16670 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
16671 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
16672 
16673 #ifndef SQLITE_OMIT_SUBQUERY
16674 SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
16675 #else
16676 # define sqlite3ExprCheckIN(x,y) SQLITE_OK
16677 #endif
16678 
16679 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
16680 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
16681 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
16682  Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
16683 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
16684 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
16685 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
16686 SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
16687 #endif
16688 
16689 /*
16690 ** The interface to the LEMON-generated parser
16691 */
16692 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
16693 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
16694 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
16695 #ifdef YYTRACKMAXSTACKDEPTH
16696 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
16697 #endif
16698 
16699 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
16700 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16701 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
16702 #else
16703 # define sqlite3CloseExtensions(X)
16704 #endif
16705 
16706 #ifndef SQLITE_OMIT_SHARED_CACHE
16707 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
16708 #else
16709  #define sqlite3TableLock(v,w,x,y,z)
16710 #endif
16711 
16712 #ifdef SQLITE_TEST
16713 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
16714 #endif
16715 
16716 #ifdef SQLITE_OMIT_VIRTUALTABLE
16717 # define sqlite3VtabClear(Y)
16718 # define sqlite3VtabSync(X,Y) SQLITE_OK
16719 # define sqlite3VtabRollback(X)
16720 # define sqlite3VtabCommit(X)
16721 # define sqlite3VtabInSync(db) 0
16722 # define sqlite3VtabLock(X)
16723 # define sqlite3VtabUnlock(X)
16724 # define sqlite3VtabUnlockList(X)
16725 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
16726 # define sqlite3GetVTable(X,Y) ((VTable*)0)
16727 #else
16728 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
16729 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
16730 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
16731 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
16732 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
16733 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
16734 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
16735 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
16736 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
16737 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
16738 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
16739 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
16740 #endif
16741 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
16742 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
16743 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
16744 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
16745 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
16746 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
16747 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
16748 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
16749 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
16750 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
16751 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
16752 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
16753 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
16754 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
16755 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
16756 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
16757 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
16758 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
16759 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
16760 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
16761 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
16762 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
16763 #ifndef SQLITE_OMIT_WAL
16764 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
16765 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
16766 #endif
16767 #ifndef SQLITE_OMIT_CTE
16768 SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
16769 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
16770 SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
16771 #else
16772 #define sqlite3WithPush(x,y,z)
16773 #define sqlite3WithDelete(x,y)
16774 #endif
16775 
16776 /* Declarations for functions in fkey.c. All of these are replaced by
16777 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
16778 ** key functionality is available. If OMIT_TRIGGER is defined but
16779 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
16780 ** this case foreign keys are parsed, but no other functionality is
16781 ** provided (enforcement of FK constraints requires the triggers sub-system).
16782 */
16783 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
16784 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
16785 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
16786 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
16787 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
16788 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
16789 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
16790 #else
16791  #define sqlite3FkActions(a,b,c,d,e,f)
16792  #define sqlite3FkCheck(a,b,c,d,e,f)
16793  #define sqlite3FkDropTable(a,b,c)
16794  #define sqlite3FkOldmask(a,b) 0
16795  #define sqlite3FkRequired(a,b,c,d) 0
16796 #endif
16797 #ifndef SQLITE_OMIT_FOREIGN_KEY
16798 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
16799 SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
16800 #else
16801  #define sqlite3FkDelete(a,b)
16802  #define sqlite3FkLocateIndex(a,b,c,d,e)
16803 #endif
16804 
16805 
16806 /*
16807 ** Available fault injectors. Should be numbered beginning with 0.
16808 */
16809 #define SQLITE_FAULTINJECTOR_MALLOC 0
16810 #define SQLITE_FAULTINJECTOR_COUNT 1
16811 
16812 /*
16813 ** The interface to the code in fault.c used for identifying "benign"
16814 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
16815 ** is not defined.
16816 */
16817 #ifndef SQLITE_OMIT_BUILTIN_TEST
16818 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
16819 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
16820 #else
16821  #define sqlite3BeginBenignMalloc()
16822  #define sqlite3EndBenignMalloc()
16823 #endif
16824 
16825 /*
16826 ** Allowed return values from sqlite3FindInIndex()
16827 */
16828 #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
16829 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
16830 #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
16831 #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
16832 #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
16833 /*
16834 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
16835 */
16836 #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
16837 #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
16838 #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
16839 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
16840 
16841 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
16842 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
16843 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
16844 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
16845 #endif
16846 
16847 SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
16848 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
16849 
16850 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
16851 #if SQLITE_MAX_EXPR_DEPTH>0
16852 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
16853 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
16854 #else
16855  #define sqlite3SelectExprHeight(x) 0
16856  #define sqlite3ExprCheckHeight(x,y)
16857 #endif
16858 
16859 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
16860 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
16861 
16862 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
16863 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
16864 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
16865 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
16866 #else
16867  #define sqlite3ConnectionBlocked(x,y)
16868  #define sqlite3ConnectionUnlocked(x)
16869  #define sqlite3ConnectionClosed(x)
16870 #endif
16871 
16872 #ifdef SQLITE_DEBUG
16873 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
16874 #endif
16875 
16876 /*
16877 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
16878 ** sqlite3IoTrace is a pointer to a printf-like routine used to
16879 ** print I/O tracing messages.
16880 */
16881 #ifdef SQLITE_ENABLE_IOTRACE
16882 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
16883 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
16884 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
16885 #else
16886 # define IOTRACE(A)
16887 # define sqlite3VdbeIOTraceSql(X)
16888 #endif
16889 
16890 /*
16891 ** These routines are available for the mem2.c debugging memory allocator
16892 ** only. They are used to verify that different "types" of memory
16893 ** allocations are properly tracked by the system.
16894 **
16895 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
16896 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
16897 ** a single bit set.
16898 **
16899 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
16900 ** argument match the type set by the previous sqlite3MemdebugSetType().
16901 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
16902 **
16903 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
16904 ** argument match the type set by the previous sqlite3MemdebugSetType().
16905 **
16906 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
16907 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
16908 ** it might have been allocated by lookaside, except the allocation was
16909 ** too large or lookaside was already full. It is important to verify
16910 ** that allocations that might have been satisfied by lookaside are not
16911 ** passed back to non-lookaside free() routines. Asserts such as the
16912 ** example above are placed on the non-lookaside free() routines to verify
16913 ** this constraint.
16914 **
16915 ** All of this is no-op for a production build. It only comes into
16916 ** play when the SQLITE_MEMDEBUG compile-time option is used.
16917 */
16918 #ifdef SQLITE_MEMDEBUG
16919 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
16920 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
16921 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
16922 #else
16923 # define sqlite3MemdebugSetType(X,Y) /* no-op */
16924 # define sqlite3MemdebugHasType(X,Y) 1
16925 # define sqlite3MemdebugNoType(X,Y) 1
16926 #endif
16927 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
16928 #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
16929 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
16930 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
16931 
16932 /*
16933 ** Threading interface
16934 */
16935 #if SQLITE_MAX_WORKER_THREADS>0
16936 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
16937 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
16938 #endif
16939 
16940 #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
16941 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
16942 #endif
16943 
16944 SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
16945 SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
16946 SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
16947 SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
16948 
16949 #endif /* SQLITEINT_H */
16950 
16951 /************** End of sqliteInt.h *******************************************/
16952 /************** Begin file global.c ******************************************/
16953 /*
16954 ** 2008 June 13
16955 **
16956 ** The author disclaims copyright to this source code. In place of
16957 ** a legal notice, here is a blessing:
16958 **
16959 ** May you do good and not evil.
16960 ** May you find forgiveness for yourself and forgive others.
16961 ** May you share freely, never taking more than you give.
16962 **
16963 *************************************************************************
16964 **
16965 ** This file contains definitions of global variables and constants.
16966 */
16967 /* #include "sqliteInt.h" */
16968 
16969 /* An array to map all upper-case characters into their corresponding
16970 ** lower-case character.
16971 **
16972 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
16973 ** handle case conversions for the UTF character set since the tables
16974 ** involved are nearly as big or bigger than SQLite itself.
16975 */
16976 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
16977 #ifdef SQLITE_ASCII
16978  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
16979  18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
16980  36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
16981  54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
16982  104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
16983  122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
16984  108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
16985  126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
16986  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
16987  162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
16988  180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
16989  198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
16990  216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
16991  234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
16992  252,253,254,255
16993 #endif
16994 #ifdef SQLITE_EBCDIC
16995  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
16996  16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
16997  32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
16998  48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
16999  64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
17000  80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
17001  96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
17002  112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
17003  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
17004  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
17005  160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
17006  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
17007  192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
17008  208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
17009  224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
17010  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
17011 #endif
17012 };
17013 
17014 /*
17015 ** The following 256 byte lookup table is used to support SQLites built-in
17016 ** equivalents to the following standard library functions:
17017 **
17018 ** isspace() 0x01
17019 ** isalpha() 0x02
17020 ** isdigit() 0x04
17021 ** isalnum() 0x06
17022 ** isxdigit() 0x08
17023 ** toupper() 0x20
17024 ** SQLite identifier character 0x40
17025 ** Quote character 0x80
17026 **
17027 ** Bit 0x20 is set if the mapped character requires translation to upper
17028 ** case. i.e. if the character is a lower-case ASCII character.
17029 ** If x is a lower-case ASCII character, then its upper-case equivalent
17030 ** is (x - 0x20). Therefore toupper() can be implemented as:
17031 **
17032 ** (x & ~(map[x]&0x20))
17033 **
17034 ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
17035 ** array. tolower() is used more often than toupper() by SQLite.
17036 **
17037 ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
17038 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
17039 ** non-ASCII UTF character. Hence the test for whether or not a character is
17040 ** part of an identifier is 0x46.
17041 */
17042 #ifdef SQLITE_ASCII
17043 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
17044  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
17045  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
17046  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
17047  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
17048  0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
17049  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
17050  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
17051  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
17052 
17053  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
17054  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
17055  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
17056  0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
17057  0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
17058  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
17059  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
17060  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
17061 
17062  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
17063  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
17064  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
17065  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
17066  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
17067  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
17068  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
17069  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
17070 
17071  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
17072  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
17073  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
17074  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
17075  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
17076  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
17077  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
17078  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
17079 };
17080 #endif
17081 
17082 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
17083 ** compatibility for legacy applications, the URI filename capability is
17084 ** disabled by default.
17085 **
17086 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
17087 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
17088 **
17089 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
17090 ** disabled. The default value may be changed by compiling with the
17091 ** SQLITE_USE_URI symbol defined.
17092 */
17093 #ifndef SQLITE_USE_URI
17094 # define SQLITE_USE_URI 0
17095 #endif
17096 
17097 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
17098 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
17099 ** that compile-time option is omitted.
17100 */
17101 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
17102 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
17103 #endif
17104 
17105 /* The minimum PMA size is set to this value multiplied by the database
17106 ** page size in bytes.
17107 */
17108 #ifndef SQLITE_SORTER_PMASZ
17109 # define SQLITE_SORTER_PMASZ 250
17110 #endif
17111 
17112 /* Statement journals spill to disk when their size exceeds the following
17113 ** threshold (in bytes). 0 means that statement journals are created and
17114 ** written to disk immediately (the default behavior for SQLite versions
17115 ** before 3.12.0). -1 means always keep the entire statement journal in
17116 ** memory. (The statement journal is also always held entirely in memory
17117 ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
17118 ** setting.)
17119 */
17120 #ifndef SQLITE_STMTJRNL_SPILL
17121 # define SQLITE_STMTJRNL_SPILL (64*1024)
17122 #endif
17123 
17124 /*
17125 ** The following singleton contains the global configuration for
17126 ** the SQLite library.
17127 */
17128 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
17129  SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
17130  1, /* bCoreMutex */
17131  SQLITE_THREADSAFE==1, /* bFullMutex */
17132  SQLITE_USE_URI, /* bOpenUri */
17133  SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
17134  0x7ffffffe, /* mxStrlen */
17135  0, /* neverCorrupt */
17136  128, /* szLookaside */
17137  500, /* nLookaside */
17138  SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
17139  {0,0,0,0,0,0,0,0}, /* m */
17140  {0,0,0,0,0,0,0,0,0}, /* mutex */
17141  {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
17142  (void*)0, /* pHeap */
17143  0, /* nHeap */
17144  0, 0, /* mnHeap, mxHeap */
17145  SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
17146  SQLITE_MAX_MMAP_SIZE, /* mxMmap */
17147  (void*)0, /* pScratch */
17148  0, /* szScratch */
17149  0, /* nScratch */
17150  (void*)0, /* pPage */
17151  0, /* szPage */
17152  SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
17153  0, /* mxParserStack */
17154  0, /* sharedCacheEnabled */
17155  SQLITE_SORTER_PMASZ, /* szPma */
17156  /* All the rest should always be initialized to zero */
17157  0, /* isInit */
17158  0, /* inProgress */
17159  0, /* isMutexInit */
17160  0, /* isMallocInit */
17161  0, /* isPCacheInit */
17162  0, /* nRefInitMutex */
17163  0, /* pInitMutex */
17164  0, /* xLog */
17165  0, /* pLogArg */
17166 #ifdef SQLITE_ENABLE_SQLLOG
17167  0, /* xSqllog */
17168  0, /* pSqllogArg */
17169 #endif
17170 #ifdef SQLITE_VDBE_COVERAGE
17171  0, /* xVdbeBranch */
17172  0, /* pVbeBranchArg */
17173 #endif
17174 #ifndef SQLITE_OMIT_BUILTIN_TEST
17175  0, /* xTestCallback */
17176 #endif
17177  0, /* bLocaltimeFault */
17178  0x7ffffffe /* iOnceResetThreshold */
17179 };
17180 
17181 /*
17182 ** Hash table for global functions - functions common to all
17183 ** database connections. After initialization, this table is
17184 ** read-only.
17185 */
17186 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
17187 
17188 /*
17189 ** Constant tokens for values 0 and 1.
17190 */
17191 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
17192  { "0", 1 },
17193  { "1", 1 }
17194 };
17195 
17196 
17197 /*
17198 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
17199 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
17200 ** the database page that contains the pending byte. It never attempts
17201 ** to read or write that page. The pending byte page is set aside
17202 ** for use by the VFS layers as space for managing file locks.
17203 **
17204 ** During testing, it is often desirable to move the pending byte to
17205 ** a different position in the file. This allows code that has to
17206 ** deal with the pending byte to run on files that are much smaller
17207 ** than 1 GiB. The sqlite3_test_control() interface can be used to
17208 ** move the pending byte.
17209 **
17210 ** IMPORTANT: Changing the pending byte to any value other than
17211 ** 0x40000000 results in an incompatible database file format!
17212 ** Changing the pending byte during operation will result in undefined
17213 ** and incorrect behavior.
17214 */
17215 #ifndef SQLITE_OMIT_WSD
17216 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
17217 #endif
17218 
17219 /* #include "opcodes.h" */
17220 /*
17221 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
17222 ** created by mkopcodeh.awk during compilation. Data is obtained
17223 ** from the comments following the "case OP_xxxx:" statements in
17224 ** the vdbe.c file.
17225 */
17226 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
17227 
17228 /*
17229 ** Name of the default collating sequence
17230 */
17231 SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
17232 
17233 /************** End of global.c **********************************************/
17234 /************** Begin file ctime.c *******************************************/
17235 /*
17236 ** 2010 February 23
17237 **
17238 ** The author disclaims copyright to this source code. In place of
17239 ** a legal notice, here is a blessing:
17240 **
17241 ** May you do good and not evil.
17242 ** May you find forgiveness for yourself and forgive others.
17243 ** May you share freely, never taking more than you give.
17244 **
17245 *************************************************************************
17246 **
17247 ** This file implements routines used to report what compile-time options
17248 ** SQLite was built with.
17249 */
17250 
17251 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
17252 
17253 /* #include "sqliteInt.h" */
17254 
17255 /*
17256 ** An array of names of all compile-time options. This array should
17257 ** be sorted A-Z.
17258 **
17259 ** This array looks large, but in a typical installation actually uses
17260 ** only a handful of compile-time options, so most times this array is usually
17261 ** rather short and uses little memory space.
17262 */
17263 static const char * const azCompileOpt[] = {
17264 
17265 /* These macros are provided to "stringify" the value of the define
17266 ** for those options in which the value is meaningful. */
17267 #define CTIMEOPT_VAL_(opt) #opt
17268 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
17269 
17270 #if SQLITE_32BIT_ROWID
17271  "32BIT_ROWID",
17272 #endif
17273 #if SQLITE_4_BYTE_ALIGNED_MALLOC
17274  "4_BYTE_ALIGNED_MALLOC",
17275 #endif
17276 #if SQLITE_CASE_SENSITIVE_LIKE
17277  "CASE_SENSITIVE_LIKE",
17278 #endif
17279 #if SQLITE_CHECK_PAGES
17280  "CHECK_PAGES",
17281 #endif
17282 #if defined(__clang__) && defined(__clang_major__)
17283  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
17284  CTIMEOPT_VAL(__clang_minor__) "."
17285  CTIMEOPT_VAL(__clang_patchlevel__),
17286 #elif defined(_MSC_VER)
17287  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
17288 #elif defined(__GNUC__) && defined(__VERSION__)
17289  "COMPILER=gcc-" __VERSION__,
17290 #endif
17291 #if SQLITE_COVERAGE_TEST
17292  "COVERAGE_TEST",
17293 #endif
17294 #if SQLITE_DEBUG
17295  "DEBUG",
17296 #endif
17297 #if SQLITE_DEFAULT_LOCKING_MODE
17298  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
17299 #endif
17300 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
17301  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
17302 #endif
17303 #if SQLITE_DISABLE_DIRSYNC
17304  "DISABLE_DIRSYNC",
17305 #endif
17306 #if SQLITE_DISABLE_LFS
17307  "DISABLE_LFS",
17308 #endif
17309 #if SQLITE_ENABLE_8_3_NAMES
17310  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
17311 #endif
17312 #if SQLITE_ENABLE_API_ARMOR
17313  "ENABLE_API_ARMOR",
17314 #endif
17315 #if SQLITE_ENABLE_ATOMIC_WRITE
17316  "ENABLE_ATOMIC_WRITE",
17317 #endif
17318 #if SQLITE_ENABLE_CEROD
17319  "ENABLE_CEROD",
17320 #endif
17321 #if SQLITE_ENABLE_COLUMN_METADATA
17322  "ENABLE_COLUMN_METADATA",
17323 #endif
17324 #if SQLITE_ENABLE_DBSTAT_VTAB
17325  "ENABLE_DBSTAT_VTAB",
17326 #endif
17327 #if SQLITE_ENABLE_EXPENSIVE_ASSERT
17328  "ENABLE_EXPENSIVE_ASSERT",
17329 #endif
17330 #if SQLITE_ENABLE_FTS1
17331  "ENABLE_FTS1",
17332 #endif
17333 #if SQLITE_ENABLE_FTS2
17334  "ENABLE_FTS2",
17335 #endif
17336 #if SQLITE_ENABLE_FTS3
17337  "ENABLE_FTS3",
17338 #endif
17339 #if SQLITE_ENABLE_FTS3_PARENTHESIS
17340  "ENABLE_FTS3_PARENTHESIS",
17341 #endif
17342 #if SQLITE_ENABLE_FTS4
17343  "ENABLE_FTS4",
17344 #endif
17345 #if SQLITE_ENABLE_FTS5
17346  "ENABLE_FTS5",
17347 #endif
17348 #if SQLITE_ENABLE_ICU
17349  "ENABLE_ICU",
17350 #endif
17351 #if SQLITE_ENABLE_IOTRACE
17352  "ENABLE_IOTRACE",
17353 #endif
17354 #if SQLITE_ENABLE_JSON1
17355  "ENABLE_JSON1",
17356 #endif
17357 #if SQLITE_ENABLE_LOAD_EXTENSION
17358  "ENABLE_LOAD_EXTENSION",
17359 #endif
17360 #if SQLITE_ENABLE_LOCKING_STYLE
17361  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
17362 #endif
17363 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
17364  "ENABLE_MEMORY_MANAGEMENT",
17365 #endif
17366 #if SQLITE_ENABLE_MEMSYS3
17367  "ENABLE_MEMSYS3",
17368 #endif
17369 #if SQLITE_ENABLE_MEMSYS5
17370  "ENABLE_MEMSYS5",
17371 #endif
17372 #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
17373  "ENABLE_OVERSIZE_CELL_CHECK",
17374 #endif
17375 #if SQLITE_ENABLE_RTREE
17376  "ENABLE_RTREE",
17377 #endif
17378 #if defined(SQLITE_ENABLE_STAT4)
17379  "ENABLE_STAT4",
17380 #elif defined(SQLITE_ENABLE_STAT3)
17381  "ENABLE_STAT3",
17382 #endif
17383 #if SQLITE_ENABLE_UNLOCK_NOTIFY
17384  "ENABLE_UNLOCK_NOTIFY",
17385 #endif
17386 #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
17387  "ENABLE_UPDATE_DELETE_LIMIT",
17388 #endif
17389 #if SQLITE_HAS_CODEC
17390  "HAS_CODEC",
17391 #endif
17392 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
17393  "HAVE_ISNAN",
17394 #endif
17395 #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17396  "HOMEGROWN_RECURSIVE_MUTEX",
17397 #endif
17398 #if SQLITE_IGNORE_AFP_LOCK_ERRORS
17399  "IGNORE_AFP_LOCK_ERRORS",
17400 #endif
17401 #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
17402  "IGNORE_FLOCK_LOCK_ERRORS",
17403 #endif
17404 #ifdef SQLITE_INT64_TYPE
17405  "INT64_TYPE",
17406 #endif
17407 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
17408  "LIKE_DOESNT_MATCH_BLOBS",
17409 #endif
17410 #if SQLITE_LOCK_TRACE
17411  "LOCK_TRACE",
17412 #endif
17413 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
17414  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
17415 #endif
17416 #ifdef SQLITE_MAX_SCHEMA_RETRY
17417  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
17418 #endif
17419 #if SQLITE_MEMDEBUG
17420  "MEMDEBUG",
17421 #endif
17422 #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
17423  "MIXED_ENDIAN_64BIT_FLOAT",
17424 #endif
17425 #if SQLITE_NO_SYNC
17426  "NO_SYNC",
17427 #endif
17428 #if SQLITE_OMIT_ALTERTABLE
17429  "OMIT_ALTERTABLE",
17430 #endif
17431 #if SQLITE_OMIT_ANALYZE
17432  "OMIT_ANALYZE",
17433 #endif
17434 #if SQLITE_OMIT_ATTACH
17435  "OMIT_ATTACH",
17436 #endif
17437 #if SQLITE_OMIT_AUTHORIZATION
17438  "OMIT_AUTHORIZATION",
17439 #endif
17440 #if SQLITE_OMIT_AUTOINCREMENT
17441  "OMIT_AUTOINCREMENT",
17442 #endif
17443 #if SQLITE_OMIT_AUTOINIT
17444  "OMIT_AUTOINIT",
17445 #endif
17446 #if SQLITE_OMIT_AUTOMATIC_INDEX
17447  "OMIT_AUTOMATIC_INDEX",
17448 #endif
17449 #if SQLITE_OMIT_AUTORESET
17450  "OMIT_AUTORESET",
17451 #endif
17452 #if SQLITE_OMIT_AUTOVACUUM
17453  "OMIT_AUTOVACUUM",
17454 #endif
17455 #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
17456  "OMIT_BETWEEN_OPTIMIZATION",
17457 #endif
17458 #if SQLITE_OMIT_BLOB_LITERAL
17459  "OMIT_BLOB_LITERAL",
17460 #endif
17461 #if SQLITE_OMIT_BTREECOUNT
17462  "OMIT_BTREECOUNT",
17463 #endif
17464 #if SQLITE_OMIT_BUILTIN_TEST
17465  "OMIT_BUILTIN_TEST",
17466 #endif
17467 #if SQLITE_OMIT_CAST
17468  "OMIT_CAST",
17469 #endif
17470 #if SQLITE_OMIT_CHECK
17471  "OMIT_CHECK",
17472 #endif
17473 #if SQLITE_OMIT_COMPLETE
17474  "OMIT_COMPLETE",
17475 #endif
17476 #if SQLITE_OMIT_COMPOUND_SELECT
17477  "OMIT_COMPOUND_SELECT",
17478 #endif
17479 #if SQLITE_OMIT_CTE
17480  "OMIT_CTE",
17481 #endif
17482 #if SQLITE_OMIT_DATETIME_FUNCS
17483  "OMIT_DATETIME_FUNCS",
17484 #endif
17485 #if SQLITE_OMIT_DECLTYPE
17486  "OMIT_DECLTYPE",
17487 #endif
17488 #if SQLITE_OMIT_DEPRECATED
17489  "OMIT_DEPRECATED",
17490 #endif
17491 #if SQLITE_OMIT_DISKIO
17492  "OMIT_DISKIO",
17493 #endif
17494 #if SQLITE_OMIT_EXPLAIN
17495  "OMIT_EXPLAIN",
17496 #endif
17497 #if SQLITE_OMIT_FLAG_PRAGMAS
17498  "OMIT_FLAG_PRAGMAS",
17499 #endif
17500 #if SQLITE_OMIT_FLOATING_POINT
17501  "OMIT_FLOATING_POINT",
17502 #endif
17503 #if SQLITE_OMIT_FOREIGN_KEY
17504  "OMIT_FOREIGN_KEY",
17505 #endif
17506 #if SQLITE_OMIT_GET_TABLE
17507  "OMIT_GET_TABLE",
17508 #endif
17509 #if SQLITE_OMIT_INCRBLOB
17510  "OMIT_INCRBLOB",
17511 #endif
17512 #if SQLITE_OMIT_INTEGRITY_CHECK
17513  "OMIT_INTEGRITY_CHECK",
17514 #endif
17515 #if SQLITE_OMIT_LIKE_OPTIMIZATION
17516  "OMIT_LIKE_OPTIMIZATION",
17517 #endif
17518 #if SQLITE_OMIT_LOAD_EXTENSION
17519  "OMIT_LOAD_EXTENSION",
17520 #endif
17521 #if SQLITE_OMIT_LOCALTIME
17522  "OMIT_LOCALTIME",
17523 #endif
17524 #if SQLITE_OMIT_LOOKASIDE
17525  "OMIT_LOOKASIDE",
17526 #endif
17527 #if SQLITE_OMIT_MEMORYDB
17528  "OMIT_MEMORYDB",
17529 #endif
17530 #if SQLITE_OMIT_OR_OPTIMIZATION
17531  "OMIT_OR_OPTIMIZATION",
17532 #endif
17533 #if SQLITE_OMIT_PAGER_PRAGMAS
17534  "OMIT_PAGER_PRAGMAS",
17535 #endif
17536 #if SQLITE_OMIT_PRAGMA
17537  "OMIT_PRAGMA",
17538 #endif
17539 #if SQLITE_OMIT_PROGRESS_CALLBACK
17540  "OMIT_PROGRESS_CALLBACK",
17541 #endif
17542 #if SQLITE_OMIT_QUICKBALANCE
17543  "OMIT_QUICKBALANCE",
17544 #endif
17545 #if SQLITE_OMIT_REINDEX
17546  "OMIT_REINDEX",
17547 #endif
17548 #if SQLITE_OMIT_SCHEMA_PRAGMAS
17549  "OMIT_SCHEMA_PRAGMAS",
17550 #endif
17551 #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
17552  "OMIT_SCHEMA_VERSION_PRAGMAS",
17553 #endif
17554 #if SQLITE_OMIT_SHARED_CACHE
17555  "OMIT_SHARED_CACHE",
17556 #endif
17557 #if SQLITE_OMIT_SUBQUERY
17558  "OMIT_SUBQUERY",
17559 #endif
17560 #if SQLITE_OMIT_TCL_VARIABLE
17561  "OMIT_TCL_VARIABLE",
17562 #endif
17563 #if SQLITE_OMIT_TEMPDB
17564  "OMIT_TEMPDB",
17565 #endif
17566 #if SQLITE_OMIT_TRACE
17567  "OMIT_TRACE",
17568 #endif
17569 #if SQLITE_OMIT_TRIGGER
17570  "OMIT_TRIGGER",
17571 #endif
17572 #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
17573  "OMIT_TRUNCATE_OPTIMIZATION",
17574 #endif
17575 #if SQLITE_OMIT_UTF16
17576  "OMIT_UTF16",
17577 #endif
17578 #if SQLITE_OMIT_VACUUM
17579  "OMIT_VACUUM",
17580 #endif
17581 #if SQLITE_OMIT_VIEW
17582  "OMIT_VIEW",
17583 #endif
17584 #if SQLITE_OMIT_VIRTUALTABLE
17585  "OMIT_VIRTUALTABLE",
17586 #endif
17587 #if SQLITE_OMIT_WAL
17588  "OMIT_WAL",
17589 #endif
17590 #if SQLITE_OMIT_WSD
17591  "OMIT_WSD",
17592 #endif
17593 #if SQLITE_OMIT_XFER_OPT
17594  "OMIT_XFER_OPT",
17595 #endif
17596 #if SQLITE_PERFORMANCE_TRACE
17597  "PERFORMANCE_TRACE",
17598 #endif
17599 #if SQLITE_PROXY_DEBUG
17600  "PROXY_DEBUG",
17601 #endif
17602 #if SQLITE_RTREE_INT_ONLY
17603  "RTREE_INT_ONLY",
17604 #endif
17605 #if SQLITE_SECURE_DELETE
17606  "SECURE_DELETE",
17607 #endif
17608 #if SQLITE_SMALL_STACK
17609  "SMALL_STACK",
17610 #endif
17611 #if SQLITE_SOUNDEX
17612  "SOUNDEX",
17613 #endif
17614 #if SQLITE_SYSTEM_MALLOC
17615  "SYSTEM_MALLOC",
17616 #endif
17617 #if SQLITE_TCL
17618  "TCL",
17619 #endif
17620 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
17621  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
17622 #endif
17623 #if SQLITE_TEST
17624  "TEST",
17625 #endif
17626 #if defined(SQLITE_THREADSAFE)
17627  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
17628 #endif
17629 #if SQLITE_USE_ALLOCA
17630  "USE_ALLOCA",
17631 #endif
17632 #if SQLITE_USER_AUTHENTICATION
17633  "USER_AUTHENTICATION",
17634 #endif
17635 #if SQLITE_WIN32_MALLOC
17636  "WIN32_MALLOC",
17637 #endif
17638 #if SQLITE_ZERO_MALLOC
17639  "ZERO_MALLOC"
17640 #endif
17641 };
17642 
17643 /*
17644 ** Given the name of a compile-time option, return true if that option
17645 ** was used and false if not.
17646 **
17647 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
17648 ** is not required for a match.
17649 */
17650 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
17651  int i, n;
17652 
17653 #if SQLITE_ENABLE_API_ARMOR
17654  if( zOptName==0 ){
17655  (void)SQLITE_MISUSE_BKPT;
17656  return 0;
17657  }
17658 #endif
17659  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
17660  n = sqlite3Strlen30(zOptName);
17661 
17662  /* Since ArraySize(azCompileOpt) is normally in single digits, a
17663  ** linear search is adequate. No need for a binary search. */
17664  for(i=0; i<ArraySize(azCompileOpt); i++){
17665  if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
17666  && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
17667  ){
17668  return 1;
17669  }
17670  }
17671  return 0;
17672 }
17673 
17674 /*
17675 ** Return the N-th compile-time option string. If N is out of range,
17676 ** return a NULL pointer.
17677 */
17678 SQLITE_API const char *sqlite3_compileoption_get(int N){
17679  if( N>=0 && N<ArraySize(azCompileOpt) ){
17680  return azCompileOpt[N];
17681  }
17682  return 0;
17683 }
17684 
17685 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
17686 
17687 /************** End of ctime.c ***********************************************/
17688 /************** Begin file status.c ******************************************/
17689 /*
17690 ** 2008 June 18
17691 **
17692 ** The author disclaims copyright to this source code. In place of
17693 ** a legal notice, here is a blessing:
17694 **
17695 ** May you do good and not evil.
17696 ** May you find forgiveness for yourself and forgive others.
17697 ** May you share freely, never taking more than you give.
17698 **
17699 *************************************************************************
17700 **
17701 ** This module implements the sqlite3_status() interface and related
17702 ** functionality.
17703 */
17704 /* #include "sqliteInt.h" */
17705 /************** Include vdbeInt.h in the middle of status.c ******************/
17706 /************** Begin file vdbeInt.h *****************************************/
17707 /*
17708 ** 2003 September 6
17709 **
17710 ** The author disclaims copyright to this source code. In place of
17711 ** a legal notice, here is a blessing:
17712 **
17713 ** May you do good and not evil.
17714 ** May you find forgiveness for yourself and forgive others.
17715 ** May you share freely, never taking more than you give.
17716 **
17717 *************************************************************************
17718 ** This is the header file for information that is private to the
17719 ** VDBE. This information used to all be at the top of the single
17720 ** source code file "vdbe.c". When that file became too big (over
17721 ** 6000 lines long) it was split up into several smaller files and
17722 ** this header information was factored out.
17723 */
17724 #ifndef SQLITE_VDBEINT_H
17725 #define SQLITE_VDBEINT_H
17726 
17727 /*
17728 ** The maximum number of times that a statement will try to reparse
17729 ** itself before giving up and returning SQLITE_SCHEMA.
17730 */
17731 #ifndef SQLITE_MAX_SCHEMA_RETRY
17732 # define SQLITE_MAX_SCHEMA_RETRY 50
17733 #endif
17734 
17735 /*
17736 ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
17737 ** "explain" P4 display logic is enabled.
17738 */
17739 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
17740  || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
17741 # define VDBE_DISPLAY_P4 1
17742 #else
17743 # define VDBE_DISPLAY_P4 0
17744 #endif
17745 
17746 /*
17747 ** SQL is translated into a sequence of instructions to be
17748 ** executed by a virtual machine. Each instruction is an instance
17749 ** of the following structure.
17750 */
17751 typedef struct VdbeOp Op;
17752 
17753 /*
17754 ** Boolean values
17755 */
17756 typedef unsigned Bool;
17757 
17758 /* Opaque type used by code in vdbesort.c */
17759 typedef struct VdbeSorter VdbeSorter;
17760 
17761 /* Elements of the linked list at Vdbe.pAuxData */
17762 typedef struct AuxData AuxData;
17763 
17764 /* Types of VDBE cursors */
17765 #define CURTYPE_BTREE 0
17766 #define CURTYPE_SORTER 1
17767 #define CURTYPE_VTAB 2
17768 #define CURTYPE_PSEUDO 3
17769 
17770 /*
17771 ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
17772 **
17773 ** * A b-tree cursor
17774 ** - In the main database or in an ephemeral database
17775 ** - On either an index or a table
17776 ** * A sorter
17777 ** * A virtual table
17778 ** * A one-row "pseudotable" stored in a single register
17779 */
17780 typedef struct VdbeCursor VdbeCursor;
17781 struct VdbeCursor {
17782  u8 eCurType; /* One of the CURTYPE_* values above */
17783  i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
17784  u8 nullRow; /* True if pointing to a row with no data */
17785  u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
17786  u8 isTable; /* True for rowid tables. False for indexes */
17787 #ifdef SQLITE_DEBUG
17788  u8 seekOp; /* Most recent seek operation on this cursor */
17789  u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
17790 #endif
17791  Bool isEphemeral:1; /* True for an ephemeral table */
17792  Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
17793  Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
17794  Pgno pgnoRoot; /* Root page of the open btree cursor */
17795  i16 nField; /* Number of fields in the header */
17796  u16 nHdrParsed; /* Number of header fields parsed so far */
17797  union {
17798  BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */
17799  sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
17800  int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */
17801  VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
17802  } uc;
17803  Btree *pBt; /* Separate file holding temporary table */
17804  KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
17805  int seekResult; /* Result of previous sqlite3BtreeMoveto() */
17806  i64 seqCount; /* Sequence counter */
17807  i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
17808  VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
17809  int *aAltMap; /* Mapping from table to index column numbers */
17810 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
17811  u64 maskUsed; /* Mask of columns used by this cursor */
17812 #endif
17813 
17814  /* Cached information about the header for the data record that the
17815  ** cursor is currently pointing to. Only valid if cacheStatus matches
17816  ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
17817  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17818  ** the cache is out of date.
17819  **
17820  ** aRow might point to (ephemeral) data for the current row, or it might
17821  ** be NULL.
17822  */
17823  u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
17824  u32 payloadSize; /* Total number of bytes in the record */
17825  u32 szRow; /* Byte available in aRow */
17826  u32 iHdrOffset; /* Offset to next unparsed byte of the header */
17827  const u8 *aRow; /* Data for the current row, if all on one page */
17828  u32 *aOffset; /* Pointer to aType[nField] */
17829  u32 aType[1]; /* Type values for all entries in the record */
17830  /* 2*nField extra array elements allocated for aType[], beyond the one
17831  ** static element declared in the structure. nField total array slots for
17832  ** aType[] and nField+1 array slots for aOffset[] */
17833 };
17834 
17835 
17836 /*
17837 ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
17838 */
17839 #define CACHE_STALE 0
17840 
17841 /*
17842 ** When a sub-program is executed (OP_Program), a structure of this type
17843 ** is allocated to store the current value of the program counter, as
17844 ** well as the current memory cell array and various other frame specific
17845 ** values stored in the Vdbe struct. When the sub-program is finished,
17846 ** these values are copied back to the Vdbe from the VdbeFrame structure,
17847 ** restoring the state of the VM to as it was before the sub-program
17848 ** began executing.
17849 **
17850 ** The memory for a VdbeFrame object is allocated and managed by a memory
17851 ** cell in the parent (calling) frame. When the memory cell is deleted or
17852 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
17853 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
17854 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
17855 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
17856 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
17857 ** child frame are released.
17858 **
17859 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
17860 ** set to NULL if the currently executing frame is the main program.
17861 */
17862 typedef struct VdbeFrame VdbeFrame;
17863 struct VdbeFrame {
17864  Vdbe *v; /* VM this frame belongs to */
17865  VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
17866  Op *aOp; /* Program instructions for parent frame */
17867  i64 *anExec; /* Event counters from parent frame */
17868  Mem *aMem; /* Array of memory cells for parent frame */
17869  VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
17870  void *token; /* Copy of SubProgram.token */
17871  i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
17872  AuxData *pAuxData; /* Linked list of auxdata allocations */
17873  int nCursor; /* Number of entries in apCsr */
17874  int pc; /* Program Counter in parent (calling) frame */
17875  int nOp; /* Size of aOp array */
17876  int nMem; /* Number of entries in aMem */
17877  int nChildMem; /* Number of memory cells for child frame */
17878  int nChildCsr; /* Number of cursors for child frame */
17879  int nChange; /* Statement changes (Vdbe.nChange) */
17880  int nDbChange; /* Value of db->nChange */
17881 };
17882 
17883 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17884 
17885 /*
17886 ** Internally, the vdbe manipulates nearly all SQL values as Mem
17887 ** structures. Each Mem struct may cache multiple representations (string,
17888 ** integer etc.) of the same value.
17889 */
17890 struct Mem {
17891  union MemValue {
17892  double r; /* Real value used when MEM_Real is set in flags */
17893  i64 i; /* Integer value used when MEM_Int is set in flags */
17894  int nZero; /* Used when bit MEM_Zero is set in flags */
17895  FuncDef *pDef; /* Used only when flags==MEM_Agg */
17896  RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
17897  VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
17898  } u;
17899  u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17900  u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17901  u8 eSubtype; /* Subtype for this value */
17902  int n; /* Number of characters in string value, excluding '\0' */
17903  char *z; /* String or BLOB value */
17904  /* ShallowCopy only needs to copy the information above */
17905  char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
17906  int szMalloc; /* Size of the zMalloc allocation */
17907  u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
17908  sqlite3 *db; /* The associated database connection */
17909  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
17910 #ifdef SQLITE_DEBUG
17911  Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
17912  void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
17913 #endif
17914 };
17915 
17916 /*
17917 ** Size of struct Mem not including the Mem.zMalloc member or anything that
17918 ** follows.
17919 */
17920 #define MEMCELLSIZE offsetof(Mem,zMalloc)
17921 
17922 /* One or more of the following flags are set to indicate the validOK
17923 ** representations of the value stored in the Mem struct.
17924 **
17925 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
17926 ** No other flags may be set in this case.
17927 **
17928 ** If the MEM_Str flag is set then Mem.z points at a string representation.
17929 ** Usually this is encoded in the same unicode encoding as the main
17930 ** database (see below for exceptions). If the MEM_Term flag is also
17931 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
17932 ** flags may coexist with the MEM_Str flag.
17933 */
17934 #define MEM_Null 0x0001 /* Value is NULL */
17935 #define MEM_Str 0x0002 /* Value is a string */
17936 #define MEM_Int 0x0004 /* Value is an integer */
17937 #define MEM_Real 0x0008 /* Value is a real number */
17938 #define MEM_Blob 0x0010 /* Value is a BLOB */
17939 #define MEM_AffMask 0x001f /* Mask of affinity bits */
17940 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
17941 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
17942 #define MEM_Undefined 0x0080 /* Value is undefined */
17943 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
17944 #define MEM_TypeMask 0x81ff /* Mask of type bits */
17945 
17946 
17947 /* Whenever Mem contains a valid string or blob representation, one of
17948 ** the following flags must be set to determine the memory management
17949 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
17950 ** string is \000 or \u0000 terminated
17951 */
17952 #define MEM_Term 0x0200 /* String rep is nul terminated */
17953 #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
17954 #define MEM_Static 0x0800 /* Mem.z points to a static string */
17955 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
17956 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
17957 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
17958 #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
17959 #ifdef SQLITE_OMIT_INCRBLOB
17960  #undef MEM_Zero
17961  #define MEM_Zero 0x0000
17962 #endif
17963 
17964 /* Return TRUE if Mem X contains dynamically allocated content - anything
17965 ** that needs to be deallocated to avoid a leak.
17966 */
17967 #define VdbeMemDynamic(X) \
17968  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
17969 
17970 /*
17971 ** Clear any existing type flags from a Mem and replace them with f
17972 */
17973 #define MemSetTypeFlag(p, f) \
17974  ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17975 
17976 /*
17977 ** Return true if a memory cell is not marked as invalid. This macro
17978 ** is for use inside assert() statements only.
17979 */
17980 #ifdef SQLITE_DEBUG
17981 #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
17982 #endif
17983 
17984 /*
17985 ** Each auxiliary data pointer stored by a user defined function
17986 ** implementation calling sqlite3_set_auxdata() is stored in an instance
17987 ** of this structure. All such structures associated with a single VM
17988 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
17989 ** when the VM is halted (if not before).
17990 */
17991 struct AuxData {
17992  int iOp; /* Instruction number of OP_Function opcode */
17993  int iArg; /* Index of function argument. */
17994  void *pAux; /* Aux data pointer */
17995  void (*xDelete)(void *); /* Destructor for the aux data */
17996  AuxData *pNext; /* Next element in list */
17997 };
17998 
17999 /*
18000 ** The "context" argument for an installable function. A pointer to an
18001 ** instance of this structure is the first argument to the routines used
18002 ** implement the SQL functions.
18003 **
18004 ** There is a typedef for this structure in sqlite.h. So all routines,
18005 ** even the public interface to SQLite, can use a pointer to this structure.
18006 ** But this file is the only place where the internal details of this
18007 ** structure are known.
18008 **
18009 ** This structure is defined inside of vdbeInt.h because it uses substructures
18010 ** (Mem) which are only defined there.
18011 */
18013  Mem *pOut; /* The return value is stored here */
18014  FuncDef *pFunc; /* Pointer to function information */
18015  Mem *pMem; /* Memory cell used to store aggregate context */
18016  Vdbe *pVdbe; /* The VM that owns this context */
18017  int iOp; /* Instruction number of OP_Function */
18018  int isError; /* Error code returned by the function. */
18019  u8 skipFlag; /* Skip accumulator loading if true */
18020  u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
18021  u8 argc; /* Number of arguments */
18022  sqlite3_value *argv[1]; /* Argument set */
18023 };
18024 
18025 /* A bitfield type for use inside of structures. Always follow with :N where
18026 ** N is the number of bits.
18027 */
18028 typedef unsigned bft; /* Bit Field Type */
18029 
18030 typedef struct ScanStatus ScanStatus;
18031 struct ScanStatus {
18032  int addrExplain; /* OP_Explain for loop */
18033  int addrLoop; /* Address of "loops" counter */
18034  int addrVisit; /* Address of "rows visited" counter */
18035  int iSelectID; /* The "Select-ID" for this loop */
18036  LogEst nEst; /* Estimated output rows per loop */
18037  char *zName; /* Name of table or index */
18038 };
18039 
18040 /*
18041 ** An instance of the virtual machine. This structure contains the complete
18042 ** state of the virtual machine.
18043 **
18044 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
18045 ** is really a pointer to an instance of this structure.
18046 */
18047 struct Vdbe {
18048  sqlite3 *db; /* The database connection that owns this statement */
18049  Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
18050  Parse *pParse; /* Parsing context used to create this Vdbe */
18051  ynVar nVar; /* Number of entries in aVar[] */
18052  ynVar nzVar; /* Number of entries in azVar[] */
18053  u32 magic; /* Magic number for sanity checking */
18054  int nMem; /* Number of memory locations currently allocated */
18055  int nCursor; /* Number of slots in apCsr[] */
18056  u32 cacheCtr; /* VdbeCursor row cache generation counter */
18057  int pc; /* The program counter */
18058  int rc; /* Value to return */
18059  int nChange; /* Number of db changes made since last reset */
18060  int iStatement; /* Statement number (or 0 if has not opened stmt) */
18061  i64 iCurrentTime; /* Value of julianday('now') for this statement */
18062  i64 nFkConstraint; /* Number of imm. FK constraints this VM */
18063  i64 nStmtDefCons; /* Number of def. constraints when stmt started */
18064  i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
18065 
18066  /* When allocating a new Vdbe object, all of the fields below should be
18067  ** initialized to zero or NULL */
18068 
18069  Op *aOp; /* Space to hold the virtual machine's program */
18070  Mem *aMem; /* The memory locations */
18071  Mem **apArg; /* Arguments to currently executing user function */
18072  Mem *aColName; /* Column names to return */
18073  Mem *pResultSet; /* Pointer to an array of results */
18074  char *zErrMsg; /* Error message written here */
18075  VdbeCursor **apCsr; /* One element of this array for each open cursor */
18076  Mem *aVar; /* Values for the OP_Variable opcode. */
18077  char **azVar; /* Name of variables */
18078 #ifndef SQLITE_OMIT_TRACE
18079  i64 startTime; /* Time when query started - used for profiling */
18080 #endif
18081  int nOp; /* Number of instructions in the program */
18082 #ifdef SQLITE_DEBUG
18083  int rcApp; /* errcode set by sqlite3_result_error_code() */
18084 #endif
18085  u16 nResColumn; /* Number of columns in one row of the result set */
18086  u8 errorAction; /* Recovery action to do in case of an error */
18087  u8 minWriteFileFormat; /* Minimum file format for writable database files */
18088  bft expired:1; /* True if the VM needs to be recompiled */
18089  bft doingRerun:1; /* True if rerunning after an auto-reprepare */
18090  bft explain:2; /* True if EXPLAIN present on SQL command */
18091  bft changeCntOn:1; /* True to update the change-counter */
18092  bft runOnlyOnce:1; /* Automatically expire on reset */
18093  bft usesStmtJournal:1; /* True if uses a statement journal */
18094  bft readOnly:1; /* True for statements that do not write */
18095  bft bIsReader:1; /* True for statements that read */
18096  bft isPrepareV2:1; /* True if prepared with prepare_v2() */
18097  yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
18098  yDbMask lockMask; /* Subset of btreeMask that requires a lock */
18099  u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
18100  char *zSql; /* Text of the SQL statement that generated this */
18101  void *pFree; /* Free this when deleting the vdbe */
18102  VdbeFrame *pFrame; /* Parent frame */
18103  VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
18104  int nFrame; /* Number of frames in pFrame list */
18105  u32 expmask; /* Binding to these vars invalidates VM */
18106  SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
18107  AuxData *pAuxData; /* Linked list of auxdata allocations */
18108 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18109  i64 *anExec; /* Number of times each op has been executed */
18110  int nScan; /* Entries in aScan[] */
18111  ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
18112 #endif
18113 };
18114 
18115 /*
18116 ** The following are allowed values for Vdbe.magic
18117 */
18118 #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
18119 #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
18120 #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
18121 #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
18122 #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
18123 
18124 /*
18125 ** Structure used to store the context required by the
18126 ** sqlite3_preupdate_*() API functions.
18127 */
18128 struct PreUpdate {
18129  Vdbe *v;
18130  VdbeCursor *pCsr; /* Cursor to read old values from */
18131  int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
18132  u8 *aRecord; /* old.* database record */
18133  KeyInfo keyinfo;
18134  UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
18135  UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
18136  int iNewReg; /* Register for new.* values */
18137  i64 iKey1; /* First key value passed to hook */
18138  i64 iKey2; /* Second key value passed to hook */
18139  Mem *aNew; /* Array of new.* values */
18140  Table *pTab; /* Schema object being upated */
18141 };
18142 
18143 /*
18144 ** Function prototypes
18145 */
18146 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
18147 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18148 void sqliteVdbePopStack(Vdbe*,int);
18149 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
18150 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
18151 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18152 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18153 #endif
18154 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18155 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
18156 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
18157 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
18158 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18159 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
18160 
18161 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18162 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
18163 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
18164 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18165 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18166 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18167 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18168 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18169 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18170 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18171 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18172 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18173 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18174 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18175 #ifdef SQLITE_OMIT_FLOATING_POINT
18176 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18177 #else
18178 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
18179 #endif
18180 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
18181 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18182 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18183 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18184 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18185 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
18186 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18187 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18188 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18189 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18190 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18191 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18192 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
18193 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
18194 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18195 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18196 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18197 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18198 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
18199 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18200 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18201 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18202 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
18203 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
18204 #endif
18205 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
18206 
18207 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
18208 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
18209 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
18210 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
18211 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
18212 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
18213 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
18214 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
18215 
18216 #if !defined(SQLITE_OMIT_SHARED_CACHE)
18217 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
18218 #else
18219 # define sqlite3VdbeEnter(X)
18220 #endif
18221 
18222 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
18223 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
18224 #else
18225 # define sqlite3VdbeLeave(X)
18226 #endif
18227 
18228 #ifdef SQLITE_DEBUG
18229 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
18230 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
18231 #endif
18232 
18233 #ifndef SQLITE_OMIT_FOREIGN_KEY
18234 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18235 #else
18236 # define sqlite3VdbeCheckFk(p,i) 0
18237 #endif
18238 
18239 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18240 #ifdef SQLITE_DEBUG
18241 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
18242 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18243 #endif
18244 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18245 
18246 #ifndef SQLITE_OMIT_INCRBLOB
18247 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
18248  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
18249 #else
18250  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18251  #define ExpandBlob(P) SQLITE_OK
18252 #endif
18253 
18254 #endif /* !defined(SQLITE_VDBEINT_H) */
18255 
18256 /************** End of vdbeInt.h *********************************************/
18257 /************** Continuing where we left off in status.c *********************/
18258 
18259 /*
18260 ** Variables in which to record status information.
18261 */
18262 #if SQLITE_PTRSIZE>4
18263 typedef sqlite3_int64 sqlite3StatValueType;
18264 #else
18265 typedef u32 sqlite3StatValueType;
18266 #endif
18267 typedef struct sqlite3StatType sqlite3StatType;
18268 static SQLITE_WSD struct sqlite3StatType {
18269  sqlite3StatValueType nowValue[10]; /* Current value */
18270  sqlite3StatValueType mxValue[10]; /* Maximum value */
18271 } sqlite3Stat = { {0,}, {0,} };
18272 
18273 /*
18274 ** Elements of sqlite3Stat[] are protected by either the memory allocator
18275 ** mutex, or by the pcache1 mutex. The following array determines which.
18276 */
18277 static const char statMutex[] = {
18278  0, /* SQLITE_STATUS_MEMORY_USED */
18279  1, /* SQLITE_STATUS_PAGECACHE_USED */
18280  1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
18281  0, /* SQLITE_STATUS_SCRATCH_USED */
18282  0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
18283  0, /* SQLITE_STATUS_MALLOC_SIZE */
18284  0, /* SQLITE_STATUS_PARSER_STACK */
18285  1, /* SQLITE_STATUS_PAGECACHE_SIZE */
18286  0, /* SQLITE_STATUS_SCRATCH_SIZE */
18287  0, /* SQLITE_STATUS_MALLOC_COUNT */
18288 };
18289 
18290 
18291 /* The "wsdStat" macro will resolve to the status information
18292 ** state vector. If writable static data is unsupported on the target,
18293 ** we have to locate the state vector at run-time. In the more common
18294 ** case where writable static data is supported, wsdStat can refer directly
18295 ** to the "sqlite3Stat" state vector declared above.
18296 */
18297 #ifdef SQLITE_OMIT_WSD
18298 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
18299 # define wsdStat x[0]
18300 #else
18301 # define wsdStatInit
18302 # define wsdStat sqlite3Stat
18303 #endif
18304 
18305 /*
18306 ** Return the current value of a status parameter. The caller must
18307 ** be holding the appropriate mutex.
18308 */
18309 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
18310  wsdStatInit;
18311  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18312  assert( op>=0 && op<ArraySize(statMutex) );
18313  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18314  : sqlite3MallocMutex()) );
18315  return wsdStat.nowValue[op];
18316 }
18317 
18318 /*
18319 ** Add N to the value of a status record. The caller must hold the
18320 ** appropriate mutex. (Locking is checked by assert()).
18321 **
18322 ** The StatusUp() routine can accept positive or negative values for N.
18323 ** The value of N is added to the current status value and the high-water
18324 ** mark is adjusted if necessary.
18325 **
18326 ** The StatusDown() routine lowers the current value by N. The highwater
18327 ** mark is unchanged. N must be non-negative for StatusDown().
18328 */
18329 SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
18330  wsdStatInit;
18331  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18332  assert( op>=0 && op<ArraySize(statMutex) );
18333  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18334  : sqlite3MallocMutex()) );
18335  wsdStat.nowValue[op] += N;
18336  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
18337  wsdStat.mxValue[op] = wsdStat.nowValue[op];
18338  }
18339 }
18340 SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
18341  wsdStatInit;
18342  assert( N>=0 );
18343  assert( op>=0 && op<ArraySize(statMutex) );
18344  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18345  : sqlite3MallocMutex()) );
18346  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18347  wsdStat.nowValue[op] -= N;
18348 }
18349 
18350 /*
18351 ** Adjust the highwater mark if necessary.
18352 ** The caller must hold the appropriate mutex.
18353 */
18354 SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
18355  sqlite3StatValueType newValue;
18356  wsdStatInit;
18357  assert( X>=0 );
18358  newValue = (sqlite3StatValueType)X;
18359  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18360  assert( op>=0 && op<ArraySize(statMutex) );
18361  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18362  : sqlite3MallocMutex()) );
18363  assert( op==SQLITE_STATUS_MALLOC_SIZE
18364  || op==SQLITE_STATUS_PAGECACHE_SIZE
18365  || op==SQLITE_STATUS_SCRATCH_SIZE
18366  || op==SQLITE_STATUS_PARSER_STACK );
18367  if( newValue>wsdStat.mxValue[op] ){
18368  wsdStat.mxValue[op] = newValue;
18369  }
18370 }
18371 
18372 /*
18373 ** Query status information.
18374 */
18375 SQLITE_API int sqlite3_status64(
18376  int op,
18377  sqlite3_int64 *pCurrent,
18378  sqlite3_int64 *pHighwater,
18379  int resetFlag
18380 ){
18381  sqlite3_mutex *pMutex;
18382  wsdStatInit;
18383  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
18384  return SQLITE_MISUSE_BKPT;
18385  }
18386 #ifdef SQLITE_ENABLE_API_ARMOR
18387  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18388 #endif
18389  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
18390  sqlite3_mutex_enter(pMutex);
18391  *pCurrent = wsdStat.nowValue[op];
18392  *pHighwater = wsdStat.mxValue[op];
18393  if( resetFlag ){
18394  wsdStat.mxValue[op] = wsdStat.nowValue[op];
18395  }
18396  sqlite3_mutex_leave(pMutex);
18397  (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
18398  return SQLITE_OK;
18399 }
18400 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
18401  sqlite3_int64 iCur = 0, iHwtr = 0;
18402  int rc;
18403 #ifdef SQLITE_ENABLE_API_ARMOR
18404  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18405 #endif
18406  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
18407  if( rc==0 ){
18408  *pCurrent = (int)iCur;
18409  *pHighwater = (int)iHwtr;
18410  }
18411  return rc;
18412 }
18413 
18414 /*
18415 ** Query status information for a single database connection
18416 */
18417 SQLITE_API int sqlite3_db_status(
18418  sqlite3 *db, /* The database connection whose status is desired */
18419  int op, /* Status verb */
18420  int *pCurrent, /* Write current value here */
18421  int *pHighwater, /* Write high-water mark here */
18422  int resetFlag /* Reset high-water mark if true */
18423 ){
18424  int rc = SQLITE_OK; /* Return code */
18425 #ifdef SQLITE_ENABLE_API_ARMOR
18426  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
18427  return SQLITE_MISUSE_BKPT;
18428  }
18429 #endif
18430  sqlite3_mutex_enter(db->mutex);
18431  switch( op ){
18432  case SQLITE_DBSTATUS_LOOKASIDE_USED: {
18433  *pCurrent = db->lookaside.nOut;
18434  *pHighwater = db->lookaside.mxOut;
18435  if( resetFlag ){
18436  db->lookaside.mxOut = db->lookaside.nOut;
18437  }
18438  break;
18439  }
18440 
18441  case SQLITE_DBSTATUS_LOOKASIDE_HIT:
18442  case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
18443  case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
18444  testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
18445  testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
18446  testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
18447  assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
18448  assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
18449  *pCurrent = 0;
18450  *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
18451  if( resetFlag ){
18452  db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
18453  }
18454  break;
18455  }
18456 
18457  /*
18458  ** Return an approximation for the amount of memory currently used
18459  ** by all pagers associated with the given database connection. The
18460  ** highwater mark is meaningless and is returned as zero.
18461  */
18462  case SQLITE_DBSTATUS_CACHE_USED_SHARED:
18463  case SQLITE_DBSTATUS_CACHE_USED: {
18464  int totalUsed = 0;
18465  int i;
18466  sqlite3BtreeEnterAll(db);
18467  for(i=0; i<db->nDb; i++){
18468  Btree *pBt = db->aDb[i].pBt;
18469  if( pBt ){
18470  Pager *pPager = sqlite3BtreePager(pBt);
18471  int nByte = sqlite3PagerMemUsed(pPager);
18472  if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
18473  nByte = nByte / sqlite3BtreeConnectionCount(pBt);
18474  }
18475  totalUsed += nByte;
18476  }
18477  }
18478  sqlite3BtreeLeaveAll(db);
18479  *pCurrent = totalUsed;
18480  *pHighwater = 0;
18481  break;
18482  }
18483 
18484  /*
18485  ** *pCurrent gets an accurate estimate of the amount of memory used
18486  ** to store the schema for all databases (main, temp, and any ATTACHed
18487  ** databases. *pHighwater is set to zero.
18488  */
18489  case SQLITE_DBSTATUS_SCHEMA_USED: {
18490  int i; /* Used to iterate through schemas */
18491  int nByte = 0; /* Used to accumulate return value */
18492 
18493  sqlite3BtreeEnterAll(db);
18494  db->pnBytesFreed = &nByte;
18495  for(i=0; i<db->nDb; i++){
18496  Schema *pSchema = db->aDb[i].pSchema;
18497  if( ALWAYS(pSchema!=0) ){
18498  HashElem *p;
18499 
18500  nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
18501  pSchema->tblHash.count
18502  + pSchema->trigHash.count
18503  + pSchema->idxHash.count
18504  + pSchema->fkeyHash.count
18505  );
18506  nByte += sqlite3_msize(pSchema->tblHash.ht);
18507  nByte += sqlite3_msize(pSchema->trigHash.ht);
18508  nByte += sqlite3_msize(pSchema->idxHash.ht);
18509  nByte += sqlite3_msize(pSchema->fkeyHash.ht);
18510 
18511  for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
18512  sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
18513  }
18514  for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
18515  sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
18516  }
18517  }
18518  }
18519  db->pnBytesFreed = 0;
18520  sqlite3BtreeLeaveAll(db);
18521 
18522  *pHighwater = 0;
18523  *pCurrent = nByte;
18524  break;
18525  }
18526 
18527  /*
18528  ** *pCurrent gets an accurate estimate of the amount of memory used
18529  ** to store all prepared statements.
18530  ** *pHighwater is set to zero.
18531  */
18532  case SQLITE_DBSTATUS_STMT_USED: {
18533  struct Vdbe *pVdbe; /* Used to iterate through VMs */
18534  int nByte = 0; /* Used to accumulate return value */
18535 
18536  db->pnBytesFreed = &nByte;
18537  for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
18538  sqlite3VdbeClearObject(db, pVdbe);
18539  sqlite3DbFree(db, pVdbe);
18540  }
18541  db->pnBytesFreed = 0;
18542 
18543  *pHighwater = 0; /* IMP: R-64479-57858 */
18544  *pCurrent = nByte;
18545 
18546  break;
18547  }
18548 
18549  /*
18550  ** Set *pCurrent to the total cache hits or misses encountered by all
18551  ** pagers the database handle is connected to. *pHighwater is always set
18552  ** to zero.
18553  */
18554  case SQLITE_DBSTATUS_CACHE_HIT:
18555  case SQLITE_DBSTATUS_CACHE_MISS:
18556  case SQLITE_DBSTATUS_CACHE_WRITE:{
18557  int i;
18558  int nRet = 0;
18559  assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
18560  assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
18561 
18562  for(i=0; i<db->nDb; i++){
18563  if( db->aDb[i].pBt ){
18564  Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
18565  sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
18566  }
18567  }
18568  *pHighwater = 0; /* IMP: R-42420-56072 */
18569  /* IMP: R-54100-20147 */
18570  /* IMP: R-29431-39229 */
18571  *pCurrent = nRet;
18572  break;
18573  }
18574 
18575  /* Set *pCurrent to non-zero if there are unresolved deferred foreign
18576  ** key constraints. Set *pCurrent to zero if all foreign key constraints
18577  ** have been satisfied. The *pHighwater is always set to zero.
18578  */
18579  case SQLITE_DBSTATUS_DEFERRED_FKS: {
18580  *pHighwater = 0; /* IMP: R-11967-56545 */
18581  *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
18582  break;
18583  }
18584 
18585  default: {
18586  rc = SQLITE_ERROR;
18587  }
18588  }
18589  sqlite3_mutex_leave(db->mutex);
18590  return rc;
18591 }
18592 
18593 /************** End of status.c **********************************************/
18594 /************** Begin file date.c ********************************************/
18595 /*
18596 ** 2003 October 31
18597 **
18598 ** The author disclaims copyright to this source code. In place of
18599 ** a legal notice, here is a blessing:
18600 **
18601 ** May you do good and not evil.
18602 ** May you find forgiveness for yourself and forgive others.
18603 ** May you share freely, never taking more than you give.
18604 **
18605 *************************************************************************
18606 ** This file contains the C functions that implement date and time
18607 ** functions for SQLite.
18608 **
18609 ** There is only one exported symbol in this file - the function
18610 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
18611 ** All other code has file scope.
18612 **
18613 ** SQLite processes all times and dates as julian day numbers. The
18614 ** dates and times are stored as the number of days since noon
18615 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
18616 ** calendar system.
18617 **
18618 ** 1970-01-01 00:00:00 is JD 2440587.5
18619 ** 2000-01-01 00:00:00 is JD 2451544.5
18620 **
18621 ** This implementation requires years to be expressed as a 4-digit number
18622 ** which means that only dates between 0000-01-01 and 9999-12-31 can
18623 ** be represented, even though julian day numbers allow a much wider
18624 ** range of dates.
18625 **
18626 ** The Gregorian calendar system is used for all dates and times,
18627 ** even those that predate the Gregorian calendar. Historians usually
18628 ** use the julian calendar for dates prior to 1582-10-15 and for some
18629 ** dates afterwards, depending on locale. Beware of this difference.
18630 **
18631 ** The conversion algorithms are implemented based on descriptions
18632 ** in the following text:
18633 **
18634 ** Jean Meeus
18635 ** Astronomical Algorithms, 2nd Edition, 1998
18636 ** ISBM 0-943396-61-1
18637 ** Willmann-Bell, Inc
18638 ** Richmond, Virginia (USA)
18639 */
18640 /* #include "sqliteInt.h" */
18641 /* #include <stdlib.h> */
18642 /* #include <assert.h> */
18643 #include <time.h>
18644 
18645 #ifndef SQLITE_OMIT_DATETIME_FUNCS
18646 
18647 /*
18648 ** The MSVC CRT on Windows CE may not have a localtime() function.
18649 ** So declare a substitute. The substitute function itself is
18650 ** defined in "os_win.c".
18651 */
18652 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
18653  (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
18654 struct tm *__cdecl localtime(const time_t *);
18655 #endif
18656 
18657 /*
18658 ** A structure for holding a single date and time.
18659 */
18660 typedef struct DateTime DateTime;
18661 struct DateTime {
18662  sqlite3_int64 iJD; /* The julian day number times 86400000 */
18663  int Y, M, D; /* Year, month, and day */
18664  int h, m; /* Hour and minutes */
18665  int tz; /* Timezone offset in minutes */
18666  double s; /* Seconds */
18667  char validYMD; /* True (1) if Y,M,D are valid */
18668  char validHMS; /* True (1) if h,m,s are valid */
18669  char validJD; /* True (1) if iJD is valid */
18670  char validTZ; /* True (1) if tz is valid */
18671  char tzSet; /* Timezone was set explicitly */
18672 };
18673 
18674 
18675 /*
18676 ** Convert zDate into one or more integers according to the conversion
18677 ** specifier zFormat.
18678 **
18679 ** zFormat[] contains 4 characters for each integer converted, except for
18680 ** the last integer which is specified by three characters. The meaning
18681 ** of a four-character format specifiers ABCD is:
18682 **
18683 ** A: number of digits to convert. Always "2" or "4".
18684 ** B: minimum value. Always "0" or "1".
18685 ** C: maximum value, decoded as:
18686 ** a: 12
18687 ** b: 14
18688 ** c: 24
18689 ** d: 31
18690 ** e: 59
18691 ** f: 9999
18692 ** D: the separator character, or \000 to indicate this is the
18693 ** last number to convert.
18694 **
18695 ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
18696 ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
18697 ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
18698 ** the 2-digit day which is the last integer in the set.
18699 **
18700 ** The function returns the number of successful conversions.
18701 */
18702 static int getDigits(const char *zDate, const char *zFormat, ...){
18703  /* The aMx[] array translates the 3rd character of each format
18704  ** spec into a max size: a b c d e f */
18705  static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
18706  va_list ap;
18707  int cnt = 0;
18708  char nextC;
18709  va_start(ap, zFormat);
18710  do{
18711  char N = zFormat[0] - '0';
18712  char min = zFormat[1] - '0';
18713  int val = 0;
18714  u16 max;
18715 
18716  assert( zFormat[2]>='a' && zFormat[2]<='f' );
18717  max = aMx[zFormat[2] - 'a'];
18718  nextC = zFormat[3];
18719  val = 0;
18720  while( N-- ){
18721  if( !sqlite3Isdigit(*zDate) ){
18722  goto end_getDigits;
18723  }
18724  val = val*10 + *zDate - '0';
18725  zDate++;
18726  }
18727  if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
18728  goto end_getDigits;
18729  }
18730  *va_arg(ap,int*) = val;
18731  zDate++;
18732  cnt++;
18733  zFormat += 4;
18734  }while( nextC );
18735 end_getDigits:
18736  va_end(ap);
18737  return cnt;
18738 }
18739 
18740 /*
18741 ** Parse a timezone extension on the end of a date-time.
18742 ** The extension is of the form:
18743 **
18744 ** (+/-)HH:MM
18745 **
18746 ** Or the "zulu" notation:
18747 **
18748 ** Z
18749 **
18750 ** If the parse is successful, write the number of minutes
18751 ** of change in p->tz and return 0. If a parser error occurs,
18752 ** return non-zero.
18753 **
18754 ** A missing specifier is not considered an error.
18755 */
18756 static int parseTimezone(const char *zDate, DateTime *p){
18757  int sgn = 0;
18758  int nHr, nMn;
18759  int c;
18760  while( sqlite3Isspace(*zDate) ){ zDate++; }
18761  p->tz = 0;
18762  c = *zDate;
18763  if( c=='-' ){
18764  sgn = -1;
18765  }else if( c=='+' ){
18766  sgn = +1;
18767  }else if( c=='Z' || c=='z' ){
18768  zDate++;
18769  goto zulu_time;
18770  }else{
18771  return c!=0;
18772  }
18773  zDate++;
18774  if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
18775  return 1;
18776  }
18777  zDate += 5;
18778  p->tz = sgn*(nMn + nHr*60);
18779 zulu_time:
18780  while( sqlite3Isspace(*zDate) ){ zDate++; }
18781  p->tzSet = 1;
18782  return *zDate!=0;
18783 }
18784 
18785 /*
18786 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
18787 ** The HH, MM, and SS must each be exactly 2 digits. The
18788 ** fractional seconds FFFF can be one or more digits.
18789 **
18790 ** Return 1 if there is a parsing error and 0 on success.
18791 */
18792 static int parseHhMmSs(const char *zDate, DateTime *p){
18793  int h, m, s;
18794  double ms = 0.0;
18795  if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
18796  return 1;
18797  }
18798  zDate += 5;
18799  if( *zDate==':' ){
18800  zDate++;
18801  if( getDigits(zDate, "20e", &s)!=1 ){
18802  return 1;
18803  }
18804  zDate += 2;
18805  if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
18806  double rScale = 1.0;
18807  zDate++;
18808  while( sqlite3Isdigit(*zDate) ){
18809  ms = ms*10.0 + *zDate - '0';
18810  rScale *= 10.0;
18811  zDate++;
18812  }
18813  ms /= rScale;
18814  }
18815  }else{
18816  s = 0;
18817  }
18818  p->validJD = 0;
18819  p->validHMS = 1;
18820  p->h = h;
18821  p->m = m;
18822  p->s = s + ms;
18823  if( parseTimezone(zDate, p) ) return 1;
18824  p->validTZ = (p->tz!=0)?1:0;
18825  return 0;
18826 }
18827 
18828 /*
18829 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
18830 ** that the YYYY-MM-DD is according to the Gregorian calendar.
18831 **
18832 ** Reference: Meeus page 61
18833 */
18834 static void computeJD(DateTime *p){
18835  int Y, M, D, A, B, X1, X2;
18836 
18837  if( p->validJD ) return;
18838  if( p->validYMD ){
18839  Y = p->Y;
18840  M = p->M;
18841  D = p->D;
18842  }else{
18843  Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
18844  M = 1;
18845  D = 1;
18846  }
18847  if( M<=2 ){
18848  Y--;
18849  M += 12;
18850  }
18851  A = Y/100;
18852  B = 2 - A + (A/4);
18853  X1 = 36525*(Y+4716)/100;
18854  X2 = 306001*(M+1)/10000;
18855  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
18856  p->validJD = 1;
18857  if( p->validHMS ){
18858  p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
18859  if( p->validTZ ){
18860  p->iJD -= p->tz*60000;
18861  p->validYMD = 0;
18862  p->validHMS = 0;
18863  p->validTZ = 0;
18864  }
18865  }
18866 }
18867 
18868 /*
18869 ** Parse dates of the form
18870 **
18871 ** YYYY-MM-DD HH:MM:SS.FFF
18872 ** YYYY-MM-DD HH:MM:SS
18873 ** YYYY-MM-DD HH:MM
18874 ** YYYY-MM-DD
18875 **
18876 ** Write the result into the DateTime structure and return 0
18877 ** on success and 1 if the input string is not a well-formed
18878 ** date.
18879 */
18880 static int parseYyyyMmDd(const char *zDate, DateTime *p){
18881  int Y, M, D, neg;
18882 
18883  if( zDate[0]=='-' ){
18884  zDate++;
18885  neg = 1;
18886  }else{
18887  neg = 0;
18888  }
18889  if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
18890  return 1;
18891  }
18892  zDate += 10;
18893  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
18894  if( parseHhMmSs(zDate, p)==0 ){
18895  /* We got the time */
18896  }else if( *zDate==0 ){
18897  p->validHMS = 0;
18898  }else{
18899  return 1;
18900  }
18901  p->validJD = 0;
18902  p->validYMD = 1;
18903  p->Y = neg ? -Y : Y;
18904  p->M = M;
18905  p->D = D;
18906  if( p->validTZ ){
18907  computeJD(p);
18908  }
18909  return 0;
18910 }
18911 
18912 /*
18913 ** Set the time to the current time reported by the VFS.
18914 **
18915 ** Return the number of errors.
18916 */
18917 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
18918  p->iJD = sqlite3StmtCurrentTime(context);
18919  if( p->iJD>0 ){
18920  p->validJD = 1;
18921  return 0;
18922  }else{
18923  return 1;
18924  }
18925 }
18926 
18927 /*
18928 ** Attempt to parse the given string into a julian day number. Return
18929 ** the number of errors.
18930 **
18931 ** The following are acceptable forms for the input string:
18932 **
18933 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
18934 ** DDDD.DD
18935 ** now
18936 **
18937 ** In the first form, the +/-HH:MM is always optional. The fractional
18938 ** seconds extension (the ".FFF") is optional. The seconds portion
18939 ** (":SS.FFF") is option. The year and date can be omitted as long
18940 ** as there is a time string. The time string can be omitted as long
18941 ** as there is a year and date.
18942 */
18943 static int parseDateOrTime(
18944  sqlite3_context *context,
18945  const char *zDate,
18946  DateTime *p
18947 ){
18948  double r;
18949  if( parseYyyyMmDd(zDate,p)==0 ){
18950  return 0;
18951  }else if( parseHhMmSs(zDate, p)==0 ){
18952  return 0;
18953  }else if( sqlite3StrICmp(zDate,"now")==0){
18954  return setDateTimeToCurrent(context, p);
18955  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
18956  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
18957  p->validJD = 1;
18958  return 0;
18959  }
18960  return 1;
18961 }
18962 
18963 /*
18964 ** Compute the Year, Month, and Day from the julian day number.
18965 */
18966 static void computeYMD(DateTime *p){
18967  int Z, A, B, C, D, E, X1;
18968  if( p->validYMD ) return;
18969  if( !p->validJD ){
18970  p->Y = 2000;
18971  p->M = 1;
18972  p->D = 1;
18973  }else{
18974  Z = (int)((p->iJD + 43200000)/86400000);
18975  A = (int)((Z - 1867216.25)/36524.25);
18976  A = Z + 1 + A - (A/4);
18977  B = A + 1524;
18978  C = (int)((B - 122.1)/365.25);
18979  D = (36525*(C&32767))/100;
18980  E = (int)((B-D)/30.6001);
18981  X1 = (int)(30.6001*E);
18982  p->D = B - D - X1;
18983  p->M = E<14 ? E-1 : E-13;
18984  p->Y = p->M>2 ? C - 4716 : C - 4715;
18985  }
18986  p->validYMD = 1;
18987 }
18988 
18989 /*
18990 ** Compute the Hour, Minute, and Seconds from the julian day number.
18991 */
18992 static void computeHMS(DateTime *p){
18993  int s;
18994  if( p->validHMS ) return;
18995  computeJD(p);
18996  s = (int)((p->iJD + 43200000) % 86400000);
18997  p->s = s/1000.0;
18998  s = (int)p->s;
18999  p->s -= s;
19000  p->h = s/3600;
19001  s -= p->h*3600;
19002  p->m = s/60;
19003  p->s += s - p->m*60;
19004  p->validHMS = 1;
19005 }
19006 
19007 /*
19008 ** Compute both YMD and HMS
19009 */
19010 static void computeYMD_HMS(DateTime *p){
19011  computeYMD(p);
19012  computeHMS(p);
19013 }
19014 
19015 /*
19016 ** Clear the YMD and HMS and the TZ
19017 */
19018 static void clearYMD_HMS_TZ(DateTime *p){
19019  p->validYMD = 0;
19020  p->validHMS = 0;
19021  p->validTZ = 0;
19022 }
19023 
19024 #ifndef SQLITE_OMIT_LOCALTIME
19025 /*
19026 ** On recent Windows platforms, the localtime_s() function is available
19027 ** as part of the "Secure CRT". It is essentially equivalent to
19028 ** localtime_r() available under most POSIX platforms, except that the
19029 ** order of the parameters is reversed.
19030 **
19031 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
19032 **
19033 ** If the user has not indicated to use localtime_r() or localtime_s()
19034 ** already, check for an MSVC build environment that provides
19035 ** localtime_s().
19036 */
19037 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
19038  && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
19039 #undef HAVE_LOCALTIME_S
19040 #define HAVE_LOCALTIME_S 1
19041 #endif
19042 
19043 /*
19044 ** The following routine implements the rough equivalent of localtime_r()
19045 ** using whatever operating-system specific localtime facility that
19046 ** is available. This routine returns 0 on success and
19047 ** non-zero on any kind of error.
19048 **
19049 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
19050 ** routine will always fail.
19051 **
19052 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
19053 ** library function localtime_r() is used to assist in the calculation of
19054 ** local time.
19055 */
19056 static int osLocaltime(time_t *t, struct tm *pTm){
19057  int rc;
19058 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
19059  struct tm *pX;
19060 #if SQLITE_THREADSAFE>0
19061  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
19062 #endif
19063  sqlite3_mutex_enter(mutex);
19064  pX = localtime(t);
19065 #ifndef SQLITE_OMIT_BUILTIN_TEST
19066  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
19067 #endif
19068  if( pX ) *pTm = *pX;
19069  sqlite3_mutex_leave(mutex);
19070  rc = pX==0;
19071 #else
19072 #ifndef SQLITE_OMIT_BUILTIN_TEST
19073  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
19074 #endif
19075 #if HAVE_LOCALTIME_R
19076  rc = localtime_r(t, pTm)==0;
19077 #else
19078  rc = localtime_s(pTm, t);
19079 #endif /* HAVE_LOCALTIME_R */
19080 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
19081  return rc;
19082 }
19083 #endif /* SQLITE_OMIT_LOCALTIME */
19084 
19085 
19086 #ifndef SQLITE_OMIT_LOCALTIME
19087 /*
19088 ** Compute the difference (in milliseconds) between localtime and UTC
19089 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
19090 ** return this value and set *pRc to SQLITE_OK.
19091 **
19092 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
19093 ** is undefined in this case.
19094 */
19095 static sqlite3_int64 localtimeOffset(
19096  DateTime *p, /* Date at which to calculate offset */
19097  sqlite3_context *pCtx, /* Write error here if one occurs */
19098  int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
19099 ){
19100  DateTime x, y;
19101  time_t t;
19102  struct tm sLocal;
19103 
19104  /* Initialize the contents of sLocal to avoid a compiler warning. */
19105  memset(&sLocal, 0, sizeof(sLocal));
19106 
19107  x = *p;
19108  computeYMD_HMS(&x);
19109  if( x.Y<1971 || x.Y>=2038 ){
19110  /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
19111  ** works for years between 1970 and 2037. For dates outside this range,
19112  ** SQLite attempts to map the year into an equivalent year within this
19113  ** range, do the calculation, then map the year back.
19114  */
19115  x.Y = 2000;
19116  x.M = 1;
19117  x.D = 1;
19118  x.h = 0;
19119  x.m = 0;
19120  x.s = 0.0;
19121  } else {
19122  int s = (int)(x.s + 0.5);
19123  x.s = s;
19124  }
19125  x.tz = 0;
19126  x.validJD = 0;
19127  computeJD(&x);
19128  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
19129  if( osLocaltime(&t, &sLocal) ){
19130  sqlite3_result_error(pCtx, "local time unavailable", -1);
19131  *pRc = SQLITE_ERROR;
19132  return 0;
19133  }
19134  y.Y = sLocal.tm_year + 1900;
19135  y.M = sLocal.tm_mon + 1;
19136  y.D = sLocal.tm_mday;
19137  y.h = sLocal.tm_hour;
19138  y.m = sLocal.tm_min;
19139  y.s = sLocal.tm_sec;
19140  y.validYMD = 1;
19141  y.validHMS = 1;
19142  y.validJD = 0;
19143  y.validTZ = 0;
19144  computeJD(&y);
19145  *pRc = SQLITE_OK;
19146  return y.iJD - x.iJD;
19147 }
19148 #endif /* SQLITE_OMIT_LOCALTIME */
19149 
19150 /*
19151 ** Process a modifier to a date-time stamp. The modifiers are
19152 ** as follows:
19153 **
19154 ** NNN days
19155 ** NNN hours
19156 ** NNN minutes
19157 ** NNN.NNNN seconds
19158 ** NNN months
19159 ** NNN years
19160 ** start of month
19161 ** start of year
19162 ** start of week
19163 ** start of day
19164 ** weekday N
19165 ** unixepoch
19166 ** localtime
19167 ** utc
19168 **
19169 ** Return 0 on success and 1 if there is any kind of error. If the error
19170 ** is in a system call (i.e. localtime()), then an error message is written
19171 ** to context pCtx. If the error is an unrecognized modifier, no error is
19172 ** written to pCtx.
19173 */
19174 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
19175  int rc = 1;
19176  int n;
19177  double r;
19178  char *z, zBuf[30];
19179  z = zBuf;
19180  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
19181  z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
19182  }
19183  z[n] = 0;
19184  switch( z[0] ){
19185 #ifndef SQLITE_OMIT_LOCALTIME
19186  case 'l': {
19187  /* localtime
19188  **
19189  ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
19190  ** show local time.
19191  */
19192  if( strcmp(z, "localtime")==0 ){
19193  computeJD(p);
19194  p->iJD += localtimeOffset(p, pCtx, &rc);
19195  clearYMD_HMS_TZ(p);
19196  }
19197  break;
19198  }
19199 #endif
19200  case 'u': {
19201  /*
19202  ** unixepoch
19203  **
19204  ** Treat the current value of p->iJD as the number of
19205  ** seconds since 1970. Convert to a real julian day number.
19206  */
19207  if( strcmp(z, "unixepoch")==0 && p->validJD ){
19208  p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
19209  clearYMD_HMS_TZ(p);
19210  rc = 0;
19211  }
19212 #ifndef SQLITE_OMIT_LOCALTIME
19213  else if( strcmp(z, "utc")==0 ){
19214  if( p->tzSet==0 ){
19215  sqlite3_int64 c1;
19216  computeJD(p);
19217  c1 = localtimeOffset(p, pCtx, &rc);
19218  if( rc==SQLITE_OK ){
19219  p->iJD -= c1;
19220  clearYMD_HMS_TZ(p);
19221  p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
19222  }
19223  p->tzSet = 1;
19224  }else{
19225  rc = SQLITE_OK;
19226  }
19227  }
19228 #endif
19229  break;
19230  }
19231  case 'w': {
19232  /*
19233  ** weekday N
19234  **
19235  ** Move the date to the same time on the next occurrence of
19236  ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
19237  ** date is already on the appropriate weekday, this is a no-op.
19238  */
19239  if( strncmp(z, "weekday ", 8)==0
19240  && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
19241  && (n=(int)r)==r && n>=0 && r<7 ){
19242  sqlite3_int64 Z;
19243  computeYMD_HMS(p);
19244  p->validTZ = 0;
19245  p->validJD = 0;
19246  computeJD(p);
19247  Z = ((p->iJD + 129600000)/86400000) % 7;
19248  if( Z>n ) Z -= 7;
19249  p->iJD += (n - Z)*86400000;
19250  clearYMD_HMS_TZ(p);
19251  rc = 0;
19252  }
19253  break;
19254  }
19255  case 's': {
19256  /*
19257  ** start of TTTTT
19258  **
19259  ** Move the date backwards to the beginning of the current day,
19260  ** or month or year.
19261  */
19262  if( strncmp(z, "start of ", 9)!=0 ) break;
19263  z += 9;
19264  computeYMD(p);
19265  p->validHMS = 1;
19266  p->h = p->m = 0;
19267  p->s = 0.0;
19268  p->validTZ = 0;
19269  p->validJD = 0;
19270  if( strcmp(z,"month")==0 ){
19271  p->D = 1;
19272  rc = 0;
19273  }else if( strcmp(z,"year")==0 ){
19274  computeYMD(p);
19275  p->M = 1;
19276  p->D = 1;
19277  rc = 0;
19278  }else if( strcmp(z,"day")==0 ){
19279  rc = 0;
19280  }
19281  break;
19282  }
19283  case '+':
19284  case '-':
19285  case '0':
19286  case '1':
19287  case '2':
19288  case '3':
19289  case '4':
19290  case '5':
19291  case '6':
19292  case '7':
19293  case '8':
19294  case '9': {
19295  double rRounder;
19296  for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
19297  if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
19298  rc = 1;
19299  break;
19300  }
19301  if( z[n]==':' ){
19302  /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
19303  ** specified number of hours, minutes, seconds, and fractional seconds
19304  ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
19305  ** omitted.
19306  */
19307  const char *z2 = z;
19308  DateTime tx;
19309  sqlite3_int64 day;
19310  if( !sqlite3Isdigit(*z2) ) z2++;
19311  memset(&tx, 0, sizeof(tx));
19312  if( parseHhMmSs(z2, &tx) ) break;
19313  computeJD(&tx);
19314  tx.iJD -= 43200000;
19315  day = tx.iJD/86400000;
19316  tx.iJD -= day*86400000;
19317  if( z[0]=='-' ) tx.iJD = -tx.iJD;
19318  computeJD(p);
19319  clearYMD_HMS_TZ(p);
19320  p->iJD += tx.iJD;
19321  rc = 0;
19322  break;
19323  }
19324  z += n;
19325  while( sqlite3Isspace(*z) ) z++;
19326  n = sqlite3Strlen30(z);
19327  if( n>10 || n<3 ) break;
19328  if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
19329  computeJD(p);
19330  rc = 0;
19331  rRounder = r<0 ? -0.5 : +0.5;
19332  if( n==3 && strcmp(z,"day")==0 ){
19333  p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
19334  }else if( n==4 && strcmp(z,"hour")==0 ){
19335  p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
19336  }else if( n==6 && strcmp(z,"minute")==0 ){
19337  p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
19338  }else if( n==6 && strcmp(z,"second")==0 ){
19339  p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
19340  }else if( n==5 && strcmp(z,"month")==0 ){
19341  int x, y;
19342  computeYMD_HMS(p);
19343  p->M += (int)r;
19344  x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
19345  p->Y += x;
19346  p->M -= x*12;
19347  p->validJD = 0;
19348  computeJD(p);
19349  y = (int)r;
19350  if( y!=r ){
19351  p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
19352  }
19353  }else if( n==4 && strcmp(z,"year")==0 ){
19354  int y = (int)r;
19355  computeYMD_HMS(p);
19356  p->Y += y;
19357  p->validJD = 0;
19358  computeJD(p);
19359  if( y!=r ){
19360  p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
19361  }
19362  }else{
19363  rc = 1;
19364  }
19365  clearYMD_HMS_TZ(p);
19366  break;
19367  }
19368  default: {
19369  break;
19370  }
19371  }
19372  return rc;
19373 }
19374 
19375 /*
19376 ** Process time function arguments. argv[0] is a date-time stamp.
19377 ** argv[1] and following are modifiers. Parse them all and write
19378 ** the resulting time into the DateTime structure p. Return 0
19379 ** on success and 1 if there are any errors.
19380 **
19381 ** If there are zero parameters (if even argv[0] is undefined)
19382 ** then assume a default value of "now" for argv[0].
19383 */
19384 static int isDate(
19385  sqlite3_context *context,
19386  int argc,
19387  sqlite3_value **argv,
19388  DateTime *p
19389 ){
19390  int i;
19391  const unsigned char *z;
19392  int eType;
19393  memset(p, 0, sizeof(*p));
19394  if( argc==0 ){
19395  return setDateTimeToCurrent(context, p);
19396  }
19397  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
19398  || eType==SQLITE_INTEGER ){
19399  p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
19400  p->validJD = 1;
19401  }else{
19402  z = sqlite3_value_text(argv[0]);
19403  if( !z || parseDateOrTime(context, (char*)z, p) ){
19404  return 1;
19405  }
19406  }
19407  for(i=1; i<argc; i++){
19408  z = sqlite3_value_text(argv[i]);
19409  if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
19410  }
19411  return 0;
19412 }
19413 
19414 
19415 /*
19416 ** The following routines implement the various date and time functions
19417 ** of SQLite.
19418 */
19419 
19420 /*
19421 ** julianday( TIMESTRING, MOD, MOD, ...)
19422 **
19423 ** Return the julian day number of the date specified in the arguments
19424 */
19425 static void juliandayFunc(
19426  sqlite3_context *context,
19427  int argc,
19428  sqlite3_value **argv
19429 ){
19430  DateTime x;
19431  if( isDate(context, argc, argv, &x)==0 ){
19432  computeJD(&x);
19433  sqlite3_result_double(context, x.iJD/86400000.0);
19434  }
19435 }
19436 
19437 /*
19438 ** datetime( TIMESTRING, MOD, MOD, ...)
19439 **
19440 ** Return YYYY-MM-DD HH:MM:SS
19441 */
19442 static void datetimeFunc(
19443  sqlite3_context *context,
19444  int argc,
19445  sqlite3_value **argv
19446 ){
19447  DateTime x;
19448  if( isDate(context, argc, argv, &x)==0 ){
19449  char zBuf[100];
19450  computeYMD_HMS(&x);
19451  sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
19452  x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
19453  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19454  }
19455 }
19456 
19457 /*
19458 ** time( TIMESTRING, MOD, MOD, ...)
19459 **
19460 ** Return HH:MM:SS
19461 */
19462 static void timeFunc(
19463  sqlite3_context *context,
19464  int argc,
19465  sqlite3_value **argv
19466 ){
19467  DateTime x;
19468  if( isDate(context, argc, argv, &x)==0 ){
19469  char zBuf[100];
19470  computeHMS(&x);
19471  sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
19472  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19473  }
19474 }
19475 
19476 /*
19477 ** date( TIMESTRING, MOD, MOD, ...)
19478 **
19479 ** Return YYYY-MM-DD
19480 */
19481 static void dateFunc(
19482  sqlite3_context *context,
19483  int argc,
19484  sqlite3_value **argv
19485 ){
19486  DateTime x;
19487  if( isDate(context, argc, argv, &x)==0 ){
19488  char zBuf[100];
19489  computeYMD(&x);
19490  sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
19491  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19492  }
19493 }
19494 
19495 /*
19496 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
19497 **
19498 ** Return a string described by FORMAT. Conversions as follows:
19499 **
19500 ** %d day of month
19501 ** %f ** fractional seconds SS.SSS
19502 ** %H hour 00-24
19503 ** %j day of year 000-366
19504 ** %J ** julian day number
19505 ** %m month 01-12
19506 ** %M minute 00-59
19507 ** %s seconds since 1970-01-01
19508 ** %S seconds 00-59
19509 ** %w day of week 0-6 sunday==0
19510 ** %W week of year 00-53
19511 ** %Y year 0000-9999
19512 ** %% %
19513 */
19514 static void strftimeFunc(
19515  sqlite3_context *context,
19516  int argc,
19517  sqlite3_value **argv
19518 ){
19519  DateTime x;
19520  u64 n;
19521  size_t i,j;
19522  char *z;
19523  sqlite3 *db;
19524  const char *zFmt;
19525  char zBuf[100];
19526  if( argc==0 ) return;
19527  zFmt = (const char*)sqlite3_value_text(argv[0]);
19528  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
19529  db = sqlite3_context_db_handle(context);
19530  for(i=0, n=1; zFmt[i]; i++, n++){
19531  if( zFmt[i]=='%' ){
19532  switch( zFmt[i+1] ){
19533  case 'd':
19534  case 'H':
19535  case 'm':
19536  case 'M':
19537  case 'S':
19538  case 'W':
19539  n++;
19540  /* fall thru */
19541  case 'w':
19542  case '%':
19543  break;
19544  case 'f':
19545  n += 8;
19546  break;
19547  case 'j':
19548  n += 3;
19549  break;
19550  case 'Y':
19551  n += 8;
19552  break;
19553  case 's':
19554  case 'J':
19555  n += 50;
19556  break;
19557  default:
19558  return; /* ERROR. return a NULL */
19559  }
19560  i++;
19561  }
19562  }
19563  testcase( n==sizeof(zBuf)-1 );
19564  testcase( n==sizeof(zBuf) );
19565  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
19566  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
19567  if( n<sizeof(zBuf) ){
19568  z = zBuf;
19569  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
19570  sqlite3_result_error_toobig(context);
19571  return;
19572  }else{
19573  z = sqlite3DbMallocRawNN(db, (int)n);
19574  if( z==0 ){
19575  sqlite3_result_error_nomem(context);
19576  return;
19577  }
19578  }
19579  computeJD(&x);
19580  computeYMD_HMS(&x);
19581  for(i=j=0; zFmt[i]; i++){
19582  if( zFmt[i]!='%' ){
19583  z[j++] = zFmt[i];
19584  }else{
19585  i++;
19586  switch( zFmt[i] ){
19587  case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
19588  case 'f': {
19589  double s = x.s;
19590  if( s>59.999 ) s = 59.999;
19591  sqlite3_snprintf(7, &z[j],"%06.3f", s);
19592  j += sqlite3Strlen30(&z[j]);
19593  break;
19594  }
19595  case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
19596  case 'W': /* Fall thru */
19597  case 'j': {
19598  int nDay; /* Number of days since 1st day of year */
19599  DateTime y = x;
19600  y.validJD = 0;
19601  y.M = 1;
19602  y.D = 1;
19603  computeJD(&y);
19604  nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
19605  if( zFmt[i]=='W' ){
19606  int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
19607  wd = (int)(((x.iJD+43200000)/86400000)%7);
19608  sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
19609  j += 2;
19610  }else{
19611  sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
19612  j += 3;
19613  }
19614  break;
19615  }
19616  case 'J': {
19617  sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
19618  j+=sqlite3Strlen30(&z[j]);
19619  break;
19620  }
19621  case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
19622  case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
19623  case 's': {
19624  sqlite3_snprintf(30,&z[j],"%lld",
19625  (i64)(x.iJD/1000 - 21086676*(i64)10000));
19626  j += sqlite3Strlen30(&z[j]);
19627  break;
19628  }
19629  case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
19630  case 'w': {
19631  z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
19632  break;
19633  }
19634  case 'Y': {
19635  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
19636  break;
19637  }
19638  default: z[j++] = '%'; break;
19639  }
19640  }
19641  }
19642  z[j] = 0;
19643  sqlite3_result_text(context, z, -1,
19644  z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
19645 }
19646 
19647 /*
19648 ** current_time()
19649 **
19650 ** This function returns the same value as time('now').
19651 */
19652 static void ctimeFunc(
19653  sqlite3_context *context,
19654  int NotUsed,
19655  sqlite3_value **NotUsed2
19656 ){
19657  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19658  timeFunc(context, 0, 0);
19659 }
19660 
19661 /*
19662 ** current_date()
19663 **
19664 ** This function returns the same value as date('now').
19665 */
19666 static void cdateFunc(
19667  sqlite3_context *context,
19668  int NotUsed,
19669  sqlite3_value **NotUsed2
19670 ){
19671  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19672  dateFunc(context, 0, 0);
19673 }
19674 
19675 /*
19676 ** current_timestamp()
19677 **
19678 ** This function returns the same value as datetime('now').
19679 */
19680 static void ctimestampFunc(
19681  sqlite3_context *context,
19682  int NotUsed,
19683  sqlite3_value **NotUsed2
19684 ){
19685  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19686  datetimeFunc(context, 0, 0);
19687 }
19688 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
19689 
19690 #ifdef SQLITE_OMIT_DATETIME_FUNCS
19691 /*
19692 ** If the library is compiled to omit the full-scale date and time
19693 ** handling (to get a smaller binary), the following minimal version
19694 ** of the functions current_time(), current_date() and current_timestamp()
19695 ** are included instead. This is to support column declarations that
19696 ** include "DEFAULT CURRENT_TIME" etc.
19697 **
19698 ** This function uses the C-library functions time(), gmtime()
19699 ** and strftime(). The format string to pass to strftime() is supplied
19700 ** as the user-data for the function.
19701 */
19702 static void currentTimeFunc(
19703  sqlite3_context *context,
19704  int argc,
19705  sqlite3_value **argv
19706 ){
19707  time_t t;
19708  char *zFormat = (char *)sqlite3_user_data(context);
19709  sqlite3_int64 iT;
19710  struct tm *pTm;
19711  struct tm sNow;
19712  char zBuf[20];
19713 
19714  UNUSED_PARAMETER(argc);
19715  UNUSED_PARAMETER(argv);
19716 
19717  iT = sqlite3StmtCurrentTime(context);
19718  if( iT<=0 ) return;
19719  t = iT/1000 - 10000*(sqlite3_int64)21086676;
19720 #if HAVE_GMTIME_R
19721  pTm = gmtime_r(&t, &sNow);
19722 #else
19723  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
19724  pTm = gmtime(&t);
19725  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
19726  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
19727 #endif
19728  if( pTm ){
19729  strftime(zBuf, 20, zFormat, &sNow);
19730  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19731  }
19732 }
19733 #endif
19734 
19735 /*
19736 ** This function registered all of the above C functions as SQL
19737 ** functions. This should be the only routine in this file with
19738 ** external linkage.
19739 */
19740 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
19741  static FuncDef aDateTimeFuncs[] = {
19742 #ifndef SQLITE_OMIT_DATETIME_FUNCS
19743  DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
19744  DFUNCTION(date, -1, 0, 0, dateFunc ),
19745  DFUNCTION(time, -1, 0, 0, timeFunc ),
19746  DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
19747  DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
19748  DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
19749  DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
19750  DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
19751 #else
19752  STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
19753  STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
19754  STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
19755 #endif
19756  };
19757  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
19758 }
19759 
19760 /************** End of date.c ************************************************/
19761 /************** Begin file os.c **********************************************/
19762 /*
19763 ** 2005 November 29
19764 **
19765 ** The author disclaims copyright to this source code. In place of
19766 ** a legal notice, here is a blessing:
19767 **
19768 ** May you do good and not evil.
19769 ** May you find forgiveness for yourself and forgive others.
19770 ** May you share freely, never taking more than you give.
19771 **
19772 ******************************************************************************
19773 **
19774 ** This file contains OS interface code that is common to all
19775 ** architectures.
19776 */
19777 /* #include "sqliteInt.h" */
19778 
19779 /*
19780 ** If we compile with the SQLITE_TEST macro set, then the following block
19781 ** of code will give us the ability to simulate a disk I/O error. This
19782 ** is used for testing the I/O recovery logic.
19783 */
19784 #if defined(SQLITE_TEST)
19785 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
19786 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
19787 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
19788 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
19789 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
19790 SQLITE_API int sqlite3_diskfull_pending = 0;
19791 SQLITE_API int sqlite3_diskfull = 0;
19792 #endif /* defined(SQLITE_TEST) */
19793 
19794 /*
19795 ** When testing, also keep a count of the number of open files.
19796 */
19797 #if defined(SQLITE_TEST)
19798 SQLITE_API int sqlite3_open_file_count = 0;
19799 #endif /* defined(SQLITE_TEST) */
19800 
19801 /*
19802 ** The default SQLite sqlite3_vfs implementations do not allocate
19803 ** memory (actually, os_unix.c allocates a small amount of memory
19804 ** from within OsOpen()), but some third-party implementations may.
19805 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
19806 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
19807 **
19808 ** The following functions are instrumented for malloc() failure
19809 ** testing:
19810 **
19811 ** sqlite3OsRead()
19812 ** sqlite3OsWrite()
19813 ** sqlite3OsSync()
19814 ** sqlite3OsFileSize()
19815 ** sqlite3OsLock()
19816 ** sqlite3OsCheckReservedLock()
19817 ** sqlite3OsFileControl()
19818 ** sqlite3OsShmMap()
19819 ** sqlite3OsOpen()
19820 ** sqlite3OsDelete()
19821 ** sqlite3OsAccess()
19822 ** sqlite3OsFullPathname()
19823 **
19824 */
19825 #if defined(SQLITE_TEST)
19826 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
19827  #define DO_OS_MALLOC_TEST(x) \
19828  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
19829  void *pTstAlloc = sqlite3Malloc(10); \
19830  if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
19831  sqlite3_free(pTstAlloc); \
19832  }
19833 #else
19834  #define DO_OS_MALLOC_TEST(x)
19835 #endif
19836 
19837 /*
19838 ** The following routines are convenience wrappers around methods
19839 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
19840 ** of this would be completely automatic if SQLite were coded using
19841 ** C++ instead of plain old C.
19842 */
19843 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
19844  if( pId->pMethods ){
19845  pId->pMethods->xClose(pId);
19846  pId->pMethods = 0;
19847  }
19848 }
19849 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
19850  DO_OS_MALLOC_TEST(id);
19851  return id->pMethods->xRead(id, pBuf, amt, offset);
19852 }
19853 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
19854  DO_OS_MALLOC_TEST(id);
19855  return id->pMethods->xWrite(id, pBuf, amt, offset);
19856 }
19857 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
19858  return id->pMethods->xTruncate(id, size);
19859 }
19860 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
19861  DO_OS_MALLOC_TEST(id);
19862  return id->pMethods->xSync(id, flags);
19863 }
19864 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
19865  DO_OS_MALLOC_TEST(id);
19866  return id->pMethods->xFileSize(id, pSize);
19867 }
19868 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
19869  DO_OS_MALLOC_TEST(id);
19870  return id->pMethods->xLock(id, lockType);
19871 }
19872 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
19873  return id->pMethods->xUnlock(id, lockType);
19874 }
19875 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
19876  DO_OS_MALLOC_TEST(id);
19877  return id->pMethods->xCheckReservedLock(id, pResOut);
19878 }
19879 
19880 /*
19881 ** Use sqlite3OsFileControl() when we are doing something that might fail
19882 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
19883 ** when simply tossing information over the wall to the VFS and we do not
19884 ** really care if the VFS receives and understands the information since it
19885 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
19886 ** routine has no return value since the return value would be meaningless.
19887 */
19888 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
19889 #ifdef SQLITE_TEST
19890  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
19891  /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
19892  ** is using a regular VFS, it is called after the corresponding
19893  ** transaction has been committed. Injecting a fault at this point
19894  ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
19895  ** but the transaction is committed anyway.
19896  **
19897  ** The core must call OsFileControl() though, not OsFileControlHint(),
19898  ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
19899  ** means the commit really has failed and an error should be returned
19900  ** to the user. */
19901  DO_OS_MALLOC_TEST(id);
19902  }
19903 #endif
19904  return id->pMethods->xFileControl(id, op, pArg);
19905 }
19906 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
19907  (void)id->pMethods->xFileControl(id, op, pArg);
19908 }
19909 
19910 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
19911  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
19912  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
19913 }
19914 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
19915  return id->pMethods->xDeviceCharacteristics(id);
19916 }
19917 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
19918  return id->pMethods->xShmLock(id, offset, n, flags);
19919 }
19920 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
19921  id->pMethods->xShmBarrier(id);
19922 }
19923 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
19924  return id->pMethods->xShmUnmap(id, deleteFlag);
19925 }
19926 SQLITE_PRIVATE int sqlite3OsShmMap(
19927  sqlite3_file *id, /* Database file handle */
19928  int iPage,
19929  int pgsz,
19930  int bExtend, /* True to extend file if necessary */
19931  void volatile **pp /* OUT: Pointer to mapping */
19932 ){
19933  DO_OS_MALLOC_TEST(id);
19934  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
19935 }
19936 
19937 #if SQLITE_MAX_MMAP_SIZE>0
19938 /* The real implementation of xFetch and xUnfetch */
19939 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19940  DO_OS_MALLOC_TEST(id);
19941  return id->pMethods->xFetch(id, iOff, iAmt, pp);
19942 }
19943 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19944  return id->pMethods->xUnfetch(id, iOff, p);
19945 }
19946 #else
19947 /* No-op stubs to use when memory-mapped I/O is disabled */
19948 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19949  *pp = 0;
19950  return SQLITE_OK;
19951 }
19952 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19953  return SQLITE_OK;
19954 }
19955 #endif
19956 
19957 /*
19958 ** The next group of routines are convenience wrappers around the
19959 ** VFS methods.
19960 */
19961 SQLITE_PRIVATE int sqlite3OsOpen(
19962  sqlite3_vfs *pVfs,
19963  const char *zPath,
19964  sqlite3_file *pFile,
19965  int flags,
19966  int *pFlagsOut
19967 ){
19968  int rc;
19969  DO_OS_MALLOC_TEST(0);
19970  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
19971  ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
19972  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
19973  ** reaching the VFS. */
19974  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
19975  assert( rc==SQLITE_OK || pFile->pMethods==0 );
19976  return rc;
19977 }
19978 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
19979  DO_OS_MALLOC_TEST(0);
19980  assert( dirSync==0 || dirSync==1 );
19981  return pVfs->xDelete(pVfs, zPath, dirSync);
19982 }
19983 SQLITE_PRIVATE int sqlite3OsAccess(
19984  sqlite3_vfs *pVfs,
19985  const char *zPath,
19986  int flags,
19987  int *pResOut
19988 ){
19989  DO_OS_MALLOC_TEST(0);
19990  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
19991 }
19992 SQLITE_PRIVATE int sqlite3OsFullPathname(
19993  sqlite3_vfs *pVfs,
19994  const char *zPath,
19995  int nPathOut,
19996  char *zPathOut
19997 ){
19998  DO_OS_MALLOC_TEST(0);
19999  zPathOut[0] = 0;
20000  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
20001 }
20002 #ifndef SQLITE_OMIT_LOAD_EXTENSION
20003 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
20004  return pVfs->xDlOpen(pVfs, zPath);
20005 }
20006 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
20007  pVfs->xDlError(pVfs, nByte, zBufOut);
20008 }
20009 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
20010  return pVfs->xDlSym(pVfs, pHdle, zSym);
20011 }
20012 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
20013  pVfs->xDlClose(pVfs, pHandle);
20014 }
20015 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
20016 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
20017  return pVfs->xRandomness(pVfs, nByte, zBufOut);
20018 }
20019 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
20020  return pVfs->xSleep(pVfs, nMicro);
20021 }
20022 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
20023  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
20024 }
20025 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
20026  int rc;
20027  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
20028  ** method to get the current date and time if that method is available
20029  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
20030  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
20031  ** unavailable.
20032  */
20033  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
20034  rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
20035  }else{
20036  double r;
20037  rc = pVfs->xCurrentTime(pVfs, &r);
20038  *pTimeOut = (sqlite3_int64)(r*86400000.0);
20039  }
20040  return rc;
20041 }
20042 
20043 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
20044  sqlite3_vfs *pVfs,
20045  const char *zFile,
20046  sqlite3_file **ppFile,
20047  int flags,
20048  int *pOutFlags
20049 ){
20050  int rc;
20051  sqlite3_file *pFile;
20052  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
20053  if( pFile ){
20054  rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
20055  if( rc!=SQLITE_OK ){
20056  sqlite3_free(pFile);
20057  }else{
20058  *ppFile = pFile;
20059  }
20060  }else{
20061  rc = SQLITE_NOMEM_BKPT;
20062  }
20063  return rc;
20064 }
20065 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
20066  assert( pFile );
20067  sqlite3OsClose(pFile);
20068  sqlite3_free(pFile);
20069 }
20070 
20071 /*
20072 ** This function is a wrapper around the OS specific implementation of
20073 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
20074 ** ability to simulate a malloc failure, so that the handling of an
20075 ** error in sqlite3_os_init() by the upper layers can be tested.
20076 */
20077 SQLITE_PRIVATE int sqlite3OsInit(void){
20078  void *p = sqlite3_malloc(10);
20079  if( p==0 ) return SQLITE_NOMEM_BKPT;
20080  sqlite3_free(p);
20081  return sqlite3_os_init();
20082 }
20083 
20084 /*
20085 ** The list of all registered VFS implementations.
20086 */
20087 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
20088 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
20089 
20090 /*
20091 ** Locate a VFS by name. If no name is given, simply return the
20092 ** first VFS on the list.
20093 */
20094 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
20095  sqlite3_vfs *pVfs = 0;
20096 #if SQLITE_THREADSAFE
20097  sqlite3_mutex *mutex;
20098 #endif
20099 #ifndef SQLITE_OMIT_AUTOINIT
20100  int rc = sqlite3_initialize();
20101  if( rc ) return 0;
20102 #endif
20103 #if SQLITE_THREADSAFE
20104  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20105 #endif
20106  sqlite3_mutex_enter(mutex);
20107  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
20108  if( zVfs==0 ) break;
20109  if( strcmp(zVfs, pVfs->zName)==0 ) break;
20110  }
20111  sqlite3_mutex_leave(mutex);
20112  return pVfs;
20113 }
20114 
20115 /*
20116 ** Unlink a VFS from the linked list
20117 */
20118 static void vfsUnlink(sqlite3_vfs *pVfs){
20119  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
20120  if( pVfs==0 ){
20121  /* No-op */
20122  }else if( vfsList==pVfs ){
20123  vfsList = pVfs->pNext;
20124  }else if( vfsList ){
20125  sqlite3_vfs *p = vfsList;
20126  while( p->pNext && p->pNext!=pVfs ){
20127  p = p->pNext;
20128  }
20129  if( p->pNext==pVfs ){
20130  p->pNext = pVfs->pNext;
20131  }
20132  }
20133 }
20134 
20135 /*
20136 ** Register a VFS with the system. It is harmless to register the same
20137 ** VFS multiple times. The new VFS becomes the default if makeDflt is
20138 ** true.
20139 */
20140 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
20141  MUTEX_LOGIC(sqlite3_mutex *mutex;)
20142 #ifndef SQLITE_OMIT_AUTOINIT
20143  int rc = sqlite3_initialize();
20144  if( rc ) return rc;
20145 #endif
20146 #ifdef SQLITE_ENABLE_API_ARMOR
20147  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
20148 #endif
20149 
20150  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
20151  sqlite3_mutex_enter(mutex);
20152  vfsUnlink(pVfs);
20153  if( makeDflt || vfsList==0 ){
20154  pVfs->pNext = vfsList;
20155  vfsList = pVfs;
20156  }else{
20157  pVfs->pNext = vfsList->pNext;
20158  vfsList->pNext = pVfs;
20159  }
20160  assert(vfsList);
20161  sqlite3_mutex_leave(mutex);
20162  return SQLITE_OK;
20163 }
20164 
20165 /*
20166 ** Unregister a VFS so that it is no longer accessible.
20167 */
20168 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
20169 #if SQLITE_THREADSAFE
20170  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20171 #endif
20172  sqlite3_mutex_enter(mutex);
20173  vfsUnlink(pVfs);
20174  sqlite3_mutex_leave(mutex);
20175  return SQLITE_OK;
20176 }
20177 
20178 /************** End of os.c **************************************************/
20179 /************** Begin file fault.c *******************************************/
20180 /*
20181 ** 2008 Jan 22
20182 **
20183 ** The author disclaims copyright to this source code. In place of
20184 ** a legal notice, here is a blessing:
20185 **
20186 ** May you do good and not evil.
20187 ** May you find forgiveness for yourself and forgive others.
20188 ** May you share freely, never taking more than you give.
20189 **
20190 *************************************************************************
20191 **
20192 ** This file contains code to support the concept of "benign"
20193 ** malloc failures (when the xMalloc() or xRealloc() method of the
20194 ** sqlite3_mem_methods structure fails to allocate a block of memory
20195 ** and returns 0).
20196 **
20197 ** Most malloc failures are non-benign. After they occur, SQLite
20198 ** abandons the current operation and returns an error code (usually
20199 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
20200 ** fatal. For example, if a malloc fails while resizing a hash table, this
20201 ** is completely recoverable simply by not carrying out the resize. The
20202 ** hash table will continue to function normally. So a malloc failure
20203 ** during a hash table resize is a benign fault.
20204 */
20205 
20206 /* #include "sqliteInt.h" */
20207 
20208 #ifndef SQLITE_OMIT_BUILTIN_TEST
20209 
20210 /*
20211 ** Global variables.
20212 */
20213 typedef struct BenignMallocHooks BenignMallocHooks;
20214 static SQLITE_WSD struct BenignMallocHooks {
20215  void (*xBenignBegin)(void);
20216  void (*xBenignEnd)(void);
20217 } sqlite3Hooks = { 0, 0 };
20218 
20219 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
20220 ** structure. If writable static data is unsupported on the target,
20221 ** we have to locate the state vector at run-time. In the more common
20222 ** case where writable static data is supported, wsdHooks can refer directly
20223 ** to the "sqlite3Hooks" state vector declared above.
20224 */
20225 #ifdef SQLITE_OMIT_WSD
20226 # define wsdHooksInit \
20227  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
20228 # define wsdHooks x[0]
20229 #else
20230 # define wsdHooksInit
20231 # define wsdHooks sqlite3Hooks
20232 #endif
20233 
20234 
20235 /*
20236 ** Register hooks to call when sqlite3BeginBenignMalloc() and
20237 ** sqlite3EndBenignMalloc() are called, respectively.
20238 */
20239 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
20240  void (*xBenignBegin)(void),
20241  void (*xBenignEnd)(void)
20242 ){
20243  wsdHooksInit;
20244  wsdHooks.xBenignBegin = xBenignBegin;
20245  wsdHooks.xBenignEnd = xBenignEnd;
20246 }
20247 
20248 /*
20249 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
20250 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
20251 ** indicates that subsequent malloc failures are non-benign.
20252 */
20253 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
20254  wsdHooksInit;
20255  if( wsdHooks.xBenignBegin ){
20256  wsdHooks.xBenignBegin();
20257  }
20258 }
20259 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
20260  wsdHooksInit;
20261  if( wsdHooks.xBenignEnd ){
20262  wsdHooks.xBenignEnd();
20263  }
20264 }
20265 
20266 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
20267 
20268 /************** End of fault.c ***********************************************/
20269 /************** Begin file mem0.c ********************************************/
20270 /*
20271 ** 2008 October 28
20272 **
20273 ** The author disclaims copyright to this source code. In place of
20274 ** a legal notice, here is a blessing:
20275 **
20276 ** May you do good and not evil.
20277 ** May you find forgiveness for yourself and forgive others.
20278 ** May you share freely, never taking more than you give.
20279 **
20280 *************************************************************************
20281 **
20282 ** This file contains a no-op memory allocation drivers for use when
20283 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
20284 ** here always fail. SQLite will not operate with these drivers. These
20285 ** are merely placeholders. Real drivers must be substituted using
20286 ** sqlite3_config() before SQLite will operate.
20287 */
20288 /* #include "sqliteInt.h" */
20289 
20290 /*
20291 ** This version of the memory allocator is the default. It is
20292 ** used when no other memory allocator is specified using compile-time
20293 ** macros.
20294 */
20295 #ifdef SQLITE_ZERO_MALLOC
20296 
20297 /*
20298 ** No-op versions of all memory allocation routines
20299 */
20300 static void *sqlite3MemMalloc(int nByte){ return 0; }
20301 static void sqlite3MemFree(void *pPrior){ return; }
20302 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
20303 static int sqlite3MemSize(void *pPrior){ return 0; }
20304 static int sqlite3MemRoundup(int n){ return n; }
20305 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
20306 static void sqlite3MemShutdown(void *NotUsed){ return; }
20307 
20308 /*
20309 ** This routine is the only routine in this file with external linkage.
20310 **
20311 ** Populate the low-level memory allocation function pointers in
20312 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20313 */
20314 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20315  static const sqlite3_mem_methods defaultMethods = {
20316  sqlite3MemMalloc,
20317  sqlite3MemFree,
20318  sqlite3MemRealloc,
20319  sqlite3MemSize,
20320  sqlite3MemRoundup,
20321  sqlite3MemInit,
20322  sqlite3MemShutdown,
20323  0
20324  };
20325  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20326 }
20327 
20328 #endif /* SQLITE_ZERO_MALLOC */
20329 
20330 /************** End of mem0.c ************************************************/
20331 /************** Begin file mem1.c ********************************************/
20332 /*
20333 ** 2007 August 14
20334 **
20335 ** The author disclaims copyright to this source code. In place of
20336 ** a legal notice, here is a blessing:
20337 **
20338 ** May you do good and not evil.
20339 ** May you find forgiveness for yourself and forgive others.
20340 ** May you share freely, never taking more than you give.
20341 **
20342 *************************************************************************
20343 **
20344 ** This file contains low-level memory allocation drivers for when
20345 ** SQLite will use the standard C-library malloc/realloc/free interface
20346 ** to obtain the memory it needs.
20347 **
20348 ** This file contains implementations of the low-level memory allocation
20349 ** routines specified in the sqlite3_mem_methods object. The content of
20350 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
20351 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
20352 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
20353 ** default configuration is to use memory allocation routines in this
20354 ** file.
20355 **
20356 ** C-preprocessor macro summary:
20357 **
20358 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
20359 ** the malloc_usable_size() interface exists
20360 ** on the target platform. Or, this symbol
20361 ** can be set manually, if desired.
20362 ** If an equivalent interface exists by
20363 ** a different name, using a separate -D
20364 ** option to rename it.
20365 **
20366 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
20367 ** memory allocator. Set this symbol to enable
20368 ** building on older macs.
20369 **
20370 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
20371 ** _msize() on windows systems. This might
20372 ** be necessary when compiling for Delphi,
20373 ** for example.
20374 */
20375 /* #include "sqliteInt.h" */
20376 
20377 /*
20378 ** This version of the memory allocator is the default. It is
20379 ** used when no other memory allocator is specified using compile-time
20380 ** macros.
20381 */
20382 #ifdef SQLITE_SYSTEM_MALLOC
20383 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20384 
20385 /*
20386 ** Use the zone allocator available on apple products unless the
20387 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
20388 */
20389 #include <sys/sysctl.h>
20390 #include <malloc/malloc.h>
20391 #include <libkern/OSAtomic.h>
20392 static malloc_zone_t* _sqliteZone_;
20393 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
20394 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
20395 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
20396 #define SQLITE_MALLOCSIZE(x) \
20397  (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
20398 
20399 #else /* if not __APPLE__ */
20400 
20401 /*
20402 ** Use standard C library malloc and free on non-Apple systems.
20403 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
20404 */
20405 #define SQLITE_MALLOC(x) malloc(x)
20406 #define SQLITE_FREE(x) free(x)
20407 #define SQLITE_REALLOC(x,y) realloc((x),(y))
20408 
20409 /*
20410 ** The malloc.h header file is needed for malloc_usable_size() function
20411 ** on some systems (e.g. Linux).
20412 */
20413 #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
20414 # define SQLITE_USE_MALLOC_H 1
20415 # define SQLITE_USE_MALLOC_USABLE_SIZE 1
20416 /*
20417 ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
20418 ** use of _msize() is automatic, but can be disabled by compiling with
20419 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
20420 ** the malloc.h header file.
20421 */
20422 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
20423 # define SQLITE_USE_MALLOC_H
20424 # define SQLITE_USE_MSIZE
20425 #endif
20426 
20427 /*
20428 ** Include the malloc.h header file, if necessary. Also set define macro
20429 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
20430 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
20431 ** The memory size function can always be overridden manually by defining
20432 ** the macro SQLITE_MALLOCSIZE to the desired function name.
20433 */
20434 #if defined(SQLITE_USE_MALLOC_H)
20435 # include <malloc.h>
20436 # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
20437 # if !defined(SQLITE_MALLOCSIZE)
20438 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
20439 # endif
20440 # elif defined(SQLITE_USE_MSIZE)
20441 # if !defined(SQLITE_MALLOCSIZE)
20442 # define SQLITE_MALLOCSIZE _msize
20443 # endif
20444 # endif
20445 #endif /* defined(SQLITE_USE_MALLOC_H) */
20446 
20447 #endif /* __APPLE__ or not __APPLE__ */
20448 
20449 /*
20450 ** Like malloc(), but remember the size of the allocation
20451 ** so that we can find it later using sqlite3MemSize().
20452 **
20453 ** For this low-level routine, we are guaranteed that nByte>0 because
20454 ** cases of nByte<=0 will be intercepted and dealt with by higher level
20455 ** routines.
20456 */
20457 static void *sqlite3MemMalloc(int nByte){
20458 #ifdef SQLITE_MALLOCSIZE
20459  void *p = SQLITE_MALLOC( nByte );
20460  if( p==0 ){
20461  testcase( sqlite3GlobalConfig.xLog!=0 );
20462  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20463  }
20464  return p;
20465 #else
20466  sqlite3_int64 *p;
20467  assert( nByte>0 );
20468  nByte = ROUND8(nByte);
20469  p = SQLITE_MALLOC( nByte+8 );
20470  if( p ){
20471  p[0] = nByte;
20472  p++;
20473  }else{
20474  testcase( sqlite3GlobalConfig.xLog!=0 );
20475  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20476  }
20477  return (void *)p;
20478 #endif
20479 }
20480 
20481 /*
20482 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
20483 ** or sqlite3MemRealloc().
20484 **
20485 ** For this low-level routine, we already know that pPrior!=0 since
20486 ** cases where pPrior==0 will have been intecepted and dealt with
20487 ** by higher-level routines.
20488 */
20489 static void sqlite3MemFree(void *pPrior){
20490 #ifdef SQLITE_MALLOCSIZE
20491  SQLITE_FREE(pPrior);
20492 #else
20493  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20494  assert( pPrior!=0 );
20495  p--;
20496  SQLITE_FREE(p);
20497 #endif
20498 }
20499 
20500 /*
20501 ** Report the allocated size of a prior return from xMalloc()
20502 ** or xRealloc().
20503 */
20504 static int sqlite3MemSize(void *pPrior){
20505 #ifdef SQLITE_MALLOCSIZE
20506  assert( pPrior!=0 );
20507  return (int)SQLITE_MALLOCSIZE(pPrior);
20508 #else
20509  sqlite3_int64 *p;
20510  assert( pPrior!=0 );
20511  p = (sqlite3_int64*)pPrior;
20512  p--;
20513  return (int)p[0];
20514 #endif
20515 }
20516 
20517 /*
20518 ** Like realloc(). Resize an allocation previously obtained from
20519 ** sqlite3MemMalloc().
20520 **
20521 ** For this low-level interface, we know that pPrior!=0. Cases where
20522 ** pPrior==0 while have been intercepted by higher-level routine and
20523 ** redirected to xMalloc. Similarly, we know that nByte>0 because
20524 ** cases where nByte<=0 will have been intercepted by higher-level
20525 ** routines and redirected to xFree.
20526 */
20527 static void *sqlite3MemRealloc(void *pPrior, int nByte){
20528 #ifdef SQLITE_MALLOCSIZE
20529  void *p = SQLITE_REALLOC(pPrior, nByte);
20530  if( p==0 ){
20531  testcase( sqlite3GlobalConfig.xLog!=0 );
20532  sqlite3_log(SQLITE_NOMEM,
20533  "failed memory resize %u to %u bytes",
20534  SQLITE_MALLOCSIZE(pPrior), nByte);
20535  }
20536  return p;
20537 #else
20538  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20539  assert( pPrior!=0 && nByte>0 );
20540  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
20541  p--;
20542  p = SQLITE_REALLOC(p, nByte+8 );
20543  if( p ){
20544  p[0] = nByte;
20545  p++;
20546  }else{
20547  testcase( sqlite3GlobalConfig.xLog!=0 );
20548  sqlite3_log(SQLITE_NOMEM,
20549  "failed memory resize %u to %u bytes",
20550  sqlite3MemSize(pPrior), nByte);
20551  }
20552  return (void*)p;
20553 #endif
20554 }
20555 
20556 /*
20557 ** Round up a request size to the next valid allocation size.
20558 */
20559 static int sqlite3MemRoundup(int n){
20560  return ROUND8(n);
20561 }
20562 
20563 /*
20564 ** Initialize this module.
20565 */
20566 static int sqlite3MemInit(void *NotUsed){
20567 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20568  int cpuCount;
20569  size_t len;
20570  if( _sqliteZone_ ){
20571  return SQLITE_OK;
20572  }
20573  len = sizeof(cpuCount);
20574  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
20575  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
20576  if( cpuCount>1 ){
20577  /* defer MT decisions to system malloc */
20578  _sqliteZone_ = malloc_default_zone();
20579  }else{
20580  /* only 1 core, use our own zone to contention over global locks,
20581  ** e.g. we have our own dedicated locks */
20582  bool success;
20583  malloc_zone_t* newzone = malloc_create_zone(4096, 0);
20584  malloc_set_zone_name(newzone, "Sqlite_Heap");
20585  do{
20586  success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
20587  (void * volatile *)&_sqliteZone_);
20588  }while(!_sqliteZone_);
20589  if( !success ){
20590  /* somebody registered a zone first */
20591  malloc_destroy_zone(newzone);
20592  }
20593  }
20594 #endif
20595  UNUSED_PARAMETER(NotUsed);
20596  return SQLITE_OK;
20597 }
20598 
20599 /*
20600 ** Deinitialize this module.
20601 */
20602 static void sqlite3MemShutdown(void *NotUsed){
20603  UNUSED_PARAMETER(NotUsed);
20604  return;
20605 }
20606 
20607 /*
20608 ** This routine is the only routine in this file with external linkage.
20609 **
20610 ** Populate the low-level memory allocation function pointers in
20611 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20612 */
20613 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20614  static const sqlite3_mem_methods defaultMethods = {
20615  sqlite3MemMalloc,
20616  sqlite3MemFree,
20617  sqlite3MemRealloc,
20618  sqlite3MemSize,
20619  sqlite3MemRoundup,
20620  sqlite3MemInit,
20621  sqlite3MemShutdown,
20622  0
20623  };
20624  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20625 }
20626 
20627 #endif /* SQLITE_SYSTEM_MALLOC */
20628 
20629 /************** End of mem1.c ************************************************/
20630 /************** Begin file mem2.c ********************************************/
20631 /*
20632 ** 2007 August 15
20633 **
20634 ** The author disclaims copyright to this source code. In place of
20635 ** a legal notice, here is a blessing:
20636 **
20637 ** May you do good and not evil.
20638 ** May you find forgiveness for yourself and forgive others.
20639 ** May you share freely, never taking more than you give.
20640 **
20641 *************************************************************************
20642 **
20643 ** This file contains low-level memory allocation drivers for when
20644 ** SQLite will use the standard C-library malloc/realloc/free interface
20645 ** to obtain the memory it needs while adding lots of additional debugging
20646 ** information to each allocation in order to help detect and fix memory
20647 ** leaks and memory usage errors.
20648 **
20649 ** This file contains implementations of the low-level memory allocation
20650 ** routines specified in the sqlite3_mem_methods object.
20651 */
20652 /* #include "sqliteInt.h" */
20653 
20654 /*
20655 ** This version of the memory allocator is used only if the
20656 ** SQLITE_MEMDEBUG macro is defined
20657 */
20658 #ifdef SQLITE_MEMDEBUG
20659 
20660 /*
20661 ** The backtrace functionality is only available with GLIBC
20662 */
20663 #ifdef __GLIBC__
20664  extern int backtrace(void**,int);
20665  extern void backtrace_symbols_fd(void*const*,int,int);
20666 #else
20667 # define backtrace(A,B) 1
20668 # define backtrace_symbols_fd(A,B,C)
20669 #endif
20670 /* #include <stdio.h> */
20671 
20672 /*
20673 ** Each memory allocation looks like this:
20674 **
20675 ** ------------------------------------------------------------------------
20676 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
20677 ** ------------------------------------------------------------------------
20678 **
20679 ** The application code sees only a pointer to the allocation. We have
20680 ** to back up from the allocation pointer to find the MemBlockHdr. The
20681 ** MemBlockHdr tells us the size of the allocation and the number of
20682 ** backtrace pointers. There is also a guard word at the end of the
20683 ** MemBlockHdr.
20684 */
20685 struct MemBlockHdr {
20686  i64 iSize; /* Size of this allocation */
20687  struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
20688  char nBacktrace; /* Number of backtraces on this alloc */
20689  char nBacktraceSlots; /* Available backtrace slots */
20690  u8 nTitle; /* Bytes of title; includes '\0' */
20691  u8 eType; /* Allocation type code */
20692  int iForeGuard; /* Guard word for sanity */
20693 };
20694 
20695 /*
20696 ** Guard words
20697 */
20698 #define FOREGUARD 0x80F5E153
20699 #define REARGUARD 0xE4676B53
20700 
20701 /*
20702 ** Number of malloc size increments to track.
20703 */
20704 #define NCSIZE 1000
20705 
20706 /*
20707 ** All of the static variables used by this module are collected
20708 ** into a single structure named "mem". This is to keep the
20709 ** static variables organized and to reduce namespace pollution
20710 ** when this module is combined with other in the amalgamation.
20711 */
20712 static struct {
20713 
20714  /*
20715  ** Mutex to control access to the memory allocation subsystem.
20716  */
20717  sqlite3_mutex *mutex;
20718 
20719  /*
20720  ** Head and tail of a linked list of all outstanding allocations
20721  */
20722  struct MemBlockHdr *pFirst;
20723  struct MemBlockHdr *pLast;
20724 
20725  /*
20726  ** The number of levels of backtrace to save in new allocations.
20727  */
20728  int nBacktrace;
20729  void (*xBacktrace)(int, int, void **);
20730 
20731  /*
20732  ** Title text to insert in front of each block
20733  */
20734  int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
20735  char zTitle[100]; /* The title text */
20736 
20737  /*
20738  ** sqlite3MallocDisallow() increments the following counter.
20739  ** sqlite3MallocAllow() decrements it.
20740  */
20741  int disallow; /* Do not allow memory allocation */
20742 
20743  /*
20744  ** Gather statistics on the sizes of memory allocations.
20745  ** nAlloc[i] is the number of allocation attempts of i*8
20746  ** bytes. i==NCSIZE is the number of allocation attempts for
20747  ** sizes more than NCSIZE*8 bytes.
20748  */
20749  int nAlloc[NCSIZE]; /* Total number of allocations */
20750  int nCurrent[NCSIZE]; /* Current number of allocations */
20751  int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
20752 
20753 } mem;
20754 
20755 
20756 /*
20757 ** Adjust memory usage statistics
20758 */
20759 static void adjustStats(int iSize, int increment){
20760  int i = ROUND8(iSize)/8;
20761  if( i>NCSIZE-1 ){
20762  i = NCSIZE - 1;
20763  }
20764  if( increment>0 ){
20765  mem.nAlloc[i]++;
20766  mem.nCurrent[i]++;
20767  if( mem.nCurrent[i]>mem.mxCurrent[i] ){
20768  mem.mxCurrent[i] = mem.nCurrent[i];
20769  }
20770  }else{
20771  mem.nCurrent[i]--;
20772  assert( mem.nCurrent[i]>=0 );
20773  }
20774 }
20775 
20776 /*
20777 ** Given an allocation, find the MemBlockHdr for that allocation.
20778 **
20779 ** This routine checks the guards at either end of the allocation and
20780 ** if they are incorrect it asserts.
20781 */
20782 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
20783  struct MemBlockHdr *p;
20784  int *pInt;
20785  u8 *pU8;
20786  int nReserve;
20787 
20788  p = (struct MemBlockHdr*)pAllocation;
20789  p--;
20790  assert( p->iForeGuard==(int)FOREGUARD );
20791  nReserve = ROUND8(p->iSize);
20792  pInt = (int*)pAllocation;
20793  pU8 = (u8*)pAllocation;
20794  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
20795  /* This checks any of the "extra" bytes allocated due
20796  ** to rounding up to an 8 byte boundary to ensure
20797  ** they haven't been overwritten.
20798  */
20799  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
20800  return p;
20801 }
20802 
20803 /*
20804 ** Return the number of bytes currently allocated at address p.
20805 */
20806 static int sqlite3MemSize(void *p){
20807  struct MemBlockHdr *pHdr;
20808  if( !p ){
20809  return 0;
20810  }
20811  pHdr = sqlite3MemsysGetHeader(p);
20812  return (int)pHdr->iSize;
20813 }
20814 
20815 /*
20816 ** Initialize the memory allocation subsystem.
20817 */
20818 static int sqlite3MemInit(void *NotUsed){
20819  UNUSED_PARAMETER(NotUsed);
20820  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
20821  if( !sqlite3GlobalConfig.bMemstat ){
20822  /* If memory status is enabled, then the malloc.c wrapper will already
20823  ** hold the STATIC_MEM mutex when the routines here are invoked. */
20824  mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20825  }
20826  return SQLITE_OK;
20827 }
20828 
20829 /*
20830 ** Deinitialize the memory allocation subsystem.
20831 */
20832 static void sqlite3MemShutdown(void *NotUsed){
20833  UNUSED_PARAMETER(NotUsed);
20834  mem.mutex = 0;
20835 }
20836 
20837 /*
20838 ** Round up a request size to the next valid allocation size.
20839 */
20840 static int sqlite3MemRoundup(int n){
20841  return ROUND8(n);
20842 }
20843 
20844 /*
20845 ** Fill a buffer with pseudo-random bytes. This is used to preset
20846 ** the content of a new memory allocation to unpredictable values and
20847 ** to clear the content of a freed allocation to unpredictable values.
20848 */
20849 static void randomFill(char *pBuf, int nByte){
20850  unsigned int x, y, r;
20851  x = SQLITE_PTR_TO_INT(pBuf);
20852  y = nByte | 1;
20853  while( nByte >= 4 ){
20854  x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20855  y = y*1103515245 + 12345;
20856  r = x ^ y;
20857  *(int*)pBuf = r;
20858  pBuf += 4;
20859  nByte -= 4;
20860  }
20861  while( nByte-- > 0 ){
20862  x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20863  y = y*1103515245 + 12345;
20864  r = x ^ y;
20865  *(pBuf++) = r & 0xff;
20866  }
20867 }
20868 
20869 /*
20870 ** Allocate nByte bytes of memory.
20871 */
20872 static void *sqlite3MemMalloc(int nByte){
20873  struct MemBlockHdr *pHdr;
20874  void **pBt;
20875  char *z;
20876  int *pInt;
20877  void *p = 0;
20878  int totalSize;
20879  int nReserve;
20880  sqlite3_mutex_enter(mem.mutex);
20881  assert( mem.disallow==0 );
20882  nReserve = ROUND8(nByte);
20883  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
20884  mem.nBacktrace*sizeof(void*) + mem.nTitle;
20885  p = malloc(totalSize);
20886  if( p ){
20887  z = p;
20888  pBt = (void**)&z[mem.nTitle];
20889  pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
20890  pHdr->pNext = 0;
20891  pHdr->pPrev = mem.pLast;
20892  if( mem.pLast ){
20893  mem.pLast->pNext = pHdr;
20894  }else{
20895  mem.pFirst = pHdr;
20896  }
20897  mem.pLast = pHdr;
20898  pHdr->iForeGuard = FOREGUARD;
20899  pHdr->eType = MEMTYPE_HEAP;
20900  pHdr->nBacktraceSlots = mem.nBacktrace;
20901  pHdr->nTitle = mem.nTitle;
20902  if( mem.nBacktrace ){
20903  void *aAddr[40];
20904  pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
20905  memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
20906  assert(pBt[0]);
20907  if( mem.xBacktrace ){
20908  mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
20909  }
20910  }else{
20911  pHdr->nBacktrace = 0;
20912  }
20913  if( mem.nTitle ){
20914  memcpy(z, mem.zTitle, mem.nTitle);
20915  }
20916  pHdr->iSize = nByte;
20917  adjustStats(nByte, +1);
20918  pInt = (int*)&pHdr[1];
20919  pInt[nReserve/sizeof(int)] = REARGUARD;
20920  randomFill((char*)pInt, nByte);
20921  memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
20922  p = (void*)pInt;
20923  }
20924  sqlite3_mutex_leave(mem.mutex);
20925  return p;
20926 }
20927 
20928 /*
20929 ** Free memory.
20930 */
20931 static void sqlite3MemFree(void *pPrior){
20932  struct MemBlockHdr *pHdr;
20933  void **pBt;
20934  char *z;
20935  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
20936  || mem.mutex!=0 );
20937  pHdr = sqlite3MemsysGetHeader(pPrior);
20938  pBt = (void**)pHdr;
20939  pBt -= pHdr->nBacktraceSlots;
20940  sqlite3_mutex_enter(mem.mutex);
20941  if( pHdr->pPrev ){
20942  assert( pHdr->pPrev->pNext==pHdr );
20943  pHdr->pPrev->pNext = pHdr->pNext;
20944  }else{
20945  assert( mem.pFirst==pHdr );
20946  mem.pFirst = pHdr->pNext;
20947  }
20948  if( pHdr->pNext ){
20949  assert( pHdr->pNext->pPrev==pHdr );
20950  pHdr->pNext->pPrev = pHdr->pPrev;
20951  }else{
20952  assert( mem.pLast==pHdr );
20953  mem.pLast = pHdr->pPrev;
20954  }
20955  z = (char*)pBt;
20956  z -= pHdr->nTitle;
20957  adjustStats((int)pHdr->iSize, -1);
20958  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
20959  (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
20960  free(z);
20961  sqlite3_mutex_leave(mem.mutex);
20962 }
20963 
20964 /*
20965 ** Change the size of an existing memory allocation.
20966 **
20967 ** For this debugging implementation, we *always* make a copy of the
20968 ** allocation into a new place in memory. In this way, if the
20969 ** higher level code is using pointer to the old allocation, it is
20970 ** much more likely to break and we are much more liking to find
20971 ** the error.
20972 */
20973 static void *sqlite3MemRealloc(void *pPrior, int nByte){
20974  struct MemBlockHdr *pOldHdr;
20975  void *pNew;
20976  assert( mem.disallow==0 );
20977  assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
20978  pOldHdr = sqlite3MemsysGetHeader(pPrior);
20979  pNew = sqlite3MemMalloc(nByte);
20980  if( pNew ){
20981  memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
20982  if( nByte>pOldHdr->iSize ){
20983  randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
20984  }
20985  sqlite3MemFree(pPrior);
20986  }
20987  return pNew;
20988 }
20989 
20990 /*
20991 ** Populate the low-level memory allocation function pointers in
20992 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20993 */
20994 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20995  static const sqlite3_mem_methods defaultMethods = {
20996  sqlite3MemMalloc,
20997  sqlite3MemFree,
20998  sqlite3MemRealloc,
20999  sqlite3MemSize,
21000  sqlite3MemRoundup,
21001  sqlite3MemInit,
21002  sqlite3MemShutdown,
21003  0
21004  };
21005  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
21006 }
21007 
21008 /*
21009 ** Set the "type" of an allocation.
21010 */
21011 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
21012  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21013  struct MemBlockHdr *pHdr;
21014  pHdr = sqlite3MemsysGetHeader(p);
21015  assert( pHdr->iForeGuard==FOREGUARD );
21016  pHdr->eType = eType;
21017  }
21018 }
21019 
21020 /*
21021 ** Return TRUE if the mask of type in eType matches the type of the
21022 ** allocation p. Also return true if p==NULL.
21023 **
21024 ** This routine is designed for use within an assert() statement, to
21025 ** verify the type of an allocation. For example:
21026 **
21027 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21028 */
21029 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
21030  int rc = 1;
21031  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21032  struct MemBlockHdr *pHdr;
21033  pHdr = sqlite3MemsysGetHeader(p);
21034  assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
21035  if( (pHdr->eType&eType)==0 ){
21036  rc = 0;
21037  }
21038  }
21039  return rc;
21040 }
21041 
21042 /*
21043 ** Return TRUE if the mask of type in eType matches no bits of the type of the
21044 ** allocation p. Also return true if p==NULL.
21045 **
21046 ** This routine is designed for use within an assert() statement, to
21047 ** verify the type of an allocation. For example:
21048 **
21049 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
21050 */
21051 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
21052  int rc = 1;
21053  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21054  struct MemBlockHdr *pHdr;
21055  pHdr = sqlite3MemsysGetHeader(p);
21056  assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
21057  if( (pHdr->eType&eType)!=0 ){
21058  rc = 0;
21059  }
21060  }
21061  return rc;
21062 }
21063 
21064 /*
21065 ** Set the number of backtrace levels kept for each allocation.
21066 ** A value of zero turns off backtracing. The number is always rounded
21067 ** up to a multiple of 2.
21068 */
21069 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
21070  if( depth<0 ){ depth = 0; }
21071  if( depth>20 ){ depth = 20; }
21072  depth = (depth+1)&0xfe;
21073  mem.nBacktrace = depth;
21074 }
21075 
21076 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
21077  mem.xBacktrace = xBacktrace;
21078 }
21079 
21080 /*
21081 ** Set the title string for subsequent allocations.
21082 */
21083 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
21084  unsigned int n = sqlite3Strlen30(zTitle) + 1;
21085  sqlite3_mutex_enter(mem.mutex);
21086  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
21087  memcpy(mem.zTitle, zTitle, n);
21088  mem.zTitle[n] = 0;
21089  mem.nTitle = ROUND8(n);
21090  sqlite3_mutex_leave(mem.mutex);
21091 }
21092 
21093 SQLITE_PRIVATE void sqlite3MemdebugSync(){
21094  struct MemBlockHdr *pHdr;
21095  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21096  void **pBt = (void**)pHdr;
21097  pBt -= pHdr->nBacktraceSlots;
21098  mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
21099  }
21100 }
21101 
21102 /*
21103 ** Open the file indicated and write a log of all unfreed memory
21104 ** allocations into that log.
21105 */
21106 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
21107  FILE *out;
21108  struct MemBlockHdr *pHdr;
21109  void **pBt;
21110  int i;
21111  out = fopen(zFilename, "w");
21112  if( out==0 ){
21113  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21114  zFilename);
21115  return;
21116  }
21117  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21118  char *z = (char*)pHdr;
21119  z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
21120  fprintf(out, "**** %lld bytes at %p from %s ****\n",
21121  pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
21122  if( pHdr->nBacktrace ){
21123  fflush(out);
21124  pBt = (void**)pHdr;
21125  pBt -= pHdr->nBacktraceSlots;
21126  backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
21127  fprintf(out, "\n");
21128  }
21129  }
21130  fprintf(out, "COUNTS:\n");
21131  for(i=0; i<NCSIZE-1; i++){
21132  if( mem.nAlloc[i] ){
21133  fprintf(out, " %5d: %10d %10d %10d\n",
21134  i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
21135  }
21136  }
21137  if( mem.nAlloc[NCSIZE-1] ){
21138  fprintf(out, " %5d: %10d %10d %10d\n",
21139  NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
21140  mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
21141  }
21142  fclose(out);
21143 }
21144 
21145 /*
21146 ** Return the number of times sqlite3MemMalloc() has been called.
21147 */
21148 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
21149  int i;
21150  int nTotal = 0;
21151  for(i=0; i<NCSIZE; i++){
21152  nTotal += mem.nAlloc[i];
21153  }
21154  return nTotal;
21155 }
21156 
21157 
21158 #endif /* SQLITE_MEMDEBUG */
21159 
21160 /************** End of mem2.c ************************************************/
21161 /************** Begin file mem3.c ********************************************/
21162 /*
21163 ** 2007 October 14
21164 **
21165 ** The author disclaims copyright to this source code. In place of
21166 ** a legal notice, here is a blessing:
21167 **
21168 ** May you do good and not evil.
21169 ** May you find forgiveness for yourself and forgive others.
21170 ** May you share freely, never taking more than you give.
21171 **
21172 *************************************************************************
21173 ** This file contains the C functions that implement a memory
21174 ** allocation subsystem for use by SQLite.
21175 **
21176 ** This version of the memory allocation subsystem omits all
21177 ** use of malloc(). The SQLite user supplies a block of memory
21178 ** before calling sqlite3_initialize() from which allocations
21179 ** are made and returned by the xMalloc() and xRealloc()
21180 ** implementations. Once sqlite3_initialize() has been called,
21181 ** the amount of memory available to SQLite is fixed and cannot
21182 ** be changed.
21183 **
21184 ** This version of the memory allocation subsystem is included
21185 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
21186 */
21187 /* #include "sqliteInt.h" */
21188 
21189 /*
21190 ** This version of the memory allocator is only built into the library
21191 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
21192 ** mean that the library will use a memory-pool by default, just that
21193 ** it is available. The mempool allocator is activated by calling
21194 ** sqlite3_config().
21195 */
21196 #ifdef SQLITE_ENABLE_MEMSYS3
21197 
21198 /*
21199 ** Maximum size (in Mem3Blocks) of a "small" chunk.
21200 */
21201 #define MX_SMALL 10
21202 
21203 
21204 /*
21205 ** Number of freelist hash slots
21206 */
21207 #define N_HASH 61
21208 
21209 /*
21210 ** A memory allocation (also called a "chunk") consists of two or
21211 ** more blocks where each block is 8 bytes. The first 8 bytes are
21212 ** a header that is not returned to the user.
21213 **
21214 ** A chunk is two or more blocks that is either checked out or
21215 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
21216 ** size of the allocation in blocks if the allocation is free.
21217 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
21218 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
21219 ** is true if the previous chunk is checked out and false if the
21220 ** previous chunk is free. The u.hdr.prevSize field is the size of
21221 ** the previous chunk in blocks if the previous chunk is on the
21222 ** freelist. If the previous chunk is checked out, then
21223 ** u.hdr.prevSize can be part of the data for that chunk and should
21224 ** not be read or written.
21225 **
21226 ** We often identify a chunk by its index in mem3.aPool[]. When
21227 ** this is done, the chunk index refers to the second block of
21228 ** the chunk. In this way, the first chunk has an index of 1.
21229 ** A chunk index of 0 means "no such chunk" and is the equivalent
21230 ** of a NULL pointer.
21231 **
21232 ** The second block of free chunks is of the form u.list. The
21233 ** two fields form a double-linked list of chunks of related sizes.
21234 ** Pointers to the head of the list are stored in mem3.aiSmall[]
21235 ** for smaller chunks and mem3.aiHash[] for larger chunks.
21236 **
21237 ** The second block of a chunk is user data if the chunk is checked
21238 ** out. If a chunk is checked out, the user data may extend into
21239 ** the u.hdr.prevSize value of the following chunk.
21240 */
21241 typedef struct Mem3Block Mem3Block;
21242 struct Mem3Block {
21243  union {
21244  struct {
21245  u32 prevSize; /* Size of previous chunk in Mem3Block elements */
21246  u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
21247  } hdr;
21248  struct {
21249  u32 next; /* Index in mem3.aPool[] of next free chunk */
21250  u32 prev; /* Index in mem3.aPool[] of previous free chunk */
21251  } list;
21252  } u;
21253 };
21254 
21255 /*
21256 ** All of the static variables used by this module are collected
21257 ** into a single structure named "mem3". This is to keep the
21258 ** static variables organized and to reduce namespace pollution
21259 ** when this module is combined with other in the amalgamation.
21260 */
21261 static SQLITE_WSD struct Mem3Global {
21262  /*
21263  ** Memory available for allocation. nPool is the size of the array
21264  ** (in Mem3Blocks) pointed to by aPool less 2.
21265  */
21266  u32 nPool;
21267  Mem3Block *aPool;
21268 
21269  /*
21270  ** True if we are evaluating an out-of-memory callback.
21271  */
21272  int alarmBusy;
21273 
21274  /*
21275  ** Mutex to control access to the memory allocation subsystem.
21276  */
21277  sqlite3_mutex *mutex;
21278 
21279  /*
21280  ** The minimum amount of free space that we have seen.
21281  */
21282  u32 mnMaster;
21283 
21284  /*
21285  ** iMaster is the index of the master chunk. Most new allocations
21286  ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
21287  ** of the current master. iMaster is 0 if there is not master chunk.
21288  ** The master chunk is not in either the aiHash[] or aiSmall[].
21289  */
21290  u32 iMaster;
21291  u32 szMaster;
21292 
21293  /*
21294  ** Array of lists of free blocks according to the block size
21295  ** for smaller chunks, or a hash on the block size for larger
21296  ** chunks.
21297  */
21298  u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
21299  u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
21300 } mem3 = { 97535575 };
21301 
21302 #define mem3 GLOBAL(struct Mem3Global, mem3)
21303 
21304 /*
21305 ** Unlink the chunk at mem3.aPool[i] from list it is currently
21306 ** on. *pRoot is the list that i is a member of.
21307 */
21308 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
21309  u32 next = mem3.aPool[i].u.list.next;
21310  u32 prev = mem3.aPool[i].u.list.prev;
21311  assert( sqlite3_mutex_held(mem3.mutex) );
21312  if( prev==0 ){
21313  *pRoot = next;
21314  }else{
21315  mem3.aPool[prev].u.list.next = next;
21316  }
21317  if( next ){
21318  mem3.aPool[next].u.list.prev = prev;
21319  }
21320  mem3.aPool[i].u.list.next = 0;
21321  mem3.aPool[i].u.list.prev = 0;
21322 }
21323 
21324 /*
21325 ** Unlink the chunk at index i from
21326 ** whatever list is currently a member of.
21327 */
21328 static void memsys3Unlink(u32 i){
21329  u32 size, hash;
21330  assert( sqlite3_mutex_held(mem3.mutex) );
21331  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21332  assert( i>=1 );
21333  size = mem3.aPool[i-1].u.hdr.size4x/4;
21334  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21335  assert( size>=2 );
21336  if( size <= MX_SMALL ){
21337  memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
21338  }else{
21339  hash = size % N_HASH;
21340  memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21341  }
21342 }
21343 
21344 /*
21345 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
21346 ** at *pRoot.
21347 */
21348 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
21349  assert( sqlite3_mutex_held(mem3.mutex) );
21350  mem3.aPool[i].u.list.next = *pRoot;
21351  mem3.aPool[i].u.list.prev = 0;
21352  if( *pRoot ){
21353  mem3.aPool[*pRoot].u.list.prev = i;
21354  }
21355  *pRoot = i;
21356 }
21357 
21358 /*
21359 ** Link the chunk at index i into either the appropriate
21360 ** small chunk list, or into the large chunk hash table.
21361 */
21362 static void memsys3Link(u32 i){
21363  u32 size, hash;
21364  assert( sqlite3_mutex_held(mem3.mutex) );
21365  assert( i>=1 );
21366  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21367  size = mem3.aPool[i-1].u.hdr.size4x/4;
21368  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21369  assert( size>=2 );
21370  if( size <= MX_SMALL ){
21371  memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
21372  }else{
21373  hash = size % N_HASH;
21374  memsys3LinkIntoList(i, &mem3.aiHash[hash]);
21375  }
21376 }
21377 
21378 /*
21379 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
21380 ** will already be held (obtained by code in malloc.c) if
21381 ** sqlite3GlobalConfig.bMemStat is true.
21382 */
21383 static void memsys3Enter(void){
21384  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
21385  mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21386  }
21387  sqlite3_mutex_enter(mem3.mutex);
21388 }
21389 static void memsys3Leave(void){
21390  sqlite3_mutex_leave(mem3.mutex);
21391 }
21392 
21393 /*
21394 ** Called when we are unable to satisfy an allocation of nBytes.
21395 */
21396 static void memsys3OutOfMemory(int nByte){
21397  if( !mem3.alarmBusy ){
21398  mem3.alarmBusy = 1;
21399  assert( sqlite3_mutex_held(mem3.mutex) );
21400  sqlite3_mutex_leave(mem3.mutex);
21401  sqlite3_release_memory(nByte);
21402  sqlite3_mutex_enter(mem3.mutex);
21403  mem3.alarmBusy = 0;
21404  }
21405 }
21406 
21407 
21408 /*
21409 ** Chunk i is a free chunk that has been unlinked. Adjust its
21410 ** size parameters for check-out and return a pointer to the
21411 ** user portion of the chunk.
21412 */
21413 static void *memsys3Checkout(u32 i, u32 nBlock){
21414  u32 x;
21415  assert( sqlite3_mutex_held(mem3.mutex) );
21416  assert( i>=1 );
21417  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
21418  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
21419  x = mem3.aPool[i-1].u.hdr.size4x;
21420  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
21421  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
21422  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
21423  return &mem3.aPool[i];
21424 }
21425 
21426 /*
21427 ** Carve a piece off of the end of the mem3.iMaster free chunk.
21428 ** Return a pointer to the new allocation. Or, if the master chunk
21429 ** is not large enough, return 0.
21430 */
21431 static void *memsys3FromMaster(u32 nBlock){
21432  assert( sqlite3_mutex_held(mem3.mutex) );
21433  assert( mem3.szMaster>=nBlock );
21434  if( nBlock>=mem3.szMaster-1 ){
21435  /* Use the entire master */
21436  void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
21437  mem3.iMaster = 0;
21438  mem3.szMaster = 0;
21439  mem3.mnMaster = 0;
21440  return p;
21441  }else{
21442  /* Split the master block. Return the tail. */
21443  u32 newi, x;
21444  newi = mem3.iMaster + mem3.szMaster - nBlock;
21445  assert( newi > mem3.iMaster+1 );
21446  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
21447  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
21448  mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
21449  mem3.szMaster -= nBlock;
21450  mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
21451  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21452  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21453  if( mem3.szMaster < mem3.mnMaster ){
21454  mem3.mnMaster = mem3.szMaster;
21455  }
21456  return (void*)&mem3.aPool[newi];
21457  }
21458 }
21459 
21460 /*
21461 ** *pRoot is the head of a list of free chunks of the same size
21462 ** or same size hash. In other words, *pRoot is an entry in either
21463 ** mem3.aiSmall[] or mem3.aiHash[].
21464 **
21465 ** This routine examines all entries on the given list and tries
21466 ** to coalesce each entries with adjacent free chunks.
21467 **
21468 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
21469 ** the current mem3.iMaster with the new larger chunk. In order for
21470 ** this mem3.iMaster replacement to work, the master chunk must be
21471 ** linked into the hash tables. That is not the normal state of
21472 ** affairs, of course. The calling routine must link the master
21473 ** chunk before invoking this routine, then must unlink the (possibly
21474 ** changed) master chunk once this routine has finished.
21475 */
21476 static void memsys3Merge(u32 *pRoot){
21477  u32 iNext, prev, size, i, x;
21478 
21479  assert( sqlite3_mutex_held(mem3.mutex) );
21480  for(i=*pRoot; i>0; i=iNext){
21481  iNext = mem3.aPool[i].u.list.next;
21482  size = mem3.aPool[i-1].u.hdr.size4x;
21483  assert( (size&1)==0 );
21484  if( (size&2)==0 ){
21485  memsys3UnlinkFromList(i, pRoot);
21486  assert( i > mem3.aPool[i-1].u.hdr.prevSize );
21487  prev = i - mem3.aPool[i-1].u.hdr.prevSize;
21488  if( prev==iNext ){
21489  iNext = mem3.aPool[prev].u.list.next;
21490  }
21491  memsys3Unlink(prev);
21492  size = i + size/4 - prev;
21493  x = mem3.aPool[prev-1].u.hdr.size4x & 2;
21494  mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
21495  mem3.aPool[prev+size-1].u.hdr.prevSize = size;
21496  memsys3Link(prev);
21497  i = prev;
21498  }else{
21499  size /= 4;
21500  }
21501  if( size>mem3.szMaster ){
21502  mem3.iMaster = i;
21503  mem3.szMaster = size;
21504  }
21505  }
21506 }
21507 
21508 /*
21509 ** Return a block of memory of at least nBytes in size.
21510 ** Return NULL if unable.
21511 **
21512 ** This function assumes that the necessary mutexes, if any, are
21513 ** already held by the caller. Hence "Unsafe".
21514 */
21515 static void *memsys3MallocUnsafe(int nByte){
21516  u32 i;
21517  u32 nBlock;
21518  u32 toFree;
21519 
21520  assert( sqlite3_mutex_held(mem3.mutex) );
21521  assert( sizeof(Mem3Block)==8 );
21522  if( nByte<=12 ){
21523  nBlock = 2;
21524  }else{
21525  nBlock = (nByte + 11)/8;
21526  }
21527  assert( nBlock>=2 );
21528 
21529  /* STEP 1:
21530  ** Look for an entry of the correct size in either the small
21531  ** chunk table or in the large chunk hash table. This is
21532  ** successful most of the time (about 9 times out of 10).
21533  */
21534  if( nBlock <= MX_SMALL ){
21535  i = mem3.aiSmall[nBlock-2];
21536  if( i>0 ){
21537  memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
21538  return memsys3Checkout(i, nBlock);
21539  }
21540  }else{
21541  int hash = nBlock % N_HASH;
21542  for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
21543  if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
21544  memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21545  return memsys3Checkout(i, nBlock);
21546  }
21547  }
21548  }
21549 
21550  /* STEP 2:
21551  ** Try to satisfy the allocation by carving a piece off of the end
21552  ** of the master chunk. This step usually works if step 1 fails.
21553  */
21554  if( mem3.szMaster>=nBlock ){
21555  return memsys3FromMaster(nBlock);
21556  }
21557 
21558 
21559  /* STEP 3:
21560  ** Loop through the entire memory pool. Coalesce adjacent free
21561  ** chunks. Recompute the master chunk as the largest free chunk.
21562  ** Then try again to satisfy the allocation by carving a piece off
21563  ** of the end of the master chunk. This step happens very
21564  ** rarely (we hope!)
21565  */
21566  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
21567  memsys3OutOfMemory(toFree);
21568  if( mem3.iMaster ){
21569  memsys3Link(mem3.iMaster);
21570  mem3.iMaster = 0;
21571  mem3.szMaster = 0;
21572  }
21573  for(i=0; i<N_HASH; i++){
21574  memsys3Merge(&mem3.aiHash[i]);
21575  }
21576  for(i=0; i<MX_SMALL-1; i++){
21577  memsys3Merge(&mem3.aiSmall[i]);
21578  }
21579  if( mem3.szMaster ){
21580  memsys3Unlink(mem3.iMaster);
21581  if( mem3.szMaster>=nBlock ){
21582  return memsys3FromMaster(nBlock);
21583  }
21584  }
21585  }
21586 
21587  /* If none of the above worked, then we fail. */
21588  return 0;
21589 }
21590 
21591 /*
21592 ** Free an outstanding memory allocation.
21593 **
21594 ** This function assumes that the necessary mutexes, if any, are
21595 ** already held by the caller. Hence "Unsafe".
21596 */
21597 static void memsys3FreeUnsafe(void *pOld){
21598  Mem3Block *p = (Mem3Block*)pOld;
21599  int i;
21600  u32 size, x;
21601  assert( sqlite3_mutex_held(mem3.mutex) );
21602  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
21603  i = p - mem3.aPool;
21604  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
21605  size = mem3.aPool[i-1].u.hdr.size4x/4;
21606  assert( i+size<=mem3.nPool+1 );
21607  mem3.aPool[i-1].u.hdr.size4x &= ~1;
21608  mem3.aPool[i+size-1].u.hdr.prevSize = size;
21609  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
21610  memsys3Link(i);
21611 
21612  /* Try to expand the master using the newly freed chunk */
21613  if( mem3.iMaster ){
21614  while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
21615  size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
21616  mem3.iMaster -= size;
21617  mem3.szMaster += size;
21618  memsys3Unlink(mem3.iMaster);
21619  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21620  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21621  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21622  }
21623  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21624  while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
21625  memsys3Unlink(mem3.iMaster+mem3.szMaster);
21626  mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
21627  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21628  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21629  }
21630  }
21631 }
21632 
21633 /*
21634 ** Return the size of an outstanding allocation, in bytes. The
21635 ** size returned omits the 8-byte header overhead. This only
21636 ** works for chunks that are currently checked out.
21637 */
21638 static int memsys3Size(void *p){
21639  Mem3Block *pBlock;
21640  assert( p!=0 );
21641  pBlock = (Mem3Block*)p;
21642  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
21643  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
21644 }
21645 
21646 /*
21647 ** Round up a request size to the next valid allocation size.
21648 */
21649 static int memsys3Roundup(int n){
21650  if( n<=12 ){
21651  return 12;
21652  }else{
21653  return ((n+11)&~7) - 4;
21654  }
21655 }
21656 
21657 /*
21658 ** Allocate nBytes of memory.
21659 */
21660 static void *memsys3Malloc(int nBytes){
21661  sqlite3_int64 *p;
21662  assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
21663  memsys3Enter();
21664  p = memsys3MallocUnsafe(nBytes);
21665  memsys3Leave();
21666  return (void*)p;
21667 }
21668 
21669 /*
21670 ** Free memory.
21671 */
21672 static void memsys3Free(void *pPrior){
21673  assert( pPrior );
21674  memsys3Enter();
21675  memsys3FreeUnsafe(pPrior);
21676  memsys3Leave();
21677 }
21678 
21679 /*
21680 ** Change the size of an existing memory allocation
21681 */
21682 static void *memsys3Realloc(void *pPrior, int nBytes){
21683  int nOld;
21684  void *p;
21685  if( pPrior==0 ){
21686  return sqlite3_malloc(nBytes);
21687  }
21688  if( nBytes<=0 ){
21689  sqlite3_free(pPrior);
21690  return 0;
21691  }
21692  nOld = memsys3Size(pPrior);
21693  if( nBytes<=nOld && nBytes>=nOld-128 ){
21694  return pPrior;
21695  }
21696  memsys3Enter();
21697  p = memsys3MallocUnsafe(nBytes);
21698  if( p ){
21699  if( nOld<nBytes ){
21700  memcpy(p, pPrior, nOld);
21701  }else{
21702  memcpy(p, pPrior, nBytes);
21703  }
21704  memsys3FreeUnsafe(pPrior);
21705  }
21706  memsys3Leave();
21707  return p;
21708 }
21709 
21710 /*
21711 ** Initialize this module.
21712 */
21713 static int memsys3Init(void *NotUsed){
21714  UNUSED_PARAMETER(NotUsed);
21715  if( !sqlite3GlobalConfig.pHeap ){
21716  return SQLITE_ERROR;
21717  }
21718 
21719  /* Store a pointer to the memory block in global structure mem3. */
21720  assert( sizeof(Mem3Block)==8 );
21721  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
21722  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
21723 
21724  /* Initialize the master block. */
21725  mem3.szMaster = mem3.nPool;
21726  mem3.mnMaster = mem3.szMaster;
21727  mem3.iMaster = 1;
21728  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
21729  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
21730  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
21731 
21732  return SQLITE_OK;
21733 }
21734 
21735 /*
21736 ** Deinitialize this module.
21737 */
21738 static void memsys3Shutdown(void *NotUsed){
21739  UNUSED_PARAMETER(NotUsed);
21740  mem3.mutex = 0;
21741  return;
21742 }
21743 
21744 
21745 
21746 /*
21747 ** Open the file indicated and write a log of all unfreed memory
21748 ** allocations into that log.
21749 */
21750 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
21751 #ifdef SQLITE_DEBUG
21752  FILE *out;
21753  u32 i, j;
21754  u32 size;
21755  if( zFilename==0 || zFilename[0]==0 ){
21756  out = stdout;
21757  }else{
21758  out = fopen(zFilename, "w");
21759  if( out==0 ){
21760  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21761  zFilename);
21762  return;
21763  }
21764  }
21765  memsys3Enter();
21766  fprintf(out, "CHUNKS:\n");
21767  for(i=1; i<=mem3.nPool; i+=size/4){
21768  size = mem3.aPool[i-1].u.hdr.size4x;
21769  if( size/4<=1 ){
21770  fprintf(out, "%p size error\n", &mem3.aPool[i]);
21771  assert( 0 );
21772  break;
21773  }
21774  if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
21775  fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
21776  assert( 0 );
21777  break;
21778  }
21779  if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
21780  fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
21781  assert( 0 );
21782  break;
21783  }
21784  if( size&1 ){
21785  fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
21786  }else{
21787  fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
21788  i==mem3.iMaster ? " **master**" : "");
21789  }
21790  }
21791  for(i=0; i<MX_SMALL-1; i++){
21792  if( mem3.aiSmall[i]==0 ) continue;
21793  fprintf(out, "small(%2d):", i);
21794  for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
21795  fprintf(out, " %p(%d)", &mem3.aPool[j],
21796  (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21797  }
21798  fprintf(out, "\n");
21799  }
21800  for(i=0; i<N_HASH; i++){
21801  if( mem3.aiHash[i]==0 ) continue;
21802  fprintf(out, "hash(%2d):", i);
21803  for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
21804  fprintf(out, " %p(%d)", &mem3.aPool[j],
21805  (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21806  }
21807  fprintf(out, "\n");
21808  }
21809  fprintf(out, "master=%d\n", mem3.iMaster);
21810  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
21811  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
21812  sqlite3_mutex_leave(mem3.mutex);
21813  if( out==stdout ){
21814  fflush(stdout);
21815  }else{
21816  fclose(out);
21817  }
21818 #else
21819  UNUSED_PARAMETER(zFilename);
21820 #endif
21821 }
21822 
21823 /*
21824 ** This routine is the only routine in this file with external
21825 ** linkage.
21826 **
21827 ** Populate the low-level memory allocation function pointers in
21828 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
21829 ** arguments specify the block of memory to manage.
21830 **
21831 ** This routine is only called by sqlite3_config(), and therefore
21832 ** is not required to be threadsafe (it is not).
21833 */
21834 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
21835  static const sqlite3_mem_methods mempoolMethods = {
21836  memsys3Malloc,
21837  memsys3Free,
21838  memsys3Realloc,
21839  memsys3Size,
21840  memsys3Roundup,
21841  memsys3Init,
21842  memsys3Shutdown,
21843  0
21844  };
21845  return &mempoolMethods;
21846 }
21847 
21848 #endif /* SQLITE_ENABLE_MEMSYS3 */
21849 
21850 /************** End of mem3.c ************************************************/
21851 /************** Begin file mem5.c ********************************************/
21852 /*
21853 ** 2007 October 14
21854 **
21855 ** The author disclaims copyright to this source code. In place of
21856 ** a legal notice, here is a blessing:
21857 **
21858 ** May you do good and not evil.
21859 ** May you find forgiveness for yourself and forgive others.
21860 ** May you share freely, never taking more than you give.
21861 **
21862 *************************************************************************
21863 ** This file contains the C functions that implement a memory
21864 ** allocation subsystem for use by SQLite.
21865 **
21866 ** This version of the memory allocation subsystem omits all
21867 ** use of malloc(). The application gives SQLite a block of memory
21868 ** before calling sqlite3_initialize() from which allocations
21869 ** are made and returned by the xMalloc() and xRealloc()
21870 ** implementations. Once sqlite3_initialize() has been called,
21871 ** the amount of memory available to SQLite is fixed and cannot
21872 ** be changed.
21873 **
21874 ** This version of the memory allocation subsystem is included
21875 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
21876 **
21877 ** This memory allocator uses the following algorithm:
21878 **
21879 ** 1. All memory allocation sizes are rounded up to a power of 2.
21880 **
21881 ** 2. If two adjacent free blocks are the halves of a larger block,
21882 ** then the two blocks are coalesced into the single larger block.
21883 **
21884 ** 3. New memory is allocated from the first available free block.
21885 **
21886 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
21887 ** Concerning Dynamic Storage Allocation". Journal of the Association for
21888 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
21889 **
21890 ** Let n be the size of the largest allocation divided by the minimum
21891 ** allocation size (after rounding all sizes up to a power of 2.) Let M
21892 ** be the maximum amount of memory ever outstanding at one time. Let
21893 ** N be the total amount of memory available for allocation. Robson
21894 ** proved that this memory allocator will never breakdown due to
21895 ** fragmentation as long as the following constraint holds:
21896 **
21897 ** N >= M*(1 + log2(n)/2) - n + 1
21898 **
21899 ** The sqlite3_status() logic tracks the maximum values of n and M so
21900 ** that an application can, at any time, verify this constraint.
21901 */
21902 /* #include "sqliteInt.h" */
21903 
21904 /*
21905 ** This version of the memory allocator is used only when
21906 ** SQLITE_ENABLE_MEMSYS5 is defined.
21907 */
21908 #ifdef SQLITE_ENABLE_MEMSYS5
21909 
21910 /*
21911 ** A minimum allocation is an instance of the following structure.
21912 ** Larger allocations are an array of these structures where the
21913 ** size of the array is a power of 2.
21914 **
21915 ** The size of this object must be a power of two. That fact is
21916 ** verified in memsys5Init().
21917 */
21918 typedef struct Mem5Link Mem5Link;
21919 struct Mem5Link {
21920  int next; /* Index of next free chunk */
21921  int prev; /* Index of previous free chunk */
21922 };
21923 
21924 /*
21925 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
21926 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
21927 ** it is not actually possible to reach this limit.
21928 */
21929 #define LOGMAX 30
21930 
21931 /*
21932 ** Masks used for mem5.aCtrl[] elements.
21933 */
21934 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
21935 #define CTRL_FREE 0x20 /* True if not checked out */
21936 
21937 /*
21938 ** All of the static variables used by this module are collected
21939 ** into a single structure named "mem5". This is to keep the
21940 ** static variables organized and to reduce namespace pollution
21941 ** when this module is combined with other in the amalgamation.
21942 */
21943 static SQLITE_WSD struct Mem5Global {
21944  /*
21945  ** Memory available for allocation
21946  */
21947  int szAtom; /* Smallest possible allocation in bytes */
21948  int nBlock; /* Number of szAtom sized blocks in zPool */
21949  u8 *zPool; /* Memory available to be allocated */
21950 
21951  /*
21952  ** Mutex to control access to the memory allocation subsystem.
21953  */
21954  sqlite3_mutex *mutex;
21955 
21956 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21957  /*
21958  ** Performance statistics
21959  */
21960  u64 nAlloc; /* Total number of calls to malloc */
21961  u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
21962  u64 totalExcess; /* Total internal fragmentation */
21963  u32 currentOut; /* Current checkout, including internal fragmentation */
21964  u32 currentCount; /* Current number of distinct checkouts */
21965  u32 maxOut; /* Maximum instantaneous currentOut */
21966  u32 maxCount; /* Maximum instantaneous currentCount */
21967  u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
21968 #endif
21969 
21970  /*
21971  ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
21972  ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
21973  ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
21974  */
21975  int aiFreelist[LOGMAX+1];
21976 
21977  /*
21978  ** Space for tracking which blocks are checked out and the size
21979  ** of each block. One byte per block.
21980  */
21981  u8 *aCtrl;
21982 
21983 } mem5;
21984 
21985 /*
21986 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
21987 */
21988 #define mem5 GLOBAL(struct Mem5Global, mem5)
21989 
21990 /*
21991 ** Assuming mem5.zPool is divided up into an array of Mem5Link
21992 ** structures, return a pointer to the idx-th such link.
21993 */
21994 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
21995 
21996 /*
21997 ** Unlink the chunk at mem5.aPool[i] from list it is currently
21998 ** on. It should be found on mem5.aiFreelist[iLogsize].
21999 */
22000 static void memsys5Unlink(int i, int iLogsize){
22001  int next, prev;
22002  assert( i>=0 && i<mem5.nBlock );
22003  assert( iLogsize>=0 && iLogsize<=LOGMAX );
22004  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
22005 
22006  next = MEM5LINK(i)->next;
22007  prev = MEM5LINK(i)->prev;
22008  if( prev<0 ){
22009  mem5.aiFreelist[iLogsize] = next;
22010  }else{
22011  MEM5LINK(prev)->next = next;
22012  }
22013  if( next>=0 ){
22014  MEM5LINK(next)->prev = prev;
22015  }
22016 }
22017 
22018 /*
22019 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
22020 ** free list.
22021 */
22022 static void memsys5Link(int i, int iLogsize){
22023  int x;
22024  assert( sqlite3_mutex_held(mem5.mutex) );
22025  assert( i>=0 && i<mem5.nBlock );
22026  assert( iLogsize>=0 && iLogsize<=LOGMAX );
22027  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
22028 
22029  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
22030  MEM5LINK(i)->prev = -1;
22031  if( x>=0 ){
22032  assert( x<mem5.nBlock );
22033  MEM5LINK(x)->prev = i;
22034  }
22035  mem5.aiFreelist[iLogsize] = i;
22036 }
22037 
22038 /*
22039 ** Obtain or release the mutex needed to access global data structures.
22040 */
22041 static void memsys5Enter(void){
22042  sqlite3_mutex_enter(mem5.mutex);
22043 }
22044 static void memsys5Leave(void){
22045  sqlite3_mutex_leave(mem5.mutex);
22046 }
22047 
22048 /*
22049 ** Return the size of an outstanding allocation, in bytes.
22050 ** This only works for chunks that are currently checked out.
22051 */
22052 static int memsys5Size(void *p){
22053  int iSize, i;
22054  assert( p!=0 );
22055  i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
22056  assert( i>=0 && i<mem5.nBlock );
22057  iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
22058  return iSize;
22059 }
22060 
22061 /*
22062 ** Return a block of memory of at least nBytes in size.
22063 ** Return NULL if unable. Return NULL if nBytes==0.
22064 **
22065 ** The caller guarantees that nByte is positive.
22066 **
22067 ** The caller has obtained a mutex prior to invoking this
22068 ** routine so there is never any chance that two or more
22069 ** threads can be in this routine at the same time.
22070 */
22071 static void *memsys5MallocUnsafe(int nByte){
22072  int i; /* Index of a mem5.aPool[] slot */
22073  int iBin; /* Index into mem5.aiFreelist[] */
22074  int iFullSz; /* Size of allocation rounded up to power of 2 */
22075  int iLogsize; /* Log2 of iFullSz/POW2_MIN */
22076 
22077  /* nByte must be a positive */
22078  assert( nByte>0 );
22079 
22080  /* No more than 1GiB per allocation */
22081  if( nByte > 0x40000000 ) return 0;
22082 
22083 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22084  /* Keep track of the maximum allocation request. Even unfulfilled
22085  ** requests are counted */
22086  if( (u32)nByte>mem5.maxRequest ){
22087  mem5.maxRequest = nByte;
22088  }
22089 #endif
22090 
22091 
22092  /* Round nByte up to the next valid power of two */
22093  for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
22094 
22095  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
22096  ** block. If not, then split a block of the next larger power of
22097  ** two in order to create a new free block of size iLogsize.
22098  */
22099  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
22100  if( iBin>LOGMAX ){
22101  testcase( sqlite3GlobalConfig.xLog!=0 );
22102  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
22103  return 0;
22104  }
22105  i = mem5.aiFreelist[iBin];
22106  memsys5Unlink(i, iBin);
22107  while( iBin>iLogsize ){
22108  int newSize;
22109 
22110  iBin--;
22111  newSize = 1 << iBin;
22112  mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
22113  memsys5Link(i+newSize, iBin);
22114  }
22115  mem5.aCtrl[i] = iLogsize;
22116 
22117 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22118  /* Update allocator performance statistics. */
22119  mem5.nAlloc++;
22120  mem5.totalAlloc += iFullSz;
22121  mem5.totalExcess += iFullSz - nByte;
22122  mem5.currentCount++;
22123  mem5.currentOut += iFullSz;
22124  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
22125  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
22126 #endif
22127 
22128 #ifdef SQLITE_DEBUG
22129  /* Make sure the allocated memory does not assume that it is set to zero
22130  ** or retains a value from a previous allocation */
22131  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
22132 #endif
22133 
22134  /* Return a pointer to the allocated memory. */
22135  return (void*)&mem5.zPool[i*mem5.szAtom];
22136 }
22137 
22138 /*
22139 ** Free an outstanding memory allocation.
22140 */
22141 static void memsys5FreeUnsafe(void *pOld){
22142  u32 size, iLogsize;
22143  int iBlock;
22144 
22145  /* Set iBlock to the index of the block pointed to by pOld in
22146  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
22147  */
22148  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
22149 
22150  /* Check that the pointer pOld points to a valid, non-free block. */
22151  assert( iBlock>=0 && iBlock<mem5.nBlock );
22152  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
22153  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
22154 
22155  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
22156  size = 1<<iLogsize;
22157  assert( iBlock+size-1<(u32)mem5.nBlock );
22158 
22159  mem5.aCtrl[iBlock] |= CTRL_FREE;
22160  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
22161 
22162 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22163  assert( mem5.currentCount>0 );
22164  assert( mem5.currentOut>=(size*mem5.szAtom) );
22165  mem5.currentCount--;
22166  mem5.currentOut -= size*mem5.szAtom;
22167  assert( mem5.currentOut>0 || mem5.currentCount==0 );
22168  assert( mem5.currentCount>0 || mem5.currentOut==0 );
22169 #endif
22170 
22171  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22172  while( ALWAYS(iLogsize<LOGMAX) ){
22173  int iBuddy;
22174  if( (iBlock>>iLogsize) & 1 ){
22175  iBuddy = iBlock - size;
22176  assert( iBuddy>=0 );
22177  }else{
22178  iBuddy = iBlock + size;
22179  if( iBuddy>=mem5.nBlock ) break;
22180  }
22181  if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
22182  memsys5Unlink(iBuddy, iLogsize);
22183  iLogsize++;
22184  if( iBuddy<iBlock ){
22185  mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
22186  mem5.aCtrl[iBlock] = 0;
22187  iBlock = iBuddy;
22188  }else{
22189  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22190  mem5.aCtrl[iBuddy] = 0;
22191  }
22192  size *= 2;
22193  }
22194 
22195 #ifdef SQLITE_DEBUG
22196  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
22197  ** not used after being freed */
22198  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
22199 #endif
22200 
22201  memsys5Link(iBlock, iLogsize);
22202 }
22203 
22204 /*
22205 ** Allocate nBytes of memory.
22206 */
22207 static void *memsys5Malloc(int nBytes){
22208  sqlite3_int64 *p = 0;
22209  if( nBytes>0 ){
22210  memsys5Enter();
22211  p = memsys5MallocUnsafe(nBytes);
22212  memsys5Leave();
22213  }
22214  return (void*)p;
22215 }
22216 
22217 /*
22218 ** Free memory.
22219 **
22220 ** The outer layer memory allocator prevents this routine from
22221 ** being called with pPrior==0.
22222 */
22223 static void memsys5Free(void *pPrior){
22224  assert( pPrior!=0 );
22225  memsys5Enter();
22226  memsys5FreeUnsafe(pPrior);
22227  memsys5Leave();
22228 }
22229 
22230 /*
22231 ** Change the size of an existing memory allocation.
22232 **
22233 ** The outer layer memory allocator prevents this routine from
22234 ** being called with pPrior==0.
22235 **
22236 ** nBytes is always a value obtained from a prior call to
22237 ** memsys5Round(). Hence nBytes is always a non-negative power
22238 ** of two. If nBytes==0 that means that an oversize allocation
22239 ** (an allocation larger than 0x40000000) was requested and this
22240 ** routine should return 0 without freeing pPrior.
22241 */
22242 static void *memsys5Realloc(void *pPrior, int nBytes){
22243  int nOld;
22244  void *p;
22245  assert( pPrior!=0 );
22246  assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
22247  assert( nBytes>=0 );
22248  if( nBytes==0 ){
22249  return 0;
22250  }
22251  nOld = memsys5Size(pPrior);
22252  if( nBytes<=nOld ){
22253  return pPrior;
22254  }
22255  p = memsys5Malloc(nBytes);
22256  if( p ){
22257  memcpy(p, pPrior, nOld);
22258  memsys5Free(pPrior);
22259  }
22260  return p;
22261 }
22262 
22263 /*
22264 ** Round up a request size to the next valid allocation size. If
22265 ** the allocation is too large to be handled by this allocation system,
22266 ** return 0.
22267 **
22268 ** All allocations must be a power of two and must be expressed by a
22269 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
22270 ** or 1073741824 bytes.
22271 */
22272 static int memsys5Roundup(int n){
22273  int iFullSz;
22274  if( n > 0x40000000 ) return 0;
22275  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
22276  return iFullSz;
22277 }
22278 
22279 /*
22280 ** Return the ceiling of the logarithm base 2 of iValue.
22281 **
22282 ** Examples: memsys5Log(1) -> 0
22283 ** memsys5Log(2) -> 1
22284 ** memsys5Log(4) -> 2
22285 ** memsys5Log(5) -> 3
22286 ** memsys5Log(8) -> 3
22287 ** memsys5Log(9) -> 4
22288 */
22289 static int memsys5Log(int iValue){
22290  int iLog;
22291  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
22292  return iLog;
22293 }
22294 
22295 /*
22296 ** Initialize the memory allocator.
22297 **
22298 ** This routine is not threadsafe. The caller must be holding a mutex
22299 ** to prevent multiple threads from entering at the same time.
22300 */
22301 static int memsys5Init(void *NotUsed){
22302  int ii; /* Loop counter */
22303  int nByte; /* Number of bytes of memory available to this allocator */
22304  u8 *zByte; /* Memory usable by this allocator */
22305  int nMinLog; /* Log base 2 of minimum allocation size in bytes */
22306  int iOffset; /* An offset into mem5.aCtrl[] */
22307 
22308  UNUSED_PARAMETER(NotUsed);
22309 
22310  /* For the purposes of this routine, disable the mutex */
22311  mem5.mutex = 0;
22312 
22313  /* The size of a Mem5Link object must be a power of two. Verify that
22314  ** this is case.
22315  */
22316  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
22317 
22318  nByte = sqlite3GlobalConfig.nHeap;
22319  zByte = (u8*)sqlite3GlobalConfig.pHeap;
22320  assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
22321 
22322  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
22323  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
22324  mem5.szAtom = (1<<nMinLog);
22325  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
22326  mem5.szAtom = mem5.szAtom << 1;
22327  }
22328 
22329  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
22330  mem5.zPool = zByte;
22331  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
22332 
22333  for(ii=0; ii<=LOGMAX; ii++){
22334  mem5.aiFreelist[ii] = -1;
22335  }
22336 
22337  iOffset = 0;
22338  for(ii=LOGMAX; ii>=0; ii--){
22339  int nAlloc = (1<<ii);
22340  if( (iOffset+nAlloc)<=mem5.nBlock ){
22341  mem5.aCtrl[iOffset] = ii | CTRL_FREE;
22342  memsys5Link(iOffset, ii);
22343  iOffset += nAlloc;
22344  }
22345  assert((iOffset+nAlloc)>mem5.nBlock);
22346  }
22347 
22348  /* If a mutex is required for normal operation, allocate one */
22349  if( sqlite3GlobalConfig.bMemstat==0 ){
22350  mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
22351  }
22352 
22353  return SQLITE_OK;
22354 }
22355 
22356 /*
22357 ** Deinitialize this module.
22358 */
22359 static void memsys5Shutdown(void *NotUsed){
22360  UNUSED_PARAMETER(NotUsed);
22361  mem5.mutex = 0;
22362  return;
22363 }
22364 
22365 #ifdef SQLITE_TEST
22366 /*
22367 ** Open the file indicated and write a log of all unfreed memory
22368 ** allocations into that log.
22369 */
22370 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
22371  FILE *out;
22372  int i, j, n;
22373  int nMinLog;
22374 
22375  if( zFilename==0 || zFilename[0]==0 ){
22376  out = stdout;
22377  }else{
22378  out = fopen(zFilename, "w");
22379  if( out==0 ){
22380  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22381  zFilename);
22382  return;
22383  }
22384  }
22385  memsys5Enter();
22386  nMinLog = memsys5Log(mem5.szAtom);
22387  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
22388  for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
22389  fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
22390  }
22391  fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
22392  fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
22393  fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
22394  fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
22395  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
22396  fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
22397  fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
22398  fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
22399  memsys5Leave();
22400  if( out==stdout ){
22401  fflush(stdout);
22402  }else{
22403  fclose(out);
22404  }
22405 }
22406 #endif
22407 
22408 /*
22409 ** This routine is the only routine in this file with external
22410 ** linkage. It returns a pointer to a static sqlite3_mem_methods
22411 ** struct populated with the memsys5 methods.
22412 */
22413 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
22414  static const sqlite3_mem_methods memsys5Methods = {
22415  memsys5Malloc,
22416  memsys5Free,
22417  memsys5Realloc,
22418  memsys5Size,
22419  memsys5Roundup,
22420  memsys5Init,
22421  memsys5Shutdown,
22422  0
22423  };
22424  return &memsys5Methods;
22425 }
22426 
22427 #endif /* SQLITE_ENABLE_MEMSYS5 */
22428 
22429 /************** End of mem5.c ************************************************/
22430 /************** Begin file mutex.c *******************************************/
22431 /*
22432 ** 2007 August 14
22433 **
22434 ** The author disclaims copyright to this source code. In place of
22435 ** a legal notice, here is a blessing:
22436 **
22437 ** May you do good and not evil.
22438 ** May you find forgiveness for yourself and forgive others.
22439 ** May you share freely, never taking more than you give.
22440 **
22441 *************************************************************************
22442 ** This file contains the C functions that implement mutexes.
22443 **
22444 ** This file contains code that is common across all mutex implementations.
22445 */
22446 /* #include "sqliteInt.h" */
22447 
22448 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
22449 /*
22450 ** For debugging purposes, record when the mutex subsystem is initialized
22451 ** and uninitialized so that we can assert() if there is an attempt to
22452 ** allocate a mutex while the system is uninitialized.
22453 */
22454 static SQLITE_WSD int mutexIsInit = 0;
22455 #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
22456 
22457 
22458 #ifndef SQLITE_MUTEX_OMIT
22459 /*
22460 ** Initialize the mutex system.
22461 */
22462 SQLITE_PRIVATE int sqlite3MutexInit(void){
22463  int rc = SQLITE_OK;
22464  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
22465  /* If the xMutexAlloc method has not been set, then the user did not
22466  ** install a mutex implementation via sqlite3_config() prior to
22467  ** sqlite3_initialize() being called. This block copies pointers to
22468  ** the default implementation into the sqlite3GlobalConfig structure.
22469  */
22470  sqlite3_mutex_methods const *pFrom;
22471  sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
22472 
22473  if( sqlite3GlobalConfig.bCoreMutex ){
22474  pFrom = sqlite3DefaultMutex();
22475  }else{
22476  pFrom = sqlite3NoopMutex();
22477  }
22478  pTo->xMutexInit = pFrom->xMutexInit;
22479  pTo->xMutexEnd = pFrom->xMutexEnd;
22480  pTo->xMutexFree = pFrom->xMutexFree;
22481  pTo->xMutexEnter = pFrom->xMutexEnter;
22482  pTo->xMutexTry = pFrom->xMutexTry;
22483  pTo->xMutexLeave = pFrom->xMutexLeave;
22484  pTo->xMutexHeld = pFrom->xMutexHeld;
22485  pTo->xMutexNotheld = pFrom->xMutexNotheld;
22486  sqlite3MemoryBarrier();
22487  pTo->xMutexAlloc = pFrom->xMutexAlloc;
22488  }
22489  assert( sqlite3GlobalConfig.mutex.xMutexInit );
22490  rc = sqlite3GlobalConfig.mutex.xMutexInit();
22491 
22492 #ifdef SQLITE_DEBUG
22493  GLOBAL(int, mutexIsInit) = 1;
22494 #endif
22495 
22496  return rc;
22497 }
22498 
22499 /*
22500 ** Shutdown the mutex system. This call frees resources allocated by
22501 ** sqlite3MutexInit().
22502 */
22503 SQLITE_PRIVATE int sqlite3MutexEnd(void){
22504  int rc = SQLITE_OK;
22505  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
22506  rc = sqlite3GlobalConfig.mutex.xMutexEnd();
22507  }
22508 
22509 #ifdef SQLITE_DEBUG
22510  GLOBAL(int, mutexIsInit) = 0;
22511 #endif
22512 
22513  return rc;
22514 }
22515 
22516 /*
22517 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
22518 */
22519 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
22520 #ifndef SQLITE_OMIT_AUTOINIT
22521  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
22522  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
22523 #endif
22524  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22525  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22526 }
22527 
22528 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
22529  if( !sqlite3GlobalConfig.bCoreMutex ){
22530  return 0;
22531  }
22532  assert( GLOBAL(int, mutexIsInit) );
22533  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22534  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22535 }
22536 
22537 /*
22538 ** Free a dynamic mutex.
22539 */
22540 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
22541  if( p ){
22542  assert( sqlite3GlobalConfig.mutex.xMutexFree );
22543  sqlite3GlobalConfig.mutex.xMutexFree(p);
22544  }
22545 }
22546 
22547 /*
22548 ** Obtain the mutex p. If some other thread already has the mutex, block
22549 ** until it can be obtained.
22550 */
22551 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
22552  if( p ){
22553  assert( sqlite3GlobalConfig.mutex.xMutexEnter );
22554  sqlite3GlobalConfig.mutex.xMutexEnter(p);
22555  }
22556 }
22557 
22558 /*
22559 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
22560 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
22561 */
22562 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
22563  int rc = SQLITE_OK;
22564  if( p ){
22565  assert( sqlite3GlobalConfig.mutex.xMutexTry );
22566  return sqlite3GlobalConfig.mutex.xMutexTry(p);
22567  }
22568  return rc;
22569 }
22570 
22571 /*
22572 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
22573 ** entered by the same thread. The behavior is undefined if the mutex
22574 ** is not currently entered. If a NULL pointer is passed as an argument
22575 ** this function is a no-op.
22576 */
22577 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
22578  if( p ){
22579  assert( sqlite3GlobalConfig.mutex.xMutexLeave );
22580  sqlite3GlobalConfig.mutex.xMutexLeave(p);
22581  }
22582 }
22583 
22584 #ifndef NDEBUG
22585 /*
22586 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22587 ** intended for use inside assert() statements.
22588 */
22589 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
22590  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
22591  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
22592 }
22593 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
22594  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
22595  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
22596 }
22597 #endif
22598 
22599 #endif /* !defined(SQLITE_MUTEX_OMIT) */
22600 
22601 /************** End of mutex.c ***********************************************/
22602 /************** Begin file mutex_noop.c **************************************/
22603 /*
22604 ** 2008 October 07
22605 **
22606 ** The author disclaims copyright to this source code. In place of
22607 ** a legal notice, here is a blessing:
22608 **
22609 ** May you do good and not evil.
22610 ** May you find forgiveness for yourself and forgive others.
22611 ** May you share freely, never taking more than you give.
22612 **
22613 *************************************************************************
22614 ** This file contains the C functions that implement mutexes.
22615 **
22616 ** This implementation in this file does not provide any mutual
22617 ** exclusion and is thus suitable for use only in applications
22618 ** that use SQLite in a single thread. The routines defined
22619 ** here are place-holders. Applications can substitute working
22620 ** mutex routines at start-time using the
22621 **
22622 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
22623 **
22624 ** interface.
22625 **
22626 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
22627 ** that does error checking on mutexes to make sure they are being
22628 ** called correctly.
22629 */
22630 /* #include "sqliteInt.h" */
22631 
22632 #ifndef SQLITE_MUTEX_OMIT
22633 
22634 #ifndef SQLITE_DEBUG
22635 /*
22636 ** Stub routines for all mutex methods.
22637 **
22638 ** This routines provide no mutual exclusion or error checking.
22639 */
22640 static int noopMutexInit(void){ return SQLITE_OK; }
22641 static int noopMutexEnd(void){ return SQLITE_OK; }
22642 static sqlite3_mutex *noopMutexAlloc(int id){
22643  UNUSED_PARAMETER(id);
22644  return (sqlite3_mutex*)8;
22645 }
22646 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22647 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22648 static int noopMutexTry(sqlite3_mutex *p){
22649  UNUSED_PARAMETER(p);
22650  return SQLITE_OK;
22651 }
22652 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22653 
22654 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
22655  static const sqlite3_mutex_methods sMutex = {
22656  noopMutexInit,
22657  noopMutexEnd,
22658  noopMutexAlloc,
22659  noopMutexFree,
22660  noopMutexEnter,
22661  noopMutexTry,
22662  noopMutexLeave,
22663 
22664  0,
22665  0,
22666  };
22667 
22668  return &sMutex;
22669 }
22670 #endif /* !SQLITE_DEBUG */
22671 
22672 #ifdef SQLITE_DEBUG
22673 /*
22674 ** In this implementation, error checking is provided for testing
22675 ** and debugging purposes. The mutexes still do not provide any
22676 ** mutual exclusion.
22677 */
22678 
22679 /*
22680 ** The mutex object
22681 */
22682 typedef struct sqlite3_debug_mutex {
22683  int id; /* The mutex type */
22684  int cnt; /* Number of entries without a matching leave */
22685 } sqlite3_debug_mutex;
22686 
22687 /*
22688 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22689 ** intended for use inside assert() statements.
22690 */
22691 static int debugMutexHeld(sqlite3_mutex *pX){
22692  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22693  return p==0 || p->cnt>0;
22694 }
22695 static int debugMutexNotheld(sqlite3_mutex *pX){
22696  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22697  return p==0 || p->cnt==0;
22698 }
22699 
22700 /*
22701 ** Initialize and deinitialize the mutex subsystem.
22702 */
22703 static int debugMutexInit(void){ return SQLITE_OK; }
22704 static int debugMutexEnd(void){ return SQLITE_OK; }
22705 
22706 /*
22707 ** The sqlite3_mutex_alloc() routine allocates a new
22708 ** mutex and returns a pointer to it. If it returns NULL
22709 ** that means that a mutex could not be allocated.
22710 */
22711 static sqlite3_mutex *debugMutexAlloc(int id){
22712  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
22713  sqlite3_debug_mutex *pNew = 0;
22714  switch( id ){
22715  case SQLITE_MUTEX_FAST:
22716  case SQLITE_MUTEX_RECURSIVE: {
22717  pNew = sqlite3Malloc(sizeof(*pNew));
22718  if( pNew ){
22719  pNew->id = id;
22720  pNew->cnt = 0;
22721  }
22722  break;
22723  }
22724  default: {
22725 #ifdef SQLITE_ENABLE_API_ARMOR
22726  if( id-2<0 || id-2>=ArraySize(aStatic) ){
22727  (void)SQLITE_MISUSE_BKPT;
22728  return 0;
22729  }
22730 #endif
22731  pNew = &aStatic[id-2];
22732  pNew->id = id;
22733  break;
22734  }
22735  }
22736  return (sqlite3_mutex*)pNew;
22737 }
22738 
22739 /*
22740 ** This routine deallocates a previously allocated mutex.
22741 */
22742 static void debugMutexFree(sqlite3_mutex *pX){
22743  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22744  assert( p->cnt==0 );
22745  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
22746  sqlite3_free(p);
22747  }else{
22748 #ifdef SQLITE_ENABLE_API_ARMOR
22749  (void)SQLITE_MISUSE_BKPT;
22750 #endif
22751  }
22752 }
22753 
22754 /*
22755 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22756 ** to enter a mutex. If another thread is already within the mutex,
22757 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22758 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
22759 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
22760 ** be entered multiple times by the same thread. In such cases the,
22761 ** mutex must be exited an equal number of times before another thread
22762 ** can enter. If the same thread tries to enter any other kind of mutex
22763 ** more than once, the behavior is undefined.
22764 */
22765 static void debugMutexEnter(sqlite3_mutex *pX){
22766  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22767  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22768  p->cnt++;
22769 }
22770 static int debugMutexTry(sqlite3_mutex *pX){
22771  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22772  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22773  p->cnt++;
22774  return SQLITE_OK;
22775 }
22776 
22777 /*
22778 ** The sqlite3_mutex_leave() routine exits a mutex that was
22779 ** previously entered by the same thread. The behavior
22780 ** is undefined if the mutex is not currently entered or
22781 ** is not currently allocated. SQLite will never do either.
22782 */
22783 static void debugMutexLeave(sqlite3_mutex *pX){
22784  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22785  assert( debugMutexHeld(pX) );
22786  p->cnt--;
22787  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22788 }
22789 
22790 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
22791  static const sqlite3_mutex_methods sMutex = {
22792  debugMutexInit,
22793  debugMutexEnd,
22794  debugMutexAlloc,
22795  debugMutexFree,
22796  debugMutexEnter,
22797  debugMutexTry,
22798  debugMutexLeave,
22799 
22800  debugMutexHeld,
22801  debugMutexNotheld
22802  };
22803 
22804  return &sMutex;
22805 }
22806 #endif /* SQLITE_DEBUG */
22807 
22808 /*
22809 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
22810 ** is used regardless of the run-time threadsafety setting.
22811 */
22812 #ifdef SQLITE_MUTEX_NOOP
22813 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
22814  return sqlite3NoopMutex();
22815 }
22816 #endif /* defined(SQLITE_MUTEX_NOOP) */
22817 #endif /* !defined(SQLITE_MUTEX_OMIT) */
22818 
22819 /************** End of mutex_noop.c ******************************************/
22820 /************** Begin file mutex_unix.c **************************************/
22821 /*
22822 ** 2007 August 28
22823 **
22824 ** The author disclaims copyright to this source code. In place of
22825 ** a legal notice, here is a blessing:
22826 **
22827 ** May you do good and not evil.
22828 ** May you find forgiveness for yourself and forgive others.
22829 ** May you share freely, never taking more than you give.
22830 **
22831 *************************************************************************
22832 ** This file contains the C functions that implement mutexes for pthreads
22833 */
22834 /* #include "sqliteInt.h" */
22835 
22836 /*
22837 ** The code in this file is only used if we are compiling threadsafe
22838 ** under unix with pthreads.
22839 **
22840 ** Note that this implementation requires a version of pthreads that
22841 ** supports recursive mutexes.
22842 */
22843 #ifdef SQLITE_MUTEX_PTHREADS
22844 
22845 #include <pthread.h>
22846 
22847 /*
22848 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
22849 ** are necessary under two condidtions: (1) Debug builds and (2) using
22850 ** home-grown mutexes. Encapsulate these conditions into a single #define.
22851 */
22852 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
22853 # define SQLITE_MUTEX_NREF 1
22854 #else
22855 # define SQLITE_MUTEX_NREF 0
22856 #endif
22857 
22858 /*
22859 ** Each recursive mutex is an instance of the following structure.
22860 */
22862  pthread_mutex_t mutex; /* Mutex controlling the lock */
22863 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22864  int id; /* Mutex type */
22865 #endif
22866 #if SQLITE_MUTEX_NREF
22867  volatile int nRef; /* Number of entrances */
22868  volatile pthread_t owner; /* Thread that is within this mutex */
22869  int trace; /* True to trace changes */
22870 #endif
22871 };
22872 #if SQLITE_MUTEX_NREF
22873 #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
22874 #elif defined(SQLITE_ENABLE_API_ARMOR)
22875 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
22876 #else
22877 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
22878 #endif
22879 
22880 /*
22881 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22882 ** intended for use only inside assert() statements. On some platforms,
22883 ** there might be race conditions that can cause these routines to
22884 ** deliver incorrect results. In particular, if pthread_equal() is
22885 ** not an atomic operation, then these routines might delivery
22886 ** incorrect results. On most platforms, pthread_equal() is a
22887 ** comparison of two integers and is therefore atomic. But we are
22888 ** told that HPUX is not such a platform. If so, then these routines
22889 ** will not always work correctly on HPUX.
22890 **
22891 ** On those platforms where pthread_equal() is not atomic, SQLite
22892 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
22893 ** make sure no assert() statements are evaluated and hence these
22894 ** routines are never called.
22895 */
22896 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
22897 static int pthreadMutexHeld(sqlite3_mutex *p){
22898  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
22899 }
22900 static int pthreadMutexNotheld(sqlite3_mutex *p){
22901  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
22902 }
22903 #endif
22904 
22905 /*
22906 ** Try to provide a memory barrier operation, needed for initialization
22907 ** and also for the implementation of xShmBarrier in the VFS in cases
22908 ** where SQLite is compiled without mutexes.
22909 */
22910 SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
22911 #if defined(SQLITE_MEMORY_BARRIER)
22912  SQLITE_MEMORY_BARRIER;
22913 #elif defined(__GNUC__) && GCC_VERSION>=4001000
22914  __sync_synchronize();
22915 #endif
22916 }
22917 
22918 /*
22919 ** Initialize and deinitialize the mutex subsystem.
22920 */
22921 static int pthreadMutexInit(void){ return SQLITE_OK; }
22922 static int pthreadMutexEnd(void){ return SQLITE_OK; }
22923 
22924 /*
22925 ** The sqlite3_mutex_alloc() routine allocates a new
22926 ** mutex and returns a pointer to it. If it returns NULL
22927 ** that means that a mutex could not be allocated. SQLite
22928 ** will unwind its stack and return an error. The argument
22929 ** to sqlite3_mutex_alloc() is one of these integer constants:
22930 **
22931 ** <ul>
22932 ** <li> SQLITE_MUTEX_FAST
22933 ** <li> SQLITE_MUTEX_RECURSIVE
22934 ** <li> SQLITE_MUTEX_STATIC_MASTER
22935 ** <li> SQLITE_MUTEX_STATIC_MEM
22936 ** <li> SQLITE_MUTEX_STATIC_OPEN
22937 ** <li> SQLITE_MUTEX_STATIC_PRNG
22938 ** <li> SQLITE_MUTEX_STATIC_LRU
22939 ** <li> SQLITE_MUTEX_STATIC_PMEM
22940 ** <li> SQLITE_MUTEX_STATIC_APP1
22941 ** <li> SQLITE_MUTEX_STATIC_APP2
22942 ** <li> SQLITE_MUTEX_STATIC_APP3
22943 ** <li> SQLITE_MUTEX_STATIC_VFS1
22944 ** <li> SQLITE_MUTEX_STATIC_VFS2
22945 ** <li> SQLITE_MUTEX_STATIC_VFS3
22946 ** </ul>
22947 **
22948 ** The first two constants cause sqlite3_mutex_alloc() to create
22949 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
22950 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
22951 ** The mutex implementation does not need to make a distinction
22952 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
22953 ** not want to. But SQLite will only request a recursive mutex in
22954 ** cases where it really needs one. If a faster non-recursive mutex
22955 ** implementation is available on the host platform, the mutex subsystem
22956 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
22957 **
22958 ** The other allowed parameters to sqlite3_mutex_alloc() each return
22959 ** a pointer to a static preexisting mutex. Six static mutexes are
22960 ** used by the current version of SQLite. Future versions of SQLite
22961 ** may add additional static mutexes. Static mutexes are for internal
22962 ** use by SQLite only. Applications that use SQLite mutexes should
22963 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
22964 ** SQLITE_MUTEX_RECURSIVE.
22965 **
22966 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
22967 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
22968 ** returns a different mutex on every call. But for the static
22969 ** mutex types, the same mutex is returned on every call that has
22970 ** the same type number.
22971 */
22972 static sqlite3_mutex *pthreadMutexAlloc(int iType){
22973  static sqlite3_mutex staticMutexes[] = {
22974  SQLITE3_MUTEX_INITIALIZER,
22975  SQLITE3_MUTEX_INITIALIZER,
22976  SQLITE3_MUTEX_INITIALIZER,
22977  SQLITE3_MUTEX_INITIALIZER,
22978  SQLITE3_MUTEX_INITIALIZER,
22979  SQLITE3_MUTEX_INITIALIZER,
22980  SQLITE3_MUTEX_INITIALIZER,
22981  SQLITE3_MUTEX_INITIALIZER,
22982  SQLITE3_MUTEX_INITIALIZER,
22983  SQLITE3_MUTEX_INITIALIZER,
22984  SQLITE3_MUTEX_INITIALIZER,
22985  SQLITE3_MUTEX_INITIALIZER
22986  };
22987  sqlite3_mutex *p;
22988  switch( iType ){
22989  case SQLITE_MUTEX_RECURSIVE: {
22990  p = sqlite3MallocZero( sizeof(*p) );
22991  if( p ){
22992 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22993  /* If recursive mutexes are not available, we will have to
22994  ** build our own. See below. */
22995  pthread_mutex_init(&p->mutex, 0);
22996 #else
22997  /* Use a recursive mutex if it is available */
22998  pthread_mutexattr_t recursiveAttr;
22999  pthread_mutexattr_init(&recursiveAttr);
23000  pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
23001  pthread_mutex_init(&p->mutex, &recursiveAttr);
23002  pthread_mutexattr_destroy(&recursiveAttr);
23003 #endif
23004  }
23005  break;
23006  }
23007  case SQLITE_MUTEX_FAST: {
23008  p = sqlite3MallocZero( sizeof(*p) );
23009  if( p ){
23010  pthread_mutex_init(&p->mutex, 0);
23011  }
23012  break;
23013  }
23014  default: {
23015 #ifdef SQLITE_ENABLE_API_ARMOR
23016  if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
23017  (void)SQLITE_MISUSE_BKPT;
23018  return 0;
23019  }
23020 #endif
23021  p = &staticMutexes[iType-2];
23022  break;
23023  }
23024  }
23025 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
23026  if( p ) p->id = iType;
23027 #endif
23028  return p;
23029 }
23030 
23031 
23032 /*
23033 ** This routine deallocates a previously
23034 ** allocated mutex. SQLite is careful to deallocate every
23035 ** mutex that it allocates.
23036 */
23037 static void pthreadMutexFree(sqlite3_mutex *p){
23038  assert( p->nRef==0 );
23039 #if SQLITE_ENABLE_API_ARMOR
23040  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
23041 #endif
23042  {
23043  pthread_mutex_destroy(&p->mutex);
23044  sqlite3_free(p);
23045  }
23046 #ifdef SQLITE_ENABLE_API_ARMOR
23047  else{
23048  (void)SQLITE_MISUSE_BKPT;
23049  }
23050 #endif
23051 }
23052 
23053 /*
23054 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23055 ** to enter a mutex. If another thread is already within the mutex,
23056 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23057 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
23058 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
23059 ** be entered multiple times by the same thread. In such cases the,
23060 ** mutex must be exited an equal number of times before another thread
23061 ** can enter. If the same thread tries to enter any other kind of mutex
23062 ** more than once, the behavior is undefined.
23063 */
23064 static void pthreadMutexEnter(sqlite3_mutex *p){
23065  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23066 
23067 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23068  /* If recursive mutexes are not available, then we have to grow
23069  ** our own. This implementation assumes that pthread_equal()
23070  ** is atomic - that it cannot be deceived into thinking self
23071  ** and p->owner are equal if p->owner changes between two values
23072  ** that are not equal to self while the comparison is taking place.
23073  ** This implementation also assumes a coherent cache - that
23074  ** separate processes cannot read different values from the same
23075  ** address at the same time. If either of these two conditions
23076  ** are not met, then the mutexes will fail and problems will result.
23077  */
23078  {
23079  pthread_t self = pthread_self();
23080  if( p->nRef>0 && pthread_equal(p->owner, self) ){
23081  p->nRef++;
23082  }else{
23083  pthread_mutex_lock(&p->mutex);
23084  assert( p->nRef==0 );
23085  p->owner = self;
23086  p->nRef = 1;
23087  }
23088  }
23089 #else
23090  /* Use the built-in recursive mutexes if they are available.
23091  */
23092  pthread_mutex_lock(&p->mutex);
23093 #if SQLITE_MUTEX_NREF
23094  assert( p->nRef>0 || p->owner==0 );
23095  p->owner = pthread_self();
23096  p->nRef++;
23097 #endif
23098 #endif
23099 
23100 #ifdef SQLITE_DEBUG
23101  if( p->trace ){
23102  printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23103  }
23104 #endif
23105 }
23106 static int pthreadMutexTry(sqlite3_mutex *p){
23107  int rc;
23108  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23109 
23110 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23111  /* If recursive mutexes are not available, then we have to grow
23112  ** our own. This implementation assumes that pthread_equal()
23113  ** is atomic - that it cannot be deceived into thinking self
23114  ** and p->owner are equal if p->owner changes between two values
23115  ** that are not equal to self while the comparison is taking place.
23116  ** This implementation also assumes a coherent cache - that
23117  ** separate processes cannot read different values from the same
23118  ** address at the same time. If either of these two conditions
23119  ** are not met, then the mutexes will fail and problems will result.
23120  */
23121  {
23122  pthread_t self = pthread_self();
23123  if( p->nRef>0 && pthread_equal(p->owner, self) ){
23124  p->nRef++;
23125  rc = SQLITE_OK;
23126  }else if( pthread_mutex_trylock(&p->mutex)==0 ){
23127  assert( p->nRef==0 );
23128  p->owner = self;
23129  p->nRef = 1;
23130  rc = SQLITE_OK;
23131  }else{
23132  rc = SQLITE_BUSY;
23133  }
23134  }
23135 #else
23136  /* Use the built-in recursive mutexes if they are available.
23137  */
23138  if( pthread_mutex_trylock(&p->mutex)==0 ){
23139 #if SQLITE_MUTEX_NREF
23140  p->owner = pthread_self();
23141  p->nRef++;
23142 #endif
23143  rc = SQLITE_OK;
23144  }else{
23145  rc = SQLITE_BUSY;
23146  }
23147 #endif
23148 
23149 #ifdef SQLITE_DEBUG
23150  if( rc==SQLITE_OK && p->trace ){
23151  printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23152  }
23153 #endif
23154  return rc;
23155 }
23156 
23157 /*
23158 ** The sqlite3_mutex_leave() routine exits a mutex that was
23159 ** previously entered by the same thread. The behavior
23160 ** is undefined if the mutex is not currently entered or
23161 ** is not currently allocated. SQLite will never do either.
23162 */
23163 static void pthreadMutexLeave(sqlite3_mutex *p){
23164  assert( pthreadMutexHeld(p) );
23165 #if SQLITE_MUTEX_NREF
23166  p->nRef--;
23167  if( p->nRef==0 ) p->owner = 0;
23168 #endif
23169  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23170 
23171 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23172  if( p->nRef==0 ){
23173  pthread_mutex_unlock(&p->mutex);
23174  }
23175 #else
23176  pthread_mutex_unlock(&p->mutex);
23177 #endif
23178 
23179 #ifdef SQLITE_DEBUG
23180  if( p->trace ){
23181  printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23182  }
23183 #endif
23184 }
23185 
23186 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23187  static const sqlite3_mutex_methods sMutex = {
23188  pthreadMutexInit,
23189  pthreadMutexEnd,
23190  pthreadMutexAlloc,
23191  pthreadMutexFree,
23192  pthreadMutexEnter,
23193  pthreadMutexTry,
23194  pthreadMutexLeave,
23195 #ifdef SQLITE_DEBUG
23196  pthreadMutexHeld,
23197  pthreadMutexNotheld
23198 #else
23199  0,
23200  0
23201 #endif
23202  };
23203 
23204  return &sMutex;
23205 }
23206 
23207 #endif /* SQLITE_MUTEX_PTHREADS */
23208 
23209 /************** End of mutex_unix.c ******************************************/
23210 /************** Begin file mutex_w32.c ***************************************/
23211 /*
23212 ** 2007 August 14
23213 **
23214 ** The author disclaims copyright to this source code. In place of
23215 ** a legal notice, here is a blessing:
23216 **
23217 ** May you do good and not evil.
23218 ** May you find forgiveness for yourself and forgive others.
23219 ** May you share freely, never taking more than you give.
23220 **
23221 *************************************************************************
23222 ** This file contains the C functions that implement mutexes for Win32.
23223 */
23224 /* #include "sqliteInt.h" */
23225 
23226 #if SQLITE_OS_WIN
23227 /*
23228 ** Include code that is common to all os_*.c files
23229 */
23230 /************** Include os_common.h in the middle of mutex_w32.c *************/
23231 /************** Begin file os_common.h ***************************************/
23232 /*
23233 ** 2004 May 22
23234 **
23235 ** The author disclaims copyright to this source code. In place of
23236 ** a legal notice, here is a blessing:
23237 **
23238 ** May you do good and not evil.
23239 ** May you find forgiveness for yourself and forgive others.
23240 ** May you share freely, never taking more than you give.
23241 **
23242 ******************************************************************************
23243 **
23244 ** This file contains macros and a little bit of code that is common to
23245 ** all of the platform-specific files (os_*.c) and is #included into those
23246 ** files.
23247 **
23248 ** This file should be #included by the os_*.c files only. It is not a
23249 ** general purpose header file.
23250 */
23251 #ifndef _OS_COMMON_H_
23252 #define _OS_COMMON_H_
23253 
23254 /*
23255 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23256 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23257 ** switch. The following code should catch this problem at compile-time.
23258 */
23259 #ifdef MEMORY_DEBUG
23260 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
23261 #endif
23262 
23263 /*
23264 ** Macros for performance tracing. Normally turned off. Only works
23265 ** on i486 hardware.
23266 */
23267 #ifdef SQLITE_PERFORMANCE_TRACE
23268 
23269 /*
23270 ** hwtime.h contains inline assembler code for implementing
23271 ** high-performance timing routines.
23272 */
23273 /************** Include hwtime.h in the middle of os_common.h ****************/
23274 /************** Begin file hwtime.h ******************************************/
23275 /*
23276 ** 2008 May 27
23277 **
23278 ** The author disclaims copyright to this source code. In place of
23279 ** a legal notice, here is a blessing:
23280 **
23281 ** May you do good and not evil.
23282 ** May you find forgiveness for yourself and forgive others.
23283 ** May you share freely, never taking more than you give.
23284 **
23285 ******************************************************************************
23286 **
23287 ** This file contains inline asm code for retrieving "high-performance"
23288 ** counters for x86 class CPUs.
23289 */
23290 #ifndef SQLITE_HWTIME_H
23291 #define SQLITE_HWTIME_H
23292 
23293 /*
23294 ** The following routine only works on pentium-class (or newer) processors.
23295 ** It uses the RDTSC opcode to read the cycle count value out of the
23296 ** processor and returns that value. This can be used for high-res
23297 ** profiling.
23298 */
23299 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23300  (defined(i386) || defined(__i386__) || defined(_M_IX86))
23301 
23302  #if defined(__GNUC__)
23303 
23304  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23305  unsigned int lo, hi;
23306  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23307  return (sqlite_uint64)hi << 32 | lo;
23308  }
23309 
23310  #elif defined(_MSC_VER)
23311 
23312  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23313  __asm {
23314  rdtsc
23315  ret ; return value at EDX:EAX
23316  }
23317  }
23318 
23319  #endif
23320 
23321 #elif (defined(__GNUC__) && defined(__x86_64__))
23322 
23323  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23324  unsigned long val;
23325  __asm__ __volatile__ ("rdtsc" : "=A" (val));
23326  return val;
23327  }
23328 
23329 #elif (defined(__GNUC__) && defined(__ppc__))
23330 
23331  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23332  unsigned long long retval;
23333  unsigned long junk;
23334  __asm__ __volatile__ ("\n\
23335  1: mftbu %1\n\
23336  mftb %L0\n\
23337  mftbu %0\n\
23338  cmpw %0,%1\n\
23339  bne 1b"
23340  : "=r" (retval), "=r" (junk));
23341  return retval;
23342  }
23343 
23344 #else
23345 
23346  #error Need implementation of sqlite3Hwtime() for your platform.
23347 
23348  /*
23349  ** To compile without implementing sqlite3Hwtime() for your platform,
23350  ** you can remove the above #error and use the following
23351  ** stub function. You will lose timing support for many
23352  ** of the debugging and testing utilities, but it should at
23353  ** least compile and run.
23354  */
23355 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23356 
23357 #endif
23358 
23359 #endif /* !defined(SQLITE_HWTIME_H) */
23360 
23361 /************** End of hwtime.h **********************************************/
23362 /************** Continuing where we left off in os_common.h ******************/
23363 
23364 static sqlite_uint64 g_start;
23365 static sqlite_uint64 g_elapsed;
23366 #define TIMER_START g_start=sqlite3Hwtime()
23367 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
23368 #define TIMER_ELAPSED g_elapsed
23369 #else
23370 #define TIMER_START
23371 #define TIMER_END
23372 #define TIMER_ELAPSED ((sqlite_uint64)0)
23373 #endif
23374 
23375 /*
23376 ** If we compile with the SQLITE_TEST macro set, then the following block
23377 ** of code will give us the ability to simulate a disk I/O error. This
23378 ** is used for testing the I/O recovery logic.
23379 */
23380 #if defined(SQLITE_TEST)
23381 SQLITE_API extern int sqlite3_io_error_hit;
23382 SQLITE_API extern int sqlite3_io_error_hardhit;
23383 SQLITE_API extern int sqlite3_io_error_pending;
23384 SQLITE_API extern int sqlite3_io_error_persist;
23385 SQLITE_API extern int sqlite3_io_error_benign;
23386 SQLITE_API extern int sqlite3_diskfull_pending;
23387 SQLITE_API extern int sqlite3_diskfull;
23388 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23389 #define SimulateIOError(CODE) \
23390  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23391  || sqlite3_io_error_pending-- == 1 ) \
23392  { local_ioerr(); CODE; }
23393 static void local_ioerr(){
23394  IOTRACE(("IOERR\n"));
23395  sqlite3_io_error_hit++;
23396  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23397 }
23398 #define SimulateDiskfullError(CODE) \
23399  if( sqlite3_diskfull_pending ){ \
23400  if( sqlite3_diskfull_pending == 1 ){ \
23401  local_ioerr(); \
23402  sqlite3_diskfull = 1; \
23403  sqlite3_io_error_hit = 1; \
23404  CODE; \
23405  }else{ \
23406  sqlite3_diskfull_pending--; \
23407  } \
23408  }
23409 #else
23410 #define SimulateIOErrorBenign(X)
23411 #define SimulateIOError(A)
23412 #define SimulateDiskfullError(A)
23413 #endif /* defined(SQLITE_TEST) */
23414 
23415 /*
23416 ** When testing, keep a count of the number of open files.
23417 */
23418 #if defined(SQLITE_TEST)
23419 SQLITE_API extern int sqlite3_open_file_count;
23420 #define OpenCounter(X) sqlite3_open_file_count+=(X)
23421 #else
23422 #define OpenCounter(X)
23423 #endif /* defined(SQLITE_TEST) */
23424 
23425 #endif /* !defined(_OS_COMMON_H_) */
23426 
23427 /************** End of os_common.h *******************************************/
23428 /************** Continuing where we left off in mutex_w32.c ******************/
23429 
23430 /*
23431 ** Include the header file for the Windows VFS.
23432 */
23433 /************** Include os_win.h in the middle of mutex_w32.c ****************/
23434 /************** Begin file os_win.h ******************************************/
23435 /*
23436 ** 2013 November 25
23437 **
23438 ** The author disclaims copyright to this source code. In place of
23439 ** a legal notice, here is a blessing:
23440 **
23441 ** May you do good and not evil.
23442 ** May you find forgiveness for yourself and forgive others.
23443 ** May you share freely, never taking more than you give.
23444 **
23445 ******************************************************************************
23446 **
23447 ** This file contains code that is specific to Windows.
23448 */
23449 #ifndef SQLITE_OS_WIN_H
23450 #define SQLITE_OS_WIN_H
23451 
23452 /*
23453 ** Include the primary Windows SDK header file.
23454 */
23455 #include "windows.h"
23456 
23457 #ifdef __CYGWIN__
23458 # include <sys/cygwin.h>
23459 # include <errno.h> /* amalgamator: dontcache */
23460 #endif
23461 
23462 /*
23463 ** Determine if we are dealing with Windows NT.
23464 **
23465 ** We ought to be able to determine if we are compiling for Windows 9x or
23466 ** Windows NT using the _WIN32_WINNT macro as follows:
23467 **
23468 ** #if defined(_WIN32_WINNT)
23469 ** # define SQLITE_OS_WINNT 1
23470 ** #else
23471 ** # define SQLITE_OS_WINNT 0
23472 ** #endif
23473 **
23474 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
23475 ** it ought to, so the above test does not work. We'll just assume that
23476 ** everything is Windows NT unless the programmer explicitly says otherwise
23477 ** by setting SQLITE_OS_WINNT to 0.
23478 */
23479 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
23480 # define SQLITE_OS_WINNT 1
23481 #endif
23482 
23483 /*
23484 ** Determine if we are dealing with Windows CE - which has a much reduced
23485 ** API.
23486 */
23487 #if defined(_WIN32_WCE)
23488 # define SQLITE_OS_WINCE 1
23489 #else
23490 # define SQLITE_OS_WINCE 0
23491 #endif
23492 
23493 /*
23494 ** Determine if we are dealing with WinRT, which provides only a subset of
23495 ** the full Win32 API.
23496 */
23497 #if !defined(SQLITE_OS_WINRT)
23498 # define SQLITE_OS_WINRT 0
23499 #endif
23500 
23501 /*
23502 ** For WinCE, some API function parameters do not appear to be declared as
23503 ** volatile.
23504 */
23505 #if SQLITE_OS_WINCE
23506 # define SQLITE_WIN32_VOLATILE
23507 #else
23508 # define SQLITE_WIN32_VOLATILE volatile
23509 #endif
23510 
23511 /*
23512 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
23513 ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
23514 */
23515 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
23516  SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
23517 # define SQLITE_OS_WIN_THREADS 1
23518 #else
23519 # define SQLITE_OS_WIN_THREADS 0
23520 #endif
23521 
23522 #endif /* SQLITE_OS_WIN_H */
23523 
23524 /************** End of os_win.h **********************************************/
23525 /************** Continuing where we left off in mutex_w32.c ******************/
23526 #endif
23527 
23528 /*
23529 ** The code in this file is only used if we are compiling multithreaded
23530 ** on a Win32 system.
23531 */
23532 #ifdef SQLITE_MUTEX_W32
23533 
23534 /*
23535 ** Each recursive mutex is an instance of the following structure.
23536 */
23537 struct sqlite3_mutex {
23538  CRITICAL_SECTION mutex; /* Mutex controlling the lock */
23539  int id; /* Mutex type */
23540 #ifdef SQLITE_DEBUG
23541  volatile int nRef; /* Number of enterances */
23542  volatile DWORD owner; /* Thread holding this mutex */
23543  volatile int trace; /* True to trace changes */
23544 #endif
23545 };
23546 
23547 /*
23548 ** These are the initializer values used when declaring a "static" mutex
23549 ** on Win32. It should be noted that all mutexes require initialization
23550 ** on the Win32 platform.
23551 */
23552 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
23553 
23554 #ifdef SQLITE_DEBUG
23555 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
23556  0L, (DWORD)0, 0 }
23557 #else
23558 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
23559 #endif
23560 
23561 #ifdef SQLITE_DEBUG
23562 /*
23563 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23564 ** intended for use only inside assert() statements.
23565 */
23566 static int winMutexHeld(sqlite3_mutex *p){
23567  return p->nRef!=0 && p->owner==GetCurrentThreadId();
23568 }
23569 
23570 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
23571  return p->nRef==0 || p->owner!=tid;
23572 }
23573 
23574 static int winMutexNotheld(sqlite3_mutex *p){
23575  DWORD tid = GetCurrentThreadId();
23576  return winMutexNotheld2(p, tid);
23577 }
23578 #endif
23579 
23580 /*
23581 ** Try to provide a memory barrier operation, needed for initialization
23582 ** and also for the xShmBarrier method of the VFS in cases when SQLite is
23583 ** compiled without mutexes (SQLITE_THREADSAFE=0).
23584 */
23585 SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
23586 #if defined(SQLITE_MEMORY_BARRIER)
23587  SQLITE_MEMORY_BARRIER;
23588 #elif defined(__GNUC__)
23589  __sync_synchronize();
23590 #elif !defined(SQLITE_DISABLE_INTRINSIC) && \
23591  defined(_MSC_VER) && _MSC_VER>=1300
23592  _ReadWriteBarrier();
23593 #elif defined(MemoryBarrier)
23594  MemoryBarrier();
23595 #endif
23596 }
23597 
23598 /*
23599 ** Initialize and deinitialize the mutex subsystem.
23600 */
23601 static sqlite3_mutex winMutex_staticMutexes[] = {
23602  SQLITE3_MUTEX_INITIALIZER,
23603  SQLITE3_MUTEX_INITIALIZER,
23604  SQLITE3_MUTEX_INITIALIZER,
23605  SQLITE3_MUTEX_INITIALIZER,
23606  SQLITE3_MUTEX_INITIALIZER,
23607  SQLITE3_MUTEX_INITIALIZER,
23608  SQLITE3_MUTEX_INITIALIZER,
23609  SQLITE3_MUTEX_INITIALIZER,
23610  SQLITE3_MUTEX_INITIALIZER,
23611  SQLITE3_MUTEX_INITIALIZER,
23612  SQLITE3_MUTEX_INITIALIZER,
23613  SQLITE3_MUTEX_INITIALIZER
23614 };
23615 
23616 static int winMutex_isInit = 0;
23617 static int winMutex_isNt = -1; /* <0 means "need to query" */
23618 
23619 /* As the winMutexInit() and winMutexEnd() functions are called as part
23620 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
23621 ** "interlocked" magic used here is probably not strictly necessary.
23622 */
23623 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
23624 
23625 SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
23626 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
23627 
23628 static int winMutexInit(void){
23629  /* The first to increment to 1 does actual initialization */
23630  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
23631  int i;
23632  for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23633 #if SQLITE_OS_WINRT
23634  InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
23635 #else
23636  InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
23637 #endif
23638  }
23639  winMutex_isInit = 1;
23640  }else{
23641  /* Another thread is (in the process of) initializing the static
23642  ** mutexes */
23643  while( !winMutex_isInit ){
23644  sqlite3_win32_sleep(1);
23645  }
23646  }
23647  return SQLITE_OK;
23648 }
23649 
23650 static int winMutexEnd(void){
23651  /* The first to decrement to 0 does actual shutdown
23652  ** (which should be the last to shutdown.) */
23653  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
23654  if( winMutex_isInit==1 ){
23655  int i;
23656  for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23657  DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
23658  }
23659  winMutex_isInit = 0;
23660  }
23661  }
23662  return SQLITE_OK;
23663 }
23664 
23665 /*
23666 ** The sqlite3_mutex_alloc() routine allocates a new
23667 ** mutex and returns a pointer to it. If it returns NULL
23668 ** that means that a mutex could not be allocated. SQLite
23669 ** will unwind its stack and return an error. The argument
23670 ** to sqlite3_mutex_alloc() is one of these integer constants:
23671 **
23672 ** <ul>
23673 ** <li> SQLITE_MUTEX_FAST
23674 ** <li> SQLITE_MUTEX_RECURSIVE
23675 ** <li> SQLITE_MUTEX_STATIC_MASTER
23676 ** <li> SQLITE_MUTEX_STATIC_MEM
23677 ** <li> SQLITE_MUTEX_STATIC_OPEN
23678 ** <li> SQLITE_MUTEX_STATIC_PRNG
23679 ** <li> SQLITE_MUTEX_STATIC_LRU
23680 ** <li> SQLITE_MUTEX_STATIC_PMEM
23681 ** <li> SQLITE_MUTEX_STATIC_APP1
23682 ** <li> SQLITE_MUTEX_STATIC_APP2
23683 ** <li> SQLITE_MUTEX_STATIC_APP3
23684 ** <li> SQLITE_MUTEX_STATIC_VFS1
23685 ** <li> SQLITE_MUTEX_STATIC_VFS2
23686 ** <li> SQLITE_MUTEX_STATIC_VFS3
23687 ** </ul>
23688 **
23689 ** The first two constants cause sqlite3_mutex_alloc() to create
23690 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23691 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23692 ** The mutex implementation does not need to make a distinction
23693 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23694 ** not want to. But SQLite will only request a recursive mutex in
23695 ** cases where it really needs one. If a faster non-recursive mutex
23696 ** implementation is available on the host platform, the mutex subsystem
23697 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
23698 **
23699 ** The other allowed parameters to sqlite3_mutex_alloc() each return
23700 ** a pointer to a static preexisting mutex. Six static mutexes are
23701 ** used by the current version of SQLite. Future versions of SQLite
23702 ** may add additional static mutexes. Static mutexes are for internal
23703 ** use by SQLite only. Applications that use SQLite mutexes should
23704 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23705 ** SQLITE_MUTEX_RECURSIVE.
23706 **
23707 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23708 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23709 ** returns a different mutex on every call. But for the static
23710 ** mutex types, the same mutex is returned on every call that has
23711 ** the same type number.
23712 */
23713 static sqlite3_mutex *winMutexAlloc(int iType){
23714  sqlite3_mutex *p;
23715 
23716  switch( iType ){
23717  case SQLITE_MUTEX_FAST:
23718  case SQLITE_MUTEX_RECURSIVE: {
23719  p = sqlite3MallocZero( sizeof(*p) );
23720  if( p ){
23721  p->id = iType;
23722 #ifdef SQLITE_DEBUG
23723 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
23724  p->trace = 1;
23725 #endif
23726 #endif
23727 #if SQLITE_OS_WINRT
23728  InitializeCriticalSectionEx(&p->mutex, 0, 0);
23729 #else
23730  InitializeCriticalSection(&p->mutex);
23731 #endif
23732  }
23733  break;
23734  }
23735  default: {
23736 #ifdef SQLITE_ENABLE_API_ARMOR
23737  if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
23738  (void)SQLITE_MISUSE_BKPT;
23739  return 0;
23740  }
23741 #endif
23742  p = &winMutex_staticMutexes[iType-2];
23743  p->id = iType;
23744 #ifdef SQLITE_DEBUG
23745 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
23746  p->trace = 1;
23747 #endif
23748 #endif
23749  break;
23750  }
23751  }
23752  return p;
23753 }
23754 
23755 
23756 /*
23757 ** This routine deallocates a previously
23758 ** allocated mutex. SQLite is careful to deallocate every
23759 ** mutex that it allocates.
23760 */
23761 static void winMutexFree(sqlite3_mutex *p){
23762  assert( p );
23763  assert( p->nRef==0 && p->owner==0 );
23764  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
23765  DeleteCriticalSection(&p->mutex);
23766  sqlite3_free(p);
23767  }else{
23768 #ifdef SQLITE_ENABLE_API_ARMOR
23769  (void)SQLITE_MISUSE_BKPT;
23770 #endif
23771  }
23772 }
23773 
23774 /*
23775 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23776 ** to enter a mutex. If another thread is already within the mutex,
23777 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23778 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
23779 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
23780 ** be entered multiple times by the same thread. In such cases the,
23781 ** mutex must be exited an equal number of times before another thread
23782 ** can enter. If the same thread tries to enter any other kind of mutex
23783 ** more than once, the behavior is undefined.
23784 */
23785 static void winMutexEnter(sqlite3_mutex *p){
23786 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23787  DWORD tid = GetCurrentThreadId();
23788 #endif
23789 #ifdef SQLITE_DEBUG
23790  assert( p );
23791  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23792 #else
23793  assert( p );
23794 #endif
23795  assert( winMutex_isInit==1 );
23796  EnterCriticalSection(&p->mutex);
23797 #ifdef SQLITE_DEBUG
23798  assert( p->nRef>0 || p->owner==0 );
23799  p->owner = tid;
23800  p->nRef++;
23801  if( p->trace ){
23802  OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23803  tid, p, p->trace, p->nRef));
23804  }
23805 #endif
23806 }
23807 
23808 static int winMutexTry(sqlite3_mutex *p){
23809 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23810  DWORD tid = GetCurrentThreadId();
23811 #endif
23812  int rc = SQLITE_BUSY;
23813  assert( p );
23814  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23815  /*
23816  ** The sqlite3_mutex_try() routine is very rarely used, and when it
23817  ** is used it is merely an optimization. So it is OK for it to always
23818  ** fail.
23819  **
23820  ** The TryEnterCriticalSection() interface is only available on WinNT.
23821  ** And some windows compilers complain if you try to use it without
23822  ** first doing some #defines that prevent SQLite from building on Win98.
23823  ** For that reason, we will omit this optimization for now. See
23824  ** ticket #2685.
23825  */
23826 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
23827  assert( winMutex_isInit==1 );
23828  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
23829  if( winMutex_isNt<0 ){
23830  winMutex_isNt = sqlite3_win32_is_nt();
23831  }
23832  assert( winMutex_isNt==0 || winMutex_isNt==1 );
23833  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
23834 #ifdef SQLITE_DEBUG
23835  p->owner = tid;
23836  p->nRef++;
23837 #endif
23838  rc = SQLITE_OK;
23839  }
23840 #else
23841  UNUSED_PARAMETER(p);
23842 #endif
23843 #ifdef SQLITE_DEBUG
23844  if( p->trace ){
23845  OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
23846  tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
23847  }
23848 #endif
23849  return rc;
23850 }
23851 
23852 /*
23853 ** The sqlite3_mutex_leave() routine exits a mutex that was
23854 ** previously entered by the same thread. The behavior
23855 ** is undefined if the mutex is not currently entered or
23856 ** is not currently allocated. SQLite will never do either.
23857 */
23858 static void winMutexLeave(sqlite3_mutex *p){
23859 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23860  DWORD tid = GetCurrentThreadId();
23861 #endif
23862  assert( p );
23863 #ifdef SQLITE_DEBUG
23864  assert( p->nRef>0 );
23865  assert( p->owner==tid );
23866  p->nRef--;
23867  if( p->nRef==0 ) p->owner = 0;
23868  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23869 #endif
23870  assert( winMutex_isInit==1 );
23871  LeaveCriticalSection(&p->mutex);
23872 #ifdef SQLITE_DEBUG
23873  if( p->trace ){
23874  OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23875  tid, p, p->trace, p->nRef));
23876  }
23877 #endif
23878 }
23879 
23880 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23881  static const sqlite3_mutex_methods sMutex = {
23882  winMutexInit,
23883  winMutexEnd,
23884  winMutexAlloc,
23885  winMutexFree,
23886  winMutexEnter,
23887  winMutexTry,
23888  winMutexLeave,
23889 #ifdef SQLITE_DEBUG
23890  winMutexHeld,
23891  winMutexNotheld
23892 #else
23893  0,
23894  0
23895 #endif
23896  };
23897  return &sMutex;
23898 }
23899 
23900 #endif /* SQLITE_MUTEX_W32 */
23901 
23902 /************** End of mutex_w32.c *******************************************/
23903 /************** Begin file malloc.c ******************************************/
23904 /*
23905 ** 2001 September 15
23906 **
23907 ** The author disclaims copyright to this source code. In place of
23908 ** a legal notice, here is a blessing:
23909 **
23910 ** May you do good and not evil.
23911 ** May you find forgiveness for yourself and forgive others.
23912 ** May you share freely, never taking more than you give.
23913 **
23914 *************************************************************************
23915 **
23916 ** Memory allocation functions used throughout sqlite.
23917 */
23918 /* #include "sqliteInt.h" */
23919 /* #include <stdarg.h> */
23920 
23921 /*
23922 ** Attempt to release up to n bytes of non-essential memory currently
23923 ** held by SQLite. An example of non-essential memory is memory used to
23924 ** cache database pages that are not currently in use.
23925 */
23926 SQLITE_API int sqlite3_release_memory(int n){
23927 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23928  return sqlite3PcacheReleaseMemory(n);
23929 #else
23930  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
23931  ** is a no-op returning zero if SQLite is not compiled with
23932  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
23933  UNUSED_PARAMETER(n);
23934  return 0;
23935 #endif
23936 }
23937 
23938 /*
23939 ** An instance of the following object records the location of
23940 ** each unused scratch buffer.
23941 */
23942 typedef struct ScratchFreeslot {
23943  struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
23944 } ScratchFreeslot;
23945 
23946 /*
23947 ** State information local to the memory allocation subsystem.
23948 */
23949 static SQLITE_WSD struct Mem0Global {
23950  sqlite3_mutex *mutex; /* Mutex to serialize access */
23951  sqlite3_int64 alarmThreshold; /* The soft heap limit */
23952 
23953  /*
23954  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
23955  ** (so that a range test can be used to determine if an allocation
23956  ** being freed came from pScratch) and a pointer to the list of
23957  ** unused scratch allocations.
23958  */
23959  void *pScratchEnd;
23960  ScratchFreeslot *pScratchFree;
23961  u32 nScratchFree;
23962 
23963  /*
23964  ** True if heap is nearly "full" where "full" is defined by the
23965  ** sqlite3_soft_heap_limit() setting.
23966  */
23967  int nearlyFull;
23968 } mem0 = { 0, 0, 0, 0, 0, 0 };
23969 
23970 #define mem0 GLOBAL(struct Mem0Global, mem0)
23971 
23972 /*
23973 ** Return the memory allocator mutex. sqlite3_status() needs it.
23974 */
23975 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
23976  return mem0.mutex;
23977 }
23978 
23979 #ifndef SQLITE_OMIT_DEPRECATED
23980 /*
23981 ** Deprecated external interface. It used to set an alarm callback
23982 ** that was invoked when memory usage grew too large. Now it is a
23983 ** no-op.
23984 */
23985 SQLITE_API int sqlite3_memory_alarm(
23986  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
23987  void *pArg,
23988  sqlite3_int64 iThreshold
23989 ){
23990  (void)xCallback;
23991  (void)pArg;
23992  (void)iThreshold;
23993  return SQLITE_OK;
23994 }
23995 #endif
23996 
23997 /*
23998 ** Set the soft heap-size limit for the library. Passing a zero or
23999 ** negative value indicates no limit.
24000 */
24001 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
24002  sqlite3_int64 priorLimit;
24003  sqlite3_int64 excess;
24004  sqlite3_int64 nUsed;
24005 #ifndef SQLITE_OMIT_AUTOINIT
24006  int rc = sqlite3_initialize();
24007  if( rc ) return -1;
24008 #endif
24009  sqlite3_mutex_enter(mem0.mutex);
24010  priorLimit = mem0.alarmThreshold;
24011  if( n<0 ){
24012  sqlite3_mutex_leave(mem0.mutex);
24013  return priorLimit;
24014  }
24015  mem0.alarmThreshold = n;
24016  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24017  mem0.nearlyFull = (n>0 && n<=nUsed);
24018  sqlite3_mutex_leave(mem0.mutex);
24019  excess = sqlite3_memory_used() - n;
24020  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
24021  return priorLimit;
24022 }
24023 SQLITE_API void sqlite3_soft_heap_limit(int n){
24024  if( n<0 ) n = 0;
24025  sqlite3_soft_heap_limit64(n);
24026 }
24027 
24028 /*
24029 ** Initialize the memory allocation subsystem.
24030 */
24031 SQLITE_PRIVATE int sqlite3MallocInit(void){
24032  int rc;
24033  if( sqlite3GlobalConfig.m.xMalloc==0 ){
24034  sqlite3MemSetDefault();
24035  }
24036  memset(&mem0, 0, sizeof(mem0));
24037  mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
24038  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
24039  && sqlite3GlobalConfig.nScratch>0 ){
24040  int i, n, sz;
24041  ScratchFreeslot *pSlot;
24042  sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
24043  sqlite3GlobalConfig.szScratch = sz;
24044  pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
24045  n = sqlite3GlobalConfig.nScratch;
24046  mem0.pScratchFree = pSlot;
24047  mem0.nScratchFree = n;
24048  for(i=0; i<n-1; i++){
24049  pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
24050  pSlot = pSlot->pNext;
24051  }
24052  pSlot->pNext = 0;
24053  mem0.pScratchEnd = (void*)&pSlot[1];
24054  }else{
24055  mem0.pScratchEnd = 0;
24056  sqlite3GlobalConfig.pScratch = 0;
24057  sqlite3GlobalConfig.szScratch = 0;
24058  sqlite3GlobalConfig.nScratch = 0;
24059  }
24060  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
24061  || sqlite3GlobalConfig.nPage<=0 ){
24062  sqlite3GlobalConfig.pPage = 0;
24063  sqlite3GlobalConfig.szPage = 0;
24064  }
24065  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
24066  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
24067  return rc;
24068 }
24069 
24070 /*
24071 ** Return true if the heap is currently under memory pressure - in other
24072 ** words if the amount of heap used is close to the limit set by
24073 ** sqlite3_soft_heap_limit().
24074 */
24075 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
24076  return mem0.nearlyFull;
24077 }
24078 
24079 /*
24080 ** Deinitialize the memory allocation subsystem.
24081 */
24082 SQLITE_PRIVATE void sqlite3MallocEnd(void){
24083  if( sqlite3GlobalConfig.m.xShutdown ){
24084  sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
24085  }
24086  memset(&mem0, 0, sizeof(mem0));
24087 }
24088 
24089 /*
24090 ** Return the amount of memory currently checked out.
24091 */
24092 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
24093  sqlite3_int64 res, mx;
24094  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
24095  return res;
24096 }
24097 
24098 /*
24099 ** Return the maximum amount of memory that has ever been
24100 ** checked out since either the beginning of this process
24101 ** or since the most recent reset.
24102 */
24103 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
24104  sqlite3_int64 res, mx;
24105  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
24106  return mx;
24107 }
24108 
24109 /*
24110 ** Trigger the alarm
24111 */
24112 static void sqlite3MallocAlarm(int nByte){
24113  if( mem0.alarmThreshold<=0 ) return;
24114  sqlite3_mutex_leave(mem0.mutex);
24115  sqlite3_release_memory(nByte);
24116  sqlite3_mutex_enter(mem0.mutex);
24117 }
24118 
24119 /*
24120 ** Do a memory allocation with statistics and alarms. Assume the
24121 ** lock is already held.
24122 */
24123 static int mallocWithAlarm(int n, void **pp){
24124  int nFull;
24125  void *p;
24126  assert( sqlite3_mutex_held(mem0.mutex) );
24127  nFull = sqlite3GlobalConfig.m.xRoundup(n);
24128  sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
24129  if( mem0.alarmThreshold>0 ){
24130  sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24131  if( nUsed >= mem0.alarmThreshold - nFull ){
24132  mem0.nearlyFull = 1;
24133  sqlite3MallocAlarm(nFull);
24134  }else{
24135  mem0.nearlyFull = 0;
24136  }
24137  }
24138  p = sqlite3GlobalConfig.m.xMalloc(nFull);
24139 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24140  if( p==0 && mem0.alarmThreshold>0 ){
24141  sqlite3MallocAlarm(nFull);
24142  p = sqlite3GlobalConfig.m.xMalloc(nFull);
24143  }
24144 #endif
24145  if( p ){
24146  nFull = sqlite3MallocSize(p);
24147  sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
24148  sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
24149  }
24150  *pp = p;
24151  return nFull;
24152 }
24153 
24154 /*
24155 ** Allocate memory. This routine is like sqlite3_malloc() except that it
24156 ** assumes the memory subsystem has already been initialized.
24157 */
24158 SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
24159  void *p;
24160  if( n==0 || n>=0x7fffff00 ){
24161  /* A memory allocation of a number of bytes which is near the maximum
24162  ** signed integer value might cause an integer overflow inside of the
24163  ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
24164  ** 255 bytes of overhead. SQLite itself will never use anything near
24165  ** this amount. The only way to reach the limit is with sqlite3_malloc() */
24166  p = 0;
24167  }else if( sqlite3GlobalConfig.bMemstat ){
24168  sqlite3_mutex_enter(mem0.mutex);
24169  mallocWithAlarm((int)n, &p);
24170  sqlite3_mutex_leave(mem0.mutex);
24171  }else{
24172  p = sqlite3GlobalConfig.m.xMalloc((int)n);
24173  }
24174  assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
24175  return p;
24176 }
24177 
24178 /*
24179 ** This version of the memory allocation is for use by the application.
24180 ** First make sure the memory subsystem is initialized, then do the
24181 ** allocation.
24182 */
24183 SQLITE_API void *sqlite3_malloc(int n){
24184 #ifndef SQLITE_OMIT_AUTOINIT
24185  if( sqlite3_initialize() ) return 0;
24186 #endif
24187  return n<=0 ? 0 : sqlite3Malloc(n);
24188 }
24189 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
24190 #ifndef SQLITE_OMIT_AUTOINIT
24191  if( sqlite3_initialize() ) return 0;
24192 #endif
24193  return sqlite3Malloc(n);
24194 }
24195 
24196 /*
24197 ** Each thread may only have a single outstanding allocation from
24198 ** xScratchMalloc(). We verify this constraint in the single-threaded
24199 ** case by setting scratchAllocOut to 1 when an allocation
24200 ** is outstanding clearing it when the allocation is freed.
24201 */
24202 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24203 static int scratchAllocOut = 0;
24204 #endif
24205 
24206 
24207 /*
24208 ** Allocate memory that is to be used and released right away.
24209 ** This routine is similar to alloca() in that it is not intended
24210 ** for situations where the memory might be held long-term. This
24211 ** routine is intended to get memory to old large transient data
24212 ** structures that would not normally fit on the stack of an
24213 ** embedded processor.
24214 */
24215 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
24216  void *p;
24217  assert( n>0 );
24218 
24219  sqlite3_mutex_enter(mem0.mutex);
24220  sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
24221  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
24222  p = mem0.pScratchFree;
24223  mem0.pScratchFree = mem0.pScratchFree->pNext;
24224  mem0.nScratchFree--;
24225  sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
24226  sqlite3_mutex_leave(mem0.mutex);
24227  }else{
24228  sqlite3_mutex_leave(mem0.mutex);
24229  p = sqlite3Malloc(n);
24230  if( sqlite3GlobalConfig.bMemstat && p ){
24231  sqlite3_mutex_enter(mem0.mutex);
24232  sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
24233  sqlite3_mutex_leave(mem0.mutex);
24234  }
24235  sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
24236  }
24237  assert( sqlite3_mutex_notheld(mem0.mutex) );
24238 
24239 
24240 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24241  /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
24242  ** buffers per thread.
24243  **
24244  ** This can only be checked in single-threaded mode.
24245  */
24246  assert( scratchAllocOut==0 );
24247  if( p ) scratchAllocOut++;
24248 #endif
24249 
24250  return p;
24251 }
24252 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
24253  if( p ){
24254 
24255 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24256  /* Verify that no more than two scratch allocation per thread
24257  ** is outstanding at one time. (This is only checked in the
24258  ** single-threaded case since checking in the multi-threaded case
24259  ** would be much more complicated.) */
24260  assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
24261  scratchAllocOut--;
24262 #endif
24263 
24264  if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
24265  /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
24266  ScratchFreeslot *pSlot;
24267  pSlot = (ScratchFreeslot*)p;
24268  sqlite3_mutex_enter(mem0.mutex);
24269  pSlot->pNext = mem0.pScratchFree;
24270  mem0.pScratchFree = pSlot;
24271  mem0.nScratchFree++;
24272  assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
24273  sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
24274  sqlite3_mutex_leave(mem0.mutex);
24275  }else{
24276  /* Release memory back to the heap */
24277  assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
24278  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
24279  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24280  if( sqlite3GlobalConfig.bMemstat ){
24281  int iSize = sqlite3MallocSize(p);
24282  sqlite3_mutex_enter(mem0.mutex);
24283  sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
24284  sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
24285  sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24286  sqlite3GlobalConfig.m.xFree(p);
24287  sqlite3_mutex_leave(mem0.mutex);
24288  }else{
24289  sqlite3GlobalConfig.m.xFree(p);
24290  }
24291  }
24292  }
24293 }
24294 
24295 /*
24296 ** TRUE if p is a lookaside memory allocation from db
24297 */
24298 #ifndef SQLITE_OMIT_LOOKASIDE
24299 static int isLookaside(sqlite3 *db, void *p){
24300  return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
24301 }
24302 #else
24303 #define isLookaside(A,B) 0
24304 #endif
24305 
24306 /*
24307 ** Return the size of a memory allocation previously obtained from
24308 ** sqlite3Malloc() or sqlite3_malloc().
24309 */
24310 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
24311  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24312  return sqlite3GlobalConfig.m.xSize(p);
24313 }
24314 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
24315  assert( p!=0 );
24316  if( db==0 || !isLookaside(db,p) ){
24317 #if SQLITE_DEBUG
24318  if( db==0 ){
24319  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24320  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24321  }else{
24322  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24323  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24324  }
24325 #endif
24326  return sqlite3GlobalConfig.m.xSize(p);
24327  }else{
24328  assert( sqlite3_mutex_held(db->mutex) );
24329  return db->lookaside.sz;
24330  }
24331 }
24332 SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
24333  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24334  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24335  return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
24336 }
24337 
24338 /*
24339 ** Free memory previously obtained from sqlite3Malloc().
24340 */
24341 SQLITE_API void sqlite3_free(void *p){
24342  if( p==0 ) return; /* IMP: R-49053-54554 */
24343  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24344  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24345  if( sqlite3GlobalConfig.bMemstat ){
24346  sqlite3_mutex_enter(mem0.mutex);
24347  sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
24348  sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24349  sqlite3GlobalConfig.m.xFree(p);
24350  sqlite3_mutex_leave(mem0.mutex);
24351  }else{
24352  sqlite3GlobalConfig.m.xFree(p);
24353  }
24354 }
24355 
24356 /*
24357 ** Add the size of memory allocation "p" to the count in
24358 ** *db->pnBytesFreed.
24359 */
24360 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
24361  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
24362 }
24363 
24364 /*
24365 ** Free memory that might be associated with a particular database
24366 ** connection.
24367 */
24368 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
24369  assert( db==0 || sqlite3_mutex_held(db->mutex) );
24370  if( p==0 ) return;
24371  if( db ){
24372  if( db->pnBytesFreed ){
24373  measureAllocationSize(db, p);
24374  return;
24375  }
24376  if( isLookaside(db, p) ){
24377  LookasideSlot *pBuf = (LookasideSlot*)p;
24378 #if SQLITE_DEBUG
24379  /* Trash all content in the buffer being freed */
24380  memset(p, 0xaa, db->lookaside.sz);
24381 #endif
24382  pBuf->pNext = db->lookaside.pFree;
24383  db->lookaside.pFree = pBuf;
24384  db->lookaside.nOut--;
24385  return;
24386  }
24387  }
24388  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24389  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24390  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
24391  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24392  sqlite3_free(p);
24393 }
24394 
24395 /*
24396 ** Change the size of an existing memory allocation
24397 */
24398 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
24399  int nOld, nNew, nDiff;
24400  void *pNew;
24401  assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
24402  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
24403  if( pOld==0 ){
24404  return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
24405  }
24406  if( nBytes==0 ){
24407  sqlite3_free(pOld); /* IMP: R-26507-47431 */
24408  return 0;
24409  }
24410  if( nBytes>=0x7fffff00 ){
24411  /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
24412  return 0;
24413  }
24414  nOld = sqlite3MallocSize(pOld);
24415  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
24416  ** argument to xRealloc is always a value returned by a prior call to
24417  ** xRoundup. */
24418  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
24419  if( nOld==nNew ){
24420  pNew = pOld;
24421  }else if( sqlite3GlobalConfig.bMemstat ){
24422  sqlite3_mutex_enter(mem0.mutex);
24423  sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
24424  nDiff = nNew - nOld;
24425  if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
24426  mem0.alarmThreshold-nDiff ){
24427  sqlite3MallocAlarm(nDiff);
24428  }
24429  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24430  if( pNew==0 && mem0.alarmThreshold>0 ){
24431  sqlite3MallocAlarm((int)nBytes);
24432  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24433  }
24434  if( pNew ){
24435  nNew = sqlite3MallocSize(pNew);
24436  sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
24437  }
24438  sqlite3_mutex_leave(mem0.mutex);
24439  }else{
24440  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24441  }
24442  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
24443  return pNew;
24444 }
24445 
24446 /*
24447 ** The public interface to sqlite3Realloc. Make sure that the memory
24448 ** subsystem is initialized prior to invoking sqliteRealloc.
24449 */
24450 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
24451 #ifndef SQLITE_OMIT_AUTOINIT
24452  if( sqlite3_initialize() ) return 0;
24453 #endif
24454  if( n<0 ) n = 0; /* IMP: R-26507-47431 */
24455  return sqlite3Realloc(pOld, n);
24456 }
24457 SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
24458 #ifndef SQLITE_OMIT_AUTOINIT
24459  if( sqlite3_initialize() ) return 0;
24460 #endif
24461  return sqlite3Realloc(pOld, n);
24462 }
24463 
24464 
24465 /*
24466 ** Allocate and zero memory.
24467 */
24468 SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
24469  void *p = sqlite3Malloc(n);
24470  if( p ){
24471  memset(p, 0, (size_t)n);
24472  }
24473  return p;
24474 }
24475 
24476 /*
24477 ** Allocate and zero memory. If the allocation fails, make
24478 ** the mallocFailed flag in the connection pointer.
24479 */
24480 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
24481  void *p;
24482  testcase( db==0 );
24483  p = sqlite3DbMallocRaw(db, n);
24484  if( p ) memset(p, 0, (size_t)n);
24485  return p;
24486 }
24487 
24488 
24489 /* Finish the work of sqlite3DbMallocRawNN for the unusual and
24490 ** slower case when the allocation cannot be fulfilled using lookaside.
24491 */
24492 static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
24493  void *p;
24494  assert( db!=0 );
24495  p = sqlite3Malloc(n);
24496  if( !p ) sqlite3OomFault(db);
24497  sqlite3MemdebugSetType(p,
24498  (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
24499  return p;
24500 }
24501 
24502 /*
24503 ** Allocate memory, either lookaside (if possible) or heap.
24504 ** If the allocation fails, set the mallocFailed flag in
24505 ** the connection pointer.
24506 **
24507 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
24508 ** failure on the same database connection) then always return 0.
24509 ** Hence for a particular database connection, once malloc starts
24510 ** failing, it fails consistently until mallocFailed is reset.
24511 ** This is an important assumption. There are many places in the
24512 ** code that do things like this:
24513 **
24514 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
24515 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
24516 ** if( b ) a[10] = 9;
24517 **
24518 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
24519 ** that all prior mallocs (ex: "a") worked too.
24520 **
24521 ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
24522 ** not a NULL pointer.
24523 */
24524 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
24525  void *p;
24526  if( db ) return sqlite3DbMallocRawNN(db, n);
24527  p = sqlite3Malloc(n);
24528  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24529  return p;
24530 }
24531 SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
24532 #ifndef SQLITE_OMIT_LOOKASIDE
24533  LookasideSlot *pBuf;
24534  assert( db!=0 );
24535  assert( sqlite3_mutex_held(db->mutex) );
24536  assert( db->pnBytesFreed==0 );
24537  if( db->lookaside.bDisable==0 ){
24538  assert( db->mallocFailed==0 );
24539  if( n>db->lookaside.sz ){
24540  db->lookaside.anStat[1]++;
24541  }else if( (pBuf = db->lookaside.pFree)==0 ){
24542  db->lookaside.anStat[2]++;
24543  }else{
24544  db->lookaside.pFree = pBuf->pNext;
24545  db->lookaside.nOut++;
24546  db->lookaside.anStat[0]++;
24547  if( db->lookaside.nOut>db->lookaside.mxOut ){
24548  db->lookaside.mxOut = db->lookaside.nOut;
24549  }
24550  return (void*)pBuf;
24551  }
24552  }else if( db->mallocFailed ){
24553  return 0;
24554  }
24555 #else
24556  assert( db!=0 );
24557  assert( sqlite3_mutex_held(db->mutex) );
24558  assert( db->pnBytesFreed==0 );
24559  if( db->mallocFailed ){
24560  return 0;
24561  }
24562 #endif
24563  return dbMallocRawFinish(db, n);
24564 }
24565 
24566 /* Forward declaration */
24567 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
24568 
24569 /*
24570 ** Resize the block of memory pointed to by p to n bytes. If the
24571 ** resize fails, set the mallocFailed flag in the connection object.
24572 */
24573 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
24574  assert( db!=0 );
24575  if( p==0 ) return sqlite3DbMallocRawNN(db, n);
24576  assert( sqlite3_mutex_held(db->mutex) );
24577  if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
24578  return dbReallocFinish(db, p, n);
24579 }
24580 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
24581  void *pNew = 0;
24582  assert( db!=0 );
24583  assert( p!=0 );
24584  if( db->mallocFailed==0 ){
24585  if( isLookaside(db, p) ){
24586  pNew = sqlite3DbMallocRawNN(db, n);
24587  if( pNew ){
24588  memcpy(pNew, p, db->lookaside.sz);
24589  sqlite3DbFree(db, p);
24590  }
24591  }else{
24592  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24593  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24594  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24595  pNew = sqlite3_realloc64(p, n);
24596  if( !pNew ){
24597  sqlite3OomFault(db);
24598  }
24599  sqlite3MemdebugSetType(pNew,
24600  (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
24601  }
24602  }
24603  return pNew;
24604 }
24605 
24606 /*
24607 ** Attempt to reallocate p. If the reallocation fails, then free p
24608 ** and set the mallocFailed flag in the database connection.
24609 */
24610 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
24611  void *pNew;
24612  pNew = sqlite3DbRealloc(db, p, n);
24613  if( !pNew ){
24614  sqlite3DbFree(db, p);
24615  }
24616  return pNew;
24617 }
24618 
24619 /*
24620 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
24621 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
24622 ** is because when memory debugging is turned on, these two functions are
24623 ** called via macros that record the current file and line number in the
24624 ** ThreadData structure.
24625 */
24626 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
24627  char *zNew;
24628  size_t n;
24629  if( z==0 ){
24630  return 0;
24631  }
24632  n = sqlite3Strlen30(z) + 1;
24633  assert( (n&0x7fffffff)==n );
24634  zNew = sqlite3DbMallocRaw(db, (int)n);
24635  if( zNew ){
24636  memcpy(zNew, z, n);
24637  }
24638  return zNew;
24639 }
24640 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
24641  char *zNew;
24642  assert( db!=0 );
24643  if( z==0 ){
24644  return 0;
24645  }
24646  assert( (n&0x7fffffff)==n );
24647  zNew = sqlite3DbMallocRawNN(db, n+1);
24648  if( zNew ){
24649  memcpy(zNew, z, (size_t)n);
24650  zNew[n] = 0;
24651  }
24652  return zNew;
24653 }
24654 
24655 /*
24656 ** Free any prior content in *pz and replace it with a copy of zNew.
24657 */
24658 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
24659  sqlite3DbFree(db, *pz);
24660  *pz = sqlite3DbStrDup(db, zNew);
24661 }
24662 
24663 /*
24664 ** Call this routine to record the fact that an OOM (out-of-memory) error
24665 ** has happened. This routine will set db->mallocFailed, and also
24666 ** temporarily disable the lookaside memory allocator and interrupt
24667 ** any running VDBEs.
24668 */
24669 SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
24670  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
24671  db->mallocFailed = 1;
24672  if( db->nVdbeExec>0 ){
24673  db->u1.isInterrupted = 1;
24674  }
24675  db->lookaside.bDisable++;
24676  }
24677 }
24678 
24679 /*
24680 ** This routine reactivates the memory allocator and clears the
24681 ** db->mallocFailed flag as necessary.
24682 **
24683 ** The memory allocator is not restarted if there are running
24684 ** VDBEs.
24685 */
24686 SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
24687  if( db->mallocFailed && db->nVdbeExec==0 ){
24688  db->mallocFailed = 0;
24689  db->u1.isInterrupted = 0;
24690  assert( db->lookaside.bDisable>0 );
24691  db->lookaside.bDisable--;
24692  }
24693 }
24694 
24695 /*
24696 ** Take actions at the end of an API call to indicate an OOM error
24697 */
24698 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
24699  sqlite3OomClear(db);
24700  sqlite3Error(db, SQLITE_NOMEM);
24701  return SQLITE_NOMEM_BKPT;
24702 }
24703 
24704 /*
24705 ** This function must be called before exiting any API function (i.e.
24706 ** returning control to the user) that has called sqlite3_malloc or
24707 ** sqlite3_realloc.
24708 **
24709 ** The returned value is normally a copy of the second argument to this
24710 ** function. However, if a malloc() failure has occurred since the previous
24711 ** invocation SQLITE_NOMEM is returned instead.
24712 **
24713 ** If an OOM as occurred, then the connection error-code (the value
24714 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
24715 */
24716 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
24717  /* If the db handle must hold the connection handle mutex here.
24718  ** Otherwise the read (and possible write) of db->mallocFailed
24719  ** is unsafe, as is the call to sqlite3Error().
24720  */
24721  assert( db!=0 );
24722  assert( sqlite3_mutex_held(db->mutex) );
24723  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
24724  return apiOomError(db);
24725  }
24726  return rc & db->errMask;
24727 }
24728 
24729 /************** End of malloc.c **********************************************/
24730 /************** Begin file printf.c ******************************************/
24731 /*
24732 ** The "printf" code that follows dates from the 1980's. It is in
24733 ** the public domain.
24734 **
24735 **************************************************************************
24736 **
24737 ** This file contains code for a set of "printf"-like routines. These
24738 ** routines format strings much like the printf() from the standard C
24739 ** library, though the implementation here has enhancements to support
24740 ** SQLite.
24741 */
24742 /* #include "sqliteInt.h" */
24743 
24744 /*
24745 ** Conversion types fall into various categories as defined by the
24746 ** following enumeration.
24747 */
24748 #define etRADIX 0 /* Integer types. %d, %x, %o, and so forth */
24749 #define etFLOAT 1 /* Floating point. %f */
24750 #define etEXP 2 /* Exponentional notation. %e and %E */
24751 #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
24752 #define etSIZE 4 /* Return number of characters processed so far. %n */
24753 #define etSTRING 5 /* Strings. %s */
24754 #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
24755 #define etPERCENT 7 /* Percent symbol. %% */
24756 #define etCHARX 8 /* Characters. %c */
24757 /* The rest are extensions, not normally found in printf() */
24758 #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
24759 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
24760  NULL pointers replaced by SQL NULL. %Q */
24761 #define etTOKEN 11 /* a pointer to a Token structure */
24762 #define etSRCLIST 12 /* a pointer to a SrcList */
24763 #define etPOINTER 13 /* The %p conversion */
24764 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
24765 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
24766 
24767 #define etINVALID 16 /* Any unrecognized conversion type */
24768 
24769 
24770 /*
24771 ** An "etByte" is an 8-bit unsigned value.
24772 */
24773 typedef unsigned char etByte;
24774 
24775 /*
24776 ** Each builtin conversion character (ex: the 'd' in "%d") is described
24777 ** by an instance of the following structure
24778 */
24779 typedef struct et_info { /* Information about each format field */
24780  char fmttype; /* The format field code letter */
24781  etByte base; /* The base for radix conversion */
24782  etByte flags; /* One or more of FLAG_ constants below */
24783  etByte type; /* Conversion paradigm */
24784  etByte charset; /* Offset into aDigits[] of the digits string */
24785  etByte prefix; /* Offset into aPrefix[] of the prefix string */
24786 } et_info;
24787 
24788 /*
24789 ** Allowed values for et_info.flags
24790 */
24791 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
24792 #define FLAG_INTERN 2 /* True if for internal use only */
24793 #define FLAG_STRING 4 /* Allow infinity precision */
24794 
24795 
24796 /*
24797 ** The following table is searched linearly, so it is good to put the
24798 ** most frequently used conversion types first.
24799 */
24800 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
24801 static const char aPrefix[] = "-x0\000X0";
24802 static const et_info fmtinfo[] = {
24803  { 'd', 10, 1, etRADIX, 0, 0 },
24804  { 's', 0, 4, etSTRING, 0, 0 },
24805  { 'g', 0, 1, etGENERIC, 30, 0 },
24806  { 'z', 0, 4, etDYNSTRING, 0, 0 },
24807  { 'q', 0, 4, etSQLESCAPE, 0, 0 },
24808  { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
24809  { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
24810  { 'c', 0, 0, etCHARX, 0, 0 },
24811  { 'o', 8, 0, etRADIX, 0, 2 },
24812  { 'u', 10, 0, etRADIX, 0, 0 },
24813  { 'x', 16, 0, etRADIX, 16, 1 },
24814  { 'X', 16, 0, etRADIX, 0, 4 },
24815 #ifndef SQLITE_OMIT_FLOATING_POINT
24816  { 'f', 0, 1, etFLOAT, 0, 0 },
24817  { 'e', 0, 1, etEXP, 30, 0 },
24818  { 'E', 0, 1, etEXP, 14, 0 },
24819  { 'G', 0, 1, etGENERIC, 14, 0 },
24820 #endif
24821  { 'i', 10, 1, etRADIX, 0, 0 },
24822  { 'n', 0, 0, etSIZE, 0, 0 },
24823  { '%', 0, 0, etPERCENT, 0, 0 },
24824  { 'p', 16, 0, etPOINTER, 0, 1 },
24825 
24826 /* All the rest have the FLAG_INTERN bit set and are thus for internal
24827 ** use only */
24828  { 'T', 0, 2, etTOKEN, 0, 0 },
24829  { 'S', 0, 2, etSRCLIST, 0, 0 },
24830  { 'r', 10, 3, etORDINAL, 0, 0 },
24831 };
24832 
24833 /*
24834 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
24835 ** conversions will work.
24836 */
24837 #ifndef SQLITE_OMIT_FLOATING_POINT
24838 /*
24839 ** "*val" is a double such that 0.1 <= *val < 10.0
24840 ** Return the ascii code for the leading digit of *val, then
24841 ** multiply "*val" by 10.0 to renormalize.
24842 **
24843 ** Example:
24844 ** input: *val = 3.14159
24845 ** output: *val = 1.4159 function return = '3'
24846 **
24847 ** The counter *cnt is incremented each time. After counter exceeds
24848 ** 16 (the number of significant digits in a 64-bit float) '0' is
24849 ** always returned.
24850 */
24851 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
24852  int digit;
24853  LONGDOUBLE_TYPE d;
24854  if( (*cnt)<=0 ) return '0';
24855  (*cnt)--;
24856  digit = (int)*val;
24857  d = digit;
24858  digit += '0';
24859  *val = (*val - d)*10.0;
24860  return (char)digit;
24861 }
24862 #endif /* SQLITE_OMIT_FLOATING_POINT */
24863 
24864 /*
24865 ** Set the StrAccum object to an error mode.
24866 */
24867 static void setStrAccumError(StrAccum *p, u8 eError){
24868  assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
24869  p->accError = eError;
24870  p->nAlloc = 0;
24871 }
24872 
24873 /*
24874 ** Extra argument values from a PrintfArguments object
24875 */
24876 static sqlite3_int64 getIntArg(PrintfArguments *p){
24877  if( p->nArg<=p->nUsed ) return 0;
24878  return sqlite3_value_int64(p->apArg[p->nUsed++]);
24879 }
24880 static double getDoubleArg(PrintfArguments *p){
24881  if( p->nArg<=p->nUsed ) return 0.0;
24882  return sqlite3_value_double(p->apArg[p->nUsed++]);
24883 }
24884 static char *getTextArg(PrintfArguments *p){
24885  if( p->nArg<=p->nUsed ) return 0;
24886  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
24887 }
24888 
24889 
24890 /*
24891 ** On machines with a small stack size, you can redefine the
24892 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
24893 */
24894 #ifndef SQLITE_PRINT_BUF_SIZE
24895 # define SQLITE_PRINT_BUF_SIZE 70
24896 #endif
24897 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
24898 
24899 /*
24900 ** Render a string given by "fmt" into the StrAccum object.
24901 */
24902 SQLITE_PRIVATE void sqlite3VXPrintf(
24903  StrAccum *pAccum, /* Accumulate results here */
24904  const char *fmt, /* Format string */
24905  va_list ap /* arguments */
24906 ){
24907  int c; /* Next character in the format string */
24908  char *bufpt; /* Pointer to the conversion buffer */
24909  int precision; /* Precision of the current field */
24910  int length; /* Length of the field */
24911  int idx; /* A general purpose loop counter */
24912  int width; /* Width of the current field */
24913  etByte flag_leftjustify; /* True if "-" flag is present */
24914  etByte flag_plussign; /* True if "+" flag is present */
24915  etByte flag_blanksign; /* True if " " flag is present */
24916  etByte flag_alternateform; /* True if "#" flag is present */
24917  etByte flag_altform2; /* True if "!" flag is present */
24918  etByte flag_zeropad; /* True if field width constant starts with zero */
24919  etByte flag_long; /* True if "l" flag is present */
24920  etByte flag_longlong; /* True if the "ll" flag is present */
24921  etByte done; /* Loop termination flag */
24922  etByte xtype = etINVALID; /* Conversion paradigm */
24923  u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
24924  u8 useIntern; /* Ok to use internal conversions (ex: %T) */
24925  char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
24926  sqlite_uint64 longvalue; /* Value for integer types */
24927  LONGDOUBLE_TYPE realvalue; /* Value for real types */
24928  const et_info *infop; /* Pointer to the appropriate info structure */
24929  char *zOut; /* Rendering buffer */
24930  int nOut; /* Size of the rendering buffer */
24931  char *zExtra = 0; /* Malloced memory used by some conversion */
24932 #ifndef SQLITE_OMIT_FLOATING_POINT
24933  int exp, e2; /* exponent of real numbers */
24934  int nsd; /* Number of significant digits returned */
24935  double rounder; /* Used for rounding floating point values */
24936  etByte flag_dp; /* True if decimal point should be shown */
24937  etByte flag_rtz; /* True if trailing zeros should be removed */
24938 #endif
24939  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
24940  char buf[etBUFSIZE]; /* Conversion buffer */
24941 
24942  bufpt = 0;
24943  if( pAccum->printfFlags ){
24944  if( (bArgList = (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
24945  pArgList = va_arg(ap, PrintfArguments*);
24946  }
24947  useIntern = pAccum->printfFlags & SQLITE_PRINTF_INTERNAL;
24948  }else{
24949  bArgList = useIntern = 0;
24950  }
24951  for(; (c=(*fmt))!=0; ++fmt){
24952  if( c!='%' ){
24953  bufpt = (char *)fmt;
24954 #if HAVE_STRCHRNUL
24955  fmt = strchrnul(fmt, '%');
24956 #else
24957  do{ fmt++; }while( *fmt && *fmt != '%' );
24958 #endif
24959  sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
24960  if( *fmt==0 ) break;
24961  }
24962  if( (c=(*++fmt))==0 ){
24963  sqlite3StrAccumAppend(pAccum, "%", 1);
24964  break;
24965  }
24966  /* Find out what flags are present */
24967  flag_leftjustify = flag_plussign = flag_blanksign =
24968  flag_alternateform = flag_altform2 = flag_zeropad = 0;
24969  done = 0;
24970  do{
24971  switch( c ){
24972  case '-': flag_leftjustify = 1; break;
24973  case '+': flag_plussign = 1; break;
24974  case ' ': flag_blanksign = 1; break;
24975  case '#': flag_alternateform = 1; break;
24976  case '!': flag_altform2 = 1; break;
24977  case '0': flag_zeropad = 1; break;
24978  default: done = 1; break;
24979  }
24980  }while( !done && (c=(*++fmt))!=0 );
24981  /* Get the field width */
24982  if( c=='*' ){
24983  if( bArgList ){
24984  width = (int)getIntArg(pArgList);
24985  }else{
24986  width = va_arg(ap,int);
24987  }
24988  if( width<0 ){
24989  flag_leftjustify = 1;
24990  width = width >= -2147483647 ? -width : 0;
24991  }
24992  c = *++fmt;
24993  }else{
24994  unsigned wx = 0;
24995  while( c>='0' && c<='9' ){
24996  wx = wx*10 + c - '0';
24997  c = *++fmt;
24998  }
24999  testcase( wx>0x7fffffff );
25000  width = wx & 0x7fffffff;
25001  }
25002  assert( width>=0 );
25003 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
25004  if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
25005  width = SQLITE_PRINTF_PRECISION_LIMIT;
25006  }
25007 #endif
25008 
25009  /* Get the precision */
25010  if( c=='.' ){
25011  c = *++fmt;
25012  if( c=='*' ){
25013  if( bArgList ){
25014  precision = (int)getIntArg(pArgList);
25015  }else{
25016  precision = va_arg(ap,int);
25017  }
25018  c = *++fmt;
25019  if( precision<0 ){
25020  precision = precision >= -2147483647 ? -precision : -1;
25021  }
25022  }else{
25023  unsigned px = 0;
25024  while( c>='0' && c<='9' ){
25025  px = px*10 + c - '0';
25026  c = *++fmt;
25027  }
25028  testcase( px>0x7fffffff );
25029  precision = px & 0x7fffffff;
25030  }
25031  }else{
25032  precision = -1;
25033  }
25034  assert( precision>=(-1) );
25035 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
25036  if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
25037  precision = SQLITE_PRINTF_PRECISION_LIMIT;
25038  }
25039 #endif
25040 
25041 
25042  /* Get the conversion type modifier */
25043  if( c=='l' ){
25044  flag_long = 1;
25045  c = *++fmt;
25046  if( c=='l' ){
25047  flag_longlong = 1;
25048  c = *++fmt;
25049  }else{
25050  flag_longlong = 0;
25051  }
25052  }else{
25053  flag_long = flag_longlong = 0;
25054  }
25055  /* Fetch the info entry for the field */
25056  infop = &fmtinfo[0];
25057  xtype = etINVALID;
25058  for(idx=0; idx<ArraySize(fmtinfo); idx++){
25059  if( c==fmtinfo[idx].fmttype ){
25060  infop = &fmtinfo[idx];
25061  if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
25062  xtype = infop->type;
25063  }else{
25064  return;
25065  }
25066  break;
25067  }
25068  }
25069 
25070  /*
25071  ** At this point, variables are initialized as follows:
25072  **
25073  ** flag_alternateform TRUE if a '#' is present.
25074  ** flag_altform2 TRUE if a '!' is present.
25075  ** flag_plussign TRUE if a '+' is present.
25076  ** flag_leftjustify TRUE if a '-' is present or if the
25077  ** field width was negative.
25078  ** flag_zeropad TRUE if the width began with 0.
25079  ** flag_long TRUE if the letter 'l' (ell) prefixed
25080  ** the conversion character.
25081  ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
25082  ** the conversion character.
25083  ** flag_blanksign TRUE if a ' ' is present.
25084  ** width The specified field width. This is
25085  ** always non-negative. Zero is the default.
25086  ** precision The specified precision. The default
25087  ** is -1.
25088  ** xtype The class of the conversion.
25089  ** infop Pointer to the appropriate info struct.
25090  */
25091  switch( xtype ){
25092  case etPOINTER:
25093  flag_longlong = sizeof(char*)==sizeof(i64);
25094  flag_long = sizeof(char*)==sizeof(long int);
25095  /* Fall through into the next case */
25096  case etORDINAL:
25097  case etRADIX:
25098  if( infop->flags & FLAG_SIGNED ){
25099  i64 v;
25100  if( bArgList ){
25101  v = getIntArg(pArgList);
25102  }else if( flag_longlong ){
25103  v = va_arg(ap,i64);
25104  }else if( flag_long ){
25105  v = va_arg(ap,long int);
25106  }else{
25107  v = va_arg(ap,int);
25108  }
25109  if( v<0 ){
25110  if( v==SMALLEST_INT64 ){
25111  longvalue = ((u64)1)<<63;
25112  }else{
25113  longvalue = -v;
25114  }
25115  prefix = '-';
25116  }else{
25117  longvalue = v;
25118  if( flag_plussign ) prefix = '+';
25119  else if( flag_blanksign ) prefix = ' ';
25120  else prefix = 0;
25121  }
25122  }else{
25123  if( bArgList ){
25124  longvalue = (u64)getIntArg(pArgList);
25125  }else if( flag_longlong ){
25126  longvalue = va_arg(ap,u64);
25127  }else if( flag_long ){
25128  longvalue = va_arg(ap,unsigned long int);
25129  }else{
25130  longvalue = va_arg(ap,unsigned int);
25131  }
25132  prefix = 0;
25133  }
25134  if( longvalue==0 ) flag_alternateform = 0;
25135  if( flag_zeropad && precision<width-(prefix!=0) ){
25136  precision = width-(prefix!=0);
25137  }
25138  if( precision<etBUFSIZE-10 ){
25139  nOut = etBUFSIZE;
25140  zOut = buf;
25141  }else{
25142  nOut = precision + 10;
25143  zOut = zExtra = sqlite3Malloc( nOut );
25144  if( zOut==0 ){
25145  setStrAccumError(pAccum, STRACCUM_NOMEM);
25146  return;
25147  }
25148  }
25149  bufpt = &zOut[nOut-1];
25150  if( xtype==etORDINAL ){
25151  static const char zOrd[] = "thstndrd";
25152  int x = (int)(longvalue % 10);
25153  if( x>=4 || (longvalue/10)%10==1 ){
25154  x = 0;
25155  }
25156  *(--bufpt) = zOrd[x*2+1];
25157  *(--bufpt) = zOrd[x*2];
25158  }
25159  {
25160  const char *cset = &aDigits[infop->charset];
25161  u8 base = infop->base;
25162  do{ /* Convert to ascii */
25163  *(--bufpt) = cset[longvalue%base];
25164  longvalue = longvalue/base;
25165  }while( longvalue>0 );
25166  }
25167  length = (int)(&zOut[nOut-1]-bufpt);
25168  for(idx=precision-length; idx>0; idx--){
25169  *(--bufpt) = '0'; /* Zero pad */
25170  }
25171  if( prefix ) *(--bufpt) = prefix; /* Add sign */
25172  if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
25173  const char *pre;
25174  char x;
25175  pre = &aPrefix[infop->prefix];
25176  for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
25177  }
25178  length = (int)(&zOut[nOut-1]-bufpt);
25179  break;
25180  case etFLOAT:
25181  case etEXP:
25182  case etGENERIC:
25183  if( bArgList ){
25184  realvalue = getDoubleArg(pArgList);
25185  }else{
25186  realvalue = va_arg(ap,double);
25187  }
25188 #ifdef SQLITE_OMIT_FLOATING_POINT
25189  length = 0;
25190 #else
25191  if( precision<0 ) precision = 6; /* Set default precision */
25192  if( realvalue<0.0 ){
25193  realvalue = -realvalue;
25194  prefix = '-';
25195  }else{
25196  if( flag_plussign ) prefix = '+';
25197  else if( flag_blanksign ) prefix = ' ';
25198  else prefix = 0;
25199  }
25200  if( xtype==etGENERIC && precision>0 ) precision--;
25201  testcase( precision>0xfff );
25202  for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
25203  if( xtype==etFLOAT ) realvalue += rounder;
25204  /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
25205  exp = 0;
25206  if( sqlite3IsNaN((double)realvalue) ){
25207  bufpt = "NaN";
25208  length = 3;
25209  break;
25210  }
25211  if( realvalue>0.0 ){
25212  LONGDOUBLE_TYPE scale = 1.0;
25213  while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
25214  while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
25215  while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
25216  realvalue /= scale;
25217  while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
25218  while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
25219  if( exp>350 ){
25220  bufpt = buf;
25221  buf[0] = prefix;
25222  memcpy(buf+(prefix!=0),"Inf",4);
25223  length = 3+(prefix!=0);
25224  break;
25225  }
25226  }
25227  bufpt = buf;
25228  /*
25229  ** If the field type is etGENERIC, then convert to either etEXP
25230  ** or etFLOAT, as appropriate.
25231  */
25232  if( xtype!=etFLOAT ){
25233  realvalue += rounder;
25234  if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
25235  }
25236  if( xtype==etGENERIC ){
25237  flag_rtz = !flag_alternateform;
25238  if( exp<-4 || exp>precision ){
25239  xtype = etEXP;
25240  }else{
25241  precision = precision - exp;
25242  xtype = etFLOAT;
25243  }
25244  }else{
25245  flag_rtz = flag_altform2;
25246  }
25247  if( xtype==etEXP ){
25248  e2 = 0;
25249  }else{
25250  e2 = exp;
25251  }
25252  if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
25253  bufpt = zExtra
25254  = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
25255  if( bufpt==0 ){
25256  setStrAccumError(pAccum, STRACCUM_NOMEM);
25257  return;
25258  }
25259  }
25260  zOut = bufpt;
25261  nsd = 16 + flag_altform2*10;
25262  flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
25263  /* The sign in front of the number */
25264  if( prefix ){
25265  *(bufpt++) = prefix;
25266  }
25267  /* Digits prior to the decimal point */
25268  if( e2<0 ){
25269  *(bufpt++) = '0';
25270  }else{
25271  for(; e2>=0; e2--){
25272  *(bufpt++) = et_getdigit(&realvalue,&nsd);
25273  }
25274  }
25275  /* The decimal point */
25276  if( flag_dp ){
25277  *(bufpt++) = '.';
25278  }
25279  /* "0" digits after the decimal point but before the first
25280  ** significant digit of the number */
25281  for(e2++; e2<0; precision--, e2++){
25282  assert( precision>0 );
25283  *(bufpt++) = '0';
25284  }
25285  /* Significant digits after the decimal point */
25286  while( (precision--)>0 ){
25287  *(bufpt++) = et_getdigit(&realvalue,&nsd);
25288  }
25289  /* Remove trailing zeros and the "." if no digits follow the "." */
25290  if( flag_rtz && flag_dp ){
25291  while( bufpt[-1]=='0' ) *(--bufpt) = 0;
25292  assert( bufpt>zOut );
25293  if( bufpt[-1]=='.' ){
25294  if( flag_altform2 ){
25295  *(bufpt++) = '0';
25296  }else{
25297  *(--bufpt) = 0;
25298  }
25299  }
25300  }
25301  /* Add the "eNNN" suffix */
25302  if( xtype==etEXP ){
25303  *(bufpt++) = aDigits[infop->charset];
25304  if( exp<0 ){
25305  *(bufpt++) = '-'; exp = -exp;
25306  }else{
25307  *(bufpt++) = '+';
25308  }
25309  if( exp>=100 ){
25310  *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
25311  exp %= 100;
25312  }
25313  *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
25314  *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
25315  }
25316  *bufpt = 0;
25317 
25318  /* The converted number is in buf[] and zero terminated. Output it.
25319  ** Note that the number is in the usual order, not reversed as with
25320  ** integer conversions. */
25321  length = (int)(bufpt-zOut);
25322  bufpt = zOut;
25323 
25324  /* Special case: Add leading zeros if the flag_zeropad flag is
25325  ** set and we are not left justified */
25326  if( flag_zeropad && !flag_leftjustify && length < width){
25327  int i;
25328  int nPad = width - length;
25329  for(i=width; i>=nPad; i--){
25330  bufpt[i] = bufpt[i-nPad];
25331  }
25332  i = prefix!=0;
25333  while( nPad-- ) bufpt[i++] = '0';
25334  length = width;
25335  }
25336 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
25337  break;
25338  case etSIZE:
25339  if( !bArgList ){
25340  *(va_arg(ap,int*)) = pAccum->nChar;
25341  }
25342  length = width = 0;
25343  break;
25344  case etPERCENT:
25345  buf[0] = '%';
25346  bufpt = buf;
25347  length = 1;
25348  break;
25349  case etCHARX:
25350  if( bArgList ){
25351  bufpt = getTextArg(pArgList);
25352  c = bufpt ? bufpt[0] : 0;
25353  }else{
25354  c = va_arg(ap,int);
25355  }
25356  if( precision>1 ){
25357  width -= precision-1;
25358  if( width>1 && !flag_leftjustify ){
25359  sqlite3AppendChar(pAccum, width-1, ' ');
25360  width = 0;
25361  }
25362  sqlite3AppendChar(pAccum, precision-1, c);
25363  }
25364  length = 1;
25365  buf[0] = c;
25366  bufpt = buf;
25367  break;
25368  case etSTRING:
25369  case etDYNSTRING:
25370  if( bArgList ){
25371  bufpt = getTextArg(pArgList);
25372  xtype = etSTRING;
25373  }else{
25374  bufpt = va_arg(ap,char*);
25375  }
25376  if( bufpt==0 ){
25377  bufpt = "";
25378  }else if( xtype==etDYNSTRING ){
25379  zExtra = bufpt;
25380  }
25381  if( precision>=0 ){
25382  for(length=0; length<precision && bufpt[length]; length++){}
25383  }else{
25384  length = sqlite3Strlen30(bufpt);
25385  }
25386  break;
25387  case etSQLESCAPE: /* Escape ' characters */
25388  case etSQLESCAPE2: /* Escape ' and enclose in '...' */
25389  case etSQLESCAPE3: { /* Escape " characters */
25390  int i, j, k, n, isnull;
25391  int needQuote;
25392  char ch;
25393  char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
25394  char *escarg;
25395 
25396  if( bArgList ){
25397  escarg = getTextArg(pArgList);
25398  }else{
25399  escarg = va_arg(ap,char*);
25400  }
25401  isnull = escarg==0;
25402  if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
25403  k = precision;
25404  for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
25405  if( ch==q ) n++;
25406  }
25407  needQuote = !isnull && xtype==etSQLESCAPE2;
25408  n += i + 3;
25409  if( n>etBUFSIZE ){
25410  bufpt = zExtra = sqlite3Malloc( n );
25411  if( bufpt==0 ){
25412  setStrAccumError(pAccum, STRACCUM_NOMEM);
25413  return;
25414  }
25415  }else{
25416  bufpt = buf;
25417  }
25418  j = 0;
25419  if( needQuote ) bufpt[j++] = q;
25420  k = i;
25421  for(i=0; i<k; i++){
25422  bufpt[j++] = ch = escarg[i];
25423  if( ch==q ) bufpt[j++] = ch;
25424  }
25425  if( needQuote ) bufpt[j++] = q;
25426  bufpt[j] = 0;
25427  length = j;
25428  /* The precision in %q and %Q means how many input characters to
25429  ** consume, not the length of the output...
25430  ** if( precision>=0 && precision<length ) length = precision; */
25431  break;
25432  }
25433  case etTOKEN: {
25434  Token *pToken = va_arg(ap, Token*);
25435  assert( bArgList==0 );
25436  if( pToken && pToken->n ){
25437  sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
25438  }
25439  length = width = 0;
25440  break;
25441  }
25442  case etSRCLIST: {
25443  SrcList *pSrc = va_arg(ap, SrcList*);
25444  int k = va_arg(ap, int);
25445  struct SrcList_item *pItem = &pSrc->a[k];
25446  assert( bArgList==0 );
25447  assert( k>=0 && k<pSrc->nSrc );
25448  if( pItem->zDatabase ){
25449  sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
25450  sqlite3StrAccumAppend(pAccum, ".", 1);
25451  }
25452  sqlite3StrAccumAppendAll(pAccum, pItem->zName);
25453  length = width = 0;
25454  break;
25455  }
25456  default: {
25457  assert( xtype==etINVALID );
25458  return;
25459  }
25460  }/* End switch over the format type */
25461  /*
25462  ** The text of the conversion is pointed to by "bufpt" and is
25463  ** "length" characters long. The field width is "width". Do
25464  ** the output.
25465  */
25466  width -= length;
25467  if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25468  sqlite3StrAccumAppend(pAccum, bufpt, length);
25469  if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25470 
25471  if( zExtra ){
25472  sqlite3DbFree(pAccum->db, zExtra);
25473  zExtra = 0;
25474  }
25475  }/* End for loop over the format string */
25476 } /* End of function */
25477 
25478 /*
25479 ** Enlarge the memory allocation on a StrAccum object so that it is
25480 ** able to accept at least N more bytes of text.
25481 **
25482 ** Return the number of bytes of text that StrAccum is able to accept
25483 ** after the attempted enlargement. The value returned might be zero.
25484 */
25485 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
25486  char *zNew;
25487  assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
25488  if( p->accError ){
25489  testcase(p->accError==STRACCUM_TOOBIG);
25490  testcase(p->accError==STRACCUM_NOMEM);
25491  return 0;
25492  }
25493  if( p->mxAlloc==0 ){
25494  N = p->nAlloc - p->nChar - 1;
25495  setStrAccumError(p, STRACCUM_TOOBIG);
25496  return N;
25497  }else{
25498  char *zOld = isMalloced(p) ? p->zText : 0;
25499  i64 szNew = p->nChar;
25500  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25501  szNew += N + 1;
25502  if( szNew+p->nChar<=p->mxAlloc ){
25503  /* Force exponential buffer size growth as long as it does not overflow,
25504  ** to avoid having to call this routine too often */
25505  szNew += p->nChar;
25506  }
25507  if( szNew > p->mxAlloc ){
25508  sqlite3StrAccumReset(p);
25509  setStrAccumError(p, STRACCUM_TOOBIG);
25510  return 0;
25511  }else{
25512  p->nAlloc = (int)szNew;
25513  }
25514  if( p->db ){
25515  zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
25516  }else{
25517  zNew = sqlite3_realloc64(zOld, p->nAlloc);
25518  }
25519  if( zNew ){
25520  assert( p->zText!=0 || p->nChar==0 );
25521  if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
25522  p->zText = zNew;
25523  p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
25524  p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25525  }else{
25526  sqlite3StrAccumReset(p);
25527  setStrAccumError(p, STRACCUM_NOMEM);
25528  return 0;
25529  }
25530  }
25531  return N;
25532 }
25533 
25534 /*
25535 ** Append N copies of character c to the given string buffer.
25536 */
25537 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
25538  testcase( p->nChar + (i64)N > 0x7fffffff );
25539  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
25540  return;
25541  }
25542  assert( (p->zText==p->zBase)==!isMalloced(p) );
25543  while( (N--)>0 ) p->zText[p->nChar++] = c;
25544 }
25545 
25546 /*
25547 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
25548 ** So enlarge if first, then do the append.
25549 **
25550 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
25551 ** work (enlarging the buffer) using tail recursion, so that the
25552 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
25553 */
25554 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
25555  N = sqlite3StrAccumEnlarge(p, N);
25556  if( N>0 ){
25557  memcpy(&p->zText[p->nChar], z, N);
25558  p->nChar += N;
25559  }
25560  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25561 }
25562 
25563 /*
25564 ** Append N bytes of text from z to the StrAccum object. Increase the
25565 ** size of the memory allocation for StrAccum if necessary.
25566 */
25567 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
25568  assert( z!=0 || N==0 );
25569  assert( p->zText!=0 || p->nChar==0 || p->accError );
25570  assert( N>=0 );
25571  assert( p->accError==0 || p->nAlloc==0 );
25572  if( p->nChar+N >= p->nAlloc ){
25573  enlargeAndAppend(p,z,N);
25574  }else{
25575  assert( p->zText );
25576  p->nChar += N;
25577  memcpy(&p->zText[p->nChar-N], z, N);
25578  }
25579 }
25580 
25581 /*
25582 ** Append the complete text of zero-terminated string z[] to the p string.
25583 */
25584 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
25585  sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
25586 }
25587 
25588 
25589 /*
25590 ** Finish off a string by making sure it is zero-terminated.
25591 ** Return a pointer to the resulting string. Return a NULL
25592 ** pointer if any kind of error was encountered.
25593 */
25594 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
25595  if( p->zText ){
25596  assert( (p->zText==p->zBase)==!isMalloced(p) );
25597  p->zText[p->nChar] = 0;
25598  if( p->mxAlloc>0 && !isMalloced(p) ){
25599  p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
25600  if( p->zText ){
25601  memcpy(p->zText, p->zBase, p->nChar+1);
25602  p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25603  }else{
25604  setStrAccumError(p, STRACCUM_NOMEM);
25605  }
25606  }
25607  }
25608  return p->zText;
25609 }
25610 
25611 /*
25612 ** Reset an StrAccum string. Reclaim all malloced memory.
25613 */
25614 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
25615  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25616  if( isMalloced(p) ){
25617  sqlite3DbFree(p->db, p->zText);
25618  p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
25619  }
25620  p->zText = 0;
25621 }
25622 
25623 /*
25624 ** Initialize a string accumulator.
25625 **
25626 ** p: The accumulator to be initialized.
25627 ** db: Pointer to a database connection. May be NULL. Lookaside
25628 ** memory is used if not NULL. db->mallocFailed is set appropriately
25629 ** when not NULL.
25630 ** zBase: An initial buffer. May be NULL in which case the initial buffer
25631 ** is malloced.
25632 ** n: Size of zBase in bytes. If total space requirements never exceed
25633 ** n then no memory allocations ever occur.
25634 ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
25635 ** allocations will ever occur.
25636 */
25637 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
25638  p->zText = p->zBase = zBase;
25639  p->db = db;
25640  p->nChar = 0;
25641  p->nAlloc = n;
25642  p->mxAlloc = mx;
25643  p->accError = 0;
25644  p->printfFlags = 0;
25645 }
25646 
25647 /*
25648 ** Print into memory obtained from sqliteMalloc(). Use the internal
25649 ** %-conversion extensions.
25650 */
25651 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
25652  char *z;
25653  char zBase[SQLITE_PRINT_BUF_SIZE];
25654  StrAccum acc;
25655  assert( db!=0 );
25656  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
25657  db->aLimit[SQLITE_LIMIT_LENGTH]);
25658  acc.printfFlags = SQLITE_PRINTF_INTERNAL;
25659  sqlite3VXPrintf(&acc, zFormat, ap);
25660  z = sqlite3StrAccumFinish(&acc);
25661  if( acc.accError==STRACCUM_NOMEM ){
25662  sqlite3OomFault(db);
25663  }
25664  return z;
25665 }
25666 
25667 /*
25668 ** Print into memory obtained from sqliteMalloc(). Use the internal
25669 ** %-conversion extensions.
25670 */
25671 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
25672  va_list ap;
25673  char *z;
25674  va_start(ap, zFormat);
25675  z = sqlite3VMPrintf(db, zFormat, ap);
25676  va_end(ap);
25677  return z;
25678 }
25679 
25680 /*
25681 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
25682 ** %-conversion extensions.
25683 */
25684 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
25685  char *z;
25686  char zBase[SQLITE_PRINT_BUF_SIZE];
25687  StrAccum acc;
25688 
25689 #ifdef SQLITE_ENABLE_API_ARMOR
25690  if( zFormat==0 ){
25691  (void)SQLITE_MISUSE_BKPT;
25692  return 0;
25693  }
25694 #endif
25695 #ifndef SQLITE_OMIT_AUTOINIT
25696  if( sqlite3_initialize() ) return 0;
25697 #endif
25698  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
25699  sqlite3VXPrintf(&acc, zFormat, ap);
25700  z = sqlite3StrAccumFinish(&acc);
25701  return z;
25702 }
25703 
25704 /*
25705 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
25706 ** %-conversion extensions.
25707 */
25708 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
25709  va_list ap;
25710  char *z;
25711 #ifndef SQLITE_OMIT_AUTOINIT
25712  if( sqlite3_initialize() ) return 0;
25713 #endif
25714  va_start(ap, zFormat);
25715  z = sqlite3_vmprintf(zFormat, ap);
25716  va_end(ap);
25717  return z;
25718 }
25719 
25720 /*
25721 ** sqlite3_snprintf() works like snprintf() except that it ignores the
25722 ** current locale settings. This is important for SQLite because we
25723 ** are not able to use a "," as the decimal point in place of "." as
25724 ** specified by some locales.
25725 **
25726 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
25727 ** from the snprintf() standard. Unfortunately, it is too late to change
25728 ** this without breaking compatibility, so we just have to live with the
25729 ** mistake.
25730 **
25731 ** sqlite3_vsnprintf() is the varargs version.
25732 */
25733 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
25734  StrAccum acc;
25735  if( n<=0 ) return zBuf;
25736 #ifdef SQLITE_ENABLE_API_ARMOR
25737  if( zBuf==0 || zFormat==0 ) {
25738  (void)SQLITE_MISUSE_BKPT;
25739  if( zBuf ) zBuf[0] = 0;
25740  return zBuf;
25741  }
25742 #endif
25743  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
25744  sqlite3VXPrintf(&acc, zFormat, ap);
25745  return sqlite3StrAccumFinish(&acc);
25746 }
25747 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
25748  char *z;
25749  va_list ap;
25750  va_start(ap,zFormat);
25751  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
25752  va_end(ap);
25753  return z;
25754 }
25755 
25756 /*
25757 ** This is the routine that actually formats the sqlite3_log() message.
25758 ** We house it in a separate routine from sqlite3_log() to avoid using
25759 ** stack space on small-stack systems when logging is disabled.
25760 **
25761 ** sqlite3_log() must render into a static buffer. It cannot dynamically
25762 ** allocate memory because it might be called while the memory allocator
25763 ** mutex is held.
25764 **
25765 ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
25766 ** certain format characters (%q) or for very large precisions or widths.
25767 ** Care must be taken that any sqlite3_log() calls that occur while the
25768 ** memory mutex is held do not use these mechanisms.
25769 */
25770 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
25771  StrAccum acc; /* String accumulator */
25772  char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
25773 
25774  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
25775  sqlite3VXPrintf(&acc, zFormat, ap);
25776  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
25777  sqlite3StrAccumFinish(&acc));
25778 }
25779 
25780 /*
25781 ** Format and write a message to the log if logging is enabled.
25782 */
25783 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
25784  va_list ap; /* Vararg list */
25785  if( sqlite3GlobalConfig.xLog ){
25786  va_start(ap, zFormat);
25787  renderLogMsg(iErrCode, zFormat, ap);
25788  va_end(ap);
25789  }
25790 }
25791 
25792 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
25793 /*
25794 ** A version of printf() that understands %lld. Used for debugging.
25795 ** The printf() built into some versions of windows does not understand %lld
25796 ** and segfaults if you give it a long long int.
25797 */
25798 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
25799  va_list ap;
25800  StrAccum acc;
25801  char zBuf[500];
25802  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25803  va_start(ap,zFormat);
25804  sqlite3VXPrintf(&acc, zFormat, ap);
25805  va_end(ap);
25806  sqlite3StrAccumFinish(&acc);
25807  fprintf(stdout,"%s", zBuf);
25808  fflush(stdout);
25809 }
25810 #endif
25811 
25812 
25813 /*
25814 ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
25815 ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
25816 */
25817 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
25818  va_list ap;
25819  va_start(ap,zFormat);
25820  sqlite3VXPrintf(p, zFormat, ap);
25821  va_end(ap);
25822 }
25823 
25824 /************** End of printf.c **********************************************/
25825 /************** Begin file treeview.c ****************************************/
25826 /*
25827 ** 2015-06-08
25828 **
25829 ** The author disclaims copyright to this source code. In place of
25830 ** a legal notice, here is a blessing:
25831 **
25832 ** May you do good and not evil.
25833 ** May you find forgiveness for yourself and forgive others.
25834 ** May you share freely, never taking more than you give.
25835 **
25836 *************************************************************************
25837 **
25838 ** This file contains C code to implement the TreeView debugging routines.
25839 ** These routines print a parse tree to standard output for debugging and
25840 ** analysis.
25841 **
25842 ** The interfaces in this file is only available when compiling
25843 ** with SQLITE_DEBUG.
25844 */
25845 /* #include "sqliteInt.h" */
25846 #ifdef SQLITE_DEBUG
25847 
25848 /*
25849 ** Add a new subitem to the tree. The moreToFollow flag indicates that this
25850 ** is not the last item in the tree.
25851 */
25852 static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
25853  if( p==0 ){
25854  p = sqlite3_malloc64( sizeof(*p) );
25855  if( p==0 ) return 0;
25856  memset(p, 0, sizeof(*p));
25857  }else{
25858  p->iLevel++;
25859  }
25860  assert( moreToFollow==0 || moreToFollow==1 );
25861  if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
25862  return p;
25863 }
25864 
25865 /*
25866 ** Finished with one layer of the tree
25867 */
25868 static void sqlite3TreeViewPop(TreeView *p){
25869  if( p==0 ) return;
25870  p->iLevel--;
25871  if( p->iLevel<0 ) sqlite3_free(p);
25872 }
25873 
25874 /*
25875 ** Generate a single line of output for the tree, with a prefix that contains
25876 ** all the appropriate tree lines
25877 */
25878 static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
25879  va_list ap;
25880  int i;
25881  StrAccum acc;
25882  char zBuf[500];
25883  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25884  if( p ){
25885  for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
25886  sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
25887  }
25888  sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
25889  }
25890  va_start(ap, zFormat);
25891  sqlite3VXPrintf(&acc, zFormat, ap);
25892  va_end(ap);
25893  if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
25894  sqlite3StrAccumFinish(&acc);
25895  fprintf(stdout,"%s", zBuf);
25896  fflush(stdout);
25897 }
25898 
25899 /*
25900 ** Shorthand for starting a new tree item that consists of a single label
25901 */
25902 static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
25903  p = sqlite3TreeViewPush(p, moreFollows);
25904  sqlite3TreeViewLine(p, "%s", zLabel);
25905 }
25906 
25907 /*
25908 ** Generate a human-readable description of a WITH clause.
25909 */
25910 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
25911  int i;
25912  if( pWith==0 ) return;
25913  if( pWith->nCte==0 ) return;
25914  if( pWith->pOuter ){
25915  sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
25916  }else{
25917  sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
25918  }
25919  if( pWith->nCte>0 ){
25920  pView = sqlite3TreeViewPush(pView, 1);
25921  for(i=0; i<pWith->nCte; i++){
25922  StrAccum x;
25923  char zLine[1000];
25924  const struct Cte *pCte = &pWith->a[i];
25925  sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25926  sqlite3XPrintf(&x, "%s", pCte->zName);
25927  if( pCte->pCols && pCte->pCols->nExpr>0 ){
25928  char cSep = '(';
25929  int j;
25930  for(j=0; j<pCte->pCols->nExpr; j++){
25931  sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
25932  cSep = ',';
25933  }
25934  sqlite3XPrintf(&x, ")");
25935  }
25936  sqlite3XPrintf(&x, " AS");
25937  sqlite3StrAccumFinish(&x);
25938  sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
25939  sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
25940  sqlite3TreeViewPop(pView);
25941  }
25942  sqlite3TreeViewPop(pView);
25943  }
25944 }
25945 
25946 
25947 /*
25948 ** Generate a human-readable description of a Select object.
25949 */
25950 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
25951  int n = 0;
25952  int cnt = 0;
25953  pView = sqlite3TreeViewPush(pView, moreToFollow);
25954  if( p->pWith ){
25955  sqlite3TreeViewWith(pView, p->pWith, 1);
25956  cnt = 1;
25957  sqlite3TreeViewPush(pView, 1);
25958  }
25959  do{
25960  sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
25961  ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
25962  ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
25963  (int)p->nSelectRow
25964  );
25965  if( cnt++ ) sqlite3TreeViewPop(pView);
25966  if( p->pPrior ){
25967  n = 1000;
25968  }else{
25969  n = 0;
25970  if( p->pSrc && p->pSrc->nSrc ) n++;
25971  if( p->pWhere ) n++;
25972  if( p->pGroupBy ) n++;
25973  if( p->pHaving ) n++;
25974  if( p->pOrderBy ) n++;
25975  if( p->pLimit ) n++;
25976  if( p->pOffset ) n++;
25977  }
25978  sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
25979  if( p->pSrc && p->pSrc->nSrc ){
25980  int i;
25981  pView = sqlite3TreeViewPush(pView, (n--)>0);
25982  sqlite3TreeViewLine(pView, "FROM");
25983  for(i=0; i<p->pSrc->nSrc; i++){
25984  struct SrcList_item *pItem = &p->pSrc->a[i];
25985  StrAccum x;
25986  char zLine[100];
25987  sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25988  sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
25989  if( pItem->zDatabase ){
25990  sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
25991  }else if( pItem->zName ){
25992  sqlite3XPrintf(&x, " %s", pItem->zName);
25993  }
25994  if( pItem->pTab ){
25995  sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
25996  }
25997  if( pItem->zAlias ){
25998  sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
25999  }
26000  if( pItem->fg.jointype & JT_LEFT ){
26001  sqlite3XPrintf(&x, " LEFT-JOIN");
26002  }
26003  sqlite3StrAccumFinish(&x);
26004  sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
26005  if( pItem->pSelect ){
26006  sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
26007  }
26008  if( pItem->fg.isTabFunc ){
26009  sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
26010  }
26011  sqlite3TreeViewPop(pView);
26012  }
26013  sqlite3TreeViewPop(pView);
26014  }
26015  if( p->pWhere ){
26016  sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
26017  sqlite3TreeViewExpr(pView, p->pWhere, 0);
26018  sqlite3TreeViewPop(pView);
26019  }
26020  if( p->pGroupBy ){
26021  sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
26022  }
26023  if( p->pHaving ){
26024  sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
26025  sqlite3TreeViewExpr(pView, p->pHaving, 0);
26026  sqlite3TreeViewPop(pView);
26027  }
26028  if( p->pOrderBy ){
26029  sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
26030  }
26031  if( p->pLimit ){
26032  sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
26033  sqlite3TreeViewExpr(pView, p->pLimit, 0);
26034  sqlite3TreeViewPop(pView);
26035  }
26036  if( p->pOffset ){
26037  sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
26038  sqlite3TreeViewExpr(pView, p->pOffset, 0);
26039  sqlite3TreeViewPop(pView);
26040  }
26041  if( p->pPrior ){
26042  const char *zOp = "UNION";
26043  switch( p->op ){
26044  case TK_ALL: zOp = "UNION ALL"; break;
26045  case TK_INTERSECT: zOp = "INTERSECT"; break;
26046  case TK_EXCEPT: zOp = "EXCEPT"; break;
26047  }
26048  sqlite3TreeViewItem(pView, zOp, 1);
26049  }
26050  p = p->pPrior;
26051  }while( p!=0 );
26052  sqlite3TreeViewPop(pView);
26053 }
26054 
26055 /*
26056 ** Generate a human-readable explanation of an expression tree.
26057 */
26058 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
26059  const char *zBinOp = 0; /* Binary operator */
26060  const char *zUniOp = 0; /* Unary operator */
26061  char zFlgs[30];
26062  pView = sqlite3TreeViewPush(pView, moreToFollow);
26063  if( pExpr==0 ){
26064  sqlite3TreeViewLine(pView, "nil");
26065  sqlite3TreeViewPop(pView);
26066  return;
26067  }
26068  if( pExpr->flags ){
26069  sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
26070  }else{
26071  zFlgs[0] = 0;
26072  }
26073  switch( pExpr->op ){
26074  case TK_AGG_COLUMN: {
26075  sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
26076  pExpr->iTable, pExpr->iColumn, zFlgs);
26077  break;
26078  }
26079  case TK_COLUMN: {
26080  if( pExpr->iTable<0 ){
26081  /* This only happens when coding check constraints */
26082  sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
26083  }else{
26084  sqlite3TreeViewLine(pView, "{%d:%d}%s",
26085  pExpr->iTable, pExpr->iColumn, zFlgs);
26086  }
26087  break;
26088  }
26089  case TK_INTEGER: {
26090  if( pExpr->flags & EP_IntValue ){
26091  sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
26092  }else{
26093  sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
26094  }
26095  break;
26096  }
26097 #ifndef SQLITE_OMIT_FLOATING_POINT
26098  case TK_FLOAT: {
26099  sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26100  break;
26101  }
26102 #endif
26103  case TK_STRING: {
26104  sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
26105  break;
26106  }
26107  case TK_NULL: {
26108  sqlite3TreeViewLine(pView,"NULL");
26109  break;
26110  }
26111 #ifndef SQLITE_OMIT_BLOB_LITERAL
26112  case TK_BLOB: {
26113  sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26114  break;
26115  }
26116 #endif
26117  case TK_VARIABLE: {
26118  sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
26119  pExpr->u.zToken, pExpr->iColumn);
26120  break;
26121  }
26122  case TK_REGISTER: {
26123  sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
26124  break;
26125  }
26126  case TK_ID: {
26127  sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
26128  break;
26129  }
26130 #ifndef SQLITE_OMIT_CAST
26131  case TK_CAST: {
26132  /* Expressions of the form: CAST(pLeft AS token) */
26133  sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
26134  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26135  break;
26136  }
26137 #endif /* SQLITE_OMIT_CAST */
26138  case TK_LT: zBinOp = "LT"; break;
26139  case TK_LE: zBinOp = "LE"; break;
26140  case TK_GT: zBinOp = "GT"; break;
26141  case TK_GE: zBinOp = "GE"; break;
26142  case TK_NE: zBinOp = "NE"; break;
26143  case TK_EQ: zBinOp = "EQ"; break;
26144  case TK_IS: zBinOp = "IS"; break;
26145  case TK_ISNOT: zBinOp = "ISNOT"; break;
26146  case TK_AND: zBinOp = "AND"; break;
26147  case TK_OR: zBinOp = "OR"; break;
26148  case TK_PLUS: zBinOp = "ADD"; break;
26149  case TK_STAR: zBinOp = "MUL"; break;
26150  case TK_MINUS: zBinOp = "SUB"; break;
26151  case TK_REM: zBinOp = "REM"; break;
26152  case TK_BITAND: zBinOp = "BITAND"; break;
26153  case TK_BITOR: zBinOp = "BITOR"; break;
26154  case TK_SLASH: zBinOp = "DIV"; break;
26155  case TK_LSHIFT: zBinOp = "LSHIFT"; break;
26156  case TK_RSHIFT: zBinOp = "RSHIFT"; break;
26157  case TK_CONCAT: zBinOp = "CONCAT"; break;
26158  case TK_DOT: zBinOp = "DOT"; break;
26159 
26160  case TK_UMINUS: zUniOp = "UMINUS"; break;
26161  case TK_UPLUS: zUniOp = "UPLUS"; break;
26162  case TK_BITNOT: zUniOp = "BITNOT"; break;
26163  case TK_NOT: zUniOp = "NOT"; break;
26164  case TK_ISNULL: zUniOp = "ISNULL"; break;
26165  case TK_NOTNULL: zUniOp = "NOTNULL"; break;
26166 
26167  case TK_SPAN: {
26168  sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
26169  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26170  break;
26171  }
26172 
26173  case TK_COLLATE: {
26174  sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
26175  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26176  break;
26177  }
26178 
26179  case TK_AGG_FUNCTION:
26180  case TK_FUNCTION: {
26181  ExprList *pFarg; /* List of function arguments */
26182  if( ExprHasProperty(pExpr, EP_TokenOnly) ){
26183  pFarg = 0;
26184  }else{
26185  pFarg = pExpr->x.pList;
26186  }
26187  if( pExpr->op==TK_AGG_FUNCTION ){
26188  sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
26189  pExpr->op2, pExpr->u.zToken);
26190  }else{
26191  sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
26192  }
26193  if( pFarg ){
26194  sqlite3TreeViewExprList(pView, pFarg, 0, 0);
26195  }
26196  break;
26197  }
26198 #ifndef SQLITE_OMIT_SUBQUERY
26199  case TK_EXISTS: {
26200  sqlite3TreeViewLine(pView, "EXISTS-expr");
26201  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26202  break;
26203  }
26204  case TK_SELECT: {
26205  sqlite3TreeViewLine(pView, "SELECT-expr");
26206  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26207  break;
26208  }
26209  case TK_IN: {
26210  sqlite3TreeViewLine(pView, "IN");
26211  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26212  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
26213  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26214  }else{
26215  sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26216  }
26217  break;
26218  }
26219 #endif /* SQLITE_OMIT_SUBQUERY */
26220 
26221  /*
26222  ** x BETWEEN y AND z
26223  **
26224  ** This is equivalent to
26225  **
26226  ** x>=y AND x<=z
26227  **
26228  ** X is stored in pExpr->pLeft.
26229  ** Y is stored in pExpr->pList->a[0].pExpr.
26230  ** Z is stored in pExpr->pList->a[1].pExpr.
26231  */
26232  case TK_BETWEEN: {
26233  Expr *pX = pExpr->pLeft;
26234  Expr *pY = pExpr->x.pList->a[0].pExpr;
26235  Expr *pZ = pExpr->x.pList->a[1].pExpr;
26236  sqlite3TreeViewLine(pView, "BETWEEN");
26237  sqlite3TreeViewExpr(pView, pX, 1);
26238  sqlite3TreeViewExpr(pView, pY, 1);
26239  sqlite3TreeViewExpr(pView, pZ, 0);
26240  break;
26241  }
26242  case TK_TRIGGER: {
26243  /* If the opcode is TK_TRIGGER, then the expression is a reference
26244  ** to a column in the new.* or old.* pseudo-tables available to
26245  ** trigger programs. In this case Expr.iTable is set to 1 for the
26246  ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
26247  ** is set to the column of the pseudo-table to read, or to -1 to
26248  ** read the rowid field.
26249  */
26250  sqlite3TreeViewLine(pView, "%s(%d)",
26251  pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
26252  break;
26253  }
26254  case TK_CASE: {
26255  sqlite3TreeViewLine(pView, "CASE");
26256  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26257  sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26258  break;
26259  }
26260 #ifndef SQLITE_OMIT_TRIGGER
26261  case TK_RAISE: {
26262  const char *zType = "unk";
26263  switch( pExpr->affinity ){
26264  case OE_Rollback: zType = "rollback"; break;
26265  case OE_Abort: zType = "abort"; break;
26266  case OE_Fail: zType = "fail"; break;
26267  case OE_Ignore: zType = "ignore"; break;
26268  }
26269  sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
26270  break;
26271  }
26272 #endif
26273  case TK_MATCH: {
26274  sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
26275  pExpr->iTable, pExpr->iColumn, zFlgs);
26276  sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26277  break;
26278  }
26279  case TK_VECTOR: {
26280  sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
26281  break;
26282  }
26283  case TK_SELECT_COLUMN: {
26284  sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
26285  sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
26286  break;
26287  }
26288  default: {
26289  sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
26290  break;
26291  }
26292  }
26293  if( zBinOp ){
26294  sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
26295  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26296  sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26297  }else if( zUniOp ){
26298  sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
26299  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26300  }
26301  sqlite3TreeViewPop(pView);
26302 }
26303 
26304 
26305 /*
26306 ** Generate a human-readable explanation of an expression list.
26307 */
26308 SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
26309  TreeView *pView,
26310  const ExprList *pList,
26311  const char *zLabel
26312 ){
26313  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
26314  if( pList==0 ){
26315  sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
26316  }else{
26317  int i;
26318  sqlite3TreeViewLine(pView, "%s", zLabel);
26319  for(i=0; i<pList->nExpr; i++){
26320  int j = pList->a[i].u.x.iOrderByCol;
26321  if( j ){
26322  sqlite3TreeViewPush(pView, 0);
26323  sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
26324  }
26325  sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
26326  if( j ) sqlite3TreeViewPop(pView);
26327  }
26328  }
26329 }
26330 SQLITE_PRIVATE void sqlite3TreeViewExprList(
26331  TreeView *pView,
26332  const ExprList *pList,
26333  u8 moreToFollow,
26334  const char *zLabel
26335 ){
26336  pView = sqlite3TreeViewPush(pView, moreToFollow);
26337  sqlite3TreeViewBareExprList(pView, pList, zLabel);
26338  sqlite3TreeViewPop(pView);
26339 }
26340 
26341 #endif /* SQLITE_DEBUG */
26342 
26343 /************** End of treeview.c ********************************************/
26344 /************** Begin file random.c ******************************************/
26345 /*
26346 ** 2001 September 15
26347 **
26348 ** The author disclaims copyright to this source code. In place of
26349 ** a legal notice, here is a blessing:
26350 **
26351 ** May you do good and not evil.
26352 ** May you find forgiveness for yourself and forgive others.
26353 ** May you share freely, never taking more than you give.
26354 **
26355 *************************************************************************
26356 ** This file contains code to implement a pseudo-random number
26357 ** generator (PRNG) for SQLite.
26358 **
26359 ** Random numbers are used by some of the database backends in order
26360 ** to generate random integer keys for tables or random filenames.
26361 */
26362 /* #include "sqliteInt.h" */
26363 
26364 
26365 /* All threads share a single random number generator.
26366 ** This structure is the current state of the generator.
26367 */
26368 static SQLITE_WSD struct sqlite3PrngType {
26369  unsigned char isInit; /* True if initialized */
26370  unsigned char i, j; /* State variables */
26371  unsigned char s[256]; /* State variables */
26372 } sqlite3Prng;
26373 
26374 /*
26375 ** Return N random bytes.
26376 */
26377 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
26378  unsigned char t;
26379  unsigned char *zBuf = pBuf;
26380 
26381  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
26382  ** state vector. If writable static data is unsupported on the target,
26383  ** we have to locate the state vector at run-time. In the more common
26384  ** case where writable static data is supported, wsdPrng can refer directly
26385  ** to the "sqlite3Prng" state vector declared above.
26386  */
26387 #ifdef SQLITE_OMIT_WSD
26388  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
26389 # define wsdPrng p[0]
26390 #else
26391 # define wsdPrng sqlite3Prng
26392 #endif
26393 
26394 #if SQLITE_THREADSAFE
26395  sqlite3_mutex *mutex;
26396 #endif
26397 
26398 #ifndef SQLITE_OMIT_AUTOINIT
26399  if( sqlite3_initialize() ) return;
26400 #endif
26401 
26402 #if SQLITE_THREADSAFE
26403  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
26404 #endif
26405 
26406  sqlite3_mutex_enter(mutex);
26407  if( N<=0 || pBuf==0 ){
26408  wsdPrng.isInit = 0;
26409  sqlite3_mutex_leave(mutex);
26410  return;
26411  }
26412 
26413  /* Initialize the state of the random number generator once,
26414  ** the first time this routine is called. The seed value does
26415  ** not need to contain a lot of randomness since we are not
26416  ** trying to do secure encryption or anything like that...
26417  **
26418  ** Nothing in this file or anywhere else in SQLite does any kind of
26419  ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
26420  ** number generator) not as an encryption device.
26421  */
26422  if( !wsdPrng.isInit ){
26423  int i;
26424  char k[256];
26425  wsdPrng.j = 0;
26426  wsdPrng.i = 0;
26427  sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
26428  for(i=0; i<256; i++){
26429  wsdPrng.s[i] = (u8)i;
26430  }
26431  for(i=0; i<256; i++){
26432  wsdPrng.j += wsdPrng.s[i] + k[i];
26433  t = wsdPrng.s[wsdPrng.j];
26434  wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
26435  wsdPrng.s[i] = t;
26436  }
26437  wsdPrng.isInit = 1;
26438  }
26439 
26440  assert( N>0 );
26441  do{
26442  wsdPrng.i++;
26443  t = wsdPrng.s[wsdPrng.i];
26444  wsdPrng.j += t;
26445  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
26446  wsdPrng.s[wsdPrng.j] = t;
26447  t += wsdPrng.s[wsdPrng.i];
26448  *(zBuf++) = wsdPrng.s[t];
26449  }while( --N );
26450  sqlite3_mutex_leave(mutex);
26451 }
26452 
26453 #ifndef SQLITE_OMIT_BUILTIN_TEST
26454 /*
26455 ** For testing purposes, we sometimes want to preserve the state of
26456 ** PRNG and restore the PRNG to its saved state at a later time, or
26457 ** to reset the PRNG to its initial state. These routines accomplish
26458 ** those tasks.
26459 **
26460 ** The sqlite3_test_control() interface calls these routines to
26461 ** control the PRNG.
26462 */
26463 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
26464 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
26465  memcpy(
26466  &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26467  &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26468  sizeof(sqlite3Prng)
26469  );
26470 }
26471 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
26472  memcpy(
26473  &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26474  &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26475  sizeof(sqlite3Prng)
26476  );
26477 }
26478 #endif /* SQLITE_OMIT_BUILTIN_TEST */
26479 
26480 /************** End of random.c **********************************************/
26481 /************** Begin file threads.c *****************************************/
26482 /*
26483 ** 2012 July 21
26484 **
26485 ** The author disclaims copyright to this source code. In place of
26486 ** a legal notice, here is a blessing:
26487 **
26488 ** May you do good and not evil.
26489 ** May you find forgiveness for yourself and forgive others.
26490 ** May you share freely, never taking more than you give.
26491 **
26492 ******************************************************************************
26493 **
26494 ** This file presents a simple cross-platform threading interface for
26495 ** use internally by SQLite.
26496 **
26497 ** A "thread" can be created using sqlite3ThreadCreate(). This thread
26498 ** runs independently of its creator until it is joined using
26499 ** sqlite3ThreadJoin(), at which point it terminates.
26500 **
26501 ** Threads do not have to be real. It could be that the work of the
26502 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
26503 ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
26504 ** single threaded systems. Nothing in SQLite requires multiple threads.
26505 ** This interface exists so that applications that want to take advantage
26506 ** of multiple cores can do so, while also allowing applications to stay
26507 ** single-threaded if desired.
26508 */
26509 /* #include "sqliteInt.h" */
26510 #if SQLITE_OS_WIN
26511 /* # include "os_win.h" */
26512 #endif
26513 
26514 #if SQLITE_MAX_WORKER_THREADS>0
26515 
26516 /********************************* Unix Pthreads ****************************/
26517 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
26518 
26519 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
26520 /* #include <pthread.h> */
26521 
26522 /* A running thread */
26523 struct SQLiteThread {
26524  pthread_t tid; /* Thread ID */
26525  int done; /* Set to true when thread finishes */
26526  void *pOut; /* Result returned by the thread */
26527  void *(*xTask)(void*); /* The thread routine */
26528  void *pIn; /* Argument to the thread */
26529 };
26530 
26531 /* Create a new thread */
26532 SQLITE_PRIVATE int sqlite3ThreadCreate(
26533  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26534  void *(*xTask)(void*), /* Routine to run in a separate thread */
26535  void *pIn /* Argument passed into xTask() */
26536 ){
26537  SQLiteThread *p;
26538  int rc;
26539 
26540  assert( ppThread!=0 );
26541  assert( xTask!=0 );
26542  /* This routine is never used in single-threaded mode */
26543  assert( sqlite3GlobalConfig.bCoreMutex!=0 );
26544 
26545  *ppThread = 0;
26546  p = sqlite3Malloc(sizeof(*p));
26547  if( p==0 ) return SQLITE_NOMEM_BKPT;
26548  memset(p, 0, sizeof(*p));
26549  p->xTask = xTask;
26550  p->pIn = pIn;
26551  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26552  ** function that returns SQLITE_ERROR when passed the argument 200, that
26553  ** forces worker threads to run sequentially and deterministically
26554  ** for testing purposes. */
26555  if( sqlite3FaultSim(200) ){
26556  rc = 1;
26557  }else{
26558  rc = pthread_create(&p->tid, 0, xTask, pIn);
26559  }
26560  if( rc ){
26561  p->done = 1;
26562  p->pOut = xTask(pIn);
26563  }
26564  *ppThread = p;
26565  return SQLITE_OK;
26566 }
26567 
26568 /* Get the results of the thread */
26569 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26570  int rc;
26571 
26572  assert( ppOut!=0 );
26573  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26574  if( p->done ){
26575  *ppOut = p->pOut;
26576  rc = SQLITE_OK;
26577  }else{
26578  rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
26579  }
26580  sqlite3_free(p);
26581  return rc;
26582 }
26583 
26584 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
26585 /******************************** End Unix Pthreads *************************/
26586 
26587 
26588 /********************************* Win32 Threads ****************************/
26589 #if SQLITE_OS_WIN_THREADS
26590 
26591 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
26592 #include <process.h>
26593 
26594 /* A running thread */
26595 struct SQLiteThread {
26596  void *tid; /* The thread handle */
26597  unsigned id; /* The thread identifier */
26598  void *(*xTask)(void*); /* The routine to run as a thread */
26599  void *pIn; /* Argument to xTask */
26600  void *pResult; /* Result of xTask */
26601 };
26602 
26603 /* Thread procedure Win32 compatibility shim */
26604 static unsigned __stdcall sqlite3ThreadProc(
26605  void *pArg /* IN: Pointer to the SQLiteThread structure */
26606 ){
26607  SQLiteThread *p = (SQLiteThread *)pArg;
26608 
26609  assert( p!=0 );
26610 #if 0
26611  /*
26612  ** This assert appears to trigger spuriously on certain
26613  ** versions of Windows, possibly due to _beginthreadex()
26614  ** and/or CreateThread() not fully setting their thread
26615  ** ID parameter before starting the thread.
26616  */
26617  assert( p->id==GetCurrentThreadId() );
26618 #endif
26619  assert( p->xTask!=0 );
26620  p->pResult = p->xTask(p->pIn);
26621 
26622  _endthreadex(0);
26623  return 0; /* NOT REACHED */
26624 }
26625 
26626 /* Create a new thread */
26627 SQLITE_PRIVATE int sqlite3ThreadCreate(
26628  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26629  void *(*xTask)(void*), /* Routine to run in a separate thread */
26630  void *pIn /* Argument passed into xTask() */
26631 ){
26632  SQLiteThread *p;
26633 
26634  assert( ppThread!=0 );
26635  assert( xTask!=0 );
26636  *ppThread = 0;
26637  p = sqlite3Malloc(sizeof(*p));
26638  if( p==0 ) return SQLITE_NOMEM_BKPT;
26639  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26640  ** function that returns SQLITE_ERROR when passed the argument 200, that
26641  ** forces worker threads to run sequentially and deterministically
26642  ** (via the sqlite3FaultSim() term of the conditional) for testing
26643  ** purposes. */
26644  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
26645  memset(p, 0, sizeof(*p));
26646  }else{
26647  p->xTask = xTask;
26648  p->pIn = pIn;
26649  p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
26650  if( p->tid==0 ){
26651  memset(p, 0, sizeof(*p));
26652  }
26653  }
26654  if( p->xTask==0 ){
26655  p->id = GetCurrentThreadId();
26656  p->pResult = xTask(pIn);
26657  }
26658  *ppThread = p;
26659  return SQLITE_OK;
26660 }
26661 
26662 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
26663 
26664 /* Get the results of the thread */
26665 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26666  DWORD rc;
26667  BOOL bRc;
26668 
26669  assert( ppOut!=0 );
26670  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26671  if( p->xTask==0 ){
26672  /* assert( p->id==GetCurrentThreadId() ); */
26673  rc = WAIT_OBJECT_0;
26674  assert( p->tid==0 );
26675  }else{
26676  assert( p->id!=0 && p->id!=GetCurrentThreadId() );
26677  rc = sqlite3Win32Wait((HANDLE)p->tid);
26678  assert( rc!=WAIT_IO_COMPLETION );
26679  bRc = CloseHandle((HANDLE)p->tid);
26680  assert( bRc );
26681  }
26682  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
26683  sqlite3_free(p);
26684  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
26685 }
26686 
26687 #endif /* SQLITE_OS_WIN_THREADS */
26688 /******************************** End Win32 Threads *************************/
26689 
26690 
26691 /********************************* Single-Threaded **************************/
26692 #ifndef SQLITE_THREADS_IMPLEMENTED
26693 /*
26694 ** This implementation does not actually create a new thread. It does the
26695 ** work of the thread in the main thread, when either the thread is created
26696 ** or when it is joined
26697 */
26698 
26699 /* A running thread */
26700 struct SQLiteThread {
26701  void *(*xTask)(void*); /* The routine to run as a thread */
26702  void *pIn; /* Argument to xTask */
26703  void *pResult; /* Result of xTask */
26704 };
26705 
26706 /* Create a new thread */
26707 SQLITE_PRIVATE int sqlite3ThreadCreate(
26708  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26709  void *(*xTask)(void*), /* Routine to run in a separate thread */
26710  void *pIn /* Argument passed into xTask() */
26711 ){
26712  SQLiteThread *p;
26713 
26714  assert( ppThread!=0 );
26715  assert( xTask!=0 );
26716  *ppThread = 0;
26717  p = sqlite3Malloc(sizeof(*p));
26718  if( p==0 ) return SQLITE_NOMEM_BKPT;
26719  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
26720  p->xTask = xTask;
26721  p->pIn = pIn;
26722  }else{
26723  p->xTask = 0;
26724  p->pResult = xTask(pIn);
26725  }
26726  *ppThread = p;
26727  return SQLITE_OK;
26728 }
26729 
26730 /* Get the results of the thread */
26731 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26732 
26733  assert( ppOut!=0 );
26734  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26735  if( p->xTask ){
26736  *ppOut = p->xTask(p->pIn);
26737  }else{
26738  *ppOut = p->pResult;
26739  }
26740  sqlite3_free(p);
26741 
26742 #if defined(SQLITE_TEST)
26743  {
26744  void *pTstAlloc = sqlite3Malloc(10);
26745  if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
26746  sqlite3_free(pTstAlloc);
26747  }
26748 #endif
26749 
26750  return SQLITE_OK;
26751 }
26752 
26753 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
26754 /****************************** End Single-Threaded *************************/
26755 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
26756 
26757 /************** End of threads.c *********************************************/
26758 /************** Begin file utf.c *********************************************/
26759 /*
26760 ** 2004 April 13
26761 **
26762 ** The author disclaims copyright to this source code. In place of
26763 ** a legal notice, here is a blessing:
26764 **
26765 ** May you do good and not evil.
26766 ** May you find forgiveness for yourself and forgive others.
26767 ** May you share freely, never taking more than you give.
26768 **
26769 *************************************************************************
26770 ** This file contains routines used to translate between UTF-8,
26771 ** UTF-16, UTF-16BE, and UTF-16LE.
26772 **
26773 ** Notes on UTF-8:
26774 **
26775 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
26776 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
26777 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
26778 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
26779 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
26780 **
26781 **
26782 ** Notes on UTF-16: (with wwww+1==uuuuu)
26783 **
26784 ** Word-0 Word-1 Value
26785 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
26786 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
26787 **
26788 **
26789 ** BOM or Byte Order Mark:
26790 ** 0xff 0xfe little-endian utf-16 follows
26791 ** 0xfe 0xff big-endian utf-16 follows
26792 **
26793 */
26794 /* #include "sqliteInt.h" */
26795 /* #include <assert.h> */
26796 /* #include "vdbeInt.h" */
26797 
26798 #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
26799 /*
26800 ** The following constant value is used by the SQLITE_BIGENDIAN and
26801 ** SQLITE_LITTLEENDIAN macros.
26802 */
26803 SQLITE_PRIVATE const int sqlite3one = 1;
26804 #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
26805 
26806 /*
26807 ** This lookup table is used to help decode the first byte of
26808 ** a multi-byte UTF8 character.
26809 */
26810 static const unsigned char sqlite3Utf8Trans1[] = {
26811  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26812  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26813  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
26814  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
26815  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26816  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26817  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26818  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
26819 };
26820 
26821 
26822 #define WRITE_UTF8(zOut, c) { \
26823  if( c<0x00080 ){ \
26824  *zOut++ = (u8)(c&0xFF); \
26825  } \
26826  else if( c<0x00800 ){ \
26827  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
26828  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26829  } \
26830  else if( c<0x10000 ){ \
26831  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
26832  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
26833  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26834  }else{ \
26835  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
26836  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
26837  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
26838  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26839  } \
26840 }
26841 
26842 #define WRITE_UTF16LE(zOut, c) { \
26843  if( c<=0xFFFF ){ \
26844  *zOut++ = (u8)(c&0x00FF); \
26845  *zOut++ = (u8)((c>>8)&0x00FF); \
26846  }else{ \
26847  *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
26848  *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
26849  *zOut++ = (u8)(c&0x00FF); \
26850  *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
26851  } \
26852 }
26853 
26854 #define WRITE_UTF16BE(zOut, c) { \
26855  if( c<=0xFFFF ){ \
26856  *zOut++ = (u8)((c>>8)&0x00FF); \
26857  *zOut++ = (u8)(c&0x00FF); \
26858  }else{ \
26859  *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
26860  *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
26861  *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
26862  *zOut++ = (u8)(c&0x00FF); \
26863  } \
26864 }
26865 
26866 #define READ_UTF16LE(zIn, TERM, c){ \
26867  c = (*zIn++); \
26868  c += ((*zIn++)<<8); \
26869  if( c>=0xD800 && c<0xE000 && TERM ){ \
26870  int c2 = (*zIn++); \
26871  c2 += ((*zIn++)<<8); \
26872  c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
26873  } \
26874 }
26875 
26876 #define READ_UTF16BE(zIn, TERM, c){ \
26877  c = ((*zIn++)<<8); \
26878  c += (*zIn++); \
26879  if( c>=0xD800 && c<0xE000 && TERM ){ \
26880  int c2 = ((*zIn++)<<8); \
26881  c2 += (*zIn++); \
26882  c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
26883  } \
26884 }
26885 
26886 /*
26887 ** Translate a single UTF-8 character. Return the unicode value.
26888 **
26889 ** During translation, assume that the byte that zTerm points
26890 ** is a 0x00.
26891 **
26892 ** Write a pointer to the next unread byte back into *pzNext.
26893 **
26894 ** Notes On Invalid UTF-8:
26895 **
26896 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
26897 ** be encoded as a multi-byte character. Any multi-byte character that
26898 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
26899 **
26900 ** * This routine never allows a UTF16 surrogate value to be encoded.
26901 ** If a multi-byte character attempts to encode a value between
26902 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
26903 **
26904 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
26905 ** byte of a character are interpreted as single-byte characters
26906 ** and rendered as themselves even though they are technically
26907 ** invalid characters.
26908 **
26909 ** * This routine accepts over-length UTF8 encodings
26910 ** for unicode values 0x80 and greater. It does not change over-length
26911 ** encodings to 0xfffd as some systems recommend.
26912 */
26913 #define READ_UTF8(zIn, zTerm, c) \
26914  c = *(zIn++); \
26915  if( c>=0xc0 ){ \
26916  c = sqlite3Utf8Trans1[c-0xc0]; \
26917  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
26918  c = (c<<6) + (0x3f & *(zIn++)); \
26919  } \
26920  if( c<0x80 \
26921  || (c&0xFFFFF800)==0xD800 \
26922  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
26923  }
26924 SQLITE_PRIVATE u32 sqlite3Utf8Read(
26925  const unsigned char **pz /* Pointer to string from which to read char */
26926 ){
26927  unsigned int c;
26928 
26929  /* Same as READ_UTF8() above but without the zTerm parameter.
26930  ** For this routine, we assume the UTF8 string is always zero-terminated.
26931  */
26932  c = *((*pz)++);
26933  if( c>=0xc0 ){
26934  c = sqlite3Utf8Trans1[c-0xc0];
26935  while( (*(*pz) & 0xc0)==0x80 ){
26936  c = (c<<6) + (0x3f & *((*pz)++));
26937  }
26938  if( c<0x80
26939  || (c&0xFFFFF800)==0xD800
26940  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
26941  }
26942  return c;
26943 }
26944 
26945 
26946 
26947 
26948 /*
26949 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
26950 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
26951 */
26952 /* #define TRANSLATE_TRACE 1 */
26953 
26954 #ifndef SQLITE_OMIT_UTF16
26955 /*
26956 ** This routine transforms the internal text encoding used by pMem to
26957 ** desiredEnc. It is an error if the string is already of the desired
26958 ** encoding, or if *pMem does not contain a string value.
26959 */
26960 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
26961  int len; /* Maximum length of output string in bytes */
26962  unsigned char *zOut; /* Output buffer */
26963  unsigned char *zIn; /* Input iterator */
26964  unsigned char *zTerm; /* End of input */
26965  unsigned char *z; /* Output iterator */
26966  unsigned int c;
26967 
26968  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
26969  assert( pMem->flags&MEM_Str );
26970  assert( pMem->enc!=desiredEnc );
26971  assert( pMem->enc!=0 );
26972  assert( pMem->n>=0 );
26973 
26974 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26975  {
26976  char zBuf[100];
26977  sqlite3VdbeMemPrettyPrint(pMem, zBuf);
26978  fprintf(stderr, "INPUT: %s\n", zBuf);
26979  }
26980 #endif
26981 
26982  /* If the translation is between UTF-16 little and big endian, then
26983  ** all that is required is to swap the byte order. This case is handled
26984  ** differently from the others.
26985  */
26986  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
26987  u8 temp;
26988  int rc;
26989  rc = sqlite3VdbeMemMakeWriteable(pMem);
26990  if( rc!=SQLITE_OK ){
26991  assert( rc==SQLITE_NOMEM );
26992  return SQLITE_NOMEM_BKPT;
26993  }
26994  zIn = (u8*)pMem->z;
26995  zTerm = &zIn[pMem->n&~1];
26996  while( zIn<zTerm ){
26997  temp = *zIn;
26998  *zIn = *(zIn+1);
26999  zIn++;
27000  *zIn++ = temp;
27001  }
27002  pMem->enc = desiredEnc;
27003  goto translate_out;
27004  }
27005 
27006  /* Set len to the maximum number of bytes required in the output buffer. */
27007  if( desiredEnc==SQLITE_UTF8 ){
27008  /* When converting from UTF-16, the maximum growth results from
27009  ** translating a 2-byte character to a 4-byte UTF-8 character.
27010  ** A single byte is required for the output string
27011  ** nul-terminator.
27012  */
27013  pMem->n &= ~1;
27014  len = pMem->n * 2 + 1;
27015  }else{
27016  /* When converting from UTF-8 to UTF-16 the maximum growth is caused
27017  ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
27018  ** character. Two bytes are required in the output buffer for the
27019  ** nul-terminator.
27020  */
27021  len = pMem->n * 2 + 2;
27022  }
27023 
27024  /* Set zIn to point at the start of the input buffer and zTerm to point 1
27025  ** byte past the end.
27026  **
27027  ** Variable zOut is set to point at the output buffer, space obtained
27028  ** from sqlite3_malloc().
27029  */
27030  zIn = (u8*)pMem->z;
27031  zTerm = &zIn[pMem->n];
27032  zOut = sqlite3DbMallocRaw(pMem->db, len);
27033  if( !zOut ){
27034  return SQLITE_NOMEM_BKPT;
27035  }
27036  z = zOut;
27037 
27038  if( pMem->enc==SQLITE_UTF8 ){
27039  if( desiredEnc==SQLITE_UTF16LE ){
27040  /* UTF-8 -> UTF-16 Little-endian */
27041  while( zIn<zTerm ){
27042  READ_UTF8(zIn, zTerm, c);
27043  WRITE_UTF16LE(z, c);
27044  }
27045  }else{
27046  assert( desiredEnc==SQLITE_UTF16BE );
27047  /* UTF-8 -> UTF-16 Big-endian */
27048  while( zIn<zTerm ){
27049  READ_UTF8(zIn, zTerm, c);
27050  WRITE_UTF16BE(z, c);
27051  }
27052  }
27053  pMem->n = (int)(z - zOut);
27054  *z++ = 0;
27055  }else{
27056  assert( desiredEnc==SQLITE_UTF8 );
27057  if( pMem->enc==SQLITE_UTF16LE ){
27058  /* UTF-16 Little-endian -> UTF-8 */
27059  while( zIn<zTerm ){
27060  READ_UTF16LE(zIn, zIn<zTerm, c);
27061  WRITE_UTF8(z, c);
27062  }
27063  }else{
27064  /* UTF-16 Big-endian -> UTF-8 */
27065  while( zIn<zTerm ){
27066  READ_UTF16BE(zIn, zIn<zTerm, c);
27067  WRITE_UTF8(z, c);
27068  }
27069  }
27070  pMem->n = (int)(z - zOut);
27071  }
27072  *z = 0;
27073  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
27074 
27075  c = pMem->flags;
27076  sqlite3VdbeMemRelease(pMem);
27077  pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
27078  pMem->enc = desiredEnc;
27079  pMem->z = (char*)zOut;
27080  pMem->zMalloc = pMem->z;
27081  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
27082 
27083 translate_out:
27084 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
27085  {
27086  char zBuf[100];
27087  sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27088  fprintf(stderr, "OUTPUT: %s\n", zBuf);
27089  }
27090 #endif
27091  return SQLITE_OK;
27092 }
27093 
27094 /*
27095 ** This routine checks for a byte-order mark at the beginning of the
27096 ** UTF-16 string stored in *pMem. If one is present, it is removed and
27097 ** the encoding of the Mem adjusted. This routine does not do any
27098 ** byte-swapping, it just sets Mem.enc appropriately.
27099 **
27100 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
27101 ** changed by this function.
27102 */
27103 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
27104  int rc = SQLITE_OK;
27105  u8 bom = 0;
27106 
27107  assert( pMem->n>=0 );
27108  if( pMem->n>1 ){
27109  u8 b1 = *(u8 *)pMem->z;
27110  u8 b2 = *(((u8 *)pMem->z) + 1);
27111  if( b1==0xFE && b2==0xFF ){
27112  bom = SQLITE_UTF16BE;
27113  }
27114  if( b1==0xFF && b2==0xFE ){
27115  bom = SQLITE_UTF16LE;
27116  }
27117  }
27118 
27119  if( bom ){
27120  rc = sqlite3VdbeMemMakeWriteable(pMem);
27121  if( rc==SQLITE_OK ){
27122  pMem->n -= 2;
27123  memmove(pMem->z, &pMem->z[2], pMem->n);
27124  pMem->z[pMem->n] = '\0';
27125  pMem->z[pMem->n+1] = '\0';
27126  pMem->flags |= MEM_Term;
27127  pMem->enc = bom;
27128  }
27129  }
27130  return rc;
27131 }
27132 #endif /* SQLITE_OMIT_UTF16 */
27133 
27134 /*
27135 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
27136 ** return the number of unicode characters in pZ up to (but not including)
27137 ** the first 0x00 byte. If nByte is not less than zero, return the
27138 ** number of unicode characters in the first nByte of pZ (or up to
27139 ** the first 0x00, whichever comes first).
27140 */
27141 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
27142  int r = 0;
27143  const u8 *z = (const u8*)zIn;
27144  const u8 *zTerm;
27145  if( nByte>=0 ){
27146  zTerm = &z[nByte];
27147  }else{
27148  zTerm = (const u8*)(-1);
27149  }
27150  assert( z<=zTerm );
27151  while( *z!=0 && z<zTerm ){
27152  SQLITE_SKIP_UTF8(z);
27153  r++;
27154  }
27155  return r;
27156 }
27157 
27158 /* This test function is not currently used by the automated test-suite.
27159 ** Hence it is only available in debug builds.
27160 */
27161 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
27162 /*
27163 ** Translate UTF-8 to UTF-8.
27164 **
27165 ** This has the effect of making sure that the string is well-formed
27166 ** UTF-8. Miscoded characters are removed.
27167 **
27168 ** The translation is done in-place and aborted if the output
27169 ** overruns the input.
27170 */
27171 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
27172  unsigned char *zOut = zIn;
27173  unsigned char *zStart = zIn;
27174  u32 c;
27175 
27176  while( zIn[0] && zOut<=zIn ){
27177  c = sqlite3Utf8Read((const u8**)&zIn);
27178  if( c!=0xfffd ){
27179  WRITE_UTF8(zOut, c);
27180  }
27181  }
27182  *zOut = 0;
27183  return (int)(zOut - zStart);
27184 }
27185 #endif
27186 
27187 #ifndef SQLITE_OMIT_UTF16
27188 /*
27189 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
27190 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
27191 ** be freed by the calling function.
27192 **
27193 ** NULL is returned if there is an allocation error.
27194 */
27195 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
27196  Mem m;
27197  memset(&m, 0, sizeof(m));
27198  m.db = db;
27199  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
27200  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
27201  if( db->mallocFailed ){
27202  sqlite3VdbeMemRelease(&m);
27203  m.z = 0;
27204  }
27205  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
27206  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
27207  assert( m.z || db->mallocFailed );
27208  return m.z;
27209 }
27210 
27211 /*
27212 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
27213 ** Return the number of bytes in the first nChar unicode characters
27214 ** in pZ. nChar must be non-negative.
27215 */
27216 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
27217  int c;
27218  unsigned char const *z = zIn;
27219  int n = 0;
27220 
27221  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
27222  while( n<nChar ){
27223  READ_UTF16BE(z, 1, c);
27224  n++;
27225  }
27226  }else{
27227  while( n<nChar ){
27228  READ_UTF16LE(z, 1, c);
27229  n++;
27230  }
27231  }
27232  return (int)(z-(unsigned char const *)zIn);
27233 }
27234 
27235 #if defined(SQLITE_TEST)
27236 /*
27237 ** This routine is called from the TCL test function "translate_selftest".
27238 ** It checks that the primitives for serializing and deserializing
27239 ** characters in each encoding are inverses of each other.
27240 */
27241 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
27242  unsigned int i, t;
27243  unsigned char zBuf[20];
27244  unsigned char *z;
27245  int n;
27246  unsigned int c;
27247 
27248  for(i=0; i<0x00110000; i++){
27249  z = zBuf;
27250  WRITE_UTF8(z, i);
27251  n = (int)(z-zBuf);
27252  assert( n>0 && n<=4 );
27253  z[0] = 0;
27254  z = zBuf;
27255  c = sqlite3Utf8Read((const u8**)&z);
27256  t = i;
27257  if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
27258  if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
27259  assert( c==t );
27260  assert( (z-zBuf)==n );
27261  }
27262  for(i=0; i<0x00110000; i++){
27263  if( i>=0xD800 && i<0xE000 ) continue;
27264  z = zBuf;
27265  WRITE_UTF16LE(z, i);
27266  n = (int)(z-zBuf);
27267  assert( n>0 && n<=4 );
27268  z[0] = 0;
27269  z = zBuf;
27270  READ_UTF16LE(z, 1, c);
27271  assert( c==i );
27272  assert( (z-zBuf)==n );
27273  }
27274  for(i=0; i<0x00110000; i++){
27275  if( i>=0xD800 && i<0xE000 ) continue;
27276  z = zBuf;
27277  WRITE_UTF16BE(z, i);
27278  n = (int)(z-zBuf);
27279  assert( n>0 && n<=4 );
27280  z[0] = 0;
27281  z = zBuf;
27282  READ_UTF16BE(z, 1, c);
27283  assert( c==i );
27284  assert( (z-zBuf)==n );
27285  }
27286 }
27287 #endif /* SQLITE_TEST */
27288 #endif /* SQLITE_OMIT_UTF16 */
27289 
27290 /************** End of utf.c *************************************************/
27291 /************** Begin file util.c ********************************************/
27292 /*
27293 ** 2001 September 15
27294 **
27295 ** The author disclaims copyright to this source code. In place of
27296 ** a legal notice, here is a blessing:
27297 **
27298 ** May you do good and not evil.
27299 ** May you find forgiveness for yourself and forgive others.
27300 ** May you share freely, never taking more than you give.
27301 **
27302 *************************************************************************
27303 ** Utility functions used throughout sqlite.
27304 **
27305 ** This file contains functions for allocating memory, comparing
27306 ** strings, and stuff like that.
27307 **
27308 */
27309 /* #include "sqliteInt.h" */
27310 /* #include <stdarg.h> */
27311 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
27312 # include <math.h>
27313 #endif
27314 
27315 /*
27316 ** Routine needed to support the testcase() macro.
27317 */
27318 #ifdef SQLITE_COVERAGE_TEST
27319 SQLITE_PRIVATE void sqlite3Coverage(int x){
27320  static unsigned dummy = 0;
27321  dummy += (unsigned)x;
27322 }
27323 #endif
27324 
27325 /*
27326 ** Give a callback to the test harness that can be used to simulate faults
27327 ** in places where it is difficult or expensive to do so purely by means
27328 ** of inputs.
27329 **
27330 ** The intent of the integer argument is to let the fault simulator know
27331 ** which of multiple sqlite3FaultSim() calls has been hit.
27332 **
27333 ** Return whatever integer value the test callback returns, or return
27334 ** SQLITE_OK if no test callback is installed.
27335 */
27336 #ifndef SQLITE_OMIT_BUILTIN_TEST
27337 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
27338  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
27339  return xCallback ? xCallback(iTest) : SQLITE_OK;
27340 }
27341 #endif
27342 
27343 #ifndef SQLITE_OMIT_FLOATING_POINT
27344 /*
27345 ** Return true if the floating point value is Not a Number (NaN).
27346 **
27347 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
27348 ** Otherwise, we have our own implementation that works on most systems.
27349 */
27350 SQLITE_PRIVATE int sqlite3IsNaN(double x){
27351  int rc; /* The value return */
27352 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
27353  /*
27354  ** Systems that support the isnan() library function should probably
27355  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
27356  ** found that many systems do not have a working isnan() function so
27357  ** this implementation is provided as an alternative.
27358  **
27359  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
27360  ** On the other hand, the use of -ffast-math comes with the following
27361  ** warning:
27362  **
27363  ** This option [-ffast-math] should never be turned on by any
27364  ** -O option since it can result in incorrect output for programs
27365  ** which depend on an exact implementation of IEEE or ISO
27366  ** rules/specifications for math functions.
27367  **
27368  ** Under MSVC, this NaN test may fail if compiled with a floating-
27369  ** point precision mode other than /fp:precise. From the MSDN
27370  ** documentation:
27371  **
27372  ** The compiler [with /fp:precise] will properly handle comparisons
27373  ** involving NaN. For example, x != x evaluates to true if x is NaN
27374  ** ...
27375  */
27376 #ifdef __FAST_MATH__
27377 # error SQLite will not work correctly with the -ffast-math option of GCC.
27378 #endif
27379  volatile double y = x;
27380  volatile double z = y;
27381  rc = (y!=z);
27382 #else /* if HAVE_ISNAN */
27383  rc = isnan(x);
27384 #endif /* HAVE_ISNAN */
27385  testcase( rc );
27386  return rc;
27387 }
27388 #endif /* SQLITE_OMIT_FLOATING_POINT */
27389 
27390 /*
27391 ** Compute a string length that is limited to what can be stored in
27392 ** lower 30 bits of a 32-bit signed integer.
27393 **
27394 ** The value returned will never be negative. Nor will it ever be greater
27395 ** than the actual length of the string. For very long strings (greater
27396 ** than 1GiB) the value returned might be less than the true string length.
27397 */
27398 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
27399  if( z==0 ) return 0;
27400  return 0x3fffffff & (int)strlen(z);
27401 }
27402 
27403 /*
27404 ** Return the declared type of a column. Or return zDflt if the column
27405 ** has no declared type.
27406 **
27407 ** The column type is an extra string stored after the zero-terminator on
27408 ** the column name if and only if the COLFLAG_HASTYPE flag is set.
27409 */
27410 SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
27411  if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
27412  return pCol->zName + strlen(pCol->zName) + 1;
27413 }
27414 
27415 /*
27416 ** Helper function for sqlite3Error() - called rarely. Broken out into
27417 ** a separate routine to avoid unnecessary register saves on entry to
27418 ** sqlite3Error().
27419 */
27420 static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
27421  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
27422  sqlite3SystemError(db, err_code);
27423 }
27424 
27425 /*
27426 ** Set the current error code to err_code and clear any prior error message.
27427 ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
27428 ** that would be appropriate.
27429 */
27430 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
27431  assert( db!=0 );
27432  db->errCode = err_code;
27433  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
27434 }
27435 
27436 /*
27437 ** Load the sqlite3.iSysErrno field if that is an appropriate thing
27438 ** to do based on the SQLite error code in rc.
27439 */
27440 SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
27441  if( rc==SQLITE_IOERR_NOMEM ) return;
27442  rc &= 0xff;
27443  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
27444  db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
27445  }
27446 }
27447 
27448 /*
27449 ** Set the most recent error code and error string for the sqlite
27450 ** handle "db". The error code is set to "err_code".
27451 **
27452 ** If it is not NULL, string zFormat specifies the format of the
27453 ** error string in the style of the printf functions: The following
27454 ** format characters are allowed:
27455 **
27456 ** %s Insert a string
27457 ** %z A string that should be freed after use
27458 ** %d Insert an integer
27459 ** %T Insert a token
27460 ** %S Insert the first element of a SrcList
27461 **
27462 ** zFormat and any string tokens that follow it are assumed to be
27463 ** encoded in UTF-8.
27464 **
27465 ** To clear the most recent error for sqlite handle "db", sqlite3Error
27466 ** should be called with err_code set to SQLITE_OK and zFormat set
27467 ** to NULL.
27468 */
27469 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
27470  assert( db!=0 );
27471  db->errCode = err_code;
27472  sqlite3SystemError(db, err_code);
27473  if( zFormat==0 ){
27474  sqlite3Error(db, err_code);
27475  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
27476  char *z;
27477  va_list ap;
27478  va_start(ap, zFormat);
27479  z = sqlite3VMPrintf(db, zFormat, ap);
27480  va_end(ap);
27481  sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
27482  }
27483 }
27484 
27485 /*
27486 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
27487 ** The following formatting characters are allowed:
27488 **
27489 ** %s Insert a string
27490 ** %z A string that should be freed after use
27491 ** %d Insert an integer
27492 ** %T Insert a token
27493 ** %S Insert the first element of a SrcList
27494 **
27495 ** This function should be used to report any error that occurs while
27496 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
27497 ** last thing the sqlite3_prepare() function does is copy the error
27498 ** stored by this function into the database handle using sqlite3Error().
27499 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
27500 ** during statement execution (sqlite3_step() etc.).
27501 */
27502 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
27503  char *zMsg;
27504  va_list ap;
27505  sqlite3 *db = pParse->db;
27506  va_start(ap, zFormat);
27507  zMsg = sqlite3VMPrintf(db, zFormat, ap);
27508  va_end(ap);
27509  if( db->suppressErr ){
27510  sqlite3DbFree(db, zMsg);
27511  }else{
27512  pParse->nErr++;
27513  sqlite3DbFree(db, pParse->zErrMsg);
27514  pParse->zErrMsg = zMsg;
27515  pParse->rc = SQLITE_ERROR;
27516  }
27517 }
27518 
27519 /*
27520 ** Convert an SQL-style quoted string into a normal string by removing
27521 ** the quote characters. The conversion is done in-place. If the
27522 ** input does not begin with a quote character, then this routine
27523 ** is a no-op.
27524 **
27525 ** The input string must be zero-terminated. A new zero-terminator
27526 ** is added to the dequoted string.
27527 **
27528 ** The return value is -1 if no dequoting occurs or the length of the
27529 ** dequoted string, exclusive of the zero terminator, if dequoting does
27530 ** occur.
27531 **
27532 ** 2002-Feb-14: This routine is extended to remove MS-Access style
27533 ** brackets from around identifiers. For example: "[a-b-c]" becomes
27534 ** "a-b-c".
27535 */
27536 SQLITE_PRIVATE void sqlite3Dequote(char *z){
27537  char quote;
27538  int i, j;
27539  if( z==0 ) return;
27540  quote = z[0];
27541  if( !sqlite3Isquote(quote) ) return;
27542  if( quote=='[' ) quote = ']';
27543  for(i=1, j=0;; i++){
27544  assert( z[i] );
27545  if( z[i]==quote ){
27546  if( z[i+1]==quote ){
27547  z[j++] = quote;
27548  i++;
27549  }else{
27550  break;
27551  }
27552  }else{
27553  z[j++] = z[i];
27554  }
27555  }
27556  z[j] = 0;
27557 }
27558 
27559 /*
27560 ** Generate a Token object from a string
27561 */
27562 SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
27563  p->z = z;
27564  p->n = sqlite3Strlen30(z);
27565 }
27566 
27567 /* Convenient short-hand */
27568 #define UpperToLower sqlite3UpperToLower
27569 
27570 /*
27571 ** Some systems have stricmp(). Others have strcasecmp(). Because
27572 ** there is no consistency, we will define our own.
27573 **
27574 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
27575 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
27576 ** the contents of two buffers containing UTF-8 strings in a
27577 ** case-independent fashion, using the same definition of "case
27578 ** independence" that SQLite uses internally when comparing identifiers.
27579 */
27580 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
27581  if( zLeft==0 ){
27582  return zRight ? -1 : 0;
27583  }else if( zRight==0 ){
27584  return 1;
27585  }
27586  return sqlite3StrICmp(zLeft, zRight);
27587 }
27588 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
27589  unsigned char *a, *b;
27590  int c;
27591  a = (unsigned char *)zLeft;
27592  b = (unsigned char *)zRight;
27593  for(;;){
27594  c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
27595  if( c || *a==0 ) break;
27596  a++;
27597  b++;
27598  }
27599  return c;
27600 }
27601 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
27602  register unsigned char *a, *b;
27603  if( zLeft==0 ){
27604  return zRight ? -1 : 0;
27605  }else if( zRight==0 ){
27606  return 1;
27607  }
27608  a = (unsigned char *)zLeft;
27609  b = (unsigned char *)zRight;
27610  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
27611  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
27612 }
27613 
27614 /*
27615 ** The string z[] is an text representation of a real number.
27616 ** Convert this string to a double and write it into *pResult.
27617 **
27618 ** The string z[] is length bytes in length (bytes, not characters) and
27619 ** uses the encoding enc. The string is not necessarily zero-terminated.
27620 **
27621 ** Return TRUE if the result is a valid real number (or integer) and FALSE
27622 ** if the string is empty or contains extraneous text. Valid numbers
27623 ** are in one of these formats:
27624 **
27625 ** [+-]digits[E[+-]digits]
27626 ** [+-]digits.[digits][E[+-]digits]
27627 ** [+-].digits[E[+-]digits]
27628 **
27629 ** Leading and trailing whitespace is ignored for the purpose of determining
27630 ** validity.
27631 **
27632 ** If some prefix of the input string is a valid number, this routine
27633 ** returns FALSE but it still converts the prefix and writes the result
27634 ** into *pResult.
27635 */
27636 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
27637 #ifndef SQLITE_OMIT_FLOATING_POINT
27638  int incr;
27639  const char *zEnd = z + length;
27640  /* sign * significand * (10 ^ (esign * exponent)) */
27641  int sign = 1; /* sign of significand */
27642  i64 s = 0; /* significand */
27643  int d = 0; /* adjust exponent for shifting decimal point */
27644  int esign = 1; /* sign of exponent */
27645  int e = 0; /* exponent */
27646  int eValid = 1; /* True exponent is either not used or is well-formed */
27647  double result;
27648  int nDigits = 0;
27649  int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27650 
27651  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27652  *pResult = 0.0; /* Default return value, in case of an error */
27653 
27654  if( enc==SQLITE_UTF8 ){
27655  incr = 1;
27656  }else{
27657  int i;
27658  incr = 2;
27659  assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27660  for(i=3-enc; i<length && z[i]==0; i+=2){}
27661  nonNum = i<length;
27662  zEnd = &z[i^1];
27663  z += (enc&1);
27664  }
27665 
27666  /* skip leading spaces */
27667  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27668  if( z>=zEnd ) return 0;
27669 
27670  /* get sign of significand */
27671  if( *z=='-' ){
27672  sign = -1;
27673  z+=incr;
27674  }else if( *z=='+' ){
27675  z+=incr;
27676  }
27677 
27678  /* copy max significant digits to significand */
27679  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
27680  s = s*10 + (*z - '0');
27681  z+=incr, nDigits++;
27682  }
27683 
27684  /* skip non-significant significand digits
27685  ** (increase exponent by d to shift decimal left) */
27686  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
27687  if( z>=zEnd ) goto do_atof_calc;
27688 
27689  /* if decimal point is present */
27690  if( *z=='.' ){
27691  z+=incr;
27692  /* copy digits from after decimal to significand
27693  ** (decrease exponent by d to shift decimal right) */
27694  while( z<zEnd && sqlite3Isdigit(*z) ){
27695  if( s<((LARGEST_INT64-9)/10) ){
27696  s = s*10 + (*z - '0');
27697  d--;
27698  }
27699  z+=incr, nDigits++;
27700  }
27701  }
27702  if( z>=zEnd ) goto do_atof_calc;
27703 
27704  /* if exponent is present */
27705  if( *z=='e' || *z=='E' ){
27706  z+=incr;
27707  eValid = 0;
27708 
27709  /* This branch is needed to avoid a (harmless) buffer overread. The
27710  ** special comment alerts the mutation tester that the correct answer
27711  ** is obtained even if the branch is omitted */
27712  if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
27713 
27714  /* get sign of exponent */
27715  if( *z=='-' ){
27716  esign = -1;
27717  z+=incr;
27718  }else if( *z=='+' ){
27719  z+=incr;
27720  }
27721  /* copy digits to exponent */
27722  while( z<zEnd && sqlite3Isdigit(*z) ){
27723  e = e<10000 ? (e*10 + (*z - '0')) : 10000;
27724  z+=incr;
27725  eValid = 1;
27726  }
27727  }
27728 
27729  /* skip trailing spaces */
27730  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27731 
27732 do_atof_calc:
27733  /* adjust exponent by d, and update sign */
27734  e = (e*esign) + d;
27735  if( e<0 ) {
27736  esign = -1;
27737  e *= -1;
27738  } else {
27739  esign = 1;
27740  }
27741 
27742  if( s==0 ) {
27743  /* In the IEEE 754 standard, zero is signed. */
27744  result = sign<0 ? -(double)0 : (double)0;
27745  } else {
27746  /* Attempt to reduce exponent.
27747  **
27748  ** Branches that are not required for the correct answer but which only
27749  ** help to obtain the correct answer faster are marked with special
27750  ** comments, as a hint to the mutation tester.
27751  */
27752  while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
27753  if( esign>0 ){
27754  if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
27755  s *= 10;
27756  }else{
27757  if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
27758  s /= 10;
27759  }
27760  e--;
27761  }
27762 
27763  /* adjust the sign of significand */
27764  s = sign<0 ? -s : s;
27765 
27766  if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
27767  result = (double)s;
27768  }else{
27769  LONGDOUBLE_TYPE scale = 1.0;
27770  /* attempt to handle extremely small/large numbers better */
27771  if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
27772  if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
27773  while( e%308 ) { scale *= 1.0e+1; e -= 1; }
27774  if( esign<0 ){
27775  result = s / scale;
27776  result /= 1.0e+308;
27777  }else{
27778  result = s * scale;
27779  result *= 1.0e+308;
27780  }
27781  }else{ assert( e>=342 );
27782  if( esign<0 ){
27783  result = 0.0*s;
27784  }else{
27785  result = 1e308*1e308*s; /* Infinity */
27786  }
27787  }
27788  }else{
27789  /* 1.0e+22 is the largest power of 10 than can be
27790  ** represented exactly. */
27791  while( e%22 ) { scale *= 1.0e+1; e -= 1; }
27792  while( e>0 ) { scale *= 1.0e+22; e -= 22; }
27793  if( esign<0 ){
27794  result = s / scale;
27795  }else{
27796  result = s * scale;
27797  }
27798  }
27799  }
27800  }
27801 
27802  /* store the result */
27803  *pResult = result;
27804 
27805  /* return true if number and no extra non-whitespace chracters after */
27806  return z==zEnd && nDigits>0 && eValid && nonNum==0;
27807 #else
27808  return !sqlite3Atoi64(z, pResult, length, enc);
27809 #endif /* SQLITE_OMIT_FLOATING_POINT */
27810 }
27811 
27812 /*
27813 ** Compare the 19-character string zNum against the text representation
27814 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
27815 ** if zNum is less than, equal to, or greater than the string.
27816 ** Note that zNum must contain exactly 19 characters.
27817 **
27818 ** Unlike memcmp() this routine is guaranteed to return the difference
27819 ** in the values of the last digit if the only difference is in the
27820 ** last digit. So, for example,
27821 **
27822 ** compare2pow63("9223372036854775800", 1)
27823 **
27824 ** will return -8.
27825 */
27826 static int compare2pow63(const char *zNum, int incr){
27827  int c = 0;
27828  int i;
27829  /* 012345678901234567 */
27830  const char *pow63 = "922337203685477580";
27831  for(i=0; c==0 && i<18; i++){
27832  c = (zNum[i*incr]-pow63[i])*10;
27833  }
27834  if( c==0 ){
27835  c = zNum[18*incr] - '8';
27836  testcase( c==(-1) );
27837  testcase( c==0 );
27838  testcase( c==(+1) );
27839  }
27840  return c;
27841 }
27842 
27843 /*
27844 ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
27845 ** routine does *not* accept hexadecimal notation.
27846 **
27847 ** If the zNum value is representable as a 64-bit twos-complement
27848 ** integer, then write that value into *pNum and return 0.
27849 **
27850 ** If zNum is exactly 9223372036854775808, return 2. This special
27851 ** case is broken out because while 9223372036854775808 cannot be a
27852 ** signed 64-bit integer, its negative -9223372036854775808 can be.
27853 **
27854 ** If zNum is too big for a 64-bit integer and is not
27855 ** 9223372036854775808 or if zNum contains any non-numeric text,
27856 ** then return 1.
27857 **
27858 ** length is the number of bytes in the string (bytes, not characters).
27859 ** The string is not necessarily zero-terminated. The encoding is
27860 ** given by enc.
27861 */
27862 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
27863  int incr;
27864  u64 u = 0;
27865  int neg = 0; /* assume positive */
27866  int i;
27867  int c = 0;
27868  int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27869  const char *zStart;
27870  const char *zEnd = zNum + length;
27871  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27872  if( enc==SQLITE_UTF8 ){
27873  incr = 1;
27874  }else{
27875  incr = 2;
27876  assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27877  for(i=3-enc; i<length && zNum[i]==0; i+=2){}
27878  nonNum = i<length;
27879  zEnd = &zNum[i^1];
27880  zNum += (enc&1);
27881  }
27882  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
27883  if( zNum<zEnd ){
27884  if( *zNum=='-' ){
27885  neg = 1;
27886  zNum+=incr;
27887  }else if( *zNum=='+' ){
27888  zNum+=incr;
27889  }
27890  }
27891  zStart = zNum;
27892  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
27893  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
27894  u = u*10 + c - '0';
27895  }
27896  if( u>LARGEST_INT64 ){
27897  *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
27898  }else if( neg ){
27899  *pNum = -(i64)u;
27900  }else{
27901  *pNum = (i64)u;
27902  }
27903  testcase( i==18 );
27904  testcase( i==19 );
27905  testcase( i==20 );
27906  if( &zNum[i]<zEnd /* Extra bytes at the end */
27907  || (i==0 && zStart==zNum) /* No digits */
27908  || i>19*incr /* Too many digits */
27909  || nonNum /* UTF16 with high-order bytes non-zero */
27910  ){
27911  /* zNum is empty or contains non-numeric text or is longer
27912  ** than 19 digits (thus guaranteeing that it is too large) */
27913  return 1;
27914  }else if( i<19*incr ){
27915  /* Less than 19 digits, so we know that it fits in 64 bits */
27916  assert( u<=LARGEST_INT64 );
27917  return 0;
27918  }else{
27919  /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
27920  c = compare2pow63(zNum, incr);
27921  if( c<0 ){
27922  /* zNum is less than 9223372036854775808 so it fits */
27923  assert( u<=LARGEST_INT64 );
27924  return 0;
27925  }else if( c>0 ){
27926  /* zNum is greater than 9223372036854775808 so it overflows */
27927  return 1;
27928  }else{
27929  /* zNum is exactly 9223372036854775808. Fits if negative. The
27930  ** special case 2 overflow if positive */
27931  assert( u-1==LARGEST_INT64 );
27932  return neg ? 0 : 2;
27933  }
27934  }
27935 }
27936 
27937 /*
27938 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
27939 ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
27940 ** whereas sqlite3Atoi64() does not.
27941 **
27942 ** Returns:
27943 **
27944 ** 0 Successful transformation. Fits in a 64-bit signed integer.
27945 ** 1 Integer too large for a 64-bit signed integer or is malformed
27946 ** 2 Special case of 9223372036854775808
27947 */
27948 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
27949 #ifndef SQLITE_OMIT_HEX_INTEGER
27950  if( z[0]=='0'
27951  && (z[1]=='x' || z[1]=='X')
27952  ){
27953  u64 u = 0;
27954  int i, k;
27955  for(i=2; z[i]=='0'; i++){}
27956  for(k=i; sqlite3Isxdigit(z[k]); k++){
27957  u = u*16 + sqlite3HexToInt(z[k]);
27958  }
27959  memcpy(pOut, &u, 8);
27960  return (z[k]==0 && k-i<=16) ? 0 : 1;
27961  }else
27962 #endif /* SQLITE_OMIT_HEX_INTEGER */
27963  {
27964  return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
27965  }
27966 }
27967 
27968 /*
27969 ** If zNum represents an integer that will fit in 32-bits, then set
27970 ** *pValue to that integer and return true. Otherwise return false.
27971 **
27972 ** This routine accepts both decimal and hexadecimal notation for integers.
27973 **
27974 ** Any non-numeric characters that following zNum are ignored.
27975 ** This is different from sqlite3Atoi64() which requires the
27976 ** input number to be zero-terminated.
27977 */
27978 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
27979  sqlite_int64 v = 0;
27980  int i, c;
27981  int neg = 0;
27982  if( zNum[0]=='-' ){
27983  neg = 1;
27984  zNum++;
27985  }else if( zNum[0]=='+' ){
27986  zNum++;
27987  }
27988 #ifndef SQLITE_OMIT_HEX_INTEGER
27989  else if( zNum[0]=='0'
27990  && (zNum[1]=='x' || zNum[1]=='X')
27991  && sqlite3Isxdigit(zNum[2])
27992  ){
27993  u32 u = 0;
27994  zNum += 2;
27995  while( zNum[0]=='0' ) zNum++;
27996  for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
27997  u = u*16 + sqlite3HexToInt(zNum[i]);
27998  }
27999  if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
28000  memcpy(pValue, &u, 4);
28001  return 1;
28002  }else{
28003  return 0;
28004  }
28005  }
28006 #endif
28007  while( zNum[0]=='0' ) zNum++;
28008  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
28009  v = v*10 + c;
28010  }
28011 
28012  /* The longest decimal representation of a 32 bit integer is 10 digits:
28013  **
28014  ** 1234567890
28015  ** 2^31 -> 2147483648
28016  */
28017  testcase( i==10 );
28018  if( i>10 ){
28019  return 0;
28020  }
28021  testcase( v-neg==2147483647 );
28022  if( v-neg>2147483647 ){
28023  return 0;
28024  }
28025  if( neg ){
28026  v = -v;
28027  }
28028  *pValue = (int)v;
28029  return 1;
28030 }
28031 
28032 /*
28033 ** Return a 32-bit integer value extracted from a string. If the
28034 ** string is not an integer, just return 0.
28035 */
28036 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
28037  int x = 0;
28038  if( z ) sqlite3GetInt32(z, &x);
28039  return x;
28040 }
28041 
28042 /*
28043 ** The variable-length integer encoding is as follows:
28044 **
28045 ** KEY:
28046 ** A = 0xxxxxxx 7 bits of data and one flag bit
28047 ** B = 1xxxxxxx 7 bits of data and one flag bit
28048 ** C = xxxxxxxx 8 bits of data
28049 **
28050 ** 7 bits - A
28051 ** 14 bits - BA
28052 ** 21 bits - BBA
28053 ** 28 bits - BBBA
28054 ** 35 bits - BBBBA
28055 ** 42 bits - BBBBBA
28056 ** 49 bits - BBBBBBA
28057 ** 56 bits - BBBBBBBA
28058 ** 64 bits - BBBBBBBBC
28059 */
28060 
28061 /*
28062 ** Write a 64-bit variable-length integer to memory starting at p[0].
28063 ** The length of data write will be between 1 and 9 bytes. The number
28064 ** of bytes written is returned.
28065 **
28066 ** A variable-length integer consists of the lower 7 bits of each byte
28067 ** for all bytes that have the 8th bit set and one byte with the 8th
28068 ** bit clear. Except, if we get to the 9th byte, it stores the full
28069 ** 8 bits and is the last byte.
28070 */
28071 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
28072  int i, j, n;
28073  u8 buf[10];
28074  if( v & (((u64)0xff000000)<<32) ){
28075  p[8] = (u8)v;
28076  v >>= 8;
28077  for(i=7; i>=0; i--){
28078  p[i] = (u8)((v & 0x7f) | 0x80);
28079  v >>= 7;
28080  }
28081  return 9;
28082  }
28083  n = 0;
28084  do{
28085  buf[n++] = (u8)((v & 0x7f) | 0x80);
28086  v >>= 7;
28087  }while( v!=0 );
28088  buf[0] &= 0x7f;
28089  assert( n<=9 );
28090  for(i=0, j=n-1; j>=0; j--, i++){
28091  p[i] = buf[j];
28092  }
28093  return n;
28094 }
28095 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
28096  if( v<=0x7f ){
28097  p[0] = v&0x7f;
28098  return 1;
28099  }
28100  if( v<=0x3fff ){
28101  p[0] = ((v>>7)&0x7f)|0x80;
28102  p[1] = v&0x7f;
28103  return 2;
28104  }
28105  return putVarint64(p,v);
28106 }
28107 
28108 /*
28109 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
28110 ** are defined here rather than simply putting the constant expressions
28111 ** inline in order to work around bugs in the RVT compiler.
28112 **
28113 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
28114 **
28115 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
28116 */
28117 #define SLOT_2_0 0x001fc07f
28118 #define SLOT_4_2_0 0xf01fc07f
28119 
28120 
28121 /*
28122 ** Read a 64-bit variable-length integer from memory starting at p[0].
28123 ** Return the number of bytes read. The value is stored in *v.
28124 */
28125 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
28126  u32 a,b,s;
28127 
28128  a = *p;
28129  /* a: p0 (unmasked) */
28130  if (!(a&0x80))
28131  {
28132  *v = a;
28133  return 1;
28134  }
28135 
28136  p++;
28137  b = *p;
28138  /* b: p1 (unmasked) */
28139  if (!(b&0x80))
28140  {
28141  a &= 0x7f;
28142  a = a<<7;
28143  a |= b;
28144  *v = a;
28145  return 2;
28146  }
28147 
28148  /* Verify that constants are precomputed correctly */
28149  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
28150  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
28151 
28152  p++;
28153  a = a<<14;
28154  a |= *p;
28155  /* a: p0<<14 | p2 (unmasked) */
28156  if (!(a&0x80))
28157  {
28158  a &= SLOT_2_0;
28159  b &= 0x7f;
28160  b = b<<7;
28161  a |= b;
28162  *v = a;
28163  return 3;
28164  }
28165 
28166  /* CSE1 from below */
28167  a &= SLOT_2_0;
28168  p++;
28169  b = b<<14;
28170  b |= *p;
28171  /* b: p1<<14 | p3 (unmasked) */
28172  if (!(b&0x80))
28173  {
28174  b &= SLOT_2_0;
28175  /* moved CSE1 up */
28176  /* a &= (0x7f<<14)|(0x7f); */
28177  a = a<<7;
28178  a |= b;
28179  *v = a;
28180  return 4;
28181  }
28182 
28183  /* a: p0<<14 | p2 (masked) */
28184  /* b: p1<<14 | p3 (unmasked) */
28185  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28186  /* moved CSE1 up */
28187  /* a &= (0x7f<<14)|(0x7f); */
28188  b &= SLOT_2_0;
28189  s = a;
28190  /* s: p0<<14 | p2 (masked) */
28191 
28192  p++;
28193  a = a<<14;
28194  a |= *p;
28195  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28196  if (!(a&0x80))
28197  {
28198  /* we can skip these cause they were (effectively) done above
28199  ** while calculating s */
28200  /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28201  /* b &= (0x7f<<14)|(0x7f); */
28202  b = b<<7;
28203  a |= b;
28204  s = s>>18;
28205  *v = ((u64)s)<<32 | a;
28206  return 5;
28207  }
28208 
28209  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28210  s = s<<7;
28211  s |= b;
28212  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28213 
28214  p++;
28215  b = b<<14;
28216  b |= *p;
28217  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
28218  if (!(b&0x80))
28219  {
28220  /* we can skip this cause it was (effectively) done above in calc'ing s */
28221  /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28222  a &= SLOT_2_0;
28223  a = a<<7;
28224  a |= b;
28225  s = s>>18;
28226  *v = ((u64)s)<<32 | a;
28227  return 6;
28228  }
28229 
28230  p++;
28231  a = a<<14;
28232  a |= *p;
28233  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
28234  if (!(a&0x80))
28235  {
28236  a &= SLOT_4_2_0;
28237  b &= SLOT_2_0;
28238  b = b<<7;
28239  a |= b;
28240  s = s>>11;
28241  *v = ((u64)s)<<32 | a;
28242  return 7;
28243  }
28244 
28245  /* CSE2 from below */
28246  a &= SLOT_2_0;
28247  p++;
28248  b = b<<14;
28249  b |= *p;
28250  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
28251  if (!(b&0x80))
28252  {
28253  b &= SLOT_4_2_0;
28254  /* moved CSE2 up */
28255  /* a &= (0x7f<<14)|(0x7f); */
28256  a = a<<7;
28257  a |= b;
28258  s = s>>4;
28259  *v = ((u64)s)<<32 | a;
28260  return 8;
28261  }
28262 
28263  p++;
28264  a = a<<15;
28265  a |= *p;
28266  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
28267 
28268  /* moved CSE2 up */
28269  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
28270  b &= SLOT_2_0;
28271  b = b<<8;
28272  a |= b;
28273 
28274  s = s<<4;
28275  b = p[-4];
28276  b &= 0x7f;
28277  b = b>>3;
28278  s |= b;
28279 
28280  *v = ((u64)s)<<32 | a;
28281 
28282  return 9;
28283 }
28284 
28285 /*
28286 ** Read a 32-bit variable-length integer from memory starting at p[0].
28287 ** Return the number of bytes read. The value is stored in *v.
28288 **
28289 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
28290 ** integer, then set *v to 0xffffffff.
28291 **
28292 ** A MACRO version, getVarint32, is provided which inlines the
28293 ** single-byte case. All code should use the MACRO version as
28294 ** this function assumes the single-byte case has already been handled.
28295 */
28296 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
28297  u32 a,b;
28298 
28299  /* The 1-byte case. Overwhelmingly the most common. Handled inline
28300  ** by the getVarin32() macro */
28301  a = *p;
28302  /* a: p0 (unmasked) */
28303 #ifndef getVarint32
28304  if (!(a&0x80))
28305  {
28306  /* Values between 0 and 127 */
28307  *v = a;
28308  return 1;
28309  }
28310 #endif
28311 
28312  /* The 2-byte case */
28313  p++;
28314  b = *p;
28315  /* b: p1 (unmasked) */
28316  if (!(b&0x80))
28317  {
28318  /* Values between 128 and 16383 */
28319  a &= 0x7f;
28320  a = a<<7;
28321  *v = a | b;
28322  return 2;
28323  }
28324 
28325  /* The 3-byte case */
28326  p++;
28327  a = a<<14;
28328  a |= *p;
28329  /* a: p0<<14 | p2 (unmasked) */
28330  if (!(a&0x80))
28331  {
28332  /* Values between 16384 and 2097151 */
28333  a &= (0x7f<<14)|(0x7f);
28334  b &= 0x7f;
28335  b = b<<7;
28336  *v = a | b;
28337  return 3;
28338  }
28339 
28340  /* A 32-bit varint is used to store size information in btrees.
28341  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
28342  ** A 3-byte varint is sufficient, for example, to record the size
28343  ** of a 1048569-byte BLOB or string.
28344  **
28345  ** We only unroll the first 1-, 2-, and 3- byte cases. The very
28346  ** rare larger cases can be handled by the slower 64-bit varint
28347  ** routine.
28348  */
28349 #if 1
28350  {
28351  u64 v64;
28352  u8 n;
28353 
28354  p -= 2;
28355  n = sqlite3GetVarint(p, &v64);
28356  assert( n>3 && n<=9 );
28357  if( (v64 & SQLITE_MAX_U32)!=v64 ){
28358  *v = 0xffffffff;
28359  }else{
28360  *v = (u32)v64;
28361  }
28362  return n;
28363  }
28364 
28365 #else
28366  /* For following code (kept for historical record only) shows an
28367  ** unrolling for the 3- and 4-byte varint cases. This code is
28368  ** slightly faster, but it is also larger and much harder to test.
28369  */
28370  p++;
28371  b = b<<14;
28372  b |= *p;
28373  /* b: p1<<14 | p3 (unmasked) */
28374  if (!(b&0x80))
28375  {
28376  /* Values between 2097152 and 268435455 */
28377  b &= (0x7f<<14)|(0x7f);
28378  a &= (0x7f<<14)|(0x7f);
28379  a = a<<7;
28380  *v = a | b;
28381  return 4;
28382  }
28383 
28384  p++;
28385  a = a<<14;
28386  a |= *p;
28387  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28388  if (!(a&0x80))
28389  {
28390  /* Values between 268435456 and 34359738367 */
28391  a &= SLOT_4_2_0;
28392  b &= SLOT_4_2_0;
28393  b = b<<7;
28394  *v = a | b;
28395  return 5;
28396  }
28397 
28398  /* We can only reach this point when reading a corrupt database
28399  ** file. In that case we are not in any hurry. Use the (relatively
28400  ** slow) general-purpose sqlite3GetVarint() routine to extract the
28401  ** value. */
28402  {
28403  u64 v64;
28404  u8 n;
28405 
28406  p -= 4;
28407  n = sqlite3GetVarint(p, &v64);
28408  assert( n>5 && n<=9 );
28409  *v = (u32)v64;
28410  return n;
28411  }
28412 #endif
28413 }
28414 
28415 /*
28416 ** Return the number of bytes that will be needed to store the given
28417 ** 64-bit integer.
28418 */
28419 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
28420  int i;
28421  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
28422  return i;
28423 }
28424 
28425 
28426 /*
28427 ** Read or write a four-byte big-endian integer value.
28428 */
28429 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
28430 #if SQLITE_BYTEORDER==4321
28431  u32 x;
28432  memcpy(&x,p,4);
28433  return x;
28434 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28435  && defined(__GNUC__) && GCC_VERSION>=4003000
28436  u32 x;
28437  memcpy(&x,p,4);
28438  return __builtin_bswap32(x);
28439 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28440  && defined(_MSC_VER) && _MSC_VER>=1300
28441  u32 x;
28442  memcpy(&x,p,4);
28443  return _byteswap_ulong(x);
28444 #else
28445  testcase( p[0]&0x80 );
28446  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
28447 #endif
28448 }
28449 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
28450 #if SQLITE_BYTEORDER==4321
28451  memcpy(p,&v,4);
28452 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28453  && defined(__GNUC__) && GCC_VERSION>=4003000
28454  u32 x = __builtin_bswap32(v);
28455  memcpy(p,&x,4);
28456 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28457  && defined(_MSC_VER) && _MSC_VER>=1300
28458  u32 x = _byteswap_ulong(v);
28459  memcpy(p,&x,4);
28460 #else
28461  p[0] = (u8)(v>>24);
28462  p[1] = (u8)(v>>16);
28463  p[2] = (u8)(v>>8);
28464  p[3] = (u8)v;
28465 #endif
28466 }
28467 
28468 
28469 
28470 /*
28471 ** Translate a single byte of Hex into an integer.
28472 ** This routine only works if h really is a valid hexadecimal
28473 ** character: 0..9a..fA..F
28474 */
28475 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
28476  assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
28477 #ifdef SQLITE_ASCII
28478  h += 9*(1&(h>>6));
28479 #endif
28480 #ifdef SQLITE_EBCDIC
28481  h += 9*(1&~(h>>4));
28482 #endif
28483  return (u8)(h & 0xf);
28484 }
28485 
28486 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
28487 /*
28488 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
28489 ** value. Return a pointer to its binary value. Space to hold the
28490 ** binary value has been obtained from malloc and must be freed by
28491 ** the calling routine.
28492 */
28493 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
28494  char *zBlob;
28495  int i;
28496 
28497  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
28498  n--;
28499  if( zBlob ){
28500  for(i=0; i<n; i+=2){
28501  zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
28502  }
28503  zBlob[i/2] = 0;
28504  }
28505  return zBlob;
28506 }
28507 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
28508 
28509 /*
28510 ** Log an error that is an API call on a connection pointer that should
28511 ** not have been used. The "type" of connection pointer is given as the
28512 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
28513 */
28514 static void logBadConnection(const char *zType){
28515  sqlite3_log(SQLITE_MISUSE,
28516  "API call with %s database connection pointer",
28517  zType
28518  );
28519 }
28520 
28521 /*
28522 ** Check to make sure we have a valid db pointer. This test is not
28523 ** foolproof but it does provide some measure of protection against
28524 ** misuse of the interface such as passing in db pointers that are
28525 ** NULL or which have been previously closed. If this routine returns
28526 ** 1 it means that the db pointer is valid and 0 if it should not be
28527 ** dereferenced for any reason. The calling function should invoke
28528 ** SQLITE_MISUSE immediately.
28529 **
28530 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
28531 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
28532 ** open properly and is not fit for general use but which can be
28533 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
28534 */
28535 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
28536  u32 magic;
28537  if( db==0 ){
28538  logBadConnection("NULL");
28539  return 0;
28540  }
28541  magic = db->magic;
28542  if( magic!=SQLITE_MAGIC_OPEN ){
28543  if( sqlite3SafetyCheckSickOrOk(db) ){
28544  testcase( sqlite3GlobalConfig.xLog!=0 );
28545  logBadConnection("unopened");
28546  }
28547  return 0;
28548  }else{
28549  return 1;
28550  }
28551 }
28552 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
28553  u32 magic;
28554  magic = db->magic;
28555  if( magic!=SQLITE_MAGIC_SICK &&
28556  magic!=SQLITE_MAGIC_OPEN &&
28557  magic!=SQLITE_MAGIC_BUSY ){
28558  testcase( sqlite3GlobalConfig.xLog!=0 );
28559  logBadConnection("invalid");
28560  return 0;
28561  }else{
28562  return 1;
28563  }
28564 }
28565 
28566 /*
28567 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
28568 ** the other 64-bit signed integer at *pA and store the result in *pA.
28569 ** Return 0 on success. Or if the operation would have resulted in an
28570 ** overflow, leave *pA unchanged and return 1.
28571 */
28572 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
28573  i64 iA = *pA;
28574  testcase( iA==0 ); testcase( iA==1 );
28575  testcase( iB==-1 ); testcase( iB==0 );
28576  if( iB>=0 ){
28577  testcase( iA>0 && LARGEST_INT64 - iA == iB );
28578  testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
28579  if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
28580  }else{
28581  testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
28582  testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
28583  if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
28584  }
28585  *pA += iB;
28586  return 0;
28587 }
28588 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
28589  testcase( iB==SMALLEST_INT64+1 );
28590  if( iB==SMALLEST_INT64 ){
28591  testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
28592  if( (*pA)>=0 ) return 1;
28593  *pA -= iB;
28594  return 0;
28595  }else{
28596  return sqlite3AddInt64(pA, -iB);
28597  }
28598 }
28599 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
28600  i64 iA = *pA;
28601  if( iB>0 ){
28602  if( iA>LARGEST_INT64/iB ) return 1;
28603  if( iA<SMALLEST_INT64/iB ) return 1;
28604  }else if( iB<0 ){
28605  if( iA>0 ){
28606  if( iB<SMALLEST_INT64/iA ) return 1;
28607  }else if( iA<0 ){
28608  if( iB==SMALLEST_INT64 ) return 1;
28609  if( iA==SMALLEST_INT64 ) return 1;
28610  if( -iA>LARGEST_INT64/-iB ) return 1;
28611  }
28612  }
28613  *pA = iA*iB;
28614  return 0;
28615 }
28616 
28617 /*
28618 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
28619 ** if the integer has a value of -2147483648, return +2147483647
28620 */
28621 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
28622  if( x>=0 ) return x;
28623  if( x==(int)0x80000000 ) return 0x7fffffff;
28624  return -x;
28625 }
28626 
28627 #ifdef SQLITE_ENABLE_8_3_NAMES
28628 /*
28629 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
28630 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
28631 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
28632 ** three characters, then shorten the suffix on z[] to be the last three
28633 ** characters of the original suffix.
28634 **
28635 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
28636 ** do the suffix shortening regardless of URI parameter.
28637 **
28638 ** Examples:
28639 **
28640 ** test.db-journal => test.nal
28641 ** test.db-wal => test.wal
28642 ** test.db-shm => test.shm
28643 ** test.db-mj7f3319fa => test.9fa
28644 */
28645 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
28646 #if SQLITE_ENABLE_8_3_NAMES<2
28647  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
28648 #endif
28649  {
28650  int i, sz;
28651  sz = sqlite3Strlen30(z);
28652  for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
28653  if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
28654  }
28655 }
28656 #endif
28657 
28658 /*
28659 ** Find (an approximate) sum of two LogEst values. This computation is
28660 ** not a simple "+" operator because LogEst is stored as a logarithmic
28661 ** value.
28662 **
28663 */
28664 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
28665  static const unsigned char x[] = {
28666  10, 10, /* 0,1 */
28667  9, 9, /* 2,3 */
28668  8, 8, /* 4,5 */
28669  7, 7, 7, /* 6,7,8 */
28670  6, 6, 6, /* 9,10,11 */
28671  5, 5, 5, /* 12-14 */
28672  4, 4, 4, 4, /* 15-18 */
28673  3, 3, 3, 3, 3, 3, /* 19-24 */
28674  2, 2, 2, 2, 2, 2, 2, /* 25-31 */
28675  };
28676  if( a>=b ){
28677  if( a>b+49 ) return a;
28678  if( a>b+31 ) return a+1;
28679  return a+x[a-b];
28680  }else{
28681  if( b>a+49 ) return b;
28682  if( b>a+31 ) return b+1;
28683  return b+x[b-a];
28684  }
28685 }
28686 
28687 /*
28688 ** Convert an integer into a LogEst. In other words, compute an
28689 ** approximation for 10*log2(x).
28690 */
28691 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
28692  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
28693  LogEst y = 40;
28694  if( x<8 ){
28695  if( x<2 ) return 0;
28696  while( x<8 ){ y -= 10; x <<= 1; }
28697  }else{
28698  while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
28699  while( x>15 ){ y += 10; x >>= 1; }
28700  }
28701  return a[x&7] + y - 10;
28702 }
28703 
28704 #ifndef SQLITE_OMIT_VIRTUALTABLE
28705 /*
28706 ** Convert a double into a LogEst
28707 ** In other words, compute an approximation for 10*log2(x).
28708 */
28709 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
28710  u64 a;
28711  LogEst e;
28712  assert( sizeof(x)==8 && sizeof(a)==8 );
28713  if( x<=1 ) return 0;
28714  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
28715  memcpy(&a, &x, 8);
28716  e = (a>>52) - 1022;
28717  return e*10;
28718 }
28719 #endif /* SQLITE_OMIT_VIRTUALTABLE */
28720 
28721 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28722  defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
28723  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28724 /*
28725 ** Convert a LogEst into an integer.
28726 **
28727 ** Note that this routine is only used when one or more of various
28728 ** non-standard compile-time options is enabled.
28729 */
28730 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
28731  u64 n;
28732  n = x%10;
28733  x /= 10;
28734  if( n>=5 ) n -= 2;
28735  else if( n>=1 ) n -= 1;
28736 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28737  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28738  if( x>60 ) return (u64)LARGEST_INT64;
28739 #else
28740  /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
28741  ** possible to this routine is 310, resulting in a maximum x of 31 */
28742  assert( x<=60 );
28743 #endif
28744  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
28745 }
28746 #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
28747 
28748 /************** End of util.c ************************************************/
28749 /************** Begin file hash.c ********************************************/
28750 /*
28751 ** 2001 September 22
28752 **
28753 ** The author disclaims copyright to this source code. In place of
28754 ** a legal notice, here is a blessing:
28755 **
28756 ** May you do good and not evil.
28757 ** May you find forgiveness for yourself and forgive others.
28758 ** May you share freely, never taking more than you give.
28759 **
28760 *************************************************************************
28761 ** This is the implementation of generic hash-tables
28762 ** used in SQLite.
28763 */
28764 /* #include "sqliteInt.h" */
28765 /* #include <assert.h> */
28766 
28767 /* Turn bulk memory into a hash table object by initializing the
28768 ** fields of the Hash structure.
28769 **
28770 ** "pNew" is a pointer to the hash table that is to be initialized.
28771 */
28772 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
28773  assert( pNew!=0 );
28774  pNew->first = 0;
28775  pNew->count = 0;
28776  pNew->htsize = 0;
28777  pNew->ht = 0;
28778 }
28779 
28780 /* Remove all entries from a hash table. Reclaim all memory.
28781 ** Call this routine to delete a hash table or to reset a hash table
28782 ** to the empty state.
28783 */
28784 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
28785  HashElem *elem; /* For looping over all elements of the table */
28786 
28787  assert( pH!=0 );
28788  elem = pH->first;
28789  pH->first = 0;
28790  sqlite3_free(pH->ht);
28791  pH->ht = 0;
28792  pH->htsize = 0;
28793  while( elem ){
28794  HashElem *next_elem = elem->next;
28795  sqlite3_free(elem);
28796  elem = next_elem;
28797  }
28798  pH->count = 0;
28799 }
28800 
28801 /*
28802 ** The hashing function.
28803 */
28804 static unsigned int strHash(const char *z){
28805  unsigned int h = 0;
28806  unsigned char c;
28807  while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
28808  /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
28809  ** 0x9e3779b1 is 2654435761 which is the closest prime number to
28810  ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
28811  h += sqlite3UpperToLower[c];
28812  h *= 0x9e3779b1;
28813  }
28814  return h;
28815 }
28816 
28817 
28818 /* Link pNew element into the hash table pH. If pEntry!=0 then also
28819 ** insert pNew into the pEntry hash bucket.
28820 */
28821 static void insertElement(
28822  Hash *pH, /* The complete hash table */
28823  struct _ht *pEntry, /* The entry into which pNew is inserted */
28824  HashElem *pNew /* The element to be inserted */
28825 ){
28826  HashElem *pHead; /* First element already in pEntry */
28827  if( pEntry ){
28828  pHead = pEntry->count ? pEntry->chain : 0;
28829  pEntry->count++;
28830  pEntry->chain = pNew;
28831  }else{
28832  pHead = 0;
28833  }
28834  if( pHead ){
28835  pNew->next = pHead;
28836  pNew->prev = pHead->prev;
28837  if( pHead->prev ){ pHead->prev->next = pNew; }
28838  else { pH->first = pNew; }
28839  pHead->prev = pNew;
28840  }else{
28841  pNew->next = pH->first;
28842  if( pH->first ){ pH->first->prev = pNew; }
28843  pNew->prev = 0;
28844  pH->first = pNew;
28845  }
28846 }
28847 
28848 
28849 /* Resize the hash table so that it cantains "new_size" buckets.
28850 **
28851 ** The hash table might fail to resize if sqlite3_malloc() fails or
28852 ** if the new size is the same as the prior size.
28853 ** Return TRUE if the resize occurs and false if not.
28854 */
28855 static int rehash(Hash *pH, unsigned int new_size){
28856  struct _ht *new_ht; /* The new hash table */
28857  HashElem *elem, *next_elem; /* For looping over existing elements */
28858 
28859 #if SQLITE_MALLOC_SOFT_LIMIT>0
28860  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
28861  new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
28862  }
28863  if( new_size==pH->htsize ) return 0;
28864 #endif
28865 
28866  /* The inability to allocates space for a larger hash table is
28867  ** a performance hit but it is not a fatal error. So mark the
28868  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
28869  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
28870  ** only zeroes the requested number of bytes whereas this module will
28871  ** use the actual amount of space allocated for the hash table (which
28872  ** may be larger than the requested amount).
28873  */
28874  sqlite3BeginBenignMalloc();
28875  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
28876  sqlite3EndBenignMalloc();
28877 
28878  if( new_ht==0 ) return 0;
28879  sqlite3_free(pH->ht);
28880  pH->ht = new_ht;
28881  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
28882  memset(new_ht, 0, new_size*sizeof(struct _ht));
28883  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
28884  unsigned int h = strHash(elem->pKey) % new_size;
28885  next_elem = elem->next;
28886  insertElement(pH, &new_ht[h], elem);
28887  }
28888  return 1;
28889 }
28890 
28891 /* This function (for internal use only) locates an element in an
28892 ** hash table that matches the given key. The hash for this key is
28893 ** also computed and returned in the *pH parameter.
28894 */
28895 static HashElem *findElementWithHash(
28896  const Hash *pH, /* The pH to be searched */
28897  const char *pKey, /* The key we are searching for */
28898  unsigned int *pHash /* Write the hash value here */
28899 ){
28900  HashElem *elem; /* Used to loop thru the element list */
28901  int count; /* Number of elements left to test */
28902  unsigned int h; /* The computed hash */
28903 
28904  if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
28905  struct _ht *pEntry;
28906  h = strHash(pKey) % pH->htsize;
28907  pEntry = &pH->ht[h];
28908  elem = pEntry->chain;
28909  count = pEntry->count;
28910  }else{
28911  h = 0;
28912  elem = pH->first;
28913  count = pH->count;
28914  }
28915  *pHash = h;
28916  while( count-- ){
28917  assert( elem!=0 );
28918  if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
28919  return elem;
28920  }
28921  elem = elem->next;
28922  }
28923  return 0;
28924 }
28925 
28926 /* Remove a single entry from the hash table given a pointer to that
28927 ** element and a hash on the element's key.
28928 */
28929 static void removeElementGivenHash(
28930  Hash *pH, /* The pH containing "elem" */
28931  HashElem* elem, /* The element to be removed from the pH */
28932  unsigned int h /* Hash value for the element */
28933 ){
28934  struct _ht *pEntry;
28935  if( elem->prev ){
28936  elem->prev->next = elem->next;
28937  }else{
28938  pH->first = elem->next;
28939  }
28940  if( elem->next ){
28941  elem->next->prev = elem->prev;
28942  }
28943  if( pH->ht ){
28944  pEntry = &pH->ht[h];
28945  if( pEntry->chain==elem ){
28946  pEntry->chain = elem->next;
28947  }
28948  pEntry->count--;
28949  assert( pEntry->count>=0 );
28950  }
28951  sqlite3_free( elem );
28952  pH->count--;
28953  if( pH->count==0 ){
28954  assert( pH->first==0 );
28955  assert( pH->count==0 );
28956  sqlite3HashClear(pH);
28957  }
28958 }
28959 
28960 /* Attempt to locate an element of the hash table pH with a key
28961 ** that matches pKey. Return the data for this element if it is
28962 ** found, or NULL if there is no match.
28963 */
28964 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
28965  HashElem *elem; /* The element that matches key */
28966  unsigned int h; /* A hash on key */
28967 
28968  assert( pH!=0 );
28969  assert( pKey!=0 );
28970  elem = findElementWithHash(pH, pKey, &h);
28971  return elem ? elem->data : 0;
28972 }
28973 
28974 /* Insert an element into the hash table pH. The key is pKey
28975 ** and the data is "data".
28976 **
28977 ** If no element exists with a matching key, then a new
28978 ** element is created and NULL is returned.
28979 **
28980 ** If another element already exists with the same key, then the
28981 ** new data replaces the old data and the old data is returned.
28982 ** The key is not copied in this instance. If a malloc fails, then
28983 ** the new data is returned and the hash table is unchanged.
28984 **
28985 ** If the "data" parameter to this function is NULL, then the
28986 ** element corresponding to "key" is removed from the hash table.
28987 */
28988 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
28989  unsigned int h; /* the hash of the key modulo hash table size */
28990  HashElem *elem; /* Used to loop thru the element list */
28991  HashElem *new_elem; /* New element added to the pH */
28992 
28993  assert( pH!=0 );
28994  assert( pKey!=0 );
28995  elem = findElementWithHash(pH,pKey,&h);
28996  if( elem ){
28997  void *old_data = elem->data;
28998  if( data==0 ){
28999  removeElementGivenHash(pH,elem,h);
29000  }else{
29001  elem->data = data;
29002  elem->pKey = pKey;
29003  }
29004  return old_data;
29005  }
29006  if( data==0 ) return 0;
29007  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
29008  if( new_elem==0 ) return data;
29009  new_elem->pKey = pKey;
29010  new_elem->data = data;
29011  pH->count++;
29012  if( pH->count>=10 && pH->count > 2*pH->htsize ){
29013  if( rehash(pH, pH->count*2) ){
29014  assert( pH->htsize>0 );
29015  h = strHash(pKey) % pH->htsize;
29016  }
29017  }
29018  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
29019  return 0;
29020 }
29021 
29022 /************** End of hash.c ************************************************/
29023 /************** Begin file opcodes.c *****************************************/
29024 /* Automatically generated. Do not edit */
29025 /* See the tool/mkopcodec.tcl script for details. */
29026 #if !defined(SQLITE_OMIT_EXPLAIN) \
29027  || defined(VDBE_PROFILE) \
29028  || defined(SQLITE_DEBUG)
29029 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
29030 # define OpHelp(X) "\0" X
29031 #else
29032 # define OpHelp(X)
29033 #endif
29034 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
29035  static const char *const azName[] = {
29036  /* 0 */ "Savepoint" OpHelp(""),
29037  /* 1 */ "AutoCommit" OpHelp(""),
29038  /* 2 */ "Transaction" OpHelp(""),
29039  /* 3 */ "SorterNext" OpHelp(""),
29040  /* 4 */ "PrevIfOpen" OpHelp(""),
29041  /* 5 */ "NextIfOpen" OpHelp(""),
29042  /* 6 */ "Prev" OpHelp(""),
29043  /* 7 */ "Next" OpHelp(""),
29044  /* 8 */ "Checkpoint" OpHelp(""),
29045  /* 9 */ "JournalMode" OpHelp(""),
29046  /* 10 */ "Vacuum" OpHelp(""),
29047  /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
29048  /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
29049  /* 13 */ "Goto" OpHelp(""),
29050  /* 14 */ "Gosub" OpHelp(""),
29051  /* 15 */ "InitCoroutine" OpHelp(""),
29052  /* 16 */ "Yield" OpHelp(""),
29053  /* 17 */ "MustBeInt" OpHelp(""),
29054  /* 18 */ "Jump" OpHelp(""),
29055  /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
29056  /* 20 */ "Once" OpHelp(""),
29057  /* 21 */ "If" OpHelp(""),
29058  /* 22 */ "IfNot" OpHelp(""),
29059  /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"),
29060  /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"),
29061  /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"),
29062  /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"),
29063  /* 27 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
29064  /* 28 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
29065  /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"),
29066  /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"),
29067  /* 31 */ "Found" OpHelp("key=r[P3@P4]"),
29068  /* 32 */ "SeekRowid" OpHelp("intkey=r[P3]"),
29069  /* 33 */ "NotExists" OpHelp("intkey=r[P3]"),
29070  /* 34 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
29071  /* 35 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
29072  /* 36 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
29073  /* 37 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
29074  /* 38 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
29075  /* 39 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
29076  /* 40 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
29077  /* 41 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
29078  /* 42 */ "ElseNotEq" OpHelp(""),
29079  /* 43 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
29080  /* 44 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
29081  /* 45 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
29082  /* 46 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
29083  /* 47 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
29084  /* 48 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
29085  /* 49 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
29086  /* 50 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
29087  /* 51 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
29088  /* 52 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
29089  /* 53 */ "Last" OpHelp(""),
29090  /* 54 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
29091  /* 55 */ "SorterSort" OpHelp(""),
29092  /* 56 */ "Sort" OpHelp(""),
29093  /* 57 */ "Rewind" OpHelp(""),
29094  /* 58 */ "IdxLE" OpHelp("key=r[P3@P4]"),
29095  /* 59 */ "IdxGT" OpHelp("key=r[P3@P4]"),
29096  /* 60 */ "IdxLT" OpHelp("key=r[P3@P4]"),
29097  /* 61 */ "IdxGE" OpHelp("key=r[P3@P4]"),
29098  /* 62 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
29099  /* 63 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
29100  /* 64 */ "Program" OpHelp(""),
29101  /* 65 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
29102  /* 66 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
29103  /* 67 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
29104  /* 68 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
29105  /* 69 */ "IncrVacuum" OpHelp(""),
29106  /* 70 */ "VNext" OpHelp(""),
29107  /* 71 */ "Init" OpHelp("Start at P2"),
29108  /* 72 */ "Return" OpHelp(""),
29109  /* 73 */ "EndCoroutine" OpHelp(""),
29110  /* 74 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
29111  /* 75 */ "Halt" OpHelp(""),
29112  /* 76 */ "Integer" OpHelp("r[P2]=P1"),
29113  /* 77 */ "Int64" OpHelp("r[P2]=P4"),
29114  /* 78 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
29115  /* 79 */ "Null" OpHelp("r[P2..P3]=NULL"),
29116  /* 80 */ "SoftNull" OpHelp("r[P1]=NULL"),
29117  /* 81 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
29118  /* 82 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
29119  /* 83 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
29120  /* 84 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
29121  /* 85 */ "SCopy" OpHelp("r[P2]=r[P1]"),
29122  /* 86 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
29123  /* 87 */ "ResultRow" OpHelp("output=r[P1@P2]"),
29124  /* 88 */ "CollSeq" OpHelp(""),
29125  /* 89 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
29126  /* 90 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
29127  /* 91 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
29128  /* 92 */ "RealAffinity" OpHelp(""),
29129  /* 93 */ "Cast" OpHelp("affinity(r[P1])"),
29130  /* 94 */ "Permutation" OpHelp(""),
29131  /* 95 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
29132  /* 96 */ "Column" OpHelp("r[P3]=PX"),
29133  /* 97 */ "String8" OpHelp("r[P2]='P4'"),
29134  /* 98 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
29135  /* 99 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
29136  /* 100 */ "Count" OpHelp("r[P2]=count()"),
29137  /* 101 */ "ReadCookie" OpHelp(""),
29138  /* 102 */ "SetCookie" OpHelp(""),
29139  /* 103 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
29140  /* 104 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
29141  /* 105 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
29142  /* 106 */ "OpenAutoindex" OpHelp("nColumn=P2"),
29143  /* 107 */ "OpenEphemeral" OpHelp("nColumn=P2"),
29144  /* 108 */ "SorterOpen" OpHelp(""),
29145  /* 109 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
29146  /* 110 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
29147  /* 111 */ "Close" OpHelp(""),
29148  /* 112 */ "ColumnsUsed" OpHelp(""),
29149  /* 113 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
29150  /* 114 */ "NewRowid" OpHelp("r[P2]=rowid"),
29151  /* 115 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
29152  /* 116 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
29153  /* 117 */ "Delete" OpHelp(""),
29154  /* 118 */ "ResetCount" OpHelp(""),
29155  /* 119 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
29156  /* 120 */ "SorterData" OpHelp("r[P2]=data"),
29157  /* 121 */ "RowKey" OpHelp("r[P2]=key"),
29158  /* 122 */ "RowData" OpHelp("r[P2]=data"),
29159  /* 123 */ "Rowid" OpHelp("r[P2]=rowid"),
29160  /* 124 */ "NullRow" OpHelp(""),
29161  /* 125 */ "SorterInsert" OpHelp(""),
29162  /* 126 */ "IdxInsert" OpHelp("key=r[P2]"),
29163  /* 127 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
29164  /* 128 */ "Seek" OpHelp("Move P3 to P1.rowid"),
29165  /* 129 */ "IdxRowid" OpHelp("r[P2]=rowid"),
29166  /* 130 */ "Destroy" OpHelp(""),
29167  /* 131 */ "Clear" OpHelp(""),
29168  /* 132 */ "Real" OpHelp("r[P2]=P4"),
29169  /* 133 */ "ResetSorter" OpHelp(""),
29170  /* 134 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
29171  /* 135 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
29172  /* 136 */ "ParseSchema" OpHelp(""),
29173  /* 137 */ "LoadAnalysis" OpHelp(""),
29174  /* 138 */ "DropTable" OpHelp(""),
29175  /* 139 */ "DropIndex" OpHelp(""),
29176  /* 140 */ "DropTrigger" OpHelp(""),
29177  /* 141 */ "IntegrityCk" OpHelp(""),
29178  /* 142 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
29179  /* 143 */ "Param" OpHelp(""),
29180  /* 144 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
29181  /* 145 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
29182  /* 146 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
29183  /* 147 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
29184  /* 148 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
29185  /* 149 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
29186  /* 150 */ "Expire" OpHelp(""),
29187  /* 151 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
29188  /* 152 */ "VBegin" OpHelp(""),
29189  /* 153 */ "VCreate" OpHelp(""),
29190  /* 154 */ "VDestroy" OpHelp(""),
29191  /* 155 */ "VOpen" OpHelp(""),
29192  /* 156 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
29193  /* 157 */ "VRename" OpHelp(""),
29194  /* 158 */ "Pagecount" OpHelp(""),
29195  /* 159 */ "MaxPgcnt" OpHelp(""),
29196  /* 160 */ "CursorHint" OpHelp(""),
29197  /* 161 */ "Noop" OpHelp(""),
29198  /* 162 */ "Explain" OpHelp(""),
29199  };
29200  return azName[i];
29201 }
29202 #endif
29203 
29204 /************** End of opcodes.c *********************************************/
29205 /************** Begin file os_unix.c *****************************************/
29206 /*
29207 ** 2004 May 22
29208 **
29209 ** The author disclaims copyright to this source code. In place of
29210 ** a legal notice, here is a blessing:
29211 **
29212 ** May you do good and not evil.
29213 ** May you find forgiveness for yourself and forgive others.
29214 ** May you share freely, never taking more than you give.
29215 **
29216 ******************************************************************************
29217 **
29218 ** This file contains the VFS implementation for unix-like operating systems
29219 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
29220 **
29221 ** There are actually several different VFS implementations in this file.
29222 ** The differences are in the way that file locking is done. The default
29223 ** implementation uses Posix Advisory Locks. Alternative implementations
29224 ** use flock(), dot-files, various proprietary locking schemas, or simply
29225 ** skip locking all together.
29226 **
29227 ** This source file is organized into divisions where the logic for various
29228 ** subfunctions is contained within the appropriate division. PLEASE
29229 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
29230 ** in the correct division and should be clearly labeled.
29231 **
29232 ** The layout of divisions is as follows:
29233 **
29234 ** * General-purpose declarations and utility functions.
29235 ** * Unique file ID logic used by VxWorks.
29236 ** * Various locking primitive implementations (all except proxy locking):
29237 ** + for Posix Advisory Locks
29238 ** + for no-op locks
29239 ** + for dot-file locks
29240 ** + for flock() locking
29241 ** + for named semaphore locks (VxWorks only)
29242 ** + for AFP filesystem locks (MacOSX only)
29243 ** * sqlite3_file methods not associated with locking.
29244 ** * Definitions of sqlite3_io_methods objects for all locking
29245 ** methods plus "finder" functions for each locking method.
29246 ** * sqlite3_vfs method implementations.
29247 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
29248 ** * Definitions of sqlite3_vfs objects for all locking methods
29249 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
29250 */
29251 /* #include "sqliteInt.h" */
29252 #if SQLITE_OS_UNIX /* This file is used on unix only */
29253 
29254 /*
29255 ** There are various methods for file locking used for concurrency
29256 ** control:
29257 **
29258 ** 1. POSIX locking (the default),
29259 ** 2. No locking,
29260 ** 3. Dot-file locking,
29261 ** 4. flock() locking,
29262 ** 5. AFP locking (OSX only),
29263 ** 6. Named POSIX semaphores (VXWorks only),
29264 ** 7. proxy locking. (OSX only)
29265 **
29266 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
29267 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
29268 ** selection of the appropriate locking style based on the filesystem
29269 ** where the database is located.
29270 */
29271 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
29272 # if defined(__APPLE__)
29273 # define SQLITE_ENABLE_LOCKING_STYLE 1
29274 # else
29275 # define SQLITE_ENABLE_LOCKING_STYLE 0
29276 # endif
29277 #endif
29278 
29279 /* Use pread() and pwrite() if they are available */
29280 #if defined(__APPLE__)
29281 # define HAVE_PREAD 1
29282 # define HAVE_PWRITE 1
29283 #endif
29284 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
29285 # undef USE_PREAD
29286 # define USE_PREAD64 1
29287 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
29288 # undef USE_PREAD64
29289 # define USE_PREAD 1
29290 #endif
29291 
29292 /*
29293 ** standard include files.
29294 */
29295 #include <sys/types.h>
29296 #include <sys/stat.h>
29297 #include <fcntl.h>
29298 #include <unistd.h>
29299 /* #include <time.h> */
29300 #include <sys/time.h>
29301 #include <errno.h>
29302 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29303 # include <sys/mman.h>
29304 #endif
29305 
29306 #if SQLITE_ENABLE_LOCKING_STYLE
29307 # include <sys/ioctl.h>
29308 # include <sys/file.h>
29309 # include <sys/param.h>
29310 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
29311 
29312 #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
29313  (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
29314 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
29315  && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
29316 # define HAVE_GETHOSTUUID 1
29317 # else
29318 # warning "gethostuuid() is disabled."
29319 # endif
29320 #endif
29321 
29322 
29323 #if OS_VXWORKS
29324 /* # include <sys/ioctl.h> */
29325 # include <semaphore.h>
29326 # include <limits.h>
29327 #endif /* OS_VXWORKS */
29328 
29329 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29330 # include <sys/mount.h>
29331 #endif
29332 
29333 #ifdef HAVE_UTIME
29334 # include <utime.h>
29335 #endif
29336 
29337 /*
29338 ** Allowed values of unixFile.fsFlags
29339 */
29340 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
29341 
29342 /*
29343 ** If we are to be thread-safe, include the pthreads header and define
29344 ** the SQLITE_UNIX_THREADS macro.
29345 */
29346 #if SQLITE_THREADSAFE
29347 /* # include <pthread.h> */
29348 # define SQLITE_UNIX_THREADS 1
29349 #endif
29350 
29351 /*
29352 ** Default permissions when creating a new file
29353 */
29354 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
29355 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
29356 #endif
29357 
29358 /*
29359 ** Default permissions when creating auto proxy dir
29360 */
29361 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29362 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
29363 #endif
29364 
29365 /*
29366 ** Maximum supported path-length.
29367 */
29368 #define MAX_PATHNAME 512
29369 
29370 /*
29371 ** Maximum supported symbolic links
29372 */
29373 #define SQLITE_MAX_SYMLINKS 100
29374 
29375 /* Always cast the getpid() return type for compatibility with
29376 ** kernel modules in VxWorks. */
29377 #define osGetpid(X) (pid_t)getpid()
29378 
29379 /*
29380 ** Only set the lastErrno if the error code is a real error and not
29381 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
29382 */
29383 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
29384 
29385 /* Forward references */
29386 typedef struct unixShm unixShm; /* Connection shared memory */
29387 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
29388 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
29389 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
29390 
29391 /*
29392 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
29393 ** cannot be closed immediately. In these cases, instances of the following
29394 ** structure are used to store the file descriptor while waiting for an
29395 ** opportunity to either close or reuse it.
29396 */
29397 struct UnixUnusedFd {
29398  int fd; /* File descriptor to close */
29399  int flags; /* Flags this file descriptor was opened with */
29400  UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
29401 };
29402 
29403 /*
29404 ** The unixFile structure is subclass of sqlite3_file specific to the unix
29405 ** VFS implementations.
29406 */
29407 typedef struct unixFile unixFile;
29408 struct unixFile {
29409  sqlite3_io_methods const *pMethod; /* Always the first entry */
29410  sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
29411  unixInodeInfo *pInode; /* Info about locks on this inode */
29412  int h; /* The file descriptor */
29413  unsigned char eFileLock; /* The type of lock held on this fd */
29414  unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
29415  int lastErrno; /* The unix errno from last I/O error */
29416  void *lockingContext; /* Locking style specific state */
29417  UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
29418  const char *zPath; /* Name of the file */
29419  unixShm *pShm; /* Shared memory segment information */
29420  int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
29421 #if SQLITE_MAX_MMAP_SIZE>0
29422  int nFetchOut; /* Number of outstanding xFetch refs */
29423  sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
29424  sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
29425  sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
29426  void *pMapRegion; /* Memory mapped region */
29427 #endif
29428 #ifdef __QNXNTO__
29429  int sectorSize; /* Device sector size */
29430  int deviceCharacteristics; /* Precomputed device characteristics */
29431 #endif
29432 #if SQLITE_ENABLE_LOCKING_STYLE
29433  int openFlags; /* The flags specified at open() */
29434 #endif
29435 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
29436  unsigned fsFlags; /* cached details from statfs() */
29437 #endif
29438 #if OS_VXWORKS
29439  struct vxworksFileId *pId; /* Unique file ID */
29440 #endif
29441 #ifdef SQLITE_DEBUG
29442  /* The next group of variables are used to track whether or not the
29443  ** transaction counter in bytes 24-27 of database files are updated
29444  ** whenever any part of the database changes. An assertion fault will
29445  ** occur if a file is updated without also updating the transaction
29446  ** counter. This test is made to avoid new problems similar to the
29447  ** one described by ticket #3584.
29448  */
29449  unsigned char transCntrChng; /* True if the transaction counter changed */
29450  unsigned char dbUpdate; /* True if any part of database file changed */
29451  unsigned char inNormalWrite; /* True if in a normal write operation */
29452 
29453 #endif
29454 
29455 #ifdef SQLITE_TEST
29456  /* In test mode, increase the size of this structure a bit so that
29457  ** it is larger than the struct CrashFile defined in test6.c.
29458  */
29459  char aPadding[32];
29460 #endif
29461 };
29462 
29463 /* This variable holds the process id (pid) from when the xRandomness()
29464 ** method was called. If xOpen() is called from a different process id,
29465 ** indicating that a fork() has occurred, the PRNG will be reset.
29466 */
29467 static pid_t randomnessPid = 0;
29468 
29469 /*
29470 ** Allowed values for the unixFile.ctrlFlags bitmask:
29471 */
29472 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
29473 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
29474 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
29475 #ifndef SQLITE_DISABLE_DIRSYNC
29476 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
29477 #else
29478 # define UNIXFILE_DIRSYNC 0x00
29479 #endif
29480 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
29481 #define UNIXFILE_DELETE 0x20 /* Delete on close */
29482 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
29483 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
29484 
29485 /*
29486 ** Include code that is common to all os_*.c files
29487 */
29488 /************** Include os_common.h in the middle of os_unix.c ***************/
29489 /************** Begin file os_common.h ***************************************/
29490 /*
29491 ** 2004 May 22
29492 **
29493 ** The author disclaims copyright to this source code. In place of
29494 ** a legal notice, here is a blessing:
29495 **
29496 ** May you do good and not evil.
29497 ** May you find forgiveness for yourself and forgive others.
29498 ** May you share freely, never taking more than you give.
29499 **
29500 ******************************************************************************
29501 **
29502 ** This file contains macros and a little bit of code that is common to
29503 ** all of the platform-specific files (os_*.c) and is #included into those
29504 ** files.
29505 **
29506 ** This file should be #included by the os_*.c files only. It is not a
29507 ** general purpose header file.
29508 */
29509 #ifndef _OS_COMMON_H_
29510 #define _OS_COMMON_H_
29511 
29512 /*
29513 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29514 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29515 ** switch. The following code should catch this problem at compile-time.
29516 */
29517 #ifdef MEMORY_DEBUG
29518 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
29519 #endif
29520 
29521 /*
29522 ** Macros for performance tracing. Normally turned off. Only works
29523 ** on i486 hardware.
29524 */
29525 #ifdef SQLITE_PERFORMANCE_TRACE
29526 
29527 /*
29528 ** hwtime.h contains inline assembler code for implementing
29529 ** high-performance timing routines.
29530 */
29531 /************** Include hwtime.h in the middle of os_common.h ****************/
29532 /************** Begin file hwtime.h ******************************************/
29533 /*
29534 ** 2008 May 27
29535 **
29536 ** The author disclaims copyright to this source code. In place of
29537 ** a legal notice, here is a blessing:
29538 **
29539 ** May you do good and not evil.
29540 ** May you find forgiveness for yourself and forgive others.
29541 ** May you share freely, never taking more than you give.
29542 **
29543 ******************************************************************************
29544 **
29545 ** This file contains inline asm code for retrieving "high-performance"
29546 ** counters for x86 class CPUs.
29547 */
29548 #ifndef SQLITE_HWTIME_H
29549 #define SQLITE_HWTIME_H
29550 
29551 /*
29552 ** The following routine only works on pentium-class (or newer) processors.
29553 ** It uses the RDTSC opcode to read the cycle count value out of the
29554 ** processor and returns that value. This can be used for high-res
29555 ** profiling.
29556 */
29557 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
29558  (defined(i386) || defined(__i386__) || defined(_M_IX86))
29559 
29560  #if defined(__GNUC__)
29561 
29562  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29563  unsigned int lo, hi;
29564  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29565  return (sqlite_uint64)hi << 32 | lo;
29566  }
29567 
29568  #elif defined(_MSC_VER)
29569 
29570  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29571  __asm {
29572  rdtsc
29573  ret ; return value at EDX:EAX
29574  }
29575  }
29576 
29577  #endif
29578 
29579 #elif (defined(__GNUC__) && defined(__x86_64__))
29580 
29581  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29582  unsigned long val;
29583  __asm__ __volatile__ ("rdtsc" : "=A" (val));
29584  return val;
29585  }
29586 
29587 #elif (defined(__GNUC__) && defined(__ppc__))
29588 
29589  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29590  unsigned long long retval;
29591  unsigned long junk;
29592  __asm__ __volatile__ ("\n\
29593  1: mftbu %1\n\
29594  mftb %L0\n\
29595  mftbu %0\n\
29596  cmpw %0,%1\n\
29597  bne 1b"
29598  : "=r" (retval), "=r" (junk));
29599  return retval;
29600  }
29601 
29602 #else
29603 
29604  #error Need implementation of sqlite3Hwtime() for your platform.
29605 
29606  /*
29607  ** To compile without implementing sqlite3Hwtime() for your platform,
29608  ** you can remove the above #error and use the following
29609  ** stub function. You will lose timing support for many
29610  ** of the debugging and testing utilities, but it should at
29611  ** least compile and run.
29612  */
29613 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29614 
29615 #endif
29616 
29617 #endif /* !defined(SQLITE_HWTIME_H) */
29618 
29619 /************** End of hwtime.h **********************************************/
29620 /************** Continuing where we left off in os_common.h ******************/
29621 
29622 static sqlite_uint64 g_start;
29623 static sqlite_uint64 g_elapsed;
29624 #define TIMER_START g_start=sqlite3Hwtime()
29625 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
29626 #define TIMER_ELAPSED g_elapsed
29627 #else
29628 #define TIMER_START
29629 #define TIMER_END
29630 #define TIMER_ELAPSED ((sqlite_uint64)0)
29631 #endif
29632 
29633 /*
29634 ** If we compile with the SQLITE_TEST macro set, then the following block
29635 ** of code will give us the ability to simulate a disk I/O error. This
29636 ** is used for testing the I/O recovery logic.
29637 */
29638 #if defined(SQLITE_TEST)
29639 SQLITE_API extern int sqlite3_io_error_hit;
29640 SQLITE_API extern int sqlite3_io_error_hardhit;
29641 SQLITE_API extern int sqlite3_io_error_pending;
29642 SQLITE_API extern int sqlite3_io_error_persist;
29643 SQLITE_API extern int sqlite3_io_error_benign;
29644 SQLITE_API extern int sqlite3_diskfull_pending;
29645 SQLITE_API extern int sqlite3_diskfull;
29646 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29647 #define SimulateIOError(CODE) \
29648  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29649  || sqlite3_io_error_pending-- == 1 ) \
29650  { local_ioerr(); CODE; }
29651 static void local_ioerr(){
29652  IOTRACE(("IOERR\n"));
29653  sqlite3_io_error_hit++;
29654  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29655 }
29656 #define SimulateDiskfullError(CODE) \
29657  if( sqlite3_diskfull_pending ){ \
29658  if( sqlite3_diskfull_pending == 1 ){ \
29659  local_ioerr(); \
29660  sqlite3_diskfull = 1; \
29661  sqlite3_io_error_hit = 1; \
29662  CODE; \
29663  }else{ \
29664  sqlite3_diskfull_pending--; \
29665  } \
29666  }
29667 #else
29668 #define SimulateIOErrorBenign(X)
29669 #define SimulateIOError(A)
29670 #define SimulateDiskfullError(A)
29671 #endif /* defined(SQLITE_TEST) */
29672 
29673 /*
29674 ** When testing, keep a count of the number of open files.
29675 */
29676 #if defined(SQLITE_TEST)
29677 SQLITE_API extern int sqlite3_open_file_count;
29678 #define OpenCounter(X) sqlite3_open_file_count+=(X)
29679 #else
29680 #define OpenCounter(X)
29681 #endif /* defined(SQLITE_TEST) */
29682 
29683 #endif /* !defined(_OS_COMMON_H_) */
29684 
29685 /************** End of os_common.h *******************************************/
29686 /************** Continuing where we left off in os_unix.c ********************/
29687 
29688 /*
29689 ** Define various macros that are missing from some systems.
29690 */
29691 #ifndef O_LARGEFILE
29692 # define O_LARGEFILE 0
29693 #endif
29694 #ifdef SQLITE_DISABLE_LFS
29695 # undef O_LARGEFILE
29696 # define O_LARGEFILE 0
29697 #endif
29698 #ifndef O_NOFOLLOW
29699 # define O_NOFOLLOW 0
29700 #endif
29701 #ifndef O_BINARY
29702 # define O_BINARY 0
29703 #endif
29704 
29705 /*
29706 ** The threadid macro resolves to the thread-id or to 0. Used for
29707 ** testing and debugging only.
29708 */
29709 #if SQLITE_THREADSAFE
29710 #define threadid pthread_self()
29711 #else
29712 #define threadid 0
29713 #endif
29714 
29715 /*
29716 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
29717 */
29718 #if !defined(HAVE_MREMAP)
29719 # if defined(__linux__) && defined(_GNU_SOURCE)
29720 # define HAVE_MREMAP 1
29721 # else
29722 # define HAVE_MREMAP 0
29723 # endif
29724 #endif
29725 
29726 /*
29727 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
29728 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
29729 */
29730 #ifdef __ANDROID__
29731 # define lseek lseek64
29732 #endif
29733 
29734 /*
29735 ** Different Unix systems declare open() in different ways. Same use
29736 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
29737 ** The difference is important when using a pointer to the function.
29738 **
29739 ** The safest way to deal with the problem is to always use this wrapper
29740 ** which always has the same well-defined interface.
29741 */
29742 static int posixOpen(const char *zFile, int flags, int mode){
29743  return open(zFile, flags, mode);
29744 }
29745 
29746 /* Forward reference */
29747 static int openDirectory(const char*, int*);
29748 static int unixGetpagesize(void);
29749 
29750 /*
29751 ** Many system calls are accessed through pointer-to-functions so that
29752 ** they may be overridden at runtime to facilitate fault injection during
29753 ** testing and sandboxing. The following array holds the names and pointers
29754 ** to all overrideable system calls.
29755 */
29756 static struct unix_syscall {
29757  const char *zName; /* Name of the system call */
29758  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
29759  sqlite3_syscall_ptr pDefault; /* Default value */
29760 } aSyscall[] = {
29761  { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
29762 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
29763 
29764  { "close", (sqlite3_syscall_ptr)close, 0 },
29765 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
29766 
29767  { "access", (sqlite3_syscall_ptr)access, 0 },
29768 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
29769 
29770  { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
29771 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
29772 
29773  { "stat", (sqlite3_syscall_ptr)stat, 0 },
29774 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
29775 
29776 /*
29777 ** The DJGPP compiler environment looks mostly like Unix, but it
29778 ** lacks the fcntl() system call. So redefine fcntl() to be something
29779 ** that always succeeds. This means that locking does not occur under
29780 ** DJGPP. But it is DOS - what did you expect?
29781 */
29782 #ifdef __DJGPP__
29783  { "fstat", 0, 0 },
29784 #define osFstat(a,b,c) 0
29785 #else
29786  { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
29787 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
29788 #endif
29789 
29790  { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
29791 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
29792 
29793  { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
29794 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
29795 
29796  { "read", (sqlite3_syscall_ptr)read, 0 },
29797 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
29798 
29799 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29800  { "pread", (sqlite3_syscall_ptr)pread, 0 },
29801 #else
29802  { "pread", (sqlite3_syscall_ptr)0, 0 },
29803 #endif
29804 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
29805 
29806 #if defined(USE_PREAD64)
29807  { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
29808 #else
29809  { "pread64", (sqlite3_syscall_ptr)0, 0 },
29810 #endif
29811 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
29812 
29813  { "write", (sqlite3_syscall_ptr)write, 0 },
29814 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
29815 
29816 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29817  { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
29818 #else
29819  { "pwrite", (sqlite3_syscall_ptr)0, 0 },
29820 #endif
29821 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
29822  aSyscall[12].pCurrent)
29823 
29824 #if defined(USE_PREAD64)
29825  { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
29826 #else
29827  { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
29828 #endif
29829 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
29830  aSyscall[13].pCurrent)
29831 
29832  { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
29833 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
29834 
29835 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
29836  { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
29837 #else
29838  { "fallocate", (sqlite3_syscall_ptr)0, 0 },
29839 #endif
29840 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
29841 
29842  { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
29843 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
29844 
29845  { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
29846 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
29847 
29848  { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
29849 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
29850 
29851  { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
29852 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
29853 
29854 #if defined(HAVE_FCHOWN)
29855  { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
29856 #else
29857  { "fchown", (sqlite3_syscall_ptr)0, 0 },
29858 #endif
29859 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
29860 
29861  { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
29862 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
29863 
29864 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29865  { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
29866 #else
29867  { "mmap", (sqlite3_syscall_ptr)0, 0 },
29868 #endif
29869 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
29870 
29871 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29872  { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
29873 #else
29874  { "munmap", (sqlite3_syscall_ptr)0, 0 },
29875 #endif
29876 #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
29877 
29878 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
29879  { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
29880 #else
29881  { "mremap", (sqlite3_syscall_ptr)0, 0 },
29882 #endif
29883 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
29884 
29885 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29886  { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
29887 #else
29888  { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
29889 #endif
29890 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
29891 
29892 #if defined(HAVE_READLINK)
29893  { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
29894 #else
29895  { "readlink", (sqlite3_syscall_ptr)0, 0 },
29896 #endif
29897 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
29898 
29899 #if defined(HAVE_LSTAT)
29900  { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
29901 #else
29902  { "lstat", (sqlite3_syscall_ptr)0, 0 },
29903 #endif
29904 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
29905 
29906 }; /* End of the overrideable system calls */
29907 
29908 
29909 /*
29910 ** On some systems, calls to fchown() will trigger a message in a security
29911 ** log if they come from non-root processes. So avoid calling fchown() if
29912 ** we are not running as root.
29913 */
29914 static int robustFchown(int fd, uid_t uid, gid_t gid){
29915 #if defined(HAVE_FCHOWN)
29916  return osGeteuid() ? 0 : osFchown(fd,uid,gid);
29917 #else
29918  return 0;
29919 #endif
29920 }
29921 
29922 /*
29923 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
29924 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
29925 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
29926 ** system call named zName.
29927 */
29928 static int unixSetSystemCall(
29929  sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
29930  const char *zName, /* Name of system call to override */
29931  sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
29932 ){
29933  unsigned int i;
29934  int rc = SQLITE_NOTFOUND;
29935 
29936  UNUSED_PARAMETER(pNotUsed);
29937  if( zName==0 ){
29938  /* If no zName is given, restore all system calls to their default
29939  ** settings and return NULL
29940  */
29941  rc = SQLITE_OK;
29942  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29943  if( aSyscall[i].pDefault ){
29944  aSyscall[i].pCurrent = aSyscall[i].pDefault;
29945  }
29946  }
29947  }else{
29948  /* If zName is specified, operate on only the one system call
29949  ** specified.
29950  */
29951  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29952  if( strcmp(zName, aSyscall[i].zName)==0 ){
29953  if( aSyscall[i].pDefault==0 ){
29954  aSyscall[i].pDefault = aSyscall[i].pCurrent;
29955  }
29956  rc = SQLITE_OK;
29957  if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
29958  aSyscall[i].pCurrent = pNewFunc;
29959  break;
29960  }
29961  }
29962  }
29963  return rc;
29964 }
29965 
29966 /*
29967 ** Return the value of a system call. Return NULL if zName is not a
29968 ** recognized system call name. NULL is also returned if the system call
29969 ** is currently undefined.
29970 */
29971 static sqlite3_syscall_ptr unixGetSystemCall(
29972  sqlite3_vfs *pNotUsed,
29973  const char *zName
29974 ){
29975  unsigned int i;
29976 
29977  UNUSED_PARAMETER(pNotUsed);
29978  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29979  if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
29980  }
29981  return 0;
29982 }
29983 
29984 /*
29985 ** Return the name of the first system call after zName. If zName==NULL
29986 ** then return the name of the first system call. Return NULL if zName
29987 ** is the last system call or if zName is not the name of a valid
29988 ** system call.
29989 */
29990 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
29991  int i = -1;
29992 
29993  UNUSED_PARAMETER(p);
29994  if( zName ){
29995  for(i=0; i<ArraySize(aSyscall)-1; i++){
29996  if( strcmp(zName, aSyscall[i].zName)==0 ) break;
29997  }
29998  }
29999  for(i++; i<ArraySize(aSyscall); i++){
30000  if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
30001  }
30002  return 0;
30003 }
30004 
30005 /*
30006 ** Do not accept any file descriptor less than this value, in order to avoid
30007 ** opening database file using file descriptors that are commonly used for
30008 ** standard input, output, and error.
30009 */
30010 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
30011 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
30012 #endif
30013 
30014 /*
30015 ** Invoke open(). Do so multiple times, until it either succeeds or
30016 ** fails for some reason other than EINTR.
30017 **
30018 ** If the file creation mode "m" is 0 then set it to the default for
30019 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
30020 ** 0644) as modified by the system umask. If m is not 0, then
30021 ** make the file creation mode be exactly m ignoring the umask.
30022 **
30023 ** The m parameter will be non-zero only when creating -wal, -journal,
30024 ** and -shm files. We want those files to have *exactly* the same
30025 ** permissions as their original database, unadulterated by the umask.
30026 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
30027 ** transaction crashes and leaves behind hot journals, then any
30028 ** process that is able to write to the database will also be able to
30029 ** recover the hot journals.
30030 */
30031 static int robust_open(const char *z, int f, mode_t m){
30032  int fd;
30033  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
30034  while(1){
30035 #if defined(O_CLOEXEC)
30036  fd = osOpen(z,f|O_CLOEXEC,m2);
30037 #else
30038  fd = osOpen(z,f,m2);
30039 #endif
30040  if( fd<0 ){
30041  if( errno==EINTR ) continue;
30042  break;
30043  }
30044  if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
30045  osClose(fd);
30046  sqlite3_log(SQLITE_WARNING,
30047  "attempt to open \"%s\" as file descriptor %d", z, fd);
30048  fd = -1;
30049  if( osOpen("/dev/null", f, m)<0 ) break;
30050  }
30051  if( fd>=0 ){
30052  if( m!=0 ){
30053  struct stat statbuf;
30054  if( osFstat(fd, &statbuf)==0
30055  && statbuf.st_size==0
30056  && (statbuf.st_mode&0777)!=m
30057  ){
30058  osFchmod(fd, m);
30059  }
30060  }
30061 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
30062  osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
30063 #endif
30064  }
30065  return fd;
30066 }
30067 
30068 /*
30069 ** Helper functions to obtain and relinquish the global mutex. The
30070 ** global mutex is used to protect the unixInodeInfo and
30071 ** vxworksFileId objects used by this file, all of which may be
30072 ** shared by multiple threads.
30073 **
30074 ** Function unixMutexHeld() is used to assert() that the global mutex
30075 ** is held when required. This function is only used as part of assert()
30076 ** statements. e.g.
30077 **
30078 ** unixEnterMutex()
30079 ** assert( unixMutexHeld() );
30080 ** unixEnterLeave()
30081 */
30082 static void unixEnterMutex(void){
30083  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30084 }
30085 static void unixLeaveMutex(void){
30086  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30087 }
30088 #ifdef SQLITE_DEBUG
30089 static int unixMutexHeld(void) {
30090  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30091 }
30092 #endif
30093 
30094 
30095 #ifdef SQLITE_HAVE_OS_TRACE
30096 /*
30097 ** Helper function for printing out trace information from debugging
30098 ** binaries. This returns the string representation of the supplied
30099 ** integer lock-type.
30100 */
30101 static const char *azFileLock(int eFileLock){
30102  switch( eFileLock ){
30103  case NO_LOCK: return "NONE";
30104  case SHARED_LOCK: return "SHARED";
30105  case RESERVED_LOCK: return "RESERVED";
30106  case PENDING_LOCK: return "PENDING";
30107  case EXCLUSIVE_LOCK: return "EXCLUSIVE";
30108  }
30109  return "ERROR";
30110 }
30111 #endif
30112 
30113 #ifdef SQLITE_LOCK_TRACE
30114 /*
30115 ** Print out information about all locking operations.
30116 **
30117 ** This routine is used for troubleshooting locks on multithreaded
30118 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
30119 ** command-line option on the compiler. This code is normally
30120 ** turned off.
30121 */
30122 static int lockTrace(int fd, int op, struct flock *p){
30123  char *zOpName, *zType;
30124  int s;
30125  int savedErrno;
30126  if( op==F_GETLK ){
30127  zOpName = "GETLK";
30128  }else if( op==F_SETLK ){
30129  zOpName = "SETLK";
30130  }else{
30131  s = osFcntl(fd, op, p);
30132  sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
30133  return s;
30134  }
30135  if( p->l_type==F_RDLCK ){
30136  zType = "RDLCK";
30137  }else if( p->l_type==F_WRLCK ){
30138  zType = "WRLCK";
30139  }else if( p->l_type==F_UNLCK ){
30140  zType = "UNLCK";
30141  }else{
30142  assert( 0 );
30143  }
30144  assert( p->l_whence==SEEK_SET );
30145  s = osFcntl(fd, op, p);
30146  savedErrno = errno;
30147  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
30148  threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
30149  (int)p->l_pid, s);
30150  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
30151  struct flock l2;
30152  l2 = *p;
30153  osFcntl(fd, F_GETLK, &l2);
30154  if( l2.l_type==F_RDLCK ){
30155  zType = "RDLCK";
30156  }else if( l2.l_type==F_WRLCK ){
30157  zType = "WRLCK";
30158  }else if( l2.l_type==F_UNLCK ){
30159  zType = "UNLCK";
30160  }else{
30161  assert( 0 );
30162  }
30163  sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
30164  zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
30165  }
30166  errno = savedErrno;
30167  return s;
30168 }
30169 #undef osFcntl
30170 #define osFcntl lockTrace
30171 #endif /* SQLITE_LOCK_TRACE */
30172 
30173 /*
30174 ** Retry ftruncate() calls that fail due to EINTR
30175 **
30176 ** All calls to ftruncate() within this file should be made through
30177 ** this wrapper. On the Android platform, bypassing the logic below
30178 ** could lead to a corrupt database.
30179 */
30180 static int robust_ftruncate(int h, sqlite3_int64 sz){
30181  int rc;
30182 #ifdef __ANDROID__
30183  /* On Android, ftruncate() always uses 32-bit offsets, even if
30184  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
30185  ** truncate a file to any size larger than 2GiB. Silently ignore any
30186  ** such attempts. */
30187  if( sz>(sqlite3_int64)0x7FFFFFFF ){
30188  rc = SQLITE_OK;
30189  }else
30190 #endif
30191  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
30192  return rc;
30193 }
30194 
30195 /*
30196 ** This routine translates a standard POSIX errno code into something
30197 ** useful to the clients of the sqlite3 functions. Specifically, it is
30198 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
30199 ** and a variety of "please close the file descriptor NOW" errors into
30200 ** SQLITE_IOERR
30201 **
30202 ** Errors during initialization of locks, or file system support for locks,
30203 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
30204 */
30205 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
30206  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
30207  (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
30208  (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
30209  (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
30210  switch (posixError) {
30211  case EACCES:
30212  case EAGAIN:
30213  case ETIMEDOUT:
30214  case EBUSY:
30215  case EINTR:
30216  case ENOLCK:
30217  /* random NFS retry error, unless during file system support
30218  * introspection, in which it actually means what it says */
30219  return SQLITE_BUSY;
30220 
30221  case EPERM:
30222  return SQLITE_PERM;
30223 
30224  default:
30225  return sqliteIOErr;
30226  }
30227 }
30228 
30229 
30230 /******************************************************************************
30231 ****************** Begin Unique File ID Utility Used By VxWorks ***************
30232 **
30233 ** On most versions of unix, we can get a unique ID for a file by concatenating
30234 ** the device number and the inode number. But this does not work on VxWorks.
30235 ** On VxWorks, a unique file id must be based on the canonical filename.
30236 **
30237 ** A pointer to an instance of the following structure can be used as a
30238 ** unique file ID in VxWorks. Each instance of this structure contains
30239 ** a copy of the canonical filename. There is also a reference count.
30240 ** The structure is reclaimed when the number of pointers to it drops to
30241 ** zero.
30242 **
30243 ** There are never very many files open at one time and lookups are not
30244 ** a performance-critical path, so it is sufficient to put these
30245 ** structures on a linked list.
30246 */
30248  struct vxworksFileId *pNext; /* Next in a list of them all */
30249  int nRef; /* Number of references to this one */
30250  int nName; /* Length of the zCanonicalName[] string */
30251  char *zCanonicalName; /* Canonical filename */
30252 };
30253 
30254 #if OS_VXWORKS
30255 /*
30256 ** All unique filenames are held on a linked list headed by this
30257 ** variable:
30258 */
30259 static struct vxworksFileId *vxworksFileList = 0;
30260 
30261 /*
30262 ** Simplify a filename into its canonical form
30263 ** by making the following changes:
30264 **
30265 ** * removing any trailing and duplicate /
30266 ** * convert /./ into just /
30267 ** * convert /A/../ where A is any simple name into just /
30268 **
30269 ** Changes are made in-place. Return the new name length.
30270 **
30271 ** The original filename is in z[0..n-1]. Return the number of
30272 ** characters in the simplified name.
30273 */
30274 static int vxworksSimplifyName(char *z, int n){
30275  int i, j;
30276  while( n>1 && z[n-1]=='/' ){ n--; }
30277  for(i=j=0; i<n; i++){
30278  if( z[i]=='/' ){
30279  if( z[i+1]=='/' ) continue;
30280  if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
30281  i += 1;
30282  continue;
30283  }
30284  if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
30285  while( j>0 && z[j-1]!='/' ){ j--; }
30286  if( j>0 ){ j--; }
30287  i += 2;
30288  continue;
30289  }
30290  }
30291  z[j++] = z[i];
30292  }
30293  z[j] = 0;
30294  return j;
30295 }
30296 
30297 /*
30298 ** Find a unique file ID for the given absolute pathname. Return
30299 ** a pointer to the vxworksFileId object. This pointer is the unique
30300 ** file ID.
30301 **
30302 ** The nRef field of the vxworksFileId object is incremented before
30303 ** the object is returned. A new vxworksFileId object is created
30304 ** and added to the global list if necessary.
30305 **
30306 ** If a memory allocation error occurs, return NULL.
30307 */
30308 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
30309  struct vxworksFileId *pNew; /* search key and new file ID */
30310  struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
30311  int n; /* Length of zAbsoluteName string */
30312 
30313  assert( zAbsoluteName[0]=='/' );
30314  n = (int)strlen(zAbsoluteName);
30315  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
30316  if( pNew==0 ) return 0;
30317  pNew->zCanonicalName = (char*)&pNew[1];
30318  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
30319  n = vxworksSimplifyName(pNew->zCanonicalName, n);
30320 
30321  /* Search for an existing entry that matching the canonical name.
30322  ** If found, increment the reference count and return a pointer to
30323  ** the existing file ID.
30324  */
30325  unixEnterMutex();
30326  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
30327  if( pCandidate->nName==n
30328  && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
30329  ){
30330  sqlite3_free(pNew);
30331  pCandidate->nRef++;
30332  unixLeaveMutex();
30333  return pCandidate;
30334  }
30335  }
30336 
30337  /* No match was found. We will make a new file ID */
30338  pNew->nRef = 1;
30339  pNew->nName = n;
30340  pNew->pNext = vxworksFileList;
30341  vxworksFileList = pNew;
30342  unixLeaveMutex();
30343  return pNew;
30344 }
30345 
30346 /*
30347 ** Decrement the reference count on a vxworksFileId object. Free
30348 ** the object when the reference count reaches zero.
30349 */
30350 static void vxworksReleaseFileId(struct vxworksFileId *pId){
30351  unixEnterMutex();
30352  assert( pId->nRef>0 );
30353  pId->nRef--;
30354  if( pId->nRef==0 ){
30355  struct vxworksFileId **pp;
30356  for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
30357  assert( *pp==pId );
30358  *pp = pId->pNext;
30359  sqlite3_free(pId);
30360  }
30361  unixLeaveMutex();
30362 }
30363 #endif /* OS_VXWORKS */
30364 /*************** End of Unique File ID Utility Used By VxWorks ****************
30365 ******************************************************************************/
30366 
30367 
30368 /******************************************************************************
30369 *************************** Posix Advisory Locking ****************************
30370 **
30371 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
30372 ** section 6.5.2.2 lines 483 through 490 specify that when a process
30373 ** sets or clears a lock, that operation overrides any prior locks set
30374 ** by the same process. It does not explicitly say so, but this implies
30375 ** that it overrides locks set by the same process using a different
30376 ** file descriptor. Consider this test case:
30377 **
30378 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
30379 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
30380 **
30381 ** Suppose ./file1 and ./file2 are really the same file (because
30382 ** one is a hard or symbolic link to the other) then if you set
30383 ** an exclusive lock on fd1, then try to get an exclusive lock
30384 ** on fd2, it works. I would have expected the second lock to
30385 ** fail since there was already a lock on the file due to fd1.
30386 ** But not so. Since both locks came from the same process, the
30387 ** second overrides the first, even though they were on different
30388 ** file descriptors opened on different file names.
30389 **
30390 ** This means that we cannot use POSIX locks to synchronize file access
30391 ** among competing threads of the same process. POSIX locks will work fine
30392 ** to synchronize access for threads in separate processes, but not
30393 ** threads within the same process.
30394 **
30395 ** To work around the problem, SQLite has to manage file locks internally
30396 ** on its own. Whenever a new database is opened, we have to find the
30397 ** specific inode of the database file (the inode is determined by the
30398 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
30399 ** and check for locks already existing on that inode. When locks are
30400 ** created or removed, we have to look at our own internal record of the
30401 ** locks to see if another thread has previously set a lock on that same
30402 ** inode.
30403 **
30404 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
30405 ** For VxWorks, we have to use the alternative unique ID system based on
30406 ** canonical filename and implemented in the previous division.)
30407 **
30408 ** The sqlite3_file structure for POSIX is no longer just an integer file
30409 ** descriptor. It is now a structure that holds the integer file
30410 ** descriptor and a pointer to a structure that describes the internal
30411 ** locks on the corresponding inode. There is one locking structure
30412 ** per inode, so if the same inode is opened twice, both unixFile structures
30413 ** point to the same locking structure. The locking structure keeps
30414 ** a reference count (so we will know when to delete it) and a "cnt"
30415 ** field that tells us its internal lock status. cnt==0 means the
30416 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
30417 ** cnt>0 means there are cnt shared locks on the file.
30418 **
30419 ** Any attempt to lock or unlock a file first checks the locking
30420 ** structure. The fcntl() system call is only invoked to set a
30421 ** POSIX lock if the internal lock structure transitions between
30422 ** a locked and an unlocked state.
30423 **
30424 ** But wait: there are yet more problems with POSIX advisory locks.
30425 **
30426 ** If you close a file descriptor that points to a file that has locks,
30427 ** all locks on that file that are owned by the current process are
30428 ** released. To work around this problem, each unixInodeInfo object
30429 ** maintains a count of the number of pending locks on tha inode.
30430 ** When an attempt is made to close an unixFile, if there are
30431 ** other unixFile open on the same inode that are holding locks, the call
30432 ** to close() the file descriptor is deferred until all of the locks clear.
30433 ** The unixInodeInfo structure keeps a list of file descriptors that need to
30434 ** be closed and that list is walked (and cleared) when the last lock
30435 ** clears.
30436 **
30437 ** Yet another problem: LinuxThreads do not play well with posix locks.
30438 **
30439 ** Many older versions of linux use the LinuxThreads library which is
30440 ** not posix compliant. Under LinuxThreads, a lock created by thread
30441 ** A cannot be modified or overridden by a different thread B.
30442 ** Only thread A can modify the lock. Locking behavior is correct
30443 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
30444 ** on linux - with NPTL a lock created by thread A can override locks
30445 ** in thread B. But there is no way to know at compile-time which
30446 ** threading library is being used. So there is no way to know at
30447 ** compile-time whether or not thread A can override locks on thread B.
30448 ** One has to do a run-time check to discover the behavior of the
30449 ** current process.
30450 **
30451 ** SQLite used to support LinuxThreads. But support for LinuxThreads
30452 ** was dropped beginning with version 3.7.0. SQLite will still work with
30453 ** LinuxThreads provided that (1) there is no more than one connection
30454 ** per database file in the same process and (2) database connections
30455 ** do not move across threads.
30456 */
30457 
30458 /*
30459 ** An instance of the following structure serves as the key used
30460 ** to locate a particular unixInodeInfo object.
30461 */
30462 struct unixFileId {
30463  dev_t dev; /* Device number */
30464 #if OS_VXWORKS
30465  struct vxworksFileId *pId; /* Unique file ID for vxworks. */
30466 #else
30467  ino_t ino; /* Inode number */
30468 #endif
30469 };
30470 
30471 /*
30472 ** An instance of the following structure is allocated for each open
30473 ** inode. Or, on LinuxThreads, there is one of these structures for
30474 ** each inode opened by each thread.
30475 **
30476 ** A single inode can have multiple file descriptors, so each unixFile
30477 ** structure contains a pointer to an instance of this object and this
30478 ** object keeps a count of the number of unixFile pointing to it.
30479 */
30480 struct unixInodeInfo {
30481  struct unixFileId fileId; /* The lookup key */
30482  int nShared; /* Number of SHARED locks held */
30483  unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
30484  unsigned char bProcessLock; /* An exclusive process lock is held */
30485  int nRef; /* Number of pointers to this structure */
30486  unixShmNode *pShmNode; /* Shared memory associated with this inode */
30487  int nLock; /* Number of outstanding file locks */
30488  UnixUnusedFd *pUnused; /* Unused file descriptors to close */
30489  unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
30490  unixInodeInfo *pPrev; /* .... doubly linked */
30491 #if SQLITE_ENABLE_LOCKING_STYLE
30492  unsigned long long sharedByte; /* for AFP simulated shared lock */
30493 #endif
30494 #if OS_VXWORKS
30495  sem_t *pSem; /* Named POSIX semaphore */
30496  char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
30497 #endif
30498 };
30499 
30500 /*
30501 ** A lists of all unixInodeInfo objects.
30502 */
30503 static unixInodeInfo *inodeList = 0;
30504 
30505 /*
30506 **
30507 ** This function - unixLogErrorAtLine(), is only ever called via the macro
30508 ** unixLogError().
30509 **
30510 ** It is invoked after an error occurs in an OS function and errno has been
30511 ** set. It logs a message using sqlite3_log() containing the current value of
30512 ** errno and, if possible, the human-readable equivalent from strerror() or
30513 ** strerror_r().
30514 **
30515 ** The first argument passed to the macro should be the error code that
30516 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
30517 ** The two subsequent arguments should be the name of the OS function that
30518 ** failed (e.g. "unlink", "open") and the associated file-system path,
30519 ** if any.
30520 */
30521 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
30522 static int unixLogErrorAtLine(
30523  int errcode, /* SQLite error code */
30524  const char *zFunc, /* Name of OS function that failed */
30525  const char *zPath, /* File path associated with error */
30526  int iLine /* Source line number where error occurred */
30527 ){
30528  char *zErr; /* Message from strerror() or equivalent */
30529  int iErrno = errno; /* Saved syscall error number */
30530 
30531  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
30532  ** the strerror() function to obtain the human-readable error message
30533  ** equivalent to errno. Otherwise, use strerror_r().
30534  */
30535 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
30536  char aErr[80];
30537  memset(aErr, 0, sizeof(aErr));
30538  zErr = aErr;
30539 
30540  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
30541  ** assume that the system provides the GNU version of strerror_r() that
30542  ** returns a pointer to a buffer containing the error message. That pointer
30543  ** may point to aErr[], or it may point to some static storage somewhere.
30544  ** Otherwise, assume that the system provides the POSIX version of
30545  ** strerror_r(), which always writes an error message into aErr[].
30546  **
30547  ** If the code incorrectly assumes that it is the POSIX version that is
30548  ** available, the error message will often be an empty string. Not a
30549  ** huge problem. Incorrectly concluding that the GNU version is available
30550  ** could lead to a segfault though.
30551  */
30552 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
30553  zErr =
30554 # endif
30555  strerror_r(iErrno, aErr, sizeof(aErr)-1);
30556 
30557 #elif SQLITE_THREADSAFE
30558  /* This is a threadsafe build, but strerror_r() is not available. */
30559  zErr = "";
30560 #else
30561  /* Non-threadsafe build, use strerror(). */
30562  zErr = strerror(iErrno);
30563 #endif
30564 
30565  if( zPath==0 ) zPath = "";
30566  sqlite3_log(errcode,
30567  "os_unix.c:%d: (%d) %s(%s) - %s",
30568  iLine, iErrno, zFunc, zPath, zErr
30569  );
30570 
30571  return errcode;
30572 }
30573 
30574 /*
30575 ** Close a file descriptor.
30576 **
30577 ** We assume that close() almost always works, since it is only in a
30578 ** very sick application or on a very sick platform that it might fail.
30579 ** If it does fail, simply leak the file descriptor, but do log the
30580 ** error.
30581 **
30582 ** Note that it is not safe to retry close() after EINTR since the
30583 ** file descriptor might have already been reused by another thread.
30584 ** So we don't even try to recover from an EINTR. Just log the error
30585 ** and move on.
30586 */
30587 static void robust_close(unixFile *pFile, int h, int lineno){
30588  if( osClose(h) ){
30589  unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
30590  pFile ? pFile->zPath : 0, lineno);
30591  }
30592 }
30593 
30594 /*
30595 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
30596 ** a convenient place to set a breakpoint.
30597 */
30598 static void storeLastErrno(unixFile *pFile, int error){
30599  pFile->lastErrno = error;
30600 }
30601 
30602 /*
30603 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
30604 */
30605 static void closePendingFds(unixFile *pFile){
30606  unixInodeInfo *pInode = pFile->pInode;
30607  UnixUnusedFd *p;
30608  UnixUnusedFd *pNext;
30609  for(p=pInode->pUnused; p; p=pNext){
30610  pNext = p->pNext;
30611  robust_close(pFile, p->fd, __LINE__);
30612  sqlite3_free(p);
30613  }
30614  pInode->pUnused = 0;
30615 }
30616 
30617 /*
30618 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
30619 **
30620 ** The mutex entered using the unixEnterMutex() function must be held
30621 ** when this function is called.
30622 */
30623 static void releaseInodeInfo(unixFile *pFile){
30624  unixInodeInfo *pInode = pFile->pInode;
30625  assert( unixMutexHeld() );
30626  if( ALWAYS(pInode) ){
30627  pInode->nRef--;
30628  if( pInode->nRef==0 ){
30629  assert( pInode->pShmNode==0 );
30630  closePendingFds(pFile);
30631  if( pInode->pPrev ){
30632  assert( pInode->pPrev->pNext==pInode );
30633  pInode->pPrev->pNext = pInode->pNext;
30634  }else{
30635  assert( inodeList==pInode );
30636  inodeList = pInode->pNext;
30637  }
30638  if( pInode->pNext ){
30639  assert( pInode->pNext->pPrev==pInode );
30640  pInode->pNext->pPrev = pInode->pPrev;
30641  }
30642  sqlite3_free(pInode);
30643  }
30644  }
30645 }
30646 
30647 /*
30648 ** Given a file descriptor, locate the unixInodeInfo object that
30649 ** describes that file descriptor. Create a new one if necessary. The
30650 ** return value might be uninitialized if an error occurs.
30651 **
30652 ** The mutex entered using the unixEnterMutex() function must be held
30653 ** when this function is called.
30654 **
30655 ** Return an appropriate error code.
30656 */
30657 static int findInodeInfo(
30658  unixFile *pFile, /* Unix file with file desc used in the key */
30659  unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
30660 ){
30661  int rc; /* System call return code */
30662  int fd; /* The file descriptor for pFile */
30663  struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
30664  struct stat statbuf; /* Low-level file information */
30665  unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
30666 
30667  assert( unixMutexHeld() );
30668 
30669  /* Get low-level information about the file that we can used to
30670  ** create a unique name for the file.
30671  */
30672  fd = pFile->h;
30673  rc = osFstat(fd, &statbuf);
30674  if( rc!=0 ){
30675  storeLastErrno(pFile, errno);
30676 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
30677  if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
30678 #endif
30679  return SQLITE_IOERR;
30680  }
30681 
30682 #ifdef __APPLE__
30683  /* On OS X on an msdos filesystem, the inode number is reported
30684  ** incorrectly for zero-size files. See ticket #3260. To work
30685  ** around this problem (we consider it a bug in OS X, not SQLite)
30686  ** we always increase the file size to 1 by writing a single byte
30687  ** prior to accessing the inode number. The one byte written is
30688  ** an ASCII 'S' character which also happens to be the first byte
30689  ** in the header of every SQLite database. In this way, if there
30690  ** is a race condition such that another thread has already populated
30691  ** the first page of the database, no damage is done.
30692  */
30693  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
30694  do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
30695  if( rc!=1 ){
30696  storeLastErrno(pFile, errno);
30697  return SQLITE_IOERR;
30698  }
30699  rc = osFstat(fd, &statbuf);
30700  if( rc!=0 ){
30701  storeLastErrno(pFile, errno);
30702  return SQLITE_IOERR;
30703  }
30704  }
30705 #endif
30706 
30707  memset(&fileId, 0, sizeof(fileId));
30708  fileId.dev = statbuf.st_dev;
30709 #if OS_VXWORKS
30710  fileId.pId = pFile->pId;
30711 #else
30712  fileId.ino = statbuf.st_ino;
30713 #endif
30714  pInode = inodeList;
30715  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
30716  pInode = pInode->pNext;
30717  }
30718  if( pInode==0 ){
30719  pInode = sqlite3_malloc64( sizeof(*pInode) );
30720  if( pInode==0 ){
30721  return SQLITE_NOMEM_BKPT;
30722  }
30723  memset(pInode, 0, sizeof(*pInode));
30724  memcpy(&pInode->fileId, &fileId, sizeof(fileId));
30725  pInode->nRef = 1;
30726  pInode->pNext = inodeList;
30727  pInode->pPrev = 0;
30728  if( inodeList ) inodeList->pPrev = pInode;
30729  inodeList = pInode;
30730  }else{
30731  pInode->nRef++;
30732  }
30733  *ppInode = pInode;
30734  return SQLITE_OK;
30735 }
30736 
30737 /*
30738 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
30739 */
30740 static int fileHasMoved(unixFile *pFile){
30741 #if OS_VXWORKS
30742  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
30743 #else
30744  struct stat buf;
30745  return pFile->pInode!=0 &&
30746  (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
30747 #endif
30748 }
30749 
30750 
30751 /*
30752 ** Check a unixFile that is a database. Verify the following:
30753 **
30754 ** (1) There is exactly one hard link on the file
30755 ** (2) The file is not a symbolic link
30756 ** (3) The file has not been renamed or unlinked
30757 **
30758 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
30759 */
30760 static void verifyDbFile(unixFile *pFile){
30761  struct stat buf;
30762  int rc;
30763 
30764  /* These verifications occurs for the main database only */
30765  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
30766 
30767  rc = osFstat(pFile->h, &buf);
30768  if( rc!=0 ){
30769  sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
30770  return;
30771  }
30772  if( buf.st_nlink==0 ){
30773  sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
30774  return;
30775  }
30776  if( buf.st_nlink>1 ){
30777  sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
30778  return;
30779  }
30780  if( fileHasMoved(pFile) ){
30781  sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
30782  return;
30783  }
30784 }
30785 
30786 
30787 /*
30788 ** This routine checks if there is a RESERVED lock held on the specified
30789 ** file by this or any other process. If such a lock is held, set *pResOut
30790 ** to a non-zero value otherwise *pResOut is set to zero. The return value
30791 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30792 */
30793 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
30794  int rc = SQLITE_OK;
30795  int reserved = 0;
30796  unixFile *pFile = (unixFile*)id;
30797 
30798  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
30799 
30800  assert( pFile );
30801  assert( pFile->eFileLock<=SHARED_LOCK );
30802  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
30803 
30804  /* Check if a thread in this process holds such a lock */
30805  if( pFile->pInode->eFileLock>SHARED_LOCK ){
30806  reserved = 1;
30807  }
30808 
30809  /* Otherwise see if some other process holds it.
30810  */
30811 #ifndef __DJGPP__
30812  if( !reserved && !pFile->pInode->bProcessLock ){
30813  struct flock lock;
30814  lock.l_whence = SEEK_SET;
30815  lock.l_start = RESERVED_BYTE;
30816  lock.l_len = 1;
30817  lock.l_type = F_WRLCK;
30818  if( osFcntl(pFile->h, F_GETLK, &lock) ){
30819  rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
30820  storeLastErrno(pFile, errno);
30821  } else if( lock.l_type!=F_UNLCK ){
30822  reserved = 1;
30823  }
30824  }
30825 #endif
30826 
30827  unixLeaveMutex();
30828  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
30829 
30830  *pResOut = reserved;
30831  return rc;
30832 }
30833 
30834 /*
30835 ** Attempt to set a system-lock on the file pFile. The lock is
30836 ** described by pLock.
30837 **
30838 ** If the pFile was opened read/write from unix-excl, then the only lock
30839 ** ever obtained is an exclusive lock, and it is obtained exactly once
30840 ** the first time any lock is attempted. All subsequent system locking
30841 ** operations become no-ops. Locking operations still happen internally,
30842 ** in order to coordinate access between separate database connections
30843 ** within this process, but all of that is handled in memory and the
30844 ** operating system does not participate.
30845 **
30846 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
30847 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
30848 ** and is read-only.
30849 **
30850 ** Zero is returned if the call completes successfully, or -1 if a call
30851 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
30852 */
30853 static int unixFileLock(unixFile *pFile, struct flock *pLock){
30854  int rc;
30855  unixInodeInfo *pInode = pFile->pInode;
30856  assert( unixMutexHeld() );
30857  assert( pInode!=0 );
30858  if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
30859  if( pInode->bProcessLock==0 ){
30860  struct flock lock;
30861  assert( pInode->nLock==0 );
30862  lock.l_whence = SEEK_SET;
30863  lock.l_start = SHARED_FIRST;
30864  lock.l_len = SHARED_SIZE;
30865  lock.l_type = F_WRLCK;
30866  rc = osFcntl(pFile->h, F_SETLK, &lock);
30867  if( rc<0 ) return rc;
30868  pInode->bProcessLock = 1;
30869  pInode->nLock++;
30870  }else{
30871  rc = 0;
30872  }
30873  }else{
30874  rc = osFcntl(pFile->h, F_SETLK, pLock);
30875  }
30876  return rc;
30877 }
30878 
30879 /*
30880 ** Lock the file with the lock specified by parameter eFileLock - one
30881 ** of the following:
30882 **
30883 ** (1) SHARED_LOCK
30884 ** (2) RESERVED_LOCK
30885 ** (3) PENDING_LOCK
30886 ** (4) EXCLUSIVE_LOCK
30887 **
30888 ** Sometimes when requesting one lock state, additional lock states
30889 ** are inserted in between. The locking might fail on one of the later
30890 ** transitions leaving the lock state different from what it started but
30891 ** still short of its goal. The following chart shows the allowed
30892 ** transitions and the inserted intermediate states:
30893 **
30894 ** UNLOCKED -> SHARED
30895 ** SHARED -> RESERVED
30896 ** SHARED -> (PENDING) -> EXCLUSIVE
30897 ** RESERVED -> (PENDING) -> EXCLUSIVE
30898 ** PENDING -> EXCLUSIVE
30899 **
30900 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
30901 ** routine to lower a locking level.
30902 */
30903 static int unixLock(sqlite3_file *id, int eFileLock){
30904  /* The following describes the implementation of the various locks and
30905  ** lock transitions in terms of the POSIX advisory shared and exclusive
30906  ** lock primitives (called read-locks and write-locks below, to avoid
30907  ** confusion with SQLite lock names). The algorithms are complicated
30908  ** slightly in order to be compatible with Windows95 systems simultaneously
30909  ** accessing the same database file, in case that is ever required.
30910  **
30911  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
30912  ** byte', each single bytes at well known offsets, and the 'shared byte
30913  ** range', a range of 510 bytes at a well known offset.
30914  **
30915  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
30916  ** byte'. If this is successful, 'shared byte range' is read-locked
30917  ** and the lock on the 'pending byte' released. (Legacy note: When
30918  ** SQLite was first developed, Windows95 systems were still very common,
30919  ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
30920  ** single randomly selected by from the 'shared byte range' is locked.
30921  ** Windows95 is now pretty much extinct, but this work-around for the
30922  ** lack of shared-locks on Windows95 lives on, for backwards
30923  ** compatibility.)
30924  **
30925  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
30926  ** A RESERVED lock is implemented by grabbing a write-lock on the
30927  ** 'reserved byte'.
30928  **
30929  ** A process may only obtain a PENDING lock after it has obtained a
30930  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
30931  ** on the 'pending byte'. This ensures that no new SHARED locks can be
30932  ** obtained, but existing SHARED locks are allowed to persist. A process
30933  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
30934  ** This property is used by the algorithm for rolling back a journal file
30935  ** after a crash.
30936  **
30937  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
30938  ** implemented by obtaining a write-lock on the entire 'shared byte
30939  ** range'. Since all other locks require a read-lock on one of the bytes
30940  ** within this range, this ensures that no other locks are held on the
30941  ** database.
30942  */
30943  int rc = SQLITE_OK;
30944  unixFile *pFile = (unixFile*)id;
30945  unixInodeInfo *pInode;
30946  struct flock lock;
30947  int tErrno = 0;
30948 
30949  assert( pFile );
30950  OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
30951  azFileLock(eFileLock), azFileLock(pFile->eFileLock),
30952  azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
30953  osGetpid(0)));
30954 
30955  /* If there is already a lock of this type or more restrictive on the
30956  ** unixFile, do nothing. Don't use the end_lock: exit path, as
30957  ** unixEnterMutex() hasn't been called yet.
30958  */
30959  if( pFile->eFileLock>=eFileLock ){
30960  OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
30961  azFileLock(eFileLock)));
30962  return SQLITE_OK;
30963  }
30964 
30965  /* Make sure the locking sequence is correct.
30966  ** (1) We never move from unlocked to anything higher than shared lock.
30967  ** (2) SQLite never explicitly requests a pendig lock.
30968  ** (3) A shared lock is always held when a reserve lock is requested.
30969  */
30970  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
30971  assert( eFileLock!=PENDING_LOCK );
30972  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
30973 
30974  /* This mutex is needed because pFile->pInode is shared across threads
30975  */
30976  unixEnterMutex();
30977  pInode = pFile->pInode;
30978 
30979  /* If some thread using this PID has a lock via a different unixFile*
30980  ** handle that precludes the requested lock, return BUSY.
30981  */
30982  if( (pFile->eFileLock!=pInode->eFileLock &&
30983  (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
30984  ){
30985  rc = SQLITE_BUSY;
30986  goto end_lock;
30987  }
30988 
30989  /* If a SHARED lock is requested, and some thread using this PID already
30990  ** has a SHARED or RESERVED lock, then increment reference counts and
30991  ** return SQLITE_OK.
30992  */
30993  if( eFileLock==SHARED_LOCK &&
30994  (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
30995  assert( eFileLock==SHARED_LOCK );
30996  assert( pFile->eFileLock==0 );
30997  assert( pInode->nShared>0 );
30998  pFile->eFileLock = SHARED_LOCK;
30999  pInode->nShared++;
31000  pInode->nLock++;
31001  goto end_lock;
31002  }
31003 
31004 
31005  /* A PENDING lock is needed before acquiring a SHARED lock and before
31006  ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
31007  ** be released.
31008  */
31009  lock.l_len = 1L;
31010  lock.l_whence = SEEK_SET;
31011  if( eFileLock==SHARED_LOCK
31012  || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
31013  ){
31014  lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
31015  lock.l_start = PENDING_BYTE;
31016  if( unixFileLock(pFile, &lock) ){
31017  tErrno = errno;
31018  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31019  if( rc!=SQLITE_BUSY ){
31020  storeLastErrno(pFile, tErrno);
31021  }
31022  goto end_lock;
31023  }
31024  }
31025 
31026 
31027  /* If control gets to this point, then actually go ahead and make
31028  ** operating system calls for the specified lock.
31029  */
31030  if( eFileLock==SHARED_LOCK ){
31031  assert( pInode->nShared==0 );
31032  assert( pInode->eFileLock==0 );
31033  assert( rc==SQLITE_OK );
31034 
31035  /* Now get the read-lock */
31036  lock.l_start = SHARED_FIRST;
31037  lock.l_len = SHARED_SIZE;
31038  if( unixFileLock(pFile, &lock) ){
31039  tErrno = errno;
31040  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31041  }
31042 
31043  /* Drop the temporary PENDING lock */
31044  lock.l_start = PENDING_BYTE;
31045  lock.l_len = 1L;
31046  lock.l_type = F_UNLCK;
31047  if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
31048  /* This could happen with a network mount */
31049  tErrno = errno;
31050  rc = SQLITE_IOERR_UNLOCK;
31051  }
31052 
31053  if( rc ){
31054  if( rc!=SQLITE_BUSY ){
31055  storeLastErrno(pFile, tErrno);
31056  }
31057  goto end_lock;
31058  }else{
31059  pFile->eFileLock = SHARED_LOCK;
31060  pInode->nLock++;
31061  pInode->nShared = 1;
31062  }
31063  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
31064  /* We are trying for an exclusive lock but another thread in this
31065  ** same process is still holding a shared lock. */
31066  rc = SQLITE_BUSY;
31067  }else{
31068  /* The request was for a RESERVED or EXCLUSIVE lock. It is
31069  ** assumed that there is a SHARED or greater lock on the file
31070  ** already.
31071  */
31072  assert( 0!=pFile->eFileLock );
31073  lock.l_type = F_WRLCK;
31074 
31075  assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
31076  if( eFileLock==RESERVED_LOCK ){
31077  lock.l_start = RESERVED_BYTE;
31078  lock.l_len = 1L;
31079  }else{
31080  lock.l_start = SHARED_FIRST;
31081  lock.l_len = SHARED_SIZE;
31082  }
31083 
31084  if( unixFileLock(pFile, &lock) ){
31085  tErrno = errno;
31086  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31087  if( rc!=SQLITE_BUSY ){
31088  storeLastErrno(pFile, tErrno);
31089  }
31090  }
31091  }
31092 
31093 
31094 #ifdef SQLITE_DEBUG
31095  /* Set up the transaction-counter change checking flags when
31096  ** transitioning from a SHARED to a RESERVED lock. The change
31097  ** from SHARED to RESERVED marks the beginning of a normal
31098  ** write operation (not a hot journal rollback).
31099  */
31100  if( rc==SQLITE_OK
31101  && pFile->eFileLock<=SHARED_LOCK
31102  && eFileLock==RESERVED_LOCK
31103  ){
31104  pFile->transCntrChng = 0;
31105  pFile->dbUpdate = 0;
31106  pFile->inNormalWrite = 1;
31107  }
31108 #endif
31109 
31110 
31111  if( rc==SQLITE_OK ){
31112  pFile->eFileLock = eFileLock;
31113  pInode->eFileLock = eFileLock;
31114  }else if( eFileLock==EXCLUSIVE_LOCK ){
31115  pFile->eFileLock = PENDING_LOCK;
31116  pInode->eFileLock = PENDING_LOCK;
31117  }
31118 
31119 end_lock:
31120  unixLeaveMutex();
31121  OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
31122  rc==SQLITE_OK ? "ok" : "failed"));
31123  return rc;
31124 }
31125 
31126 /*
31127 ** Add the file descriptor used by file handle pFile to the corresponding
31128 ** pUnused list.
31129 */
31130 static void setPendingFd(unixFile *pFile){
31131  unixInodeInfo *pInode = pFile->pInode;
31132  UnixUnusedFd *p = pFile->pUnused;
31133  p->pNext = pInode->pUnused;
31134  pInode->pUnused = p;
31135  pFile->h = -1;
31136  pFile->pUnused = 0;
31137 }
31138 
31139 /*
31140 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31141 ** must be either NO_LOCK or SHARED_LOCK.
31142 **
31143 ** If the locking level of the file descriptor is already at or below
31144 ** the requested locking level, this routine is a no-op.
31145 **
31146 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
31147 ** the byte range is divided into 2 parts and the first part is unlocked then
31148 ** set to a read lock, then the other part is simply unlocked. This works
31149 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
31150 ** remove the write lock on a region when a read lock is set.
31151 */
31152 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
31153  unixFile *pFile = (unixFile*)id;
31154  unixInodeInfo *pInode;
31155  struct flock lock;
31156  int rc = SQLITE_OK;
31157 
31158  assert( pFile );
31159  OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
31160  pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
31161  osGetpid(0)));
31162 
31163  assert( eFileLock<=SHARED_LOCK );
31164  if( pFile->eFileLock<=eFileLock ){
31165  return SQLITE_OK;
31166  }
31167  unixEnterMutex();
31168  pInode = pFile->pInode;
31169  assert( pInode->nShared!=0 );
31170  if( pFile->eFileLock>SHARED_LOCK ){
31171  assert( pInode->eFileLock==pFile->eFileLock );
31172 
31173 #ifdef SQLITE_DEBUG
31174  /* When reducing a lock such that other processes can start
31175  ** reading the database file again, make sure that the
31176  ** transaction counter was updated if any part of the database
31177  ** file changed. If the transaction counter is not updated,
31178  ** other connections to the same file might not realize that
31179  ** the file has changed and hence might not know to flush their
31180  ** cache. The use of a stale cache can lead to database corruption.
31181  */
31182  pFile->inNormalWrite = 0;
31183 #endif
31184 
31185  /* downgrading to a shared lock on NFS involves clearing the write lock
31186  ** before establishing the readlock - to avoid a race condition we downgrade
31187  ** the lock in 2 blocks, so that part of the range will be covered by a
31188  ** write lock until the rest is covered by a read lock:
31189  ** 1: [WWWWW]
31190  ** 2: [....W]
31191  ** 3: [RRRRW]
31192  ** 4: [RRRR.]
31193  */
31194  if( eFileLock==SHARED_LOCK ){
31195 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
31196  (void)handleNFSUnlock;
31197  assert( handleNFSUnlock==0 );
31198 #endif
31199 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31200  if( handleNFSUnlock ){
31201  int tErrno; /* Error code from system call errors */
31202  off_t divSize = SHARED_SIZE - 1;
31203 
31204  lock.l_type = F_UNLCK;
31205  lock.l_whence = SEEK_SET;
31206  lock.l_start = SHARED_FIRST;
31207  lock.l_len = divSize;
31208  if( unixFileLock(pFile, &lock)==(-1) ){
31209  tErrno = errno;
31210  rc = SQLITE_IOERR_UNLOCK;
31211  storeLastErrno(pFile, tErrno);
31212  goto end_unlock;
31213  }
31214  lock.l_type = F_RDLCK;
31215  lock.l_whence = SEEK_SET;
31216  lock.l_start = SHARED_FIRST;
31217  lock.l_len = divSize;
31218  if( unixFileLock(pFile, &lock)==(-1) ){
31219  tErrno = errno;
31220  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
31221  if( IS_LOCK_ERROR(rc) ){
31222  storeLastErrno(pFile, tErrno);
31223  }
31224  goto end_unlock;
31225  }
31226  lock.l_type = F_UNLCK;
31227  lock.l_whence = SEEK_SET;
31228  lock.l_start = SHARED_FIRST+divSize;
31229  lock.l_len = SHARED_SIZE-divSize;
31230  if( unixFileLock(pFile, &lock)==(-1) ){
31231  tErrno = errno;
31232  rc = SQLITE_IOERR_UNLOCK;
31233  storeLastErrno(pFile, tErrno);
31234  goto end_unlock;
31235  }
31236  }else
31237 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31238  {
31239  lock.l_type = F_RDLCK;
31240  lock.l_whence = SEEK_SET;
31241  lock.l_start = SHARED_FIRST;
31242  lock.l_len = SHARED_SIZE;
31243  if( unixFileLock(pFile, &lock) ){
31244  /* In theory, the call to unixFileLock() cannot fail because another
31245  ** process is holding an incompatible lock. If it does, this
31246  ** indicates that the other process is not following the locking
31247  ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
31248  ** SQLITE_BUSY would confuse the upper layer (in practice it causes
31249  ** an assert to fail). */
31250  rc = SQLITE_IOERR_RDLOCK;
31251  storeLastErrno(pFile, errno);
31252  goto end_unlock;
31253  }
31254  }
31255  }
31256  lock.l_type = F_UNLCK;
31257  lock.l_whence = SEEK_SET;
31258  lock.l_start = PENDING_BYTE;
31259  lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
31260  if( unixFileLock(pFile, &lock)==0 ){
31261  pInode->eFileLock = SHARED_LOCK;
31262  }else{
31263  rc = SQLITE_IOERR_UNLOCK;
31264  storeLastErrno(pFile, errno);
31265  goto end_unlock;
31266  }
31267  }
31268  if( eFileLock==NO_LOCK ){
31269  /* Decrement the shared lock counter. Release the lock using an
31270  ** OS call only when all threads in this same process have released
31271  ** the lock.
31272  */
31273  pInode->nShared--;
31274  if( pInode->nShared==0 ){
31275  lock.l_type = F_UNLCK;
31276  lock.l_whence = SEEK_SET;
31277  lock.l_start = lock.l_len = 0L;
31278  if( unixFileLock(pFile, &lock)==0 ){
31279  pInode->eFileLock = NO_LOCK;
31280  }else{
31281  rc = SQLITE_IOERR_UNLOCK;
31282  storeLastErrno(pFile, errno);
31283  pInode->eFileLock = NO_LOCK;
31284  pFile->eFileLock = NO_LOCK;
31285  }
31286  }
31287 
31288  /* Decrement the count of locks against this same file. When the
31289  ** count reaches zero, close any other file descriptors whose close
31290  ** was deferred because of outstanding locks.
31291  */
31292  pInode->nLock--;
31293  assert( pInode->nLock>=0 );
31294  if( pInode->nLock==0 ){
31295  closePendingFds(pFile);
31296  }
31297  }
31298 
31299 end_unlock:
31300  unixLeaveMutex();
31301  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
31302  return rc;
31303 }
31304 
31305 /*
31306 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31307 ** must be either NO_LOCK or SHARED_LOCK.
31308 **
31309 ** If the locking level of the file descriptor is already at or below
31310 ** the requested locking level, this routine is a no-op.
31311 */
31312 static int unixUnlock(sqlite3_file *id, int eFileLock){
31313 #if SQLITE_MAX_MMAP_SIZE>0
31314  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
31315 #endif
31316  return posixUnlock(id, eFileLock, 0);
31317 }
31318 
31319 #if SQLITE_MAX_MMAP_SIZE>0
31320 static int unixMapfile(unixFile *pFd, i64 nByte);
31321 static void unixUnmapfile(unixFile *pFd);
31322 #endif
31323 
31324 /*
31325 ** This function performs the parts of the "close file" operation
31326 ** common to all locking schemes. It closes the directory and file
31327 ** handles, if they are valid, and sets all fields of the unixFile
31328 ** structure to 0.
31329 **
31330 ** It is *not* necessary to hold the mutex when this routine is called,
31331 ** even on VxWorks. A mutex will be acquired on VxWorks by the
31332 ** vxworksReleaseFileId() routine.
31333 */
31334 static int closeUnixFile(sqlite3_file *id){
31335  unixFile *pFile = (unixFile*)id;
31336 #if SQLITE_MAX_MMAP_SIZE>0
31337  unixUnmapfile(pFile);
31338 #endif
31339  if( pFile->h>=0 ){
31340  robust_close(pFile, pFile->h, __LINE__);
31341  pFile->h = -1;
31342  }
31343 #if OS_VXWORKS
31344  if( pFile->pId ){
31345  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31346  osUnlink(pFile->pId->zCanonicalName);
31347  }
31348  vxworksReleaseFileId(pFile->pId);
31349  pFile->pId = 0;
31350  }
31351 #endif
31352 #ifdef SQLITE_UNLINK_AFTER_CLOSE
31353  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31354  osUnlink(pFile->zPath);
31355  sqlite3_free(*(char**)&pFile->zPath);
31356  pFile->zPath = 0;
31357  }
31358 #endif
31359  OSTRACE(("CLOSE %-3d\n", pFile->h));
31360  OpenCounter(-1);
31361  sqlite3_free(pFile->pUnused);
31362  memset(pFile, 0, sizeof(unixFile));
31363  return SQLITE_OK;
31364 }
31365 
31366 /*
31367 ** Close a file.
31368 */
31369 static int unixClose(sqlite3_file *id){
31370  int rc = SQLITE_OK;
31371  unixFile *pFile = (unixFile *)id;
31372  verifyDbFile(pFile);
31373  unixUnlock(id, NO_LOCK);
31374  unixEnterMutex();
31375 
31376  /* unixFile.pInode is always valid here. Otherwise, a different close
31377  ** routine (e.g. nolockClose()) would be called instead.
31378  */
31379  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
31380  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
31381  /* If there are outstanding locks, do not actually close the file just
31382  ** yet because that would clear those locks. Instead, add the file
31383  ** descriptor to pInode->pUnused list. It will be automatically closed
31384  ** when the last lock is cleared.
31385  */
31386  setPendingFd(pFile);
31387  }
31388  releaseInodeInfo(pFile);
31389  rc = closeUnixFile(id);
31390  unixLeaveMutex();
31391  return rc;
31392 }
31393 
31394 /************** End of the posix advisory lock implementation *****************
31395 ******************************************************************************/
31396 
31397 /******************************************************************************
31398 ****************************** No-op Locking **********************************
31399 **
31400 ** Of the various locking implementations available, this is by far the
31401 ** simplest: locking is ignored. No attempt is made to lock the database
31402 ** file for reading or writing.
31403 **
31404 ** This locking mode is appropriate for use on read-only databases
31405 ** (ex: databases that are burned into CD-ROM, for example.) It can
31406 ** also be used if the application employs some external mechanism to
31407 ** prevent simultaneous access of the same database by two or more
31408 ** database connections. But there is a serious risk of database
31409 ** corruption if this locking mode is used in situations where multiple
31410 ** database connections are accessing the same database file at the same
31411 ** time and one or more of those connections are writing.
31412 */
31413 
31414 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
31415  UNUSED_PARAMETER(NotUsed);
31416  *pResOut = 0;
31417  return SQLITE_OK;
31418 }
31419 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
31420  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31421  return SQLITE_OK;
31422 }
31423 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
31424  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31425  return SQLITE_OK;
31426 }
31427 
31428 /*
31429 ** Close the file.
31430 */
31431 static int nolockClose(sqlite3_file *id) {
31432  return closeUnixFile(id);
31433 }
31434 
31435 /******************* End of the no-op lock implementation *********************
31436 ******************************************************************************/
31437 
31438 /******************************************************************************
31439 ************************* Begin dot-file Locking ******************************
31440 **
31441 ** The dotfile locking implementation uses the existence of separate lock
31442 ** files (really a directory) to control access to the database. This works
31443 ** on just about every filesystem imaginable. But there are serious downsides:
31444 **
31445 ** (1) There is zero concurrency. A single reader blocks all other
31446 ** connections from reading or writing the database.
31447 **
31448 ** (2) An application crash or power loss can leave stale lock files
31449 ** sitting around that need to be cleared manually.
31450 **
31451 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
31452 ** other locking strategy is available.
31453 **
31454 ** Dotfile locking works by creating a subdirectory in the same directory as
31455 ** the database and with the same name but with a ".lock" extension added.
31456 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
31457 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
31458 */
31459 
31460 /*
31461 ** The file suffix added to the data base filename in order to create the
31462 ** lock directory.
31463 */
31464 #define DOTLOCK_SUFFIX ".lock"
31465 
31466 /*
31467 ** This routine checks if there is a RESERVED lock held on the specified
31468 ** file by this or any other process. If such a lock is held, set *pResOut
31469 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31470 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31471 **
31472 ** In dotfile locking, either a lock exists or it does not. So in this
31473 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
31474 ** is held on the file and false if the file is unlocked.
31475 */
31476 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
31477  int rc = SQLITE_OK;
31478  int reserved = 0;
31479  unixFile *pFile = (unixFile*)id;
31480 
31481  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31482 
31483  assert( pFile );
31484  reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
31485  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
31486  *pResOut = reserved;
31487  return rc;
31488 }
31489 
31490 /*
31491 ** Lock the file with the lock specified by parameter eFileLock - one
31492 ** of the following:
31493 **
31494 ** (1) SHARED_LOCK
31495 ** (2) RESERVED_LOCK
31496 ** (3) PENDING_LOCK
31497 ** (4) EXCLUSIVE_LOCK
31498 **
31499 ** Sometimes when requesting one lock state, additional lock states
31500 ** are inserted in between. The locking might fail on one of the later
31501 ** transitions leaving the lock state different from what it started but
31502 ** still short of its goal. The following chart shows the allowed
31503 ** transitions and the inserted intermediate states:
31504 **
31505 ** UNLOCKED -> SHARED
31506 ** SHARED -> RESERVED
31507 ** SHARED -> (PENDING) -> EXCLUSIVE
31508 ** RESERVED -> (PENDING) -> EXCLUSIVE
31509 ** PENDING -> EXCLUSIVE
31510 **
31511 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31512 ** routine to lower a locking level.
31513 **
31514 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
31515 ** But we track the other locking levels internally.
31516 */
31517 static int dotlockLock(sqlite3_file *id, int eFileLock) {
31518  unixFile *pFile = (unixFile*)id;
31519  char *zLockFile = (char *)pFile->lockingContext;
31520  int rc = SQLITE_OK;
31521 
31522 
31523  /* If we have any lock, then the lock file already exists. All we have
31524  ** to do is adjust our internal record of the lock level.
31525  */
31526  if( pFile->eFileLock > NO_LOCK ){
31527  pFile->eFileLock = eFileLock;
31528  /* Always update the timestamp on the old file */
31529 #ifdef HAVE_UTIME
31530  utime(zLockFile, NULL);
31531 #else
31532  utimes(zLockFile, NULL);
31533 #endif
31534  return SQLITE_OK;
31535  }
31536 
31537  /* grab an exclusive lock */
31538  rc = osMkdir(zLockFile, 0777);
31539  if( rc<0 ){
31540  /* failed to open/create the lock directory */
31541  int tErrno = errno;
31542  if( EEXIST == tErrno ){
31543  rc = SQLITE_BUSY;
31544  } else {
31545  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31546  if( rc!=SQLITE_BUSY ){
31547  storeLastErrno(pFile, tErrno);
31548  }
31549  }
31550  return rc;
31551  }
31552 
31553  /* got it, set the type and return ok */
31554  pFile->eFileLock = eFileLock;
31555  return rc;
31556 }
31557 
31558 /*
31559 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31560 ** must be either NO_LOCK or SHARED_LOCK.
31561 **
31562 ** If the locking level of the file descriptor is already at or below
31563 ** the requested locking level, this routine is a no-op.
31564 **
31565 ** When the locking level reaches NO_LOCK, delete the lock file.
31566 */
31567 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
31568  unixFile *pFile = (unixFile*)id;
31569  char *zLockFile = (char *)pFile->lockingContext;
31570  int rc;
31571 
31572  assert( pFile );
31573  OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
31574  pFile->eFileLock, osGetpid(0)));
31575  assert( eFileLock<=SHARED_LOCK );
31576 
31577  /* no-op if possible */
31578  if( pFile->eFileLock==eFileLock ){
31579  return SQLITE_OK;
31580  }
31581 
31582  /* To downgrade to shared, simply update our internal notion of the
31583  ** lock state. No need to mess with the file on disk.
31584  */
31585  if( eFileLock==SHARED_LOCK ){
31586  pFile->eFileLock = SHARED_LOCK;
31587  return SQLITE_OK;
31588  }
31589 
31590  /* To fully unlock the database, delete the lock file */
31591  assert( eFileLock==NO_LOCK );
31592  rc = osRmdir(zLockFile);
31593  if( rc<0 ){
31594  int tErrno = errno;
31595  if( tErrno==ENOENT ){
31596  rc = SQLITE_OK;
31597  }else{
31598  rc = SQLITE_IOERR_UNLOCK;
31599  storeLastErrno(pFile, tErrno);
31600  }
31601  return rc;
31602  }
31603  pFile->eFileLock = NO_LOCK;
31604  return SQLITE_OK;
31605 }
31606 
31607 /*
31608 ** Close a file. Make sure the lock has been released before closing.
31609 */
31610 static int dotlockClose(sqlite3_file *id) {
31611  unixFile *pFile = (unixFile*)id;
31612  assert( id!=0 );
31613  dotlockUnlock(id, NO_LOCK);
31614  sqlite3_free(pFile->lockingContext);
31615  return closeUnixFile(id);
31616 }
31617 /****************** End of the dot-file lock implementation *******************
31618 ******************************************************************************/
31619 
31620 /******************************************************************************
31621 ************************** Begin flock Locking ********************************
31622 **
31623 ** Use the flock() system call to do file locking.
31624 **
31625 ** flock() locking is like dot-file locking in that the various
31626 ** fine-grain locking levels supported by SQLite are collapsed into
31627 ** a single exclusive lock. In other words, SHARED, RESERVED, and
31628 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
31629 ** still works when you do this, but concurrency is reduced since
31630 ** only a single process can be reading the database at a time.
31631 **
31632 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
31633 */
31634 #if SQLITE_ENABLE_LOCKING_STYLE
31635 
31636 /*
31637 ** Retry flock() calls that fail with EINTR
31638 */
31639 #ifdef EINTR
31640 static int robust_flock(int fd, int op){
31641  int rc;
31642  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
31643  return rc;
31644 }
31645 #else
31646 # define robust_flock(a,b) flock(a,b)
31647 #endif
31648 
31649 
31650 /*
31651 ** This routine checks if there is a RESERVED lock held on the specified
31652 ** file by this or any other process. If such a lock is held, set *pResOut
31653 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31654 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31655 */
31656 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
31657  int rc = SQLITE_OK;
31658  int reserved = 0;
31659  unixFile *pFile = (unixFile*)id;
31660 
31661  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31662 
31663  assert( pFile );
31664 
31665  /* Check if a thread in this process holds such a lock */
31666  if( pFile->eFileLock>SHARED_LOCK ){
31667  reserved = 1;
31668  }
31669 
31670  /* Otherwise see if some other process holds it. */
31671  if( !reserved ){
31672  /* attempt to get the lock */
31673  int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
31674  if( !lrc ){
31675  /* got the lock, unlock it */
31676  lrc = robust_flock(pFile->h, LOCK_UN);
31677  if ( lrc ) {
31678  int tErrno = errno;
31679  /* unlock failed with an error */
31680  lrc = SQLITE_IOERR_UNLOCK;
31681  storeLastErrno(pFile, tErrno);
31682  rc = lrc;
31683  }
31684  } else {
31685  int tErrno = errno;
31686  reserved = 1;
31687  /* someone else might have it reserved */
31688  lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31689  if( IS_LOCK_ERROR(lrc) ){
31690  storeLastErrno(pFile, tErrno);
31691  rc = lrc;
31692  }
31693  }
31694  }
31695  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
31696 
31697 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31698  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31699  rc = SQLITE_OK;
31700  reserved=1;
31701  }
31702 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31703  *pResOut = reserved;
31704  return rc;
31705 }
31706 
31707 /*
31708 ** Lock the file with the lock specified by parameter eFileLock - one
31709 ** of the following:
31710 **
31711 ** (1) SHARED_LOCK
31712 ** (2) RESERVED_LOCK
31713 ** (3) PENDING_LOCK
31714 ** (4) EXCLUSIVE_LOCK
31715 **
31716 ** Sometimes when requesting one lock state, additional lock states
31717 ** are inserted in between. The locking might fail on one of the later
31718 ** transitions leaving the lock state different from what it started but
31719 ** still short of its goal. The following chart shows the allowed
31720 ** transitions and the inserted intermediate states:
31721 **
31722 ** UNLOCKED -> SHARED
31723 ** SHARED -> RESERVED
31724 ** SHARED -> (PENDING) -> EXCLUSIVE
31725 ** RESERVED -> (PENDING) -> EXCLUSIVE
31726 ** PENDING -> EXCLUSIVE
31727 **
31728 ** flock() only really support EXCLUSIVE locks. We track intermediate
31729 ** lock states in the sqlite3_file structure, but all locks SHARED or
31730 ** above are really EXCLUSIVE locks and exclude all other processes from
31731 ** access the file.
31732 **
31733 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31734 ** routine to lower a locking level.
31735 */
31736 static int flockLock(sqlite3_file *id, int eFileLock) {
31737  int rc = SQLITE_OK;
31738  unixFile *pFile = (unixFile*)id;
31739 
31740  assert( pFile );
31741 
31742  /* if we already have a lock, it is exclusive.
31743  ** Just adjust level and punt on outta here. */
31744  if (pFile->eFileLock > NO_LOCK) {
31745  pFile->eFileLock = eFileLock;
31746  return SQLITE_OK;
31747  }
31748 
31749  /* grab an exclusive lock */
31750 
31751  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
31752  int tErrno = errno;
31753  /* didn't get, must be busy */
31754  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31755  if( IS_LOCK_ERROR(rc) ){
31756  storeLastErrno(pFile, tErrno);
31757  }
31758  } else {
31759  /* got it, set the type and return ok */
31760  pFile->eFileLock = eFileLock;
31761  }
31762  OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
31763  rc==SQLITE_OK ? "ok" : "failed"));
31764 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31765  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31766  rc = SQLITE_BUSY;
31767  }
31768 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31769  return rc;
31770 }
31771 
31772 
31773 /*
31774 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31775 ** must be either NO_LOCK or SHARED_LOCK.
31776 **
31777 ** If the locking level of the file descriptor is already at or below
31778 ** the requested locking level, this routine is a no-op.
31779 */
31780 static int flockUnlock(sqlite3_file *id, int eFileLock) {
31781  unixFile *pFile = (unixFile*)id;
31782 
31783  assert( pFile );
31784  OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
31785  pFile->eFileLock, osGetpid(0)));
31786  assert( eFileLock<=SHARED_LOCK );
31787 
31788  /* no-op if possible */
31789  if( pFile->eFileLock==eFileLock ){
31790  return SQLITE_OK;
31791  }
31792 
31793  /* shared can just be set because we always have an exclusive */
31794  if (eFileLock==SHARED_LOCK) {
31795  pFile->eFileLock = eFileLock;
31796  return SQLITE_OK;
31797  }
31798 
31799  /* no, really, unlock. */
31800  if( robust_flock(pFile->h, LOCK_UN) ){
31801 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31802  return SQLITE_OK;
31803 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31804  return SQLITE_IOERR_UNLOCK;
31805  }else{
31806  pFile->eFileLock = NO_LOCK;
31807  return SQLITE_OK;
31808  }
31809 }
31810 
31811 /*
31812 ** Close a file.
31813 */
31814 static int flockClose(sqlite3_file *id) {
31815  assert( id!=0 );
31816  flockUnlock(id, NO_LOCK);
31817  return closeUnixFile(id);
31818 }
31819 
31820 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
31821 
31822 /******************* End of the flock lock implementation *********************
31823 ******************************************************************************/
31824 
31825 /******************************************************************************
31826 ************************ Begin Named Semaphore Locking ************************
31827 **
31828 ** Named semaphore locking is only supported on VxWorks.
31829 **
31830 ** Semaphore locking is like dot-lock and flock in that it really only
31831 ** supports EXCLUSIVE locking. Only a single process can read or write
31832 ** the database file at a time. This reduces potential concurrency, but
31833 ** makes the lock implementation much easier.
31834 */
31835 #if OS_VXWORKS
31836 
31837 /*
31838 ** This routine checks if there is a RESERVED lock held on the specified
31839 ** file by this or any other process. If such a lock is held, set *pResOut
31840 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31841 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31842 */
31843 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
31844  int rc = SQLITE_OK;
31845  int reserved = 0;
31846  unixFile *pFile = (unixFile*)id;
31847 
31848  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31849 
31850  assert( pFile );
31851 
31852  /* Check if a thread in this process holds such a lock */
31853  if( pFile->eFileLock>SHARED_LOCK ){
31854  reserved = 1;
31855  }
31856 
31857  /* Otherwise see if some other process holds it. */
31858  if( !reserved ){
31859  sem_t *pSem = pFile->pInode->pSem;
31860 
31861  if( sem_trywait(pSem)==-1 ){
31862  int tErrno = errno;
31863  if( EAGAIN != tErrno ){
31864  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
31865  storeLastErrno(pFile, tErrno);
31866  } else {
31867  /* someone else has the lock when we are in NO_LOCK */
31868  reserved = (pFile->eFileLock < SHARED_LOCK);
31869  }
31870  }else{
31871  /* we could have it if we want it */
31872  sem_post(pSem);
31873  }
31874  }
31875  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
31876 
31877  *pResOut = reserved;
31878  return rc;
31879 }
31880 
31881 /*
31882 ** Lock the file with the lock specified by parameter eFileLock - one
31883 ** of the following:
31884 **
31885 ** (1) SHARED_LOCK
31886 ** (2) RESERVED_LOCK
31887 ** (3) PENDING_LOCK
31888 ** (4) EXCLUSIVE_LOCK
31889 **
31890 ** Sometimes when requesting one lock state, additional lock states
31891 ** are inserted in between. The locking might fail on one of the later
31892 ** transitions leaving the lock state different from what it started but
31893 ** still short of its goal. The following chart shows the allowed
31894 ** transitions and the inserted intermediate states:
31895 **
31896 ** UNLOCKED -> SHARED
31897 ** SHARED -> RESERVED
31898 ** SHARED -> (PENDING) -> EXCLUSIVE
31899 ** RESERVED -> (PENDING) -> EXCLUSIVE
31900 ** PENDING -> EXCLUSIVE
31901 **
31902 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
31903 ** lock states in the sqlite3_file structure, but all locks SHARED or
31904 ** above are really EXCLUSIVE locks and exclude all other processes from
31905 ** access the file.
31906 **
31907 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31908 ** routine to lower a locking level.
31909 */
31910 static int semXLock(sqlite3_file *id, int eFileLock) {
31911  unixFile *pFile = (unixFile*)id;
31912  sem_t *pSem = pFile->pInode->pSem;
31913  int rc = SQLITE_OK;
31914 
31915  /* if we already have a lock, it is exclusive.
31916  ** Just adjust level and punt on outta here. */
31917  if (pFile->eFileLock > NO_LOCK) {
31918  pFile->eFileLock = eFileLock;
31919  rc = SQLITE_OK;
31920  goto sem_end_lock;
31921  }
31922 
31923  /* lock semaphore now but bail out when already locked. */
31924  if( sem_trywait(pSem)==-1 ){
31925  rc = SQLITE_BUSY;
31926  goto sem_end_lock;
31927  }
31928 
31929  /* got it, set the type and return ok */
31930  pFile->eFileLock = eFileLock;
31931 
31932  sem_end_lock:
31933  return rc;
31934 }
31935 
31936 /*
31937 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31938 ** must be either NO_LOCK or SHARED_LOCK.
31939 **
31940 ** If the locking level of the file descriptor is already at or below
31941 ** the requested locking level, this routine is a no-op.
31942 */
31943 static int semXUnlock(sqlite3_file *id, int eFileLock) {
31944  unixFile *pFile = (unixFile*)id;
31945  sem_t *pSem = pFile->pInode->pSem;
31946 
31947  assert( pFile );
31948  assert( pSem );
31949  OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
31950  pFile->eFileLock, osGetpid(0)));
31951  assert( eFileLock<=SHARED_LOCK );
31952 
31953  /* no-op if possible */
31954  if( pFile->eFileLock==eFileLock ){
31955  return SQLITE_OK;
31956  }
31957 
31958  /* shared can just be set because we always have an exclusive */
31959  if (eFileLock==SHARED_LOCK) {
31960  pFile->eFileLock = eFileLock;
31961  return SQLITE_OK;
31962  }
31963 
31964  /* no, really unlock. */
31965  if ( sem_post(pSem)==-1 ) {
31966  int rc, tErrno = errno;
31967  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
31968  if( IS_LOCK_ERROR(rc) ){
31969  storeLastErrno(pFile, tErrno);
31970  }
31971  return rc;
31972  }
31973  pFile->eFileLock = NO_LOCK;
31974  return SQLITE_OK;
31975 }
31976 
31977 /*
31978  ** Close a file.
31979  */
31980 static int semXClose(sqlite3_file *id) {
31981  if( id ){
31982  unixFile *pFile = (unixFile*)id;
31983  semXUnlock(id, NO_LOCK);
31984  assert( pFile );
31985  unixEnterMutex();
31986  releaseInodeInfo(pFile);
31987  unixLeaveMutex();
31988  closeUnixFile(id);
31989  }
31990  return SQLITE_OK;
31991 }
31992 
31993 #endif /* OS_VXWORKS */
31994 /*
31995 ** Named semaphore locking is only available on VxWorks.
31996 **
31997 *************** End of the named semaphore lock implementation ****************
31998 ******************************************************************************/
31999 
32000 
32001 /******************************************************************************
32002 *************************** Begin AFP Locking *********************************
32003 **
32004 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
32005 ** on Apple Macintosh computers - both OS9 and OSX.
32006 **
32007 ** Third-party implementations of AFP are available. But this code here
32008 ** only works on OSX.
32009 */
32010 
32011 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32012 /*
32013 ** The afpLockingContext structure contains all afp lock specific state
32014 */
32015 typedef struct afpLockingContext afpLockingContext;
32016 struct afpLockingContext {
32017  int reserved;
32018  const char *dbPath; /* Name of the open file */
32019 };
32020 
32021 struct ByteRangeLockPB2
32022 {
32023  unsigned long long offset; /* offset to first byte to lock */
32024  unsigned long long length; /* nbr of bytes to lock */
32025  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
32026  unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
32027  unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
32028  int fd; /* file desc to assoc this lock with */
32029 };
32030 
32031 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
32032 
32033 /*
32034 ** This is a utility for setting or clearing a bit-range lock on an
32035 ** AFP filesystem.
32036 **
32037 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
32038 */
32039 static int afpSetLock(
32040  const char *path, /* Name of the file to be locked or unlocked */
32041  unixFile *pFile, /* Open file descriptor on path */
32042  unsigned long long offset, /* First byte to be locked */
32043  unsigned long long length, /* Number of bytes to lock */
32044  int setLockFlag /* True to set lock. False to clear lock */
32045 ){
32046  struct ByteRangeLockPB2 pb;
32047  int err;
32048 
32049  pb.unLockFlag = setLockFlag ? 0 : 1;
32050  pb.startEndFlag = 0;
32051  pb.offset = offset;
32052  pb.length = length;
32053  pb.fd = pFile->h;
32054 
32055  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
32056  (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
32057  offset, length));
32058  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
32059  if ( err==-1 ) {
32060  int rc;
32061  int tErrno = errno;
32062  OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
32063  path, tErrno, strerror(tErrno)));
32064 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
32065  rc = SQLITE_BUSY;
32066 #else
32067  rc = sqliteErrorFromPosixError(tErrno,
32068  setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
32069 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
32070  if( IS_LOCK_ERROR(rc) ){
32071  storeLastErrno(pFile, tErrno);
32072  }
32073  return rc;
32074  } else {
32075  return SQLITE_OK;
32076  }
32077 }
32078 
32079 /*
32080 ** This routine checks if there is a RESERVED lock held on the specified
32081 ** file by this or any other process. If such a lock is held, set *pResOut
32082 ** to a non-zero value otherwise *pResOut is set to zero. The return value
32083 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32084 */
32085 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
32086  int rc = SQLITE_OK;
32087  int reserved = 0;
32088  unixFile *pFile = (unixFile*)id;
32089  afpLockingContext *context;
32090 
32091  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32092 
32093  assert( pFile );
32094  context = (afpLockingContext *) pFile->lockingContext;
32095  if( context->reserved ){
32096  *pResOut = 1;
32097  return SQLITE_OK;
32098  }
32099  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
32100 
32101  /* Check if a thread in this process holds such a lock */
32102  if( pFile->pInode->eFileLock>SHARED_LOCK ){
32103  reserved = 1;
32104  }
32105 
32106  /* Otherwise see if some other process holds it.
32107  */
32108  if( !reserved ){
32109  /* lock the RESERVED byte */
32110  int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32111  if( SQLITE_OK==lrc ){
32112  /* if we succeeded in taking the reserved lock, unlock it to restore
32113  ** the original state */
32114  lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32115  } else {
32116  /* if we failed to get the lock then someone else must have it */
32117  reserved = 1;
32118  }
32119  if( IS_LOCK_ERROR(lrc) ){
32120  rc=lrc;
32121  }
32122  }
32123 
32124  unixLeaveMutex();
32125  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
32126 
32127  *pResOut = reserved;
32128  return rc;
32129 }
32130 
32131 /*
32132 ** Lock the file with the lock specified by parameter eFileLock - one
32133 ** of the following:
32134 **
32135 ** (1) SHARED_LOCK
32136 ** (2) RESERVED_LOCK
32137 ** (3) PENDING_LOCK
32138 ** (4) EXCLUSIVE_LOCK
32139 **
32140 ** Sometimes when requesting one lock state, additional lock states
32141 ** are inserted in between. The locking might fail on one of the later
32142 ** transitions leaving the lock state different from what it started but
32143 ** still short of its goal. The following chart shows the allowed
32144 ** transitions and the inserted intermediate states:
32145 **
32146 ** UNLOCKED -> SHARED
32147 ** SHARED -> RESERVED
32148 ** SHARED -> (PENDING) -> EXCLUSIVE
32149 ** RESERVED -> (PENDING) -> EXCLUSIVE
32150 ** PENDING -> EXCLUSIVE
32151 **
32152 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
32153 ** routine to lower a locking level.
32154 */
32155 static int afpLock(sqlite3_file *id, int eFileLock){
32156  int rc = SQLITE_OK;
32157  unixFile *pFile = (unixFile*)id;
32158  unixInodeInfo *pInode = pFile->pInode;
32159  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32160 
32161  assert( pFile );
32162  OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
32163  azFileLock(eFileLock), azFileLock(pFile->eFileLock),
32164  azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
32165 
32166  /* If there is already a lock of this type or more restrictive on the
32167  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
32168  ** unixEnterMutex() hasn't been called yet.
32169  */
32170  if( pFile->eFileLock>=eFileLock ){
32171  OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
32172  azFileLock(eFileLock)));
32173  return SQLITE_OK;
32174  }
32175 
32176  /* Make sure the locking sequence is correct
32177  ** (1) We never move from unlocked to anything higher than shared lock.
32178  ** (2) SQLite never explicitly requests a pendig lock.
32179  ** (3) A shared lock is always held when a reserve lock is requested.
32180  */
32181  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
32182  assert( eFileLock!=PENDING_LOCK );
32183  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
32184 
32185  /* This mutex is needed because pFile->pInode is shared across threads
32186  */
32187  unixEnterMutex();
32188  pInode = pFile->pInode;
32189 
32190  /* If some thread using this PID has a lock via a different unixFile*
32191  ** handle that precludes the requested lock, return BUSY.
32192  */
32193  if( (pFile->eFileLock!=pInode->eFileLock &&
32194  (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
32195  ){
32196  rc = SQLITE_BUSY;
32197  goto afp_end_lock;
32198  }
32199 
32200  /* If a SHARED lock is requested, and some thread using this PID already
32201  ** has a SHARED or RESERVED lock, then increment reference counts and
32202  ** return SQLITE_OK.
32203  */
32204  if( eFileLock==SHARED_LOCK &&
32205  (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
32206  assert( eFileLock==SHARED_LOCK );
32207  assert( pFile->eFileLock==0 );
32208  assert( pInode->nShared>0 );
32209  pFile->eFileLock = SHARED_LOCK;
32210  pInode->nShared++;
32211  pInode->nLock++;
32212  goto afp_end_lock;
32213  }
32214 
32215  /* A PENDING lock is needed before acquiring a SHARED lock and before
32216  ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
32217  ** be released.
32218  */
32219  if( eFileLock==SHARED_LOCK
32220  || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
32221  ){
32222  int failed;
32223  failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
32224  if (failed) {
32225  rc = failed;
32226  goto afp_end_lock;
32227  }
32228  }
32229 
32230  /* If control gets to this point, then actually go ahead and make
32231  ** operating system calls for the specified lock.
32232  */
32233  if( eFileLock==SHARED_LOCK ){
32234  int lrc1, lrc2, lrc1Errno = 0;
32235  long lk, mask;
32236 
32237  assert( pInode->nShared==0 );
32238  assert( pInode->eFileLock==0 );
32239 
32240  mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
32241  /* Now get the read-lock SHARED_LOCK */
32242  /* note that the quality of the randomness doesn't matter that much */
32243  lk = random();
32244  pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
32245  lrc1 = afpSetLock(context->dbPath, pFile,
32246  SHARED_FIRST+pInode->sharedByte, 1, 1);
32247  if( IS_LOCK_ERROR(lrc1) ){
32248  lrc1Errno = pFile->lastErrno;
32249  }
32250  /* Drop the temporary PENDING lock */
32251  lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32252 
32253  if( IS_LOCK_ERROR(lrc1) ) {
32254  storeLastErrno(pFile, lrc1Errno);
32255  rc = lrc1;
32256  goto afp_end_lock;
32257  } else if( IS_LOCK_ERROR(lrc2) ){
32258  rc = lrc2;
32259  goto afp_end_lock;
32260  } else if( lrc1 != SQLITE_OK ) {
32261  rc = lrc1;
32262  } else {
32263  pFile->eFileLock = SHARED_LOCK;
32264  pInode->nLock++;
32265  pInode->nShared = 1;
32266  }
32267  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
32268  /* We are trying for an exclusive lock but another thread in this
32269  ** same process is still holding a shared lock. */
32270  rc = SQLITE_BUSY;
32271  }else{
32272  /* The request was for a RESERVED or EXCLUSIVE lock. It is
32273  ** assumed that there is a SHARED or greater lock on the file
32274  ** already.
32275  */
32276  int failed = 0;
32277  assert( 0!=pFile->eFileLock );
32278  if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
32279  /* Acquire a RESERVED lock */
32280  failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32281  if( !failed ){
32282  context->reserved = 1;
32283  }
32284  }
32285  if (!failed && eFileLock == EXCLUSIVE_LOCK) {
32286  /* Acquire an EXCLUSIVE lock */
32287 
32288  /* Remove the shared lock before trying the range. we'll need to
32289  ** reestablish the shared lock if we can't get the afpUnlock
32290  */
32291  if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
32292  pInode->sharedByte, 1, 0)) ){
32293  int failed2 = SQLITE_OK;
32294  /* now attemmpt to get the exclusive lock range */
32295  failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
32296  SHARED_SIZE, 1);
32297  if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
32298  SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
32299  /* Can't reestablish the shared lock. Sqlite can't deal, this is
32300  ** a critical I/O error
32301  */
32302  rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
32303  SQLITE_IOERR_LOCK;
32304  goto afp_end_lock;
32305  }
32306  }else{
32307  rc = failed;
32308  }
32309  }
32310  if( failed ){
32311  rc = failed;
32312  }
32313  }
32314 
32315  if( rc==SQLITE_OK ){
32316  pFile->eFileLock = eFileLock;
32317  pInode->eFileLock = eFileLock;
32318  }else if( eFileLock==EXCLUSIVE_LOCK ){
32319  pFile->eFileLock = PENDING_LOCK;
32320  pInode->eFileLock = PENDING_LOCK;
32321  }
32322 
32323 afp_end_lock:
32324  unixLeaveMutex();
32325  OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
32326  rc==SQLITE_OK ? "ok" : "failed"));
32327  return rc;
32328 }
32329 
32330 /*
32331 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32332 ** must be either NO_LOCK or SHARED_LOCK.
32333 **
32334 ** If the locking level of the file descriptor is already at or below
32335 ** the requested locking level, this routine is a no-op.
32336 */
32337 static int afpUnlock(sqlite3_file *id, int eFileLock) {
32338  int rc = SQLITE_OK;
32339  unixFile *pFile = (unixFile*)id;
32340  unixInodeInfo *pInode;
32341  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32342  int skipShared = 0;
32343 #ifdef SQLITE_TEST
32344  int h = pFile->h;
32345 #endif
32346 
32347  assert( pFile );
32348  OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
32349  pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
32350  osGetpid(0)));
32351 
32352  assert( eFileLock<=SHARED_LOCK );
32353  if( pFile->eFileLock<=eFileLock ){
32354  return SQLITE_OK;
32355  }
32356  unixEnterMutex();
32357  pInode = pFile->pInode;
32358  assert( pInode->nShared!=0 );
32359  if( pFile->eFileLock>SHARED_LOCK ){
32360  assert( pInode->eFileLock==pFile->eFileLock );
32361  SimulateIOErrorBenign(1);
32362  SimulateIOError( h=(-1) )
32363  SimulateIOErrorBenign(0);
32364 
32365 #ifdef SQLITE_DEBUG
32366  /* When reducing a lock such that other processes can start
32367  ** reading the database file again, make sure that the
32368  ** transaction counter was updated if any part of the database
32369  ** file changed. If the transaction counter is not updated,
32370  ** other connections to the same file might not realize that
32371  ** the file has changed and hence might not know to flush their
32372  ** cache. The use of a stale cache can lead to database corruption.
32373  */
32374  assert( pFile->inNormalWrite==0
32375  || pFile->dbUpdate==0
32376  || pFile->transCntrChng==1 );
32377  pFile->inNormalWrite = 0;
32378 #endif
32379 
32380  if( pFile->eFileLock==EXCLUSIVE_LOCK ){
32381  rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
32382  if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
32383  /* only re-establish the shared lock if necessary */
32384  int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32385  rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
32386  } else {
32387  skipShared = 1;
32388  }
32389  }
32390  if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
32391  rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32392  }
32393  if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
32394  rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32395  if( !rc ){
32396  context->reserved = 0;
32397  }
32398  }
32399  if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
32400  pInode->eFileLock = SHARED_LOCK;
32401  }
32402  }
32403  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
32404 
32405  /* Decrement the shared lock counter. Release the lock using an
32406  ** OS call only when all threads in this same process have released
32407  ** the lock.
32408  */
32409  unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32410  pInode->nShared--;
32411  if( pInode->nShared==0 ){
32412  SimulateIOErrorBenign(1);
32413  SimulateIOError( h=(-1) )
32414  SimulateIOErrorBenign(0);
32415  if( !skipShared ){
32416  rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
32417  }
32418  if( !rc ){
32419  pInode->eFileLock = NO_LOCK;
32420  pFile->eFileLock = NO_LOCK;
32421  }
32422  }
32423  if( rc==SQLITE_OK ){
32424  pInode->nLock--;
32425  assert( pInode->nLock>=0 );
32426  if( pInode->nLock==0 ){
32427  closePendingFds(pFile);
32428  }
32429  }
32430  }
32431 
32432  unixLeaveMutex();
32433  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
32434  return rc;
32435 }
32436 
32437 /*
32438 ** Close a file & cleanup AFP specific locking context
32439 */
32440 static int afpClose(sqlite3_file *id) {
32441  int rc = SQLITE_OK;
32442  unixFile *pFile = (unixFile*)id;
32443  assert( id!=0 );
32444  afpUnlock(id, NO_LOCK);
32445  unixEnterMutex();
32446  if( pFile->pInode && pFile->pInode->nLock ){
32447  /* If there are outstanding locks, do not actually close the file just
32448  ** yet because that would clear those locks. Instead, add the file
32449  ** descriptor to pInode->aPending. It will be automatically closed when
32450  ** the last lock is cleared.
32451  */
32452  setPendingFd(pFile);
32453  }
32454  releaseInodeInfo(pFile);
32455  sqlite3_free(pFile->lockingContext);
32456  rc = closeUnixFile(id);
32457  unixLeaveMutex();
32458  return rc;
32459 }
32460 
32461 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32462 /*
32463 ** The code above is the AFP lock implementation. The code is specific
32464 ** to MacOSX and does not work on other unix platforms. No alternative
32465 ** is available. If you don't compile for a mac, then the "unix-afp"
32466 ** VFS is not available.
32467 **
32468 ********************* End of the AFP lock implementation **********************
32469 ******************************************************************************/
32470 
32471 /******************************************************************************
32472 *************************** Begin NFS Locking ********************************/
32473 
32474 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32475 /*
32476  ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32477  ** must be either NO_LOCK or SHARED_LOCK.
32478  **
32479  ** If the locking level of the file descriptor is already at or below
32480  ** the requested locking level, this routine is a no-op.
32481  */
32482 static int nfsUnlock(sqlite3_file *id, int eFileLock){
32483  return posixUnlock(id, eFileLock, 1);
32484 }
32485 
32486 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32487 /*
32488 ** The code above is the NFS lock implementation. The code is specific
32489 ** to MacOSX and does not work on other unix platforms. No alternative
32490 ** is available.
32491 **
32492 ********************* End of the NFS lock implementation **********************
32493 ******************************************************************************/
32494 
32495 /******************************************************************************
32496 **************** Non-locking sqlite3_file methods *****************************
32497 **
32498 ** The next division contains implementations for all methods of the
32499 ** sqlite3_file object other than the locking methods. The locking
32500 ** methods were defined in divisions above (one locking method per
32501 ** division). Those methods that are common to all locking modes
32502 ** are gather together into this division.
32503 */
32504 
32505 /*
32506 ** Seek to the offset passed as the second argument, then read cnt
32507 ** bytes into pBuf. Return the number of bytes actually read.
32508 **
32509 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
32510 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
32511 ** one system to another. Since SQLite does not define USE_PREAD
32512 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
32513 ** See tickets #2741 and #2681.
32514 **
32515 ** To avoid stomping the errno value on a failed read the lastErrno value
32516 ** is set before returning.
32517 */
32518 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
32519  int got;
32520  int prior = 0;
32521 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
32522  i64 newOffset;
32523 #endif
32524  TIMER_START;
32525  assert( cnt==(cnt&0x1ffff) );
32526  assert( id->h>2 );
32527  do{
32528 #if defined(USE_PREAD)
32529  got = osPread(id->h, pBuf, cnt, offset);
32530  SimulateIOError( got = -1 );
32531 #elif defined(USE_PREAD64)
32532  got = osPread64(id->h, pBuf, cnt, offset);
32533  SimulateIOError( got = -1 );
32534 #else
32535  newOffset = lseek(id->h, offset, SEEK_SET);
32536  SimulateIOError( newOffset = -1 );
32537  if( newOffset<0 ){
32538  storeLastErrno((unixFile*)id, errno);
32539  return -1;
32540  }
32541  got = osRead(id->h, pBuf, cnt);
32542 #endif
32543  if( got==cnt ) break;
32544  if( got<0 ){
32545  if( errno==EINTR ){ got = 1; continue; }
32546  prior = 0;
32547  storeLastErrno((unixFile*)id, errno);
32548  break;
32549  }else if( got>0 ){
32550  cnt -= got;
32551  offset += got;
32552  prior += got;
32553  pBuf = (void*)(got + (char*)pBuf);
32554  }
32555  }while( got>0 );
32556  TIMER_END;
32557  OSTRACE(("READ %-3d %5d %7lld %llu\n",
32558  id->h, got+prior, offset-prior, TIMER_ELAPSED));
32559  return got+prior;
32560 }
32561 
32562 /*
32563 ** Read data from a file into a buffer. Return SQLITE_OK if all
32564 ** bytes were read successfully and SQLITE_IOERR if anything goes
32565 ** wrong.
32566 */
32567 static int unixRead(
32568  sqlite3_file *id,
32569  void *pBuf,
32570  int amt,
32571  sqlite3_int64 offset
32572 ){
32573  unixFile *pFile = (unixFile *)id;
32574  int got;
32575  assert( id );
32576  assert( offset>=0 );
32577  assert( amt>0 );
32578 
32579  /* If this is a database file (not a journal, master-journal or temp
32580  ** file), the bytes in the locking range should never be read or written. */
32581 #if 0
32582  assert( pFile->pUnused==0
32583  || offset>=PENDING_BYTE+512
32584  || offset+amt<=PENDING_BYTE
32585  );
32586 #endif
32587 
32588 #if SQLITE_MAX_MMAP_SIZE>0
32589  /* Deal with as much of this read request as possible by transfering
32590  ** data from the memory mapping using memcpy(). */
32591  if( offset<pFile->mmapSize ){
32592  if( offset+amt <= pFile->mmapSize ){
32593  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
32594  return SQLITE_OK;
32595  }else{
32596  int nCopy = pFile->mmapSize - offset;
32597  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
32598  pBuf = &((u8 *)pBuf)[nCopy];
32599  amt -= nCopy;
32600  offset += nCopy;
32601  }
32602  }
32603 #endif
32604 
32605  got = seekAndRead(pFile, offset, pBuf, amt);
32606  if( got==amt ){
32607  return SQLITE_OK;
32608  }else if( got<0 ){
32609  /* lastErrno set by seekAndRead */
32610  return SQLITE_IOERR_READ;
32611  }else{
32612  storeLastErrno(pFile, 0); /* not a system error */
32613  /* Unread parts of the buffer must be zero-filled */
32614  memset(&((char*)pBuf)[got], 0, amt-got);
32615  return SQLITE_IOERR_SHORT_READ;
32616  }
32617 }
32618 
32619 /*
32620 ** Attempt to seek the file-descriptor passed as the first argument to
32621 ** absolute offset iOff, then attempt to write nBuf bytes of data from
32622 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
32623 ** return the actual number of bytes written (which may be less than
32624 ** nBuf).
32625 */
32626 static int seekAndWriteFd(
32627  int fd, /* File descriptor to write to */
32628  i64 iOff, /* File offset to begin writing at */
32629  const void *pBuf, /* Copy data from this buffer to the file */
32630  int nBuf, /* Size of buffer pBuf in bytes */
32631  int *piErrno /* OUT: Error number if error occurs */
32632 ){
32633  int rc = 0; /* Value returned by system call */
32634 
32635  assert( nBuf==(nBuf&0x1ffff) );
32636  assert( fd>2 );
32637  assert( piErrno!=0 );
32638  nBuf &= 0x1ffff;
32639  TIMER_START;
32640 
32641 #if defined(USE_PREAD)
32642  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
32643 #elif defined(USE_PREAD64)
32644  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
32645 #else
32646  do{
32647  i64 iSeek = lseek(fd, iOff, SEEK_SET);
32648  SimulateIOError( iSeek = -1 );
32649  if( iSeek<0 ){
32650  rc = -1;
32651  break;
32652  }
32653  rc = osWrite(fd, pBuf, nBuf);
32654  }while( rc<0 && errno==EINTR );
32655 #endif
32656 
32657  TIMER_END;
32658  OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
32659 
32660  if( rc<0 ) *piErrno = errno;
32661  return rc;
32662 }
32663 
32664 
32665 /*
32666 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
32667 ** Return the number of bytes actually read. Update the offset.
32668 **
32669 ** To avoid stomping the errno value on a failed write the lastErrno value
32670 ** is set before returning.
32671 */
32672 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
32673  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
32674 }
32675 
32676 
32677 /*
32678 ** Write data from a buffer into a file. Return SQLITE_OK on success
32679 ** or some other error code on failure.
32680 */
32681 static int unixWrite(
32682  sqlite3_file *id,
32683  const void *pBuf,
32684  int amt,
32685  sqlite3_int64 offset
32686 ){
32687  unixFile *pFile = (unixFile*)id;
32688  int wrote = 0;
32689  assert( id );
32690  assert( amt>0 );
32691 
32692  /* If this is a database file (not a journal, master-journal or temp
32693  ** file), the bytes in the locking range should never be read or written. */
32694 #if 0
32695  assert( pFile->pUnused==0
32696  || offset>=PENDING_BYTE+512
32697  || offset+amt<=PENDING_BYTE
32698  );
32699 #endif
32700 
32701 #ifdef SQLITE_DEBUG
32702  /* If we are doing a normal write to a database file (as opposed to
32703  ** doing a hot-journal rollback or a write to some file other than a
32704  ** normal database file) then record the fact that the database
32705  ** has changed. If the transaction counter is modified, record that
32706  ** fact too.
32707  */
32708  if( pFile->inNormalWrite ){
32709  pFile->dbUpdate = 1; /* The database has been modified */
32710  if( offset<=24 && offset+amt>=27 ){
32711  int rc;
32712  char oldCntr[4];
32713  SimulateIOErrorBenign(1);
32714  rc = seekAndRead(pFile, 24, oldCntr, 4);
32715  SimulateIOErrorBenign(0);
32716  if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
32717  pFile->transCntrChng = 1; /* The transaction counter has changed */
32718  }
32719  }
32720  }
32721 #endif
32722 
32723 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
32724  /* Deal with as much of this write request as possible by transfering
32725  ** data from the memory mapping using memcpy(). */
32726  if( offset<pFile->mmapSize ){
32727  if( offset+amt <= pFile->mmapSize ){
32728  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
32729  return SQLITE_OK;
32730  }else{
32731  int nCopy = pFile->mmapSize - offset;
32732  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
32733  pBuf = &((u8 *)pBuf)[nCopy];
32734  amt -= nCopy;
32735  offset += nCopy;
32736  }
32737  }
32738 #endif
32739 
32740  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
32741  amt -= wrote;
32742  offset += wrote;
32743  pBuf = &((char*)pBuf)[wrote];
32744  }
32745  SimulateIOError(( wrote=(-1), amt=1 ));
32746  SimulateDiskfullError(( wrote=0, amt=1 ));
32747 
32748  if( amt>wrote ){
32749  if( wrote<0 && pFile->lastErrno!=ENOSPC ){
32750  /* lastErrno set by seekAndWrite */
32751  return SQLITE_IOERR_WRITE;
32752  }else{
32753  storeLastErrno(pFile, 0); /* not a system error */
32754  return SQLITE_FULL;
32755  }
32756  }
32757 
32758  return SQLITE_OK;
32759 }
32760 
32761 #ifdef SQLITE_TEST
32762 /*
32763 ** Count the number of fullsyncs and normal syncs. This is used to test
32764 ** that syncs and fullsyncs are occurring at the right times.
32765 */
32766 SQLITE_API int sqlite3_sync_count = 0;
32767 SQLITE_API int sqlite3_fullsync_count = 0;
32768 #endif
32769 
32770 /*
32771 ** We do not trust systems to provide a working fdatasync(). Some do.
32772 ** Others do no. To be safe, we will stick with the (slightly slower)
32773 ** fsync(). If you know that your system does support fdatasync() correctly,
32774 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
32775 */
32776 #if !defined(fdatasync) && !HAVE_FDATASYNC
32777 # define fdatasync fsync
32778 #endif
32779 
32780 /*
32781 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
32782 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
32783 ** only available on Mac OS X. But that could change.
32784 */
32785 #ifdef F_FULLFSYNC
32786 # define HAVE_FULLFSYNC 1
32787 #else
32788 # define HAVE_FULLFSYNC 0
32789 #endif
32790 
32791 
32792 /*
32793 ** The fsync() system call does not work as advertised on many
32794 ** unix systems. The following procedure is an attempt to make
32795 ** it work better.
32796 **
32797 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
32798 ** for testing when we want to run through the test suite quickly.
32799 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
32800 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
32801 ** or power failure will likely corrupt the database file.
32802 **
32803 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
32804 ** The idea behind dataOnly is that it should only write the file content
32805 ** to disk, not the inode. We only set dataOnly if the file size is
32806 ** unchanged since the file size is part of the inode. However,
32807 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
32808 ** file size has changed. The only real difference between fdatasync()
32809 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
32810 ** inode if the mtime or owner or other inode attributes have changed.
32811 ** We only care about the file size, not the other file attributes, so
32812 ** as far as SQLite is concerned, an fdatasync() is always adequate.
32813 ** So, we always use fdatasync() if it is available, regardless of
32814 ** the value of the dataOnly flag.
32815 */
32816 static int full_fsync(int fd, int fullSync, int dataOnly){
32817  int rc;
32818 
32819  /* The following "ifdef/elif/else/" block has the same structure as
32820  ** the one below. It is replicated here solely to avoid cluttering
32821  ** up the real code with the UNUSED_PARAMETER() macros.
32822  */
32823 #ifdef SQLITE_NO_SYNC
32824  UNUSED_PARAMETER(fd);
32825  UNUSED_PARAMETER(fullSync);
32826  UNUSED_PARAMETER(dataOnly);
32827 #elif HAVE_FULLFSYNC
32828  UNUSED_PARAMETER(dataOnly);
32829 #else
32830  UNUSED_PARAMETER(fullSync);
32831  UNUSED_PARAMETER(dataOnly);
32832 #endif
32833 
32834  /* Record the number of times that we do a normal fsync() and
32835  ** FULLSYNC. This is used during testing to verify that this procedure
32836  ** gets called with the correct arguments.
32837  */
32838 #ifdef SQLITE_TEST
32839  if( fullSync ) sqlite3_fullsync_count++;
32840  sqlite3_sync_count++;
32841 #endif
32842 
32843  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32844  ** no-op. But go ahead and call fstat() to validate the file
32845  ** descriptor as we need a method to provoke a failure during
32846  ** coverate testing.
32847  */
32848 #ifdef SQLITE_NO_SYNC
32849  {
32850  struct stat buf;
32851  rc = osFstat(fd, &buf);
32852  }
32853 #elif HAVE_FULLFSYNC
32854  if( fullSync ){
32855  rc = osFcntl(fd, F_FULLFSYNC, 0);
32856  }else{
32857  rc = 1;
32858  }
32859  /* If the FULLFSYNC failed, fall back to attempting an fsync().
32860  ** It shouldn't be possible for fullfsync to fail on the local
32861  ** file system (on OSX), so failure indicates that FULLFSYNC
32862  ** isn't supported for this file system. So, attempt an fsync
32863  ** and (for now) ignore the overhead of a superfluous fcntl call.
32864  ** It'd be better to detect fullfsync support once and avoid
32865  ** the fcntl call every time sync is called.
32866  */
32867  if( rc ) rc = fsync(fd);
32868 
32869 #elif defined(__APPLE__)
32870  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
32871  ** so currently we default to the macro that redefines fdatasync to fsync
32872  */
32873  rc = fsync(fd);
32874 #else
32875  rc = fdatasync(fd);
32876 #if OS_VXWORKS
32877  if( rc==-1 && errno==ENOTSUP ){
32878  rc = fsync(fd);
32879  }
32880 #endif /* OS_VXWORKS */
32881 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
32882 
32883  if( OS_VXWORKS && rc!= -1 ){
32884  rc = 0;
32885  }
32886  return rc;
32887 }
32888 
32889 /*
32890 ** Open a file descriptor to the directory containing file zFilename.
32891 ** If successful, *pFd is set to the opened file descriptor and
32892 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
32893 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
32894 ** value.
32895 **
32896 ** The directory file descriptor is used for only one thing - to
32897 ** fsync() a directory to make sure file creation and deletion events
32898 ** are flushed to disk. Such fsyncs are not needed on newer
32899 ** journaling filesystems, but are required on older filesystems.
32900 **
32901 ** This routine can be overridden using the xSetSysCall interface.
32902 ** The ability to override this routine was added in support of the
32903 ** chromium sandbox. Opening a directory is a security risk (we are
32904 ** told) so making it overrideable allows the chromium sandbox to
32905 ** replace this routine with a harmless no-op. To make this routine
32906 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
32907 ** *pFd set to a negative number.
32908 **
32909 ** If SQLITE_OK is returned, the caller is responsible for closing
32910 ** the file descriptor *pFd using close().
32911 */
32912 static int openDirectory(const char *zFilename, int *pFd){
32913  int ii;
32914  int fd = -1;
32915  char zDirname[MAX_PATHNAME+1];
32916 
32917  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
32918  for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
32919  if( ii>0 ){
32920  zDirname[ii] = '\0';
32921  }else{
32922  if( zDirname[0]!='/' ) zDirname[0] = '.';
32923  zDirname[1] = 0;
32924  }
32925  fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
32926  if( fd>=0 ){
32927  OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
32928  }
32929  *pFd = fd;
32930  if( fd>=0 ) return SQLITE_OK;
32931  return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
32932 }
32933 
32934 /*
32935 ** Make sure all writes to a particular file are committed to disk.
32936 **
32937 ** If dataOnly==0 then both the file itself and its metadata (file
32938 ** size, access time, etc) are synced. If dataOnly!=0 then only the
32939 ** file data is synced.
32940 **
32941 ** Under Unix, also make sure that the directory entry for the file
32942 ** has been created by fsync-ing the directory that contains the file.
32943 ** If we do not do this and we encounter a power failure, the directory
32944 ** entry for the journal might not exist after we reboot. The next
32945 ** SQLite to access the file will not know that the journal exists (because
32946 ** the directory entry for the journal was never created) and the transaction
32947 ** will not roll back - possibly leading to database corruption.
32948 */
32949 static int unixSync(sqlite3_file *id, int flags){
32950  int rc;
32951  unixFile *pFile = (unixFile*)id;
32952 
32953  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
32954  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
32955 
32956  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32957  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32958  || (flags&0x0F)==SQLITE_SYNC_FULL
32959  );
32960 
32961  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32962  ** line is to test that doing so does not cause any problems.
32963  */
32964  SimulateDiskfullError( return SQLITE_FULL );
32965 
32966  assert( pFile );
32967  OSTRACE(("SYNC %-3d\n", pFile->h));
32968  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
32969  SimulateIOError( rc=1 );
32970  if( rc ){
32971  storeLastErrno(pFile, errno);
32972  return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
32973  }
32974 
32975  /* Also fsync the directory containing the file if the DIRSYNC flag
32976  ** is set. This is a one-time occurrence. Many systems (examples: AIX)
32977  ** are unable to fsync a directory, so ignore errors on the fsync.
32978  */
32979  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
32980  int dirfd;
32981  OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
32982  HAVE_FULLFSYNC, isFullsync));
32983  rc = osOpenDirectory(pFile->zPath, &dirfd);
32984  if( rc==SQLITE_OK ){
32985  full_fsync(dirfd, 0, 0);
32986  robust_close(pFile, dirfd, __LINE__);
32987  }else{
32988  assert( rc==SQLITE_CANTOPEN );
32989  rc = SQLITE_OK;
32990  }
32991  pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
32992  }
32993  return rc;
32994 }
32995 
32996 /*
32997 ** Truncate an open file to a specified size
32998 */
32999 static int unixTruncate(sqlite3_file *id, i64 nByte){
33000  unixFile *pFile = (unixFile *)id;
33001  int rc;
33002  assert( pFile );
33003  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
33004 
33005  /* If the user has configured a chunk-size for this file, truncate the
33006  ** file so that it consists of an integer number of chunks (i.e. the
33007  ** actual file size after the operation may be larger than the requested
33008  ** size).
33009  */
33010  if( pFile->szChunk>0 ){
33011  nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
33012  }
33013 
33014  rc = robust_ftruncate(pFile->h, nByte);
33015  if( rc ){
33016  storeLastErrno(pFile, errno);
33017  return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
33018  }else{
33019 #ifdef SQLITE_DEBUG
33020  /* If we are doing a normal write to a database file (as opposed to
33021  ** doing a hot-journal rollback or a write to some file other than a
33022  ** normal database file) and we truncate the file to zero length,
33023  ** that effectively updates the change counter. This might happen
33024  ** when restoring a database using the backup API from a zero-length
33025  ** source.
33026  */
33027  if( pFile->inNormalWrite && nByte==0 ){
33028  pFile->transCntrChng = 1;
33029  }
33030 #endif
33031 
33032 #if SQLITE_MAX_MMAP_SIZE>0
33033  /* If the file was just truncated to a size smaller than the currently
33034  ** mapped region, reduce the effective mapping size as well. SQLite will
33035  ** use read() and write() to access data beyond this point from now on.
33036  */
33037  if( nByte<pFile->mmapSize ){
33038  pFile->mmapSize = nByte;
33039  }
33040 #endif
33041 
33042  return SQLITE_OK;
33043  }
33044 }
33045 
33046 /*
33047 ** Determine the current size of a file in bytes
33048 */
33049 static int unixFileSize(sqlite3_file *id, i64 *pSize){
33050  int rc;
33051  struct stat buf;
33052  assert( id );
33053  rc = osFstat(((unixFile*)id)->h, &buf);
33054  SimulateIOError( rc=1 );
33055  if( rc!=0 ){
33056  storeLastErrno((unixFile*)id, errno);
33057  return SQLITE_IOERR_FSTAT;
33058  }
33059  *pSize = buf.st_size;
33060 
33061  /* When opening a zero-size database, the findInodeInfo() procedure
33062  ** writes a single byte into that file in order to work around a bug
33063  ** in the OS-X msdos filesystem. In order to avoid problems with upper
33064  ** layers, we need to report this file size as zero even though it is
33065  ** really 1. Ticket #3260.
33066  */
33067  if( *pSize==1 ) *pSize = 0;
33068 
33069 
33070  return SQLITE_OK;
33071 }
33072 
33073 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33074 /*
33075 ** Handler for proxy-locking file-control verbs. Defined below in the
33076 ** proxying locking division.
33077 */
33078 static int proxyFileControl(sqlite3_file*,int,void*);
33079 #endif
33080 
33081 /*
33082 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
33083 ** file-control operation. Enlarge the database to nBytes in size
33084 ** (rounded up to the next chunk-size). If the database is already
33085 ** nBytes or larger, this routine is a no-op.
33086 */
33087 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
33088  if( pFile->szChunk>0 ){
33089  i64 nSize; /* Required file size */
33090  struct stat buf; /* Used to hold return values of fstat() */
33091 
33092  if( osFstat(pFile->h, &buf) ){
33093  return SQLITE_IOERR_FSTAT;
33094  }
33095 
33096  nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
33097  if( nSize>(i64)buf.st_size ){
33098 
33099 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
33100  /* The code below is handling the return value of osFallocate()
33101  ** correctly. posix_fallocate() is defined to "returns zero on success,
33102  ** or an error number on failure". See the manpage for details. */
33103  int err;
33104  do{
33105  err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
33106  }while( err==EINTR );
33107  if( err ) return SQLITE_IOERR_WRITE;
33108 #else
33109  /* If the OS does not have posix_fallocate(), fake it. Write a
33110  ** single byte to the last byte in each block that falls entirely
33111  ** within the extended region. Then, if required, a single byte
33112  ** at offset (nSize-1), to set the size of the file correctly.
33113  ** This is a similar technique to that used by glibc on systems
33114  ** that do not have a real fallocate() call.
33115  */
33116  int nBlk = buf.st_blksize; /* File-system block size */
33117  int nWrite = 0; /* Number of bytes written by seekAndWrite */
33118  i64 iWrite; /* Next offset to write to */
33119 
33120  iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
33121  assert( iWrite>=buf.st_size );
33122  assert( ((iWrite+1)%nBlk)==0 );
33123  for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
33124  if( iWrite>=nSize ) iWrite = nSize - 1;
33125  nWrite = seekAndWrite(pFile, iWrite, "", 1);
33126  if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
33127  }
33128 #endif
33129  }
33130  }
33131 
33132 #if SQLITE_MAX_MMAP_SIZE>0
33133  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
33134  int rc;
33135  if( pFile->szChunk<=0 ){
33136  if( robust_ftruncate(pFile->h, nByte) ){
33137  storeLastErrno(pFile, errno);
33138  return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
33139  }
33140  }
33141 
33142  rc = unixMapfile(pFile, nByte);
33143  return rc;
33144  }
33145 #endif
33146 
33147  return SQLITE_OK;
33148 }
33149 
33150 /*
33151 ** If *pArg is initially negative then this is a query. Set *pArg to
33152 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
33153 **
33154 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
33155 */
33156 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
33157  if( *pArg<0 ){
33158  *pArg = (pFile->ctrlFlags & mask)!=0;
33159  }else if( (*pArg)==0 ){
33160  pFile->ctrlFlags &= ~mask;
33161  }else{
33162  pFile->ctrlFlags |= mask;
33163  }
33164 }
33165 
33166 /* Forward declaration */
33167 static int unixGetTempname(int nBuf, char *zBuf);
33168 
33169 /*
33170 ** Information and control of an open file handle.
33171 */
33172 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
33173  unixFile *pFile = (unixFile*)id;
33174  switch( op ){
33175  case SQLITE_FCNTL_LOCKSTATE: {
33176  *(int*)pArg = pFile->eFileLock;
33177  return SQLITE_OK;
33178  }
33179  case SQLITE_FCNTL_LAST_ERRNO: {
33180  *(int*)pArg = pFile->lastErrno;
33181  return SQLITE_OK;
33182  }
33183  case SQLITE_FCNTL_CHUNK_SIZE: {
33184  pFile->szChunk = *(int *)pArg;
33185  return SQLITE_OK;
33186  }
33187  case SQLITE_FCNTL_SIZE_HINT: {
33188  int rc;
33189  SimulateIOErrorBenign(1);
33190  rc = fcntlSizeHint(pFile, *(i64 *)pArg);
33191  SimulateIOErrorBenign(0);
33192  return rc;
33193  }
33194  case SQLITE_FCNTL_PERSIST_WAL: {
33195  unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
33196  return SQLITE_OK;
33197  }
33198  case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
33199  unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
33200  return SQLITE_OK;
33201  }
33202  case SQLITE_FCNTL_VFSNAME: {
33203  *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
33204  return SQLITE_OK;
33205  }
33206  case SQLITE_FCNTL_TEMPFILENAME: {
33207  char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
33208  if( zTFile ){
33209  unixGetTempname(pFile->pVfs->mxPathname, zTFile);
33210  *(char**)pArg = zTFile;
33211  }
33212  return SQLITE_OK;
33213  }
33214  case SQLITE_FCNTL_HAS_MOVED: {
33215  *(int*)pArg = fileHasMoved(pFile);
33216  return SQLITE_OK;
33217  }
33218 #if SQLITE_MAX_MMAP_SIZE>0
33219  case SQLITE_FCNTL_MMAP_SIZE: {
33220  i64 newLimit = *(i64*)pArg;
33221  int rc = SQLITE_OK;
33222  if( newLimit>sqlite3GlobalConfig.mxMmap ){
33223  newLimit = sqlite3GlobalConfig.mxMmap;
33224  }
33225  *(i64*)pArg = pFile->mmapSizeMax;
33226  if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33227  pFile->mmapSizeMax = newLimit;
33228  if( pFile->mmapSize>0 ){
33229  unixUnmapfile(pFile);
33230  rc = unixMapfile(pFile, -1);
33231  }
33232  }
33233  return rc;
33234  }
33235 #endif
33236 #ifdef SQLITE_DEBUG
33237  /* The pager calls this method to signal that it has done
33238  ** a rollback and that the database is therefore unchanged and
33239  ** it hence it is OK for the transaction change counter to be
33240  ** unchanged.
33241  */
33242  case SQLITE_FCNTL_DB_UNCHANGED: {
33243  ((unixFile*)id)->dbUpdate = 0;
33244  return SQLITE_OK;
33245  }
33246 #endif
33247 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33248  case SQLITE_FCNTL_SET_LOCKPROXYFILE:
33249  case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
33250  return proxyFileControl(id,op,pArg);
33251  }
33252 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
33253  }
33254  return SQLITE_NOTFOUND;
33255 }
33256 
33257 /*
33258 ** Return the sector size in bytes of the underlying block device for
33259 ** the specified file. This is almost always 512 bytes, but may be
33260 ** larger for some devices.
33261 **
33262 ** SQLite code assumes this function cannot fail. It also assumes that
33263 ** if two files are created in the same file-system directory (i.e.
33264 ** a database and its journal file) that the sector size will be the
33265 ** same for both.
33266 */
33267 #ifndef __QNXNTO__
33268 static int unixSectorSize(sqlite3_file *NotUsed){
33269  UNUSED_PARAMETER(NotUsed);
33270  return SQLITE_DEFAULT_SECTOR_SIZE;
33271 }
33272 #endif
33273 
33274 /*
33275 ** The following version of unixSectorSize() is optimized for QNX.
33276 */
33277 #ifdef __QNXNTO__
33278 #include <sys/dcmd_blk.h>
33279 #include <sys/statvfs.h>
33280 static int unixSectorSize(sqlite3_file *id){
33281  unixFile *pFile = (unixFile*)id;
33282  if( pFile->sectorSize == 0 ){
33283  struct statvfs fsInfo;
33284 
33285  /* Set defaults for non-supported filesystems */
33286  pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33287  pFile->deviceCharacteristics = 0;
33288  if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
33289  return pFile->sectorSize;
33290  }
33291 
33292  if( !strcmp(fsInfo.f_basetype, "tmp") ) {
33293  pFile->sectorSize = fsInfo.f_bsize;
33294  pFile->deviceCharacteristics =
33295  SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
33296  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33297  ** the write succeeds */
33298  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33299  ** so it is ordered */
33300  0;
33301  }else if( strstr(fsInfo.f_basetype, "etfs") ){
33302  pFile->sectorSize = fsInfo.f_bsize;
33303  pFile->deviceCharacteristics =
33304  /* etfs cluster size writes are atomic */
33305  (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
33306  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33307  ** the write succeeds */
33308  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33309  ** so it is ordered */
33310  0;
33311  }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
33312  pFile->sectorSize = fsInfo.f_bsize;
33313  pFile->deviceCharacteristics =
33314  SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
33315  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33316  ** the write succeeds */
33317  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33318  ** so it is ordered */
33319  0;
33320  }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
33321  pFile->sectorSize = fsInfo.f_bsize;
33322  pFile->deviceCharacteristics =
33323  /* full bitset of atomics from max sector size and smaller */
33324  ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33325  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33326  ** so it is ordered */
33327  0;
33328  }else if( strstr(fsInfo.f_basetype, "dos") ){
33329  pFile->sectorSize = fsInfo.f_bsize;
33330  pFile->deviceCharacteristics =
33331  /* full bitset of atomics from max sector size and smaller */
33332  ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33333  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33334  ** so it is ordered */
33335  0;
33336  }else{
33337  pFile->deviceCharacteristics =
33338  SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
33339  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33340  ** the write succeeds */
33341  0;
33342  }
33343  }
33344  /* Last chance verification. If the sector size isn't a multiple of 512
33345  ** then it isn't valid.*/
33346  if( pFile->sectorSize % 512 != 0 ){
33347  pFile->deviceCharacteristics = 0;
33348  pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33349  }
33350  return pFile->sectorSize;
33351 }
33352 #endif /* __QNXNTO__ */
33353 
33354 /*
33355 ** Return the device characteristics for the file.
33356 **
33357 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
33358 ** However, that choice is controversial since technically the underlying
33359 ** file system does not always provide powersafe overwrites. (In other
33360 ** words, after a power-loss event, parts of the file that were never
33361 ** written might end up being altered.) However, non-PSOW behavior is very,
33362 ** very rare. And asserting PSOW makes a large reduction in the amount
33363 ** of required I/O for journaling, since a lot of padding is eliminated.
33364 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
33365 ** available to turn it off and URI query parameter available to turn it off.
33366 */
33367 static int unixDeviceCharacteristics(sqlite3_file *id){
33368  unixFile *p = (unixFile*)id;
33369  int rc = 0;
33370 #ifdef __QNXNTO__
33371  if( p->sectorSize==0 ) unixSectorSize(id);
33372  rc = p->deviceCharacteristics;
33373 #endif
33374  if( p->ctrlFlags & UNIXFILE_PSOW ){
33375  rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
33376  }
33377  return rc;
33378 }
33379 
33380 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
33381 
33382 /*
33383 ** Return the system page size.
33384 **
33385 ** This function should not be called directly by other code in this file.
33386 ** Instead, it should be called via macro osGetpagesize().
33387 */
33388 static int unixGetpagesize(void){
33389 #if OS_VXWORKS
33390  return 1024;
33391 #elif defined(_BSD_SOURCE)
33392  return getpagesize();
33393 #else
33394  return (int)sysconf(_SC_PAGESIZE);
33395 #endif
33396 }
33397 
33398 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
33399 
33400 #ifndef SQLITE_OMIT_WAL
33401 
33402 /*
33403 ** Object used to represent an shared memory buffer.
33404 **
33405 ** When multiple threads all reference the same wal-index, each thread
33406 ** has its own unixShm object, but they all point to a single instance
33407 ** of this unixShmNode object. In other words, each wal-index is opened
33408 ** only once per process.
33409 **
33410 ** Each unixShmNode object is connected to a single unixInodeInfo object.
33411 ** We could coalesce this object into unixInodeInfo, but that would mean
33412 ** every open file that does not use shared memory (in other words, most
33413 ** open files) would have to carry around this extra information. So
33414 ** the unixInodeInfo object contains a pointer to this unixShmNode object
33415 ** and the unixShmNode object is created only when needed.
33416 **
33417 ** unixMutexHeld() must be true when creating or destroying
33418 ** this object or while reading or writing the following fields:
33419 **
33420 ** nRef
33421 **
33422 ** The following fields are read-only after the object is created:
33423 **
33424 ** fid
33425 ** zFilename
33426 **
33427 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
33428 ** unixMutexHeld() is true when reading or writing any other field
33429 ** in this structure.
33430 */
33431 struct unixShmNode {
33432  unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
33433  sqlite3_mutex *mutex; /* Mutex to access this object */
33434  char *zFilename; /* Name of the mmapped file */
33435  int h; /* Open file descriptor */
33436  int szRegion; /* Size of shared-memory regions */
33437  u16 nRegion; /* Size of array apRegion */
33438  u8 isReadonly; /* True if read-only */
33439  char **apRegion; /* Array of mapped shared-memory regions */
33440  int nRef; /* Number of unixShm objects pointing to this */
33441  unixShm *pFirst; /* All unixShm objects pointing to this */
33442 #ifdef SQLITE_DEBUG
33443  u8 exclMask; /* Mask of exclusive locks held */
33444  u8 sharedMask; /* Mask of shared locks held */
33445  u8 nextShmId; /* Next available unixShm.id value */
33446 #endif
33447 };
33448 
33449 /*
33450 ** Structure used internally by this VFS to record the state of an
33451 ** open shared memory connection.
33452 **
33453 ** The following fields are initialized when this object is created and
33454 ** are read-only thereafter:
33455 **
33456 ** unixShm.pFile
33457 ** unixShm.id
33458 **
33459 ** All other fields are read/write. The unixShm.pFile->mutex must be held
33460 ** while accessing any read/write fields.
33461 */
33462 struct unixShm {
33463  unixShmNode *pShmNode; /* The underlying unixShmNode object */
33464  unixShm *pNext; /* Next unixShm with the same unixShmNode */
33465  u8 hasMutex; /* True if holding the unixShmNode mutex */
33466  u8 id; /* Id of this connection within its unixShmNode */
33467  u16 sharedMask; /* Mask of shared locks held */
33468  u16 exclMask; /* Mask of exclusive locks held */
33469 };
33470 
33471 /*
33472 ** Constants used for locking
33473 */
33474 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
33475 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
33476 
33477 /*
33478 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
33479 **
33480 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
33481 ** otherwise.
33482 */
33483 static int unixShmSystemLock(
33484  unixFile *pFile, /* Open connection to the WAL file */
33485  int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
33486  int ofst, /* First byte of the locking range */
33487  int n /* Number of bytes to lock */
33488 ){
33489  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
33490  struct flock f; /* The posix advisory locking structure */
33491  int rc = SQLITE_OK; /* Result code form fcntl() */
33492 
33493  /* Access to the unixShmNode object is serialized by the caller */
33494  pShmNode = pFile->pInode->pShmNode;
33495  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
33496 
33497  /* Shared locks never span more than one byte */
33498  assert( n==1 || lockType!=F_RDLCK );
33499 
33500  /* Locks are within range */
33501  assert( n>=1 && n<=SQLITE_SHM_NLOCK );
33502 
33503  if( pShmNode->h>=0 ){
33504  /* Initialize the locking parameters */
33505  memset(&f, 0, sizeof(f));
33506  f.l_type = lockType;
33507  f.l_whence = SEEK_SET;
33508  f.l_start = ofst;
33509  f.l_len = n;
33510 
33511  rc = osFcntl(pShmNode->h, F_SETLK, &f);
33512  rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
33513  }
33514 
33515  /* Update the global lock state and do debug tracing */
33516 #ifdef SQLITE_DEBUG
33517  { u16 mask;
33518  OSTRACE(("SHM-LOCK "));
33519  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
33520  if( rc==SQLITE_OK ){
33521  if( lockType==F_UNLCK ){
33522  OSTRACE(("unlock %d ok", ofst));
33523  pShmNode->exclMask &= ~mask;
33524  pShmNode->sharedMask &= ~mask;
33525  }else if( lockType==F_RDLCK ){
33526  OSTRACE(("read-lock %d ok", ofst));
33527  pShmNode->exclMask &= ~mask;
33528  pShmNode->sharedMask |= mask;
33529  }else{
33530  assert( lockType==F_WRLCK );
33531  OSTRACE(("write-lock %d ok", ofst));
33532  pShmNode->exclMask |= mask;
33533  pShmNode->sharedMask &= ~mask;
33534  }
33535  }else{
33536  if( lockType==F_UNLCK ){
33537  OSTRACE(("unlock %d failed", ofst));
33538  }else if( lockType==F_RDLCK ){
33539  OSTRACE(("read-lock failed"));
33540  }else{
33541  assert( lockType==F_WRLCK );
33542  OSTRACE(("write-lock %d failed", ofst));
33543  }
33544  }
33545  OSTRACE((" - afterwards %03x,%03x\n",
33546  pShmNode->sharedMask, pShmNode->exclMask));
33547  }
33548 #endif
33549 
33550  return rc;
33551 }
33552 
33553 /*
33554 ** Return the minimum number of 32KB shm regions that should be mapped at
33555 ** a time, assuming that each mapping must be an integer multiple of the
33556 ** current system page-size.
33557 **
33558 ** Usually, this is 1. The exception seems to be systems that are configured
33559 ** to use 64KB pages - in this case each mapping must cover at least two
33560 ** shm regions.
33561 */
33562 static int unixShmRegionPerMap(void){
33563  int shmsz = 32*1024; /* SHM region size */
33564  int pgsz = osGetpagesize(); /* System page size */
33565  assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
33566  if( pgsz<shmsz ) return 1;
33567  return pgsz/shmsz;
33568 }
33569 
33570 /*
33571 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
33572 **
33573 ** This is not a VFS shared-memory method; it is a utility function called
33574 ** by VFS shared-memory methods.
33575 */
33576 static void unixShmPurge(unixFile *pFd){
33577  unixShmNode *p = pFd->pInode->pShmNode;
33578  assert( unixMutexHeld() );
33579  if( p && ALWAYS(p->nRef==0) ){
33580  int nShmPerMap = unixShmRegionPerMap();
33581  int i;
33582  assert( p->pInode==pFd->pInode );
33583  sqlite3_mutex_free(p->mutex);
33584  for(i=0; i<p->nRegion; i+=nShmPerMap){
33585  if( p->h>=0 ){
33586  osMunmap(p->apRegion[i], p->szRegion);
33587  }else{
33588  sqlite3_free(p->apRegion[i]);
33589  }
33590  }
33591  sqlite3_free(p->apRegion);
33592  if( p->h>=0 ){
33593  robust_close(pFd, p->h, __LINE__);
33594  p->h = -1;
33595  }
33596  p->pInode->pShmNode = 0;
33597  sqlite3_free(p);
33598  }
33599 }
33600 
33601 /*
33602 ** Open a shared-memory area associated with open database file pDbFd.
33603 ** This particular implementation uses mmapped files.
33604 **
33605 ** The file used to implement shared-memory is in the same directory
33606 ** as the open database file and has the same name as the open database
33607 ** file with the "-shm" suffix added. For example, if the database file
33608 ** is "/home/user1/config.db" then the file that is created and mmapped
33609 ** for shared memory will be called "/home/user1/config.db-shm".
33610 **
33611 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
33612 ** some other tmpfs mount. But if a file in a different directory
33613 ** from the database file is used, then differing access permissions
33614 ** or a chroot() might cause two different processes on the same
33615 ** database to end up using different files for shared memory -
33616 ** meaning that their memory would not really be shared - resulting
33617 ** in database corruption. Nevertheless, this tmpfs file usage
33618 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
33619 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
33620 ** option results in an incompatible build of SQLite; builds of SQLite
33621 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
33622 ** same database file at the same time, database corruption will likely
33623 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
33624 ** "unsupported" and may go away in a future SQLite release.
33625 **
33626 ** When opening a new shared-memory file, if no other instances of that
33627 ** file are currently open, in this process or in other processes, then
33628 ** the file must be truncated to zero length or have its header cleared.
33629 **
33630 ** If the original database file (pDbFd) is using the "unix-excl" VFS
33631 ** that means that an exclusive lock is held on the database file and
33632 ** that no other processes are able to read or write the database. In
33633 ** that case, we do not really need shared memory. No shared memory
33634 ** file is created. The shared memory will be simulated with heap memory.
33635 */
33636 static int unixOpenSharedMemory(unixFile *pDbFd){
33637  struct unixShm *p = 0; /* The connection to be opened */
33638  struct unixShmNode *pShmNode; /* The underlying mmapped file */
33639  int rc; /* Result code */
33640  unixInodeInfo *pInode; /* The inode of fd */
33641  char *zShmFilename; /* Name of the file used for SHM */
33642  int nShmFilename; /* Size of the SHM filename in bytes */
33643 
33644  /* Allocate space for the new unixShm object. */
33645  p = sqlite3_malloc64( sizeof(*p) );
33646  if( p==0 ) return SQLITE_NOMEM_BKPT;
33647  memset(p, 0, sizeof(*p));
33648  assert( pDbFd->pShm==0 );
33649 
33650  /* Check to see if a unixShmNode object already exists. Reuse an existing
33651  ** one if present. Create a new one if necessary.
33652  */
33653  unixEnterMutex();
33654  pInode = pDbFd->pInode;
33655  pShmNode = pInode->pShmNode;
33656  if( pShmNode==0 ){
33657  struct stat sStat; /* fstat() info for database file */
33658 #ifndef SQLITE_SHM_DIRECTORY
33659  const char *zBasePath = pDbFd->zPath;
33660 #endif
33661 
33662  /* Call fstat() to figure out the permissions on the database file. If
33663  ** a new *-shm file is created, an attempt will be made to create it
33664  ** with the same permissions.
33665  */
33666  if( osFstat(pDbFd->h, &sStat) ){
33667  rc = SQLITE_IOERR_FSTAT;
33668  goto shm_open_err;
33669  }
33670 
33671 #ifdef SQLITE_SHM_DIRECTORY
33672  nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
33673 #else
33674  nShmFilename = 6 + (int)strlen(zBasePath);
33675 #endif
33676  pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
33677  if( pShmNode==0 ){
33678  rc = SQLITE_NOMEM_BKPT;
33679  goto shm_open_err;
33680  }
33681  memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
33682  zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
33683 #ifdef SQLITE_SHM_DIRECTORY
33684  sqlite3_snprintf(nShmFilename, zShmFilename,
33685  SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
33686  (u32)sStat.st_ino, (u32)sStat.st_dev);
33687 #else
33688  sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
33689  sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
33690 #endif
33691  pShmNode->h = -1;
33692  pDbFd->pInode->pShmNode = pShmNode;
33693  pShmNode->pInode = pDbFd->pInode;
33694  if( sqlite3GlobalConfig.bCoreMutex ){
33695  pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33696  if( pShmNode->mutex==0 ){
33697  rc = SQLITE_NOMEM_BKPT;
33698  goto shm_open_err;
33699  }
33700  }
33701 
33702  if( pInode->bProcessLock==0 ){
33703  int openFlags = O_RDWR | O_CREAT;
33704  if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
33705  openFlags = O_RDONLY;
33706  pShmNode->isReadonly = 1;
33707  }
33708  pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
33709  if( pShmNode->h<0 ){
33710  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
33711  goto shm_open_err;
33712  }
33713 
33714  /* If this process is running as root, make sure that the SHM file
33715  ** is owned by the same user that owns the original database. Otherwise,
33716  ** the original owner will not be able to connect.
33717  */
33718  robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
33719 
33720  /* Check to see if another process is holding the dead-man switch.
33721  ** If not, truncate the file to zero length.
33722  */
33723  rc = SQLITE_OK;
33724  if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
33725  if( robust_ftruncate(pShmNode->h, 0) ){
33726  rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
33727  }
33728  }
33729  if( rc==SQLITE_OK ){
33730  rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
33731  }
33732  if( rc ) goto shm_open_err;
33733  }
33734  }
33735 
33736  /* Make the new connection a child of the unixShmNode */
33737  p->pShmNode = pShmNode;
33738 #ifdef SQLITE_DEBUG
33739  p->id = pShmNode->nextShmId++;
33740 #endif
33741  pShmNode->nRef++;
33742  pDbFd->pShm = p;
33743  unixLeaveMutex();
33744 
33745  /* The reference count on pShmNode has already been incremented under
33746  ** the cover of the unixEnterMutex() mutex and the pointer from the
33747  ** new (struct unixShm) object to the pShmNode has been set. All that is
33748  ** left to do is to link the new object into the linked list starting
33749  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
33750  ** mutex.
33751  */
33752  sqlite3_mutex_enter(pShmNode->mutex);
33753  p->pNext = pShmNode->pFirst;
33754  pShmNode->pFirst = p;
33755  sqlite3_mutex_leave(pShmNode->mutex);
33756  return SQLITE_OK;
33757 
33758  /* Jump here on any error */
33759 shm_open_err:
33760  unixShmPurge(pDbFd); /* This call frees pShmNode if required */
33761  sqlite3_free(p);
33762  unixLeaveMutex();
33763  return rc;
33764 }
33765 
33766 /*
33767 ** This function is called to obtain a pointer to region iRegion of the
33768 ** shared-memory associated with the database file fd. Shared-memory regions
33769 ** are numbered starting from zero. Each shared-memory region is szRegion
33770 ** bytes in size.
33771 **
33772 ** If an error occurs, an error code is returned and *pp is set to NULL.
33773 **
33774 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
33775 ** region has not been allocated (by any client, including one running in a
33776 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
33777 ** bExtend is non-zero and the requested shared-memory region has not yet
33778 ** been allocated, it is allocated by this function.
33779 **
33780 ** If the shared-memory region has already been allocated or is allocated by
33781 ** this call as described above, then it is mapped into this processes
33782 ** address space (if it is not already), *pp is set to point to the mapped
33783 ** memory and SQLITE_OK returned.
33784 */
33785 static int unixShmMap(
33786  sqlite3_file *fd, /* Handle open on database file */
33787  int iRegion, /* Region to retrieve */
33788  int szRegion, /* Size of regions */
33789  int bExtend, /* True to extend file if necessary */
33790  void volatile **pp /* OUT: Mapped memory */
33791 ){
33792  unixFile *pDbFd = (unixFile*)fd;
33793  unixShm *p;
33794  unixShmNode *pShmNode;
33795  int rc = SQLITE_OK;
33796  int nShmPerMap = unixShmRegionPerMap();
33797  int nReqRegion;
33798 
33799  /* If the shared-memory file has not yet been opened, open it now. */
33800  if( pDbFd->pShm==0 ){
33801  rc = unixOpenSharedMemory(pDbFd);
33802  if( rc!=SQLITE_OK ) return rc;
33803  }
33804 
33805  p = pDbFd->pShm;
33806  pShmNode = p->pShmNode;
33807  sqlite3_mutex_enter(pShmNode->mutex);
33808  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33809  assert( pShmNode->pInode==pDbFd->pInode );
33810  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33811  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33812 
33813  /* Minimum number of regions required to be mapped. */
33814  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
33815 
33816  if( pShmNode->nRegion<nReqRegion ){
33817  char **apNew; /* New apRegion[] array */
33818  int nByte = nReqRegion*szRegion; /* Minimum required file size */
33819  struct stat sStat; /* Used by fstat() */
33820 
33821  pShmNode->szRegion = szRegion;
33822 
33823  if( pShmNode->h>=0 ){
33824  /* The requested region is not mapped into this processes address space.
33825  ** Check to see if it has been allocated (i.e. if the wal-index file is
33826  ** large enough to contain the requested region).
33827  */
33828  if( osFstat(pShmNode->h, &sStat) ){
33829  rc = SQLITE_IOERR_SHMSIZE;
33830  goto shmpage_out;
33831  }
33832 
33833  if( sStat.st_size<nByte ){
33834  /* The requested memory region does not exist. If bExtend is set to
33835  ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
33836  */
33837  if( !bExtend ){
33838  goto shmpage_out;
33839  }
33840 
33841  /* Alternatively, if bExtend is true, extend the file. Do this by
33842  ** writing a single byte to the end of each (OS) page being
33843  ** allocated or extended. Technically, we need only write to the
33844  ** last page in order to extend the file. But writing to all new
33845  ** pages forces the OS to allocate them immediately, which reduces
33846  ** the chances of SIGBUS while accessing the mapped region later on.
33847  */
33848  else{
33849  static const int pgsz = 4096;
33850  int iPg;
33851 
33852  /* Write to the last byte of each newly allocated or extended page */
33853  assert( (nByte % pgsz)==0 );
33854  for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
33855  int x = 0;
33856  if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
33857  const char *zFile = pShmNode->zFilename;
33858  rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
33859  goto shmpage_out;
33860  }
33861  }
33862  }
33863  }
33864  }
33865 
33866  /* Map the requested memory region into this processes address space. */
33867  apNew = (char **)sqlite3_realloc(
33868  pShmNode->apRegion, nReqRegion*sizeof(char *)
33869  );
33870  if( !apNew ){
33871  rc = SQLITE_IOERR_NOMEM_BKPT;
33872  goto shmpage_out;
33873  }
33874  pShmNode->apRegion = apNew;
33875  while( pShmNode->nRegion<nReqRegion ){
33876  int nMap = szRegion*nShmPerMap;
33877  int i;
33878  void *pMem;
33879  if( pShmNode->h>=0 ){
33880  pMem = osMmap(0, nMap,
33881  pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
33882  MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
33883  );
33884  if( pMem==MAP_FAILED ){
33885  rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
33886  goto shmpage_out;
33887  }
33888  }else{
33889  pMem = sqlite3_malloc64(szRegion);
33890  if( pMem==0 ){
33891  rc = SQLITE_NOMEM_BKPT;
33892  goto shmpage_out;
33893  }
33894  memset(pMem, 0, szRegion);
33895  }
33896 
33897  for(i=0; i<nShmPerMap; i++){
33898  pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
33899  }
33900  pShmNode->nRegion += nShmPerMap;
33901  }
33902  }
33903 
33904 shmpage_out:
33905  if( pShmNode->nRegion>iRegion ){
33906  *pp = pShmNode->apRegion[iRegion];
33907  }else{
33908  *pp = 0;
33909  }
33910  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
33911  sqlite3_mutex_leave(pShmNode->mutex);
33912  return rc;
33913 }
33914 
33915 /*
33916 ** Change the lock state for a shared-memory segment.
33917 **
33918 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
33919 ** different here than in posix. In xShmLock(), one can go from unlocked
33920 ** to shared and back or from unlocked to exclusive and back. But one may
33921 ** not go from shared to exclusive or from exclusive to shared.
33922 */
33923 static int unixShmLock(
33924  sqlite3_file *fd, /* Database file holding the shared memory */
33925  int ofst, /* First lock to acquire or release */
33926  int n, /* Number of locks to acquire or release */
33927  int flags /* What to do with the lock */
33928 ){
33929  unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
33930  unixShm *p = pDbFd->pShm; /* The shared memory being locked */
33931  unixShm *pX; /* For looping over all siblings */
33932  unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
33933  int rc = SQLITE_OK; /* Result code */
33934  u16 mask; /* Mask of locks to take or release */
33935 
33936  assert( pShmNode==pDbFd->pInode->pShmNode );
33937  assert( pShmNode->pInode==pDbFd->pInode );
33938  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33939  assert( n>=1 );
33940  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33941  || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
33942  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33943  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33944  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33945  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33946  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33947 
33948  mask = (1<<(ofst+n)) - (1<<ofst);
33949  assert( n>1 || mask==(1<<ofst) );
33950  sqlite3_mutex_enter(pShmNode->mutex);
33951  if( flags & SQLITE_SHM_UNLOCK ){
33952  u16 allMask = 0; /* Mask of locks held by siblings */
33953 
33954  /* See if any siblings hold this same lock */
33955  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33956  if( pX==p ) continue;
33957  assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33958  allMask |= pX->sharedMask;
33959  }
33960 
33961  /* Unlock the system-level locks */
33962  if( (mask & allMask)==0 ){
33963  rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
33964  }else{
33965  rc = SQLITE_OK;
33966  }
33967 
33968  /* Undo the local locks */
33969  if( rc==SQLITE_OK ){
33970  p->exclMask &= ~mask;
33971  p->sharedMask &= ~mask;
33972  }
33973  }else if( flags & SQLITE_SHM_SHARED ){
33974  u16 allShared = 0; /* Union of locks held by connections other than "p" */
33975 
33976  /* Find out which shared locks are already held by sibling connections.
33977  ** If any sibling already holds an exclusive lock, go ahead and return
33978  ** SQLITE_BUSY.
33979  */
33980  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33981  if( (pX->exclMask & mask)!=0 ){
33982  rc = SQLITE_BUSY;
33983  break;
33984  }
33985  allShared |= pX->sharedMask;
33986  }
33987 
33988  /* Get shared locks at the system level, if necessary */
33989  if( rc==SQLITE_OK ){
33990  if( (allShared & mask)==0 ){
33991  rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
33992  }else{
33993  rc = SQLITE_OK;
33994  }
33995  }
33996 
33997  /* Get the local shared locks */
33998  if( rc==SQLITE_OK ){
33999  p->sharedMask |= mask;
34000  }
34001  }else{
34002  /* Make sure no sibling connections hold locks that will block this
34003  ** lock. If any do, return SQLITE_BUSY right away.
34004  */
34005  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34006  if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
34007  rc = SQLITE_BUSY;
34008  break;
34009  }
34010  }
34011 
34012  /* Get the exclusive locks at the system level. Then if successful
34013  ** also mark the local connection as being locked.
34014  */
34015  if( rc==SQLITE_OK ){
34016  rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
34017  if( rc==SQLITE_OK ){
34018  assert( (p->sharedMask & mask)==0 );
34019  p->exclMask |= mask;
34020  }
34021  }
34022  }
34023  sqlite3_mutex_leave(pShmNode->mutex);
34024  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
34025  p->id, osGetpid(0), p->sharedMask, p->exclMask));
34026  return rc;
34027 }
34028 
34029 /*
34030 ** Implement a memory barrier or memory fence on shared memory.
34031 **
34032 ** All loads and stores begun before the barrier must complete before
34033 ** any load or store begun after the barrier.
34034 */
34035 static void unixShmBarrier(
34036  sqlite3_file *fd /* Database file holding the shared memory */
34037 ){
34038  UNUSED_PARAMETER(fd);
34039  sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
34040  unixEnterMutex(); /* Also mutex, for redundancy */
34041  unixLeaveMutex();
34042 }
34043 
34044 /*
34045 ** Close a connection to shared-memory. Delete the underlying
34046 ** storage if deleteFlag is true.
34047 **
34048 ** If there is no shared memory associated with the connection then this
34049 ** routine is a harmless no-op.
34050 */
34051 static int unixShmUnmap(
34052  sqlite3_file *fd, /* The underlying database file */
34053  int deleteFlag /* Delete shared-memory if true */
34054 ){
34055  unixShm *p; /* The connection to be closed */
34056  unixShmNode *pShmNode; /* The underlying shared-memory file */
34057  unixShm **pp; /* For looping over sibling connections */
34058  unixFile *pDbFd; /* The underlying database file */
34059 
34060  pDbFd = (unixFile*)fd;
34061  p = pDbFd->pShm;
34062  if( p==0 ) return SQLITE_OK;
34063  pShmNode = p->pShmNode;
34064 
34065  assert( pShmNode==pDbFd->pInode->pShmNode );
34066  assert( pShmNode->pInode==pDbFd->pInode );
34067 
34068  /* Remove connection p from the set of connections associated
34069  ** with pShmNode */
34070  sqlite3_mutex_enter(pShmNode->mutex);
34071  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
34072  *pp = p->pNext;
34073 
34074  /* Free the connection p */
34075  sqlite3_free(p);
34076  pDbFd->pShm = 0;
34077  sqlite3_mutex_leave(pShmNode->mutex);
34078 
34079  /* If pShmNode->nRef has reached 0, then close the underlying
34080  ** shared-memory file, too */
34081  unixEnterMutex();
34082  assert( pShmNode->nRef>0 );
34083  pShmNode->nRef--;
34084  if( pShmNode->nRef==0 ){
34085  if( deleteFlag && pShmNode->h>=0 ){
34086  osUnlink(pShmNode->zFilename);
34087  }
34088  unixShmPurge(pDbFd);
34089  }
34090  unixLeaveMutex();
34091 
34092  return SQLITE_OK;
34093 }
34094 
34095 
34096 #else
34097 # define unixShmMap 0
34098 # define unixShmLock 0
34099 # define unixShmBarrier 0
34100 # define unixShmUnmap 0
34101 #endif /* #ifndef SQLITE_OMIT_WAL */
34102 
34103 #if SQLITE_MAX_MMAP_SIZE>0
34104 /*
34105 ** If it is currently memory mapped, unmap file pFd.
34106 */
34107 static void unixUnmapfile(unixFile *pFd){
34108  assert( pFd->nFetchOut==0 );
34109  if( pFd->pMapRegion ){
34110  osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
34111  pFd->pMapRegion = 0;
34112  pFd->mmapSize = 0;
34113  pFd->mmapSizeActual = 0;
34114  }
34115 }
34116 
34117 /*
34118 ** Attempt to set the size of the memory mapping maintained by file
34119 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
34120 **
34121 ** If successful, this function sets the following variables:
34122 **
34123 ** unixFile.pMapRegion
34124 ** unixFile.mmapSize
34125 ** unixFile.mmapSizeActual
34126 **
34127 ** If unsuccessful, an error message is logged via sqlite3_log() and
34128 ** the three variables above are zeroed. In this case SQLite should
34129 ** continue accessing the database using the xRead() and xWrite()
34130 ** methods.
34131 */
34132 static void unixRemapfile(
34133  unixFile *pFd, /* File descriptor object */
34134  i64 nNew /* Required mapping size */
34135 ){
34136  const char *zErr = "mmap";
34137  int h = pFd->h; /* File descriptor open on db file */
34138  u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
34139  i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
34140  u8 *pNew = 0; /* Location of new mapping */
34141  int flags = PROT_READ; /* Flags to pass to mmap() */
34142 
34143  assert( pFd->nFetchOut==0 );
34144  assert( nNew>pFd->mmapSize );
34145  assert( nNew<=pFd->mmapSizeMax );
34146  assert( nNew>0 );
34147  assert( pFd->mmapSizeActual>=pFd->mmapSize );
34148  assert( MAP_FAILED!=0 );
34149 
34150 #ifdef SQLITE_MMAP_READWRITE
34151  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
34152 #endif
34153 
34154  if( pOrig ){
34155 #if HAVE_MREMAP
34156  i64 nReuse = pFd->mmapSize;
34157 #else
34158  const int szSyspage = osGetpagesize();
34159  i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
34160 #endif
34161  u8 *pReq = &pOrig[nReuse];
34162 
34163  /* Unmap any pages of the existing mapping that cannot be reused. */
34164  if( nReuse!=nOrig ){
34165  osMunmap(pReq, nOrig-nReuse);
34166  }
34167 
34168 #if HAVE_MREMAP
34169  pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
34170  zErr = "mremap";
34171 #else
34172  pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
34173  if( pNew!=MAP_FAILED ){
34174  if( pNew!=pReq ){
34175  osMunmap(pNew, nNew - nReuse);
34176  pNew = 0;
34177  }else{
34178  pNew = pOrig;
34179  }
34180  }
34181 #endif
34182 
34183  /* The attempt to extend the existing mapping failed. Free it. */
34184  if( pNew==MAP_FAILED || pNew==0 ){
34185  osMunmap(pOrig, nReuse);
34186  }
34187  }
34188 
34189  /* If pNew is still NULL, try to create an entirely new mapping. */
34190  if( pNew==0 ){
34191  pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
34192  }
34193 
34194  if( pNew==MAP_FAILED ){
34195  pNew = 0;
34196  nNew = 0;
34197  unixLogError(SQLITE_OK, zErr, pFd->zPath);
34198 
34199  /* If the mmap() above failed, assume that all subsequent mmap() calls
34200  ** will probably fail too. Fall back to using xRead/xWrite exclusively
34201  ** in this case. */
34202  pFd->mmapSizeMax = 0;
34203  }
34204  pFd->pMapRegion = (void *)pNew;
34205  pFd->mmapSize = pFd->mmapSizeActual = nNew;
34206 }
34207 
34208 /*
34209 ** Memory map or remap the file opened by file-descriptor pFd (if the file
34210 ** is already mapped, the existing mapping is replaced by the new). Or, if
34211 ** there already exists a mapping for this file, and there are still
34212 ** outstanding xFetch() references to it, this function is a no-op.
34213 **
34214 ** If parameter nByte is non-negative, then it is the requested size of
34215 ** the mapping to create. Otherwise, if nByte is less than zero, then the
34216 ** requested size is the size of the file on disk. The actual size of the
34217 ** created mapping is either the requested size or the value configured
34218 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
34219 **
34220 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
34221 ** recreated as a result of outstanding references) or an SQLite error
34222 ** code otherwise.
34223 */
34224 static int unixMapfile(unixFile *pFd, i64 nMap){
34225  assert( nMap>=0 || pFd->nFetchOut==0 );
34226  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34227  if( pFd->nFetchOut>0 ) return SQLITE_OK;
34228 
34229  if( nMap<0 ){
34230  struct stat statbuf; /* Low-level file information */
34231  if( osFstat(pFd->h, &statbuf) ){
34232  return SQLITE_IOERR_FSTAT;
34233  }
34234  nMap = statbuf.st_size;
34235  }
34236  if( nMap>pFd->mmapSizeMax ){
34237  nMap = pFd->mmapSizeMax;
34238  }
34239 
34240  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34241  if( nMap!=pFd->mmapSize ){
34242  unixRemapfile(pFd, nMap);
34243  }
34244 
34245  return SQLITE_OK;
34246 }
34247 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
34248 
34249 /*
34250 ** If possible, return a pointer to a mapping of file fd starting at offset
34251 ** iOff. The mapping must be valid for at least nAmt bytes.
34252 **
34253 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
34254 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
34255 ** Finally, if an error does occur, return an SQLite error code. The final
34256 ** value of *pp is undefined in this case.
34257 **
34258 ** If this function does return a pointer, the caller must eventually
34259 ** release the reference by calling unixUnfetch().
34260 */
34261 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
34262 #if SQLITE_MAX_MMAP_SIZE>0
34263  unixFile *pFd = (unixFile *)fd; /* The underlying database file */
34264 #endif
34265  *pp = 0;
34266 
34267 #if SQLITE_MAX_MMAP_SIZE>0
34268  if( pFd->mmapSizeMax>0 ){
34269  if( pFd->pMapRegion==0 ){
34270  int rc = unixMapfile(pFd, -1);
34271  if( rc!=SQLITE_OK ) return rc;
34272  }
34273  if( pFd->mmapSize >= iOff+nAmt ){
34274  *pp = &((u8 *)pFd->pMapRegion)[iOff];
34275  pFd->nFetchOut++;
34276  }
34277  }
34278 #endif
34279  return SQLITE_OK;
34280 }
34281 
34282 /*
34283 ** If the third argument is non-NULL, then this function releases a
34284 ** reference obtained by an earlier call to unixFetch(). The second
34285 ** argument passed to this function must be the same as the corresponding
34286 ** argument that was passed to the unixFetch() invocation.
34287 **
34288 ** Or, if the third argument is NULL, then this function is being called
34289 ** to inform the VFS layer that, according to POSIX, any existing mapping
34290 ** may now be invalid and should be unmapped.
34291 */
34292 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
34293 #if SQLITE_MAX_MMAP_SIZE>0
34294  unixFile *pFd = (unixFile *)fd; /* The underlying database file */
34295  UNUSED_PARAMETER(iOff);
34296 
34297  /* If p==0 (unmap the entire file) then there must be no outstanding
34298  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
34299  ** then there must be at least one outstanding. */
34300  assert( (p==0)==(pFd->nFetchOut==0) );
34301 
34302  /* If p!=0, it must match the iOff value. */
34303  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
34304 
34305  if( p ){
34306  pFd->nFetchOut--;
34307  }else{
34308  unixUnmapfile(pFd);
34309  }
34310 
34311  assert( pFd->nFetchOut>=0 );
34312 #else
34313  UNUSED_PARAMETER(fd);
34314  UNUSED_PARAMETER(p);
34315  UNUSED_PARAMETER(iOff);
34316 #endif
34317  return SQLITE_OK;
34318 }
34319 
34320 /*
34321 ** Here ends the implementation of all sqlite3_file methods.
34322 **
34323 ********************** End sqlite3_file Methods *******************************
34324 ******************************************************************************/
34325 
34326 /*
34327 ** This division contains definitions of sqlite3_io_methods objects that
34328 ** implement various file locking strategies. It also contains definitions
34329 ** of "finder" functions. A finder-function is used to locate the appropriate
34330 ** sqlite3_io_methods object for a particular database file. The pAppData
34331 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
34332 ** the correct finder-function for that VFS.
34333 **
34334 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
34335 ** object. The only interesting finder-function is autolockIoFinder, which
34336 ** looks at the filesystem type and tries to guess the best locking
34337 ** strategy from that.
34338 **
34339 ** For finder-function F, two objects are created:
34340 **
34341 ** (1) The real finder-function named "FImpt()".
34342 **
34343 ** (2) A constant pointer to this function named just "F".
34344 **
34345 **
34346 ** A pointer to the F pointer is used as the pAppData value for VFS
34347 ** objects. We have to do this instead of letting pAppData point
34348 ** directly at the finder-function since C90 rules prevent a void*
34349 ** from be cast into a function pointer.
34350 **
34351 **
34352 ** Each instance of this macro generates two objects:
34353 **
34354 ** * A constant sqlite3_io_methods object call METHOD that has locking
34355 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
34356 **
34357 ** * An I/O method finder function called FINDER that returns a pointer
34358 ** to the METHOD object in the previous bullet.
34359 */
34360 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
34361 static const sqlite3_io_methods METHOD = { \
34362  VERSION, /* iVersion */ \
34363  CLOSE, /* xClose */ \
34364  unixRead, /* xRead */ \
34365  unixWrite, /* xWrite */ \
34366  unixTruncate, /* xTruncate */ \
34367  unixSync, /* xSync */ \
34368  unixFileSize, /* xFileSize */ \
34369  LOCK, /* xLock */ \
34370  UNLOCK, /* xUnlock */ \
34371  CKLOCK, /* xCheckReservedLock */ \
34372  unixFileControl, /* xFileControl */ \
34373  unixSectorSize, /* xSectorSize */ \
34374  unixDeviceCharacteristics, /* xDeviceCapabilities */ \
34375  SHMMAP, /* xShmMap */ \
34376  unixShmLock, /* xShmLock */ \
34377  unixShmBarrier, /* xShmBarrier */ \
34378  unixShmUnmap, /* xShmUnmap */ \
34379  unixFetch, /* xFetch */ \
34380  unixUnfetch, /* xUnfetch */ \
34381 }; \
34382 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
34383  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
34384  return &METHOD; \
34385 } \
34386 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
34387  = FINDER##Impl;
34388 
34389 /*
34390 ** Here are all of the sqlite3_io_methods objects for each of the
34391 ** locking strategies. Functions that return pointers to these methods
34392 ** are also created.
34393 */
34394 IOMETHODS(
34395  posixIoFinder, /* Finder function name */
34396  posixIoMethods, /* sqlite3_io_methods object name */
34397  3, /* shared memory and mmap are enabled */
34398  unixClose, /* xClose method */
34399  unixLock, /* xLock method */
34400  unixUnlock, /* xUnlock method */
34401  unixCheckReservedLock, /* xCheckReservedLock method */
34402  unixShmMap /* xShmMap method */
34403 )
34404 IOMETHODS(
34405  nolockIoFinder, /* Finder function name */
34406  nolockIoMethods, /* sqlite3_io_methods object name */
34407  3, /* shared memory is disabled */
34408  nolockClose, /* xClose method */
34409  nolockLock, /* xLock method */
34410  nolockUnlock, /* xUnlock method */
34411  nolockCheckReservedLock, /* xCheckReservedLock method */
34412  0 /* xShmMap method */
34413 )
34414 IOMETHODS(
34415  dotlockIoFinder, /* Finder function name */
34416  dotlockIoMethods, /* sqlite3_io_methods object name */
34417  1, /* shared memory is disabled */
34418  dotlockClose, /* xClose method */
34419  dotlockLock, /* xLock method */
34420  dotlockUnlock, /* xUnlock method */
34421  dotlockCheckReservedLock, /* xCheckReservedLock method */
34422  0 /* xShmMap method */
34423 )
34424 
34425 #if SQLITE_ENABLE_LOCKING_STYLE
34426 IOMETHODS(
34427  flockIoFinder, /* Finder function name */
34428  flockIoMethods, /* sqlite3_io_methods object name */
34429  1, /* shared memory is disabled */
34430  flockClose, /* xClose method */
34431  flockLock, /* xLock method */
34432  flockUnlock, /* xUnlock method */
34433  flockCheckReservedLock, /* xCheckReservedLock method */
34434  0 /* xShmMap method */
34435 )
34436 #endif
34437 
34438 #if OS_VXWORKS
34439 IOMETHODS(
34440  semIoFinder, /* Finder function name */
34441  semIoMethods, /* sqlite3_io_methods object name */
34442  1, /* shared memory is disabled */
34443  semXClose, /* xClose method */
34444  semXLock, /* xLock method */
34445  semXUnlock, /* xUnlock method */
34446  semXCheckReservedLock, /* xCheckReservedLock method */
34447  0 /* xShmMap method */
34448 )
34449 #endif
34450 
34451 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34452 IOMETHODS(
34453  afpIoFinder, /* Finder function name */
34454  afpIoMethods, /* sqlite3_io_methods object name */
34455  1, /* shared memory is disabled */
34456  afpClose, /* xClose method */
34457  afpLock, /* xLock method */
34458  afpUnlock, /* xUnlock method */
34459  afpCheckReservedLock, /* xCheckReservedLock method */
34460  0 /* xShmMap method */
34461 )
34462 #endif
34463 
34464 /*
34465 ** The proxy locking method is a "super-method" in the sense that it
34466 ** opens secondary file descriptors for the conch and lock files and
34467 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
34468 ** secondary files. For this reason, the division that implements
34469 ** proxy locking is located much further down in the file. But we need
34470 ** to go ahead and define the sqlite3_io_methods and finder function
34471 ** for proxy locking here. So we forward declare the I/O methods.
34472 */
34473 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34474 static int proxyClose(sqlite3_file*);
34475 static int proxyLock(sqlite3_file*, int);
34476 static int proxyUnlock(sqlite3_file*, int);
34477 static int proxyCheckReservedLock(sqlite3_file*, int*);
34478 IOMETHODS(
34479  proxyIoFinder, /* Finder function name */
34480  proxyIoMethods, /* sqlite3_io_methods object name */
34481  1, /* shared memory is disabled */
34482  proxyClose, /* xClose method */
34483  proxyLock, /* xLock method */
34484  proxyUnlock, /* xUnlock method */
34485  proxyCheckReservedLock, /* xCheckReservedLock method */
34486  0 /* xShmMap method */
34487 )
34488 #endif
34489 
34490 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
34491 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34492 IOMETHODS(
34493  nfsIoFinder, /* Finder function name */
34494  nfsIoMethods, /* sqlite3_io_methods object name */
34495  1, /* shared memory is disabled */
34496  unixClose, /* xClose method */
34497  unixLock, /* xLock method */
34498  nfsUnlock, /* xUnlock method */
34499  unixCheckReservedLock, /* xCheckReservedLock method */
34500  0 /* xShmMap method */
34501 )
34502 #endif
34503 
34504 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34505 /*
34506 ** This "finder" function attempts to determine the best locking strategy
34507 ** for the database file "filePath". It then returns the sqlite3_io_methods
34508 ** object that implements that strategy.
34509 **
34510 ** This is for MacOSX only.
34511 */
34512 static const sqlite3_io_methods *autolockIoFinderImpl(
34513  const char *filePath, /* name of the database file */
34514  unixFile *pNew /* open file object for the database file */
34515 ){
34516  static const struct Mapping {
34517  const char *zFilesystem; /* Filesystem type name */
34518  const sqlite3_io_methods *pMethods; /* Appropriate locking method */
34519  } aMap[] = {
34520  { "hfs", &posixIoMethods },
34521  { "ufs", &posixIoMethods },
34522  { "afpfs", &afpIoMethods },
34523  { "smbfs", &afpIoMethods },
34524  { "webdav", &nolockIoMethods },
34525  { 0, 0 }
34526  };
34527  int i;
34528  struct statfs fsInfo;
34529  struct flock lockInfo;
34530 
34531  if( !filePath ){
34532  /* If filePath==NULL that means we are dealing with a transient file
34533  ** that does not need to be locked. */
34534  return &nolockIoMethods;
34535  }
34536  if( statfs(filePath, &fsInfo) != -1 ){
34537  if( fsInfo.f_flags & MNT_RDONLY ){
34538  return &nolockIoMethods;
34539  }
34540  for(i=0; aMap[i].zFilesystem; i++){
34541  if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
34542  return aMap[i].pMethods;
34543  }
34544  }
34545  }
34546 
34547  /* Default case. Handles, amongst others, "nfs".
34548  ** Test byte-range lock using fcntl(). If the call succeeds,
34549  ** assume that the file-system supports POSIX style locks.
34550  */
34551  lockInfo.l_len = 1;
34552  lockInfo.l_start = 0;
34553  lockInfo.l_whence = SEEK_SET;
34554  lockInfo.l_type = F_RDLCK;
34555  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34556  if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
34557  return &nfsIoMethods;
34558  } else {
34559  return &posixIoMethods;
34560  }
34561  }else{
34562  return &dotlockIoMethods;
34563  }
34564 }
34565 static const sqlite3_io_methods
34566  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
34567 
34568 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
34569 
34570 #if OS_VXWORKS
34571 /*
34572 ** This "finder" function for VxWorks checks to see if posix advisory
34573 ** locking works. If it does, then that is what is used. If it does not
34574 ** work, then fallback to named semaphore locking.
34575 */
34576 static const sqlite3_io_methods *vxworksIoFinderImpl(
34577  const char *filePath, /* name of the database file */
34578  unixFile *pNew /* the open file object */
34579 ){
34580  struct flock lockInfo;
34581 
34582  if( !filePath ){
34583  /* If filePath==NULL that means we are dealing with a transient file
34584  ** that does not need to be locked. */
34585  return &nolockIoMethods;
34586  }
34587 
34588  /* Test if fcntl() is supported and use POSIX style locks.
34589  ** Otherwise fall back to the named semaphore method.
34590  */
34591  lockInfo.l_len = 1;
34592  lockInfo.l_start = 0;
34593  lockInfo.l_whence = SEEK_SET;
34594  lockInfo.l_type = F_RDLCK;
34595  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34596  return &posixIoMethods;
34597  }else{
34598  return &semIoMethods;
34599  }
34600 }
34601 static const sqlite3_io_methods
34602  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
34603 
34604 #endif /* OS_VXWORKS */
34605 
34606 /*
34607 ** An abstract type for a pointer to an IO method finder function:
34608 */
34609 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
34610 
34611 
34612 /****************************************************************************
34613 **************************** sqlite3_vfs methods ****************************
34614 **
34615 ** This division contains the implementation of methods on the
34616 ** sqlite3_vfs object.
34617 */
34618 
34619 /*
34620 ** Initialize the contents of the unixFile structure pointed to by pId.
34621 */
34622 static int fillInUnixFile(
34623  sqlite3_vfs *pVfs, /* Pointer to vfs object */
34624  int h, /* Open file descriptor of file being opened */
34625  sqlite3_file *pId, /* Write to the unixFile structure here */
34626  const char *zFilename, /* Name of the file being opened */
34627  int ctrlFlags /* Zero or more UNIXFILE_* values */
34628 ){
34629  const sqlite3_io_methods *pLockingStyle;
34630  unixFile *pNew = (unixFile *)pId;
34631  int rc = SQLITE_OK;
34632 
34633  assert( pNew->pInode==NULL );
34634 
34635  /* Usually the path zFilename should not be a relative pathname. The
34636  ** exception is when opening the proxy "conch" file in builds that
34637  ** include the special Apple locking styles.
34638  */
34639 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34640  assert( zFilename==0 || zFilename[0]=='/'
34641  || pVfs->pAppData==(void*)&autolockIoFinder );
34642 #else
34643  assert( zFilename==0 || zFilename[0]=='/' );
34644 #endif
34645 
34646  /* No locking occurs in temporary files */
34647  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
34648 
34649  OSTRACE(("OPEN %-3d %s\n", h, zFilename));
34650  pNew->h = h;
34651  pNew->pVfs = pVfs;
34652  pNew->zPath = zFilename;
34653  pNew->ctrlFlags = (u8)ctrlFlags;
34654 #if SQLITE_MAX_MMAP_SIZE>0
34655  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34656 #endif
34657  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
34658  "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34659  pNew->ctrlFlags |= UNIXFILE_PSOW;
34660  }
34661  if( strcmp(pVfs->zName,"unix-excl")==0 ){
34662  pNew->ctrlFlags |= UNIXFILE_EXCL;
34663  }
34664 
34665 #if OS_VXWORKS
34666  pNew->pId = vxworksFindFileId(zFilename);
34667  if( pNew->pId==0 ){
34668  ctrlFlags |= UNIXFILE_NOLOCK;
34669  rc = SQLITE_NOMEM_BKPT;
34670  }
34671 #endif
34672 
34673  if( ctrlFlags & UNIXFILE_NOLOCK ){
34674  pLockingStyle = &nolockIoMethods;
34675  }else{
34676  pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
34677 #if SQLITE_ENABLE_LOCKING_STYLE
34678  /* Cache zFilename in the locking context (AFP and dotlock override) for
34679  ** proxyLock activation is possible (remote proxy is based on db name)
34680  ** zFilename remains valid until file is closed, to support */
34681  pNew->lockingContext = (void*)zFilename;
34682 #endif
34683  }
34684 
34685  if( pLockingStyle == &posixIoMethods
34686 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34687  || pLockingStyle == &nfsIoMethods
34688 #endif
34689  ){
34690  unixEnterMutex();
34691  rc = findInodeInfo(pNew, &pNew->pInode);
34692  if( rc!=SQLITE_OK ){
34693  /* If an error occurred in findInodeInfo(), close the file descriptor
34694  ** immediately, before releasing the mutex. findInodeInfo() may fail
34695  ** in two scenarios:
34696  **
34697  ** (a) A call to fstat() failed.
34698  ** (b) A malloc failed.
34699  **
34700  ** Scenario (b) may only occur if the process is holding no other
34701  ** file descriptors open on the same file. If there were other file
34702  ** descriptors on this file, then no malloc would be required by
34703  ** findInodeInfo(). If this is the case, it is quite safe to close
34704  ** handle h - as it is guaranteed that no posix locks will be released
34705  ** by doing so.
34706  **
34707  ** If scenario (a) caused the error then things are not so safe. The
34708  ** implicit assumption here is that if fstat() fails, things are in
34709  ** such bad shape that dropping a lock or two doesn't matter much.
34710  */
34711  robust_close(pNew, h, __LINE__);
34712  h = -1;
34713  }
34714  unixLeaveMutex();
34715  }
34716 
34717 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34718  else if( pLockingStyle == &afpIoMethods ){
34719  /* AFP locking uses the file path so it needs to be included in
34720  ** the afpLockingContext.
34721  */
34722  afpLockingContext *pCtx;
34723  pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
34724  if( pCtx==0 ){
34725  rc = SQLITE_NOMEM_BKPT;
34726  }else{
34727  /* NB: zFilename exists and remains valid until the file is closed
34728  ** according to requirement F11141. So we do not need to make a
34729  ** copy of the filename. */
34730  pCtx->dbPath = zFilename;
34731  pCtx->reserved = 0;
34732  srandomdev();
34733  unixEnterMutex();
34734  rc = findInodeInfo(pNew, &pNew->pInode);
34735  if( rc!=SQLITE_OK ){
34736  sqlite3_free(pNew->lockingContext);
34737  robust_close(pNew, h, __LINE__);
34738  h = -1;
34739  }
34740  unixLeaveMutex();
34741  }
34742  }
34743 #endif
34744 
34745  else if( pLockingStyle == &dotlockIoMethods ){
34746  /* Dotfile locking uses the file path so it needs to be included in
34747  ** the dotlockLockingContext
34748  */
34749  char *zLockFile;
34750  int nFilename;
34751  assert( zFilename!=0 );
34752  nFilename = (int)strlen(zFilename) + 6;
34753  zLockFile = (char *)sqlite3_malloc64(nFilename);
34754  if( zLockFile==0 ){
34755  rc = SQLITE_NOMEM_BKPT;
34756  }else{
34757  sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
34758  }
34759  pNew->lockingContext = zLockFile;
34760  }
34761 
34762 #if OS_VXWORKS
34763  else if( pLockingStyle == &semIoMethods ){
34764  /* Named semaphore locking uses the file path so it needs to be
34765  ** included in the semLockingContext
34766  */
34767  unixEnterMutex();
34768  rc = findInodeInfo(pNew, &pNew->pInode);
34769  if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
34770  char *zSemName = pNew->pInode->aSemName;
34771  int n;
34772  sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
34773  pNew->pId->zCanonicalName);
34774  for( n=1; zSemName[n]; n++ )
34775  if( zSemName[n]=='/' ) zSemName[n] = '_';
34776  pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
34777  if( pNew->pInode->pSem == SEM_FAILED ){
34778  rc = SQLITE_NOMEM_BKPT;
34779  pNew->pInode->aSemName[0] = '\0';
34780  }
34781  }
34782  unixLeaveMutex();
34783  }
34784 #endif
34785 
34786  storeLastErrno(pNew, 0);
34787 #if OS_VXWORKS
34788  if( rc!=SQLITE_OK ){
34789  if( h>=0 ) robust_close(pNew, h, __LINE__);
34790  h = -1;
34791  osUnlink(zFilename);
34792  pNew->ctrlFlags |= UNIXFILE_DELETE;
34793  }
34794 #endif
34795  if( rc!=SQLITE_OK ){
34796  if( h>=0 ) robust_close(pNew, h, __LINE__);
34797  }else{
34798  pNew->pMethod = pLockingStyle;
34799  OpenCounter(+1);
34800  verifyDbFile(pNew);
34801  }
34802  return rc;
34803 }
34804 
34805 /*
34806 ** Return the name of a directory in which to put temporary files.
34807 ** If no suitable temporary file directory can be found, return NULL.
34808 */
34809 static const char *unixTempFileDir(void){
34810  static const char *azDirs[] = {
34811  0,
34812  0,
34813  "/var/tmp",
34814  "/usr/tmp",
34815  "/tmp",
34816  "."
34817  };
34818  unsigned int i = 0;
34819  struct stat buf;
34820  const char *zDir = sqlite3_temp_directory;
34821 
34822  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
34823  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
34824  while(1){
34825  if( zDir!=0
34826  && osStat(zDir, &buf)==0
34827  && S_ISDIR(buf.st_mode)
34828  && osAccess(zDir, 03)==0
34829  ){
34830  return zDir;
34831  }
34832  if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
34833  zDir = azDirs[i++];
34834  }
34835  return 0;
34836 }
34837 
34838 /*
34839 ** Create a temporary file name in zBuf. zBuf must be allocated
34840 ** by the calling process and must be big enough to hold at least
34841 ** pVfs->mxPathname bytes.
34842 */
34843 static int unixGetTempname(int nBuf, char *zBuf){
34844  const char *zDir;
34845  int iLimit = 0;
34846 
34847  /* It's odd to simulate an io-error here, but really this is just
34848  ** using the io-error infrastructure to test that SQLite handles this
34849  ** function failing.
34850  */
34851  zBuf[0] = 0;
34852  SimulateIOError( return SQLITE_IOERR );
34853 
34854  zDir = unixTempFileDir();
34855  if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
34856  do{
34857  u64 r;
34858  sqlite3_randomness(sizeof(r), &r);
34859  assert( nBuf>2 );
34860  zBuf[nBuf-2] = 0;
34861  sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
34862  zDir, r, 0);
34863  if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
34864  }while( osAccess(zBuf,0)==0 );
34865  return SQLITE_OK;
34866 }
34867 
34868 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34869 /*
34870 ** Routine to transform a unixFile into a proxy-locking unixFile.
34871 ** Implementation in the proxy-lock division, but used by unixOpen()
34872 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
34873 */
34874 static int proxyTransformUnixFile(unixFile*, const char*);
34875 #endif
34876 
34877 /*
34878 ** Search for an unused file descriptor that was opened on the database
34879 ** file (not a journal or master-journal file) identified by pathname
34880 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
34881 ** argument to this function.
34882 **
34883 ** Such a file descriptor may exist if a database connection was closed
34884 ** but the associated file descriptor could not be closed because some
34885 ** other file descriptor open on the same file is holding a file-lock.
34886 ** Refer to comments in the unixClose() function and the lengthy comment
34887 ** describing "Posix Advisory Locking" at the start of this file for
34888 ** further details. Also, ticket #4018.
34889 **
34890 ** If a suitable file descriptor is found, then it is returned. If no
34891 ** such file descriptor is located, -1 is returned.
34892 */
34893 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
34894  UnixUnusedFd *pUnused = 0;
34895 
34896  /* Do not search for an unused file descriptor on vxworks. Not because
34897  ** vxworks would not benefit from the change (it might, we're not sure),
34898  ** but because no way to test it is currently available. It is better
34899  ** not to risk breaking vxworks support for the sake of such an obscure
34900  ** feature. */
34901 #if !OS_VXWORKS
34902  struct stat sStat; /* Results of stat() call */
34903 
34904  /* A stat() call may fail for various reasons. If this happens, it is
34905  ** almost certain that an open() call on the same path will also fail.
34906  ** For this reason, if an error occurs in the stat() call here, it is
34907  ** ignored and -1 is returned. The caller will try to open a new file
34908  ** descriptor on the same path, fail, and return an error to SQLite.
34909  **
34910  ** Even if a subsequent open() call does succeed, the consequences of
34911  ** not searching for a reusable file descriptor are not dire. */
34912  if( 0==osStat(zPath, &sStat) ){
34913  unixInodeInfo *pInode;
34914 
34915  unixEnterMutex();
34916  pInode = inodeList;
34917  while( pInode && (pInode->fileId.dev!=sStat.st_dev
34918  || pInode->fileId.ino!=sStat.st_ino) ){
34919  pInode = pInode->pNext;
34920  }
34921  if( pInode ){
34922  UnixUnusedFd **pp;
34923  for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
34924  pUnused = *pp;
34925  if( pUnused ){
34926  *pp = pUnused->pNext;
34927  }
34928  }
34929  unixLeaveMutex();
34930  }
34931 #endif /* if !OS_VXWORKS */
34932  return pUnused;
34933 }
34934 
34935 /*
34936 ** Find the mode, uid and gid of file zFile.
34937 */
34938 static int getFileMode(
34939  const char *zFile, /* File name */
34940  mode_t *pMode, /* OUT: Permissions of zFile */
34941  uid_t *pUid, /* OUT: uid of zFile. */
34942  gid_t *pGid /* OUT: gid of zFile. */
34943 ){
34944  struct stat sStat; /* Output of stat() on database file */
34945  int rc = SQLITE_OK;
34946  if( 0==osStat(zFile, &sStat) ){
34947  *pMode = sStat.st_mode & 0777;
34948  *pUid = sStat.st_uid;
34949  *pGid = sStat.st_gid;
34950  }else{
34951  rc = SQLITE_IOERR_FSTAT;
34952  }
34953  return rc;
34954 }
34955 
34956 /*
34957 ** This function is called by unixOpen() to determine the unix permissions
34958 ** to create new files with. If no error occurs, then SQLITE_OK is returned
34959 ** and a value suitable for passing as the third argument to open(2) is
34960 ** written to *pMode. If an IO error occurs, an SQLite error code is
34961 ** returned and the value of *pMode is not modified.
34962 **
34963 ** In most cases, this routine sets *pMode to 0, which will become
34964 ** an indication to robust_open() to create the file using
34965 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
34966 ** But if the file being opened is a WAL or regular journal file, then
34967 ** this function queries the file-system for the permissions on the
34968 ** corresponding database file and sets *pMode to this value. Whenever
34969 ** possible, WAL and journal files are created using the same permissions
34970 ** as the associated database file.
34971 **
34972 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
34973 ** original filename is unavailable. But 8_3_NAMES is only used for
34974 ** FAT filesystems and permissions do not matter there, so just use
34975 ** the default permissions.
34976 */
34977 static int findCreateFileMode(
34978  const char *zPath, /* Path of file (possibly) being created */
34979  int flags, /* Flags passed as 4th argument to xOpen() */
34980  mode_t *pMode, /* OUT: Permissions to open file with */
34981  uid_t *pUid, /* OUT: uid to set on the file */
34982  gid_t *pGid /* OUT: gid to set on the file */
34983 ){
34984  int rc = SQLITE_OK; /* Return Code */
34985  *pMode = 0;
34986  *pUid = 0;
34987  *pGid = 0;
34988  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
34989  char zDb[MAX_PATHNAME+1]; /* Database file path */
34990  int nDb; /* Number of valid bytes in zDb */
34991 
34992  /* zPath is a path to a WAL or journal file. The following block derives
34993  ** the path to the associated database file from zPath. This block handles
34994  ** the following naming conventions:
34995  **
34996  ** "<path to db>-journal"
34997  ** "<path to db>-wal"
34998  ** "<path to db>-journalNN"
34999  ** "<path to db>-walNN"
35000  **
35001  ** where NN is a decimal number. The NN naming schemes are
35002  ** used by the test_multiplex.c module.
35003  */
35004  nDb = sqlite3Strlen30(zPath) - 1;
35005  while( zPath[nDb]!='-' ){
35006 #ifndef SQLITE_ENABLE_8_3_NAMES
35007  /* In the normal case (8+3 filenames disabled) the journal filename
35008  ** is guaranteed to contain a '-' character. */
35009  assert( nDb>0 );
35010  assert( sqlite3Isalnum(zPath[nDb]) );
35011 #else
35012  /* If 8+3 names are possible, then the journal file might not contain
35013  ** a '-' character. So check for that case and return early. */
35014  if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
35015 #endif
35016  nDb--;
35017  }
35018  memcpy(zDb, zPath, nDb);
35019  zDb[nDb] = '\0';
35020 
35021  rc = getFileMode(zDb, pMode, pUid, pGid);
35022  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
35023  *pMode = 0600;
35024  }else if( flags & SQLITE_OPEN_URI ){
35025  /* If this is a main database file and the file was opened using a URI
35026  ** filename, check for the "modeof" parameter. If present, interpret
35027  ** its value as a filename and try to copy the mode, uid and gid from
35028  ** that file. */
35029  const char *z = sqlite3_uri_parameter(zPath, "modeof");
35030  if( z ){
35031  rc = getFileMode(z, pMode, pUid, pGid);
35032  }
35033  }
35034  return rc;
35035 }
35036 
35037 /*
35038 ** Open the file zPath.
35039 **
35040 ** Previously, the SQLite OS layer used three functions in place of this
35041 ** one:
35042 **
35043 ** sqlite3OsOpenReadWrite();
35044 ** sqlite3OsOpenReadOnly();
35045 ** sqlite3OsOpenExclusive();
35046 **
35047 ** These calls correspond to the following combinations of flags:
35048 **
35049 ** ReadWrite() -> (READWRITE | CREATE)
35050 ** ReadOnly() -> (READONLY)
35051 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
35052 **
35053 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
35054 ** true, the file was configured to be automatically deleted when the
35055 ** file handle closed. To achieve the same effect using this new
35056 ** interface, add the DELETEONCLOSE flag to those specified above for
35057 ** OpenExclusive().
35058 */
35059 static int unixOpen(
35060  sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
35061  const char *zPath, /* Pathname of file to be opened */
35062  sqlite3_file *pFile, /* The file descriptor to be filled in */
35063  int flags, /* Input flags to control the opening */
35064  int *pOutFlags /* Output flags returned to SQLite core */
35065 ){
35066  unixFile *p = (unixFile *)pFile;
35067  int fd = -1; /* File descriptor returned by open() */
35068  int openFlags = 0; /* Flags to pass to open() */
35069  int eType = flags&0xFFFFFF00; /* Type of file to open */
35070  int noLock; /* True to omit locking primitives */
35071  int rc = SQLITE_OK; /* Function Return Code */
35072  int ctrlFlags = 0; /* UNIXFILE_* flags */
35073 
35074  int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
35075  int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
35076  int isCreate = (flags & SQLITE_OPEN_CREATE);
35077  int isReadonly = (flags & SQLITE_OPEN_READONLY);
35078  int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
35079 #if SQLITE_ENABLE_LOCKING_STYLE
35080  int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
35081 #endif
35082 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
35083  struct statfs fsInfo;
35084 #endif
35085 
35086  /* If creating a master or main-file journal, this function will open
35087  ** a file-descriptor on the directory too. The first time unixSync()
35088  ** is called the directory file descriptor will be fsync()ed and close()d.
35089  */
35090  int syncDir = (isCreate && (
35091  eType==SQLITE_OPEN_MASTER_JOURNAL
35092  || eType==SQLITE_OPEN_MAIN_JOURNAL
35093  || eType==SQLITE_OPEN_WAL
35094  ));
35095 
35096  /* If argument zPath is a NULL pointer, this function is required to open
35097  ** a temporary file. Use this buffer to store the file name in.
35098  */
35099  char zTmpname[MAX_PATHNAME+2];
35100  const char *zName = zPath;
35101 
35102  /* Check the following statements are true:
35103  **
35104  ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
35105  ** (b) if CREATE is set, then READWRITE must also be set, and
35106  ** (c) if EXCLUSIVE is set, then CREATE must also be set.
35107  ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
35108  */
35109  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35110  assert(isCreate==0 || isReadWrite);
35111  assert(isExclusive==0 || isCreate);
35112  assert(isDelete==0 || isCreate);
35113 
35114  /* The main DB, main journal, WAL file and master journal are never
35115  ** automatically deleted. Nor are they ever temporary files. */
35116  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35117  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35118  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35119  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35120 
35121  /* Assert that the upper layer has set one of the "file-type" flags. */
35122  assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
35123  || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
35124  || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
35125  || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35126  );
35127 
35128  /* Detect a pid change and reset the PRNG. There is a race condition
35129  ** here such that two or more threads all trying to open databases at
35130  ** the same instant might all reset the PRNG. But multiple resets
35131  ** are harmless.
35132  */
35133  if( randomnessPid!=osGetpid(0) ){
35134  randomnessPid = osGetpid(0);
35135  sqlite3_randomness(0,0);
35136  }
35137 
35138  memset(p, 0, sizeof(unixFile));
35139 
35140  if( eType==SQLITE_OPEN_MAIN_DB ){
35141  UnixUnusedFd *pUnused;
35142  pUnused = findReusableFd(zName, flags);
35143  if( pUnused ){
35144  fd = pUnused->fd;
35145  }else{
35146  pUnused = sqlite3_malloc64(sizeof(*pUnused));
35147  if( !pUnused ){
35148  return SQLITE_NOMEM_BKPT;
35149  }
35150  }
35151  p->pUnused = pUnused;
35152 
35153  /* Database filenames are double-zero terminated if they are not
35154  ** URIs with parameters. Hence, they can always be passed into
35155  ** sqlite3_uri_parameter(). */
35156  assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
35157 
35158  }else if( !zName ){
35159  /* If zName is NULL, the upper layer is requesting a temp file. */
35160  assert(isDelete && !syncDir);
35161  rc = unixGetTempname(pVfs->mxPathname, zTmpname);
35162  if( rc!=SQLITE_OK ){
35163  return rc;
35164  }
35165  zName = zTmpname;
35166 
35167  /* Generated temporary filenames are always double-zero terminated
35168  ** for use by sqlite3_uri_parameter(). */
35169  assert( zName[strlen(zName)+1]==0 );
35170  }
35171 
35172  /* Determine the value of the flags parameter passed to POSIX function
35173  ** open(). These must be calculated even if open() is not called, as
35174  ** they may be stored as part of the file handle and used by the
35175  ** 'conch file' locking functions later on. */
35176  if( isReadonly ) openFlags |= O_RDONLY;
35177  if( isReadWrite ) openFlags |= O_RDWR;
35178  if( isCreate ) openFlags |= O_CREAT;
35179  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
35180  openFlags |= (O_LARGEFILE|O_BINARY);
35181 
35182  if( fd<0 ){
35183  mode_t openMode; /* Permissions to create file with */
35184  uid_t uid; /* Userid for the file */
35185  gid_t gid; /* Groupid for the file */
35186  rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
35187  if( rc!=SQLITE_OK ){
35188  assert( !p->pUnused );
35189  assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
35190  return rc;
35191  }
35192  fd = robust_open(zName, openFlags, openMode);
35193  OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
35194  assert( !isExclusive || (openFlags & O_CREAT)!=0 );
35195  if( fd<0 && errno!=EISDIR && isReadWrite ){
35196  /* Failed to open the file for read/write access. Try read-only. */
35197  flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
35198  openFlags &= ~(O_RDWR|O_CREAT);
35199  flags |= SQLITE_OPEN_READONLY;
35200  openFlags |= O_RDONLY;
35201  isReadonly = 1;
35202  fd = robust_open(zName, openFlags, openMode);
35203  }
35204  if( fd<0 ){
35205  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
35206  goto open_finished;
35207  }
35208 
35209  /* If this process is running as root and if creating a new rollback
35210  ** journal or WAL file, set the ownership of the journal or WAL to be
35211  ** the same as the original database.
35212  */
35213  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
35214  robustFchown(fd, uid, gid);
35215  }
35216  }
35217  assert( fd>=0 );
35218  if( pOutFlags ){
35219  *pOutFlags = flags;
35220  }
35221 
35222  if( p->pUnused ){
35223  p->pUnused->fd = fd;
35224  p->pUnused->flags = flags;
35225  }
35226 
35227  if( isDelete ){
35228 #if OS_VXWORKS
35229  zPath = zName;
35230 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
35231  zPath = sqlite3_mprintf("%s", zName);
35232  if( zPath==0 ){
35233  robust_close(p, fd, __LINE__);
35234  return SQLITE_NOMEM_BKPT;
35235  }
35236 #else
35237  osUnlink(zName);
35238 #endif
35239  }
35240 #if SQLITE_ENABLE_LOCKING_STYLE
35241  else{
35242  p->openFlags = openFlags;
35243  }
35244 #endif
35245 
35246 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
35247  if( fstatfs(fd, &fsInfo) == -1 ){
35248  storeLastErrno(p, errno);
35249  robust_close(p, fd, __LINE__);
35250  return SQLITE_IOERR_ACCESS;
35251  }
35252  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
35253  ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35254  }
35255  if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
35256  ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35257  }
35258 #endif
35259 
35260  /* Set up appropriate ctrlFlags */
35261  if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
35262  if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
35263  noLock = eType!=SQLITE_OPEN_MAIN_DB;
35264  if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
35265  if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
35266  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
35267 
35268 #if SQLITE_ENABLE_LOCKING_STYLE
35269 #if SQLITE_PREFER_PROXY_LOCKING
35270  isAutoProxy = 1;
35271 #endif
35272  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
35273  char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
35274  int useProxy = 0;
35275 
35276  /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
35277  ** never use proxy, NULL means use proxy for non-local files only. */
35278  if( envforce!=NULL ){
35279  useProxy = atoi(envforce)>0;
35280  }else{
35281  useProxy = !(fsInfo.f_flags&MNT_LOCAL);
35282  }
35283  if( useProxy ){
35284  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35285  if( rc==SQLITE_OK ){
35286  rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
35287  if( rc!=SQLITE_OK ){
35288  /* Use unixClose to clean up the resources added in fillInUnixFile
35289  ** and clear all the structure's references. Specifically,
35290  ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
35291  */
35292  unixClose(pFile);
35293  return rc;
35294  }
35295  }
35296  goto open_finished;
35297  }
35298  }
35299 #endif
35300 
35301  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35302 
35303 open_finished:
35304  if( rc!=SQLITE_OK ){
35305  sqlite3_free(p->pUnused);
35306  }
35307  return rc;
35308 }
35309 
35310 
35311 /*
35312 ** Delete the file at zPath. If the dirSync argument is true, fsync()
35313 ** the directory after deleting the file.
35314 */
35315 static int unixDelete(
35316  sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
35317  const char *zPath, /* Name of file to be deleted */
35318  int dirSync /* If true, fsync() directory after deleting file */
35319 ){
35320  int rc = SQLITE_OK;
35321  UNUSED_PARAMETER(NotUsed);
35322  SimulateIOError(return SQLITE_IOERR_DELETE);
35323  if( osUnlink(zPath)==(-1) ){
35324  if( errno==ENOENT
35325 #if OS_VXWORKS
35326  || osAccess(zPath,0)!=0
35327 #endif
35328  ){
35329  rc = SQLITE_IOERR_DELETE_NOENT;
35330  }else{
35331  rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
35332  }
35333  return rc;
35334  }
35335 #ifndef SQLITE_DISABLE_DIRSYNC
35336  if( (dirSync & 1)!=0 ){
35337  int fd;
35338  rc = osOpenDirectory(zPath, &fd);
35339  if( rc==SQLITE_OK ){
35340  if( full_fsync(fd,0,0) ){
35341  rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
35342  }
35343  robust_close(0, fd, __LINE__);
35344  }else{
35345  assert( rc==SQLITE_CANTOPEN );
35346  rc = SQLITE_OK;
35347  }
35348  }
35349 #endif
35350  return rc;
35351 }
35352 
35353 /*
35354 ** Test the existence of or access permissions of file zPath. The
35355 ** test performed depends on the value of flags:
35356 **
35357 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
35358 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
35359 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
35360 **
35361 ** Otherwise return 0.
35362 */
35363 static int unixAccess(
35364  sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
35365  const char *zPath, /* Path of the file to examine */
35366  int flags, /* What do we want to learn about the zPath file? */
35367  int *pResOut /* Write result boolean here */
35368 ){
35369  UNUSED_PARAMETER(NotUsed);
35370  SimulateIOError( return SQLITE_IOERR_ACCESS; );
35371  assert( pResOut!=0 );
35372 
35373  /* The spec says there are three possible values for flags. But only
35374  ** two of them are actually used */
35375  assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
35376 
35377  if( flags==SQLITE_ACCESS_EXISTS ){
35378  struct stat buf;
35379  *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
35380  }else{
35381  *pResOut = osAccess(zPath, W_OK|R_OK)==0;
35382  }
35383  return SQLITE_OK;
35384 }
35385 
35386 /*
35387 **
35388 */
35389 static int mkFullPathname(
35390  const char *zPath, /* Input path */
35391  char *zOut, /* Output buffer */
35392  int nOut /* Allocated size of buffer zOut */
35393 ){
35394  int nPath = sqlite3Strlen30(zPath);
35395  int iOff = 0;
35396  if( zPath[0]!='/' ){
35397  if( osGetcwd(zOut, nOut-2)==0 ){
35398  return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
35399  }
35400  iOff = sqlite3Strlen30(zOut);
35401  zOut[iOff++] = '/';
35402  }
35403  if( (iOff+nPath+1)>nOut ){
35404  /* SQLite assumes that xFullPathname() nul-terminates the output buffer
35405  ** even if it returns an error. */
35406  zOut[iOff] = '\0';
35407  return SQLITE_CANTOPEN_BKPT;
35408  }
35409  sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
35410  return SQLITE_OK;
35411 }
35412 
35413 /*
35414 ** Turn a relative pathname into a full pathname. The relative path
35415 ** is stored as a nul-terminated string in the buffer pointed to by
35416 ** zPath.
35417 **
35418 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
35419 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
35420 ** this buffer before returning.
35421 */
35422 static int unixFullPathname(
35423  sqlite3_vfs *pVfs, /* Pointer to vfs object */
35424  const char *zPath, /* Possibly relative input path */
35425  int nOut, /* Size of output buffer in bytes */
35426  char *zOut /* Output buffer */
35427 ){
35428 #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
35429  return mkFullPathname(zPath, zOut, nOut);
35430 #else
35431  int rc = SQLITE_OK;
35432  int nByte;
35433  int nLink = 1; /* Number of symbolic links followed so far */
35434  const char *zIn = zPath; /* Input path for each iteration of loop */
35435  char *zDel = 0;
35436 
35437  assert( pVfs->mxPathname==MAX_PATHNAME );
35438  UNUSED_PARAMETER(pVfs);
35439 
35440  /* It's odd to simulate an io-error here, but really this is just
35441  ** using the io-error infrastructure to test that SQLite handles this
35442  ** function failing. This function could fail if, for example, the
35443  ** current working directory has been unlinked.
35444  */
35445  SimulateIOError( return SQLITE_ERROR );
35446 
35447  do {
35448 
35449  /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
35450  ** link, or false otherwise. */
35451  int bLink = 0;
35452  struct stat buf;
35453  if( osLstat(zIn, &buf)!=0 ){
35454  if( errno!=ENOENT ){
35455  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
35456  }
35457  }else{
35458  bLink = S_ISLNK(buf.st_mode);
35459  }
35460 
35461  if( bLink ){
35462  if( zDel==0 ){
35463  zDel = sqlite3_malloc(nOut);
35464  if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
35465  }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
35466  rc = SQLITE_CANTOPEN_BKPT;
35467  }
35468 
35469  if( rc==SQLITE_OK ){
35470  nByte = osReadlink(zIn, zDel, nOut-1);
35471  if( nByte<0 ){
35472  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
35473  }else{
35474  if( zDel[0]!='/' ){
35475  int n;
35476  for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
35477  if( nByte+n+1>nOut ){
35478  rc = SQLITE_CANTOPEN_BKPT;
35479  }else{
35480  memmove(&zDel[n], zDel, nByte+1);
35481  memcpy(zDel, zIn, n);
35482  nByte += n;
35483  }
35484  }
35485  zDel[nByte] = '\0';
35486  }
35487  }
35488 
35489  zIn = zDel;
35490  }
35491 
35492  assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
35493  if( rc==SQLITE_OK && zIn!=zOut ){
35494  rc = mkFullPathname(zIn, zOut, nOut);
35495  }
35496  if( bLink==0 ) break;
35497  zIn = zOut;
35498  }while( rc==SQLITE_OK );
35499 
35500  sqlite3_free(zDel);
35501  return rc;
35502 #endif /* HAVE_READLINK && HAVE_LSTAT */
35503 }
35504 
35505 
35506 #ifndef SQLITE_OMIT_LOAD_EXTENSION
35507 /*
35508 ** Interfaces for opening a shared library, finding entry points
35509 ** within the shared library, and closing the shared library.
35510 */
35511 #include <dlfcn.h>
35512 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
35513  UNUSED_PARAMETER(NotUsed);
35514  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
35515 }
35516 
35517 /*
35518 ** SQLite calls this function immediately after a call to unixDlSym() or
35519 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
35520 ** message is available, it is written to zBufOut. If no error message
35521 ** is available, zBufOut is left unmodified and SQLite uses a default
35522 ** error message.
35523 */
35524 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
35525  const char *zErr;
35526  UNUSED_PARAMETER(NotUsed);
35527  unixEnterMutex();
35528  zErr = dlerror();
35529  if( zErr ){
35530  sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
35531  }
35532  unixLeaveMutex();
35533 }
35534 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
35535  /*
35536  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
35537  ** cast into a pointer to a function. And yet the library dlsym() routine
35538  ** returns a void* which is really a pointer to a function. So how do we
35539  ** use dlsym() with -pedantic-errors?
35540  **
35541  ** Variable x below is defined to be a pointer to a function taking
35542  ** parameters void* and const char* and returning a pointer to a function.
35543  ** We initialize x by assigning it a pointer to the dlsym() function.
35544  ** (That assignment requires a cast.) Then we call the function that
35545  ** x points to.
35546  **
35547  ** This work-around is unlikely to work correctly on any system where
35548  ** you really cannot cast a function pointer into void*. But then, on the
35549  ** other hand, dlsym() will not work on such a system either, so we have
35550  ** not really lost anything.
35551  */
35552  void (*(*x)(void*,const char*))(void);
35553  UNUSED_PARAMETER(NotUsed);
35554  x = (void(*(*)(void*,const char*))(void))dlsym;
35555  return (*x)(p, zSym);
35556 }
35557 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
35558  UNUSED_PARAMETER(NotUsed);
35559  dlclose(pHandle);
35560 }
35561 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
35562  #define unixDlOpen 0
35563  #define unixDlError 0
35564  #define unixDlSym 0
35565  #define unixDlClose 0
35566 #endif
35567 
35568 /*
35569 ** Write nBuf bytes of random data to the supplied buffer zBuf.
35570 */
35571 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
35572  UNUSED_PARAMETER(NotUsed);
35573  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
35574 
35575  /* We have to initialize zBuf to prevent valgrind from reporting
35576  ** errors. The reports issued by valgrind are incorrect - we would
35577  ** prefer that the randomness be increased by making use of the
35578  ** uninitialized space in zBuf - but valgrind errors tend to worry
35579  ** some users. Rather than argue, it seems easier just to initialize
35580  ** the whole array and silence valgrind, even if that means less randomness
35581  ** in the random seed.
35582  **
35583  ** When testing, initializing zBuf[] to zero is all we do. That means
35584  ** that we always use the same random number sequence. This makes the
35585  ** tests repeatable.
35586  */
35587  memset(zBuf, 0, nBuf);
35588  randomnessPid = osGetpid(0);
35589 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
35590  {
35591  int fd, got;
35592  fd = robust_open("/dev/urandom", O_RDONLY, 0);
35593  if( fd<0 ){
35594  time_t t;
35595  time(&t);
35596  memcpy(zBuf, &t, sizeof(t));
35597  memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
35598  assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
35599  nBuf = sizeof(t) + sizeof(randomnessPid);
35600  }else{
35601  do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
35602  robust_close(0, fd, __LINE__);
35603  }
35604  }
35605 #endif
35606  return nBuf;
35607 }
35608 
35609 
35610 /*
35611 ** Sleep for a little while. Return the amount of time slept.
35612 ** The argument is the number of microseconds we want to sleep.
35613 ** The return value is the number of microseconds of sleep actually
35614 ** requested from the underlying operating system, a number which
35615 ** might be greater than or equal to the argument, but not less
35616 ** than the argument.
35617 */
35618 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
35619 #if OS_VXWORKS
35620  struct timespec sp;
35621 
35622  sp.tv_sec = microseconds / 1000000;
35623  sp.tv_nsec = (microseconds % 1000000) * 1000;
35624  nanosleep(&sp, NULL);
35625  UNUSED_PARAMETER(NotUsed);
35626  return microseconds;
35627 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
35628  usleep(microseconds);
35629  UNUSED_PARAMETER(NotUsed);
35630  return microseconds;
35631 #else
35632  int seconds = (microseconds+999999)/1000000;
35633  sleep(seconds);
35634  UNUSED_PARAMETER(NotUsed);
35635  return seconds*1000000;
35636 #endif
35637 }
35638 
35639 /*
35640 ** The following variable, if set to a non-zero value, is interpreted as
35641 ** the number of seconds since 1970 and is used to set the result of
35642 ** sqlite3OsCurrentTime() during testing.
35643 */
35644 #ifdef SQLITE_TEST
35645 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
35646 #endif
35647 
35648 /*
35649 ** Find the current time (in Universal Coordinated Time). Write into *piNow
35650 ** the current time and date as a Julian Day number times 86_400_000. In
35651 ** other words, write into *piNow the number of milliseconds since the Julian
35652 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35653 ** proleptic Gregorian calendar.
35654 **
35655 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
35656 ** cannot be found.
35657 */
35658 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
35659  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35660  int rc = SQLITE_OK;
35661 #if defined(NO_GETTOD)
35662  time_t t;
35663  time(&t);
35664  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
35665 #elif OS_VXWORKS
35666  struct timespec sNow;
35667  clock_gettime(CLOCK_REALTIME, &sNow);
35668  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
35669 #else
35670  struct timeval sNow;
35671  (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
35672  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
35673 #endif
35674 
35675 #ifdef SQLITE_TEST
35676  if( sqlite3_current_time ){
35677  *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35678  }
35679 #endif
35680  UNUSED_PARAMETER(NotUsed);
35681  return rc;
35682 }
35683 
35684 #ifndef SQLITE_OMIT_DEPRECATED
35685 /*
35686 ** Find the current time (in Universal Coordinated Time). Write the
35687 ** current time and date as a Julian Day number into *prNow and
35688 ** return 0. Return 1 if the time and date cannot be found.
35689 */
35690 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
35691  sqlite3_int64 i = 0;
35692  int rc;
35693  UNUSED_PARAMETER(NotUsed);
35694  rc = unixCurrentTimeInt64(0, &i);
35695  *prNow = i/86400000.0;
35696  return rc;
35697 }
35698 #else
35699 # define unixCurrentTime 0
35700 #endif
35701 
35702 /*
35703 ** The xGetLastError() method is designed to return a better
35704 ** low-level error message when operating-system problems come up
35705 ** during SQLite operation. Only the integer return code is currently
35706 ** used.
35707 */
35708 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
35709  UNUSED_PARAMETER(NotUsed);
35710  UNUSED_PARAMETER(NotUsed2);
35711  UNUSED_PARAMETER(NotUsed3);
35712  return errno;
35713 }
35714 
35715 
35716 /*
35717 ************************ End of sqlite3_vfs methods ***************************
35718 ******************************************************************************/
35719 
35720 /******************************************************************************
35721 ************************** Begin Proxy Locking ********************************
35722 **
35723 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
35724 ** other locking methods on secondary lock files. Proxy locking is a
35725 ** meta-layer over top of the primitive locking implemented above. For
35726 ** this reason, the division that implements of proxy locking is deferred
35727 ** until late in the file (here) after all of the other I/O methods have
35728 ** been defined - so that the primitive locking methods are available
35729 ** as services to help with the implementation of proxy locking.
35730 **
35731 ****
35732 **
35733 ** The default locking schemes in SQLite use byte-range locks on the
35734 ** database file to coordinate safe, concurrent access by multiple readers
35735 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
35736 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
35737 ** as POSIX read & write locks over fixed set of locations (via fsctl),
35738 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
35739 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
35740 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
35741 ** address in the shared range is taken for a SHARED lock, the entire
35742 ** shared range is taken for an EXCLUSIVE lock):
35743 **
35744 ** PENDING_BYTE 0x40000000
35745 ** RESERVED_BYTE 0x40000001
35746 ** SHARED_RANGE 0x40000002 -> 0x40000200
35747 **
35748 ** This works well on the local file system, but shows a nearly 100x
35749 ** slowdown in read performance on AFP because the AFP client disables
35750 ** the read cache when byte-range locks are present. Enabling the read
35751 ** cache exposes a cache coherency problem that is present on all OS X
35752 ** supported network file systems. NFS and AFP both observe the
35753 ** close-to-open semantics for ensuring cache coherency
35754 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
35755 ** address the requirements for concurrent database access by multiple
35756 ** readers and writers
35757 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
35758 **
35759 ** To address the performance and cache coherency issues, proxy file locking
35760 ** changes the way database access is controlled by limiting access to a
35761 ** single host at a time and moving file locks off of the database file
35762 ** and onto a proxy file on the local file system.
35763 **
35764 **
35765 ** Using proxy locks
35766 ** -----------------
35767 **
35768 ** C APIs
35769 **
35770 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
35771 ** <proxy_path> | ":auto:");
35772 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
35773 ** &<proxy_path>);
35774 **
35775 **
35776 ** SQL pragmas
35777 **
35778 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
35779 ** PRAGMA [database.]lock_proxy_file
35780 **
35781 ** Specifying ":auto:" means that if there is a conch file with a matching
35782 ** host ID in it, the proxy path in the conch file will be used, otherwise
35783 ** a proxy path based on the user's temp dir
35784 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
35785 ** actual proxy file name is generated from the name and path of the
35786 ** database file. For example:
35787 **
35788 ** For database path "/Users/me/foo.db"
35789 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
35790 **
35791 ** Once a lock proxy is configured for a database connection, it can not
35792 ** be removed, however it may be switched to a different proxy path via
35793 ** the above APIs (assuming the conch file is not being held by another
35794 ** connection or process).
35795 **
35796 **
35797 ** How proxy locking works
35798 ** -----------------------
35799 **
35800 ** Proxy file locking relies primarily on two new supporting files:
35801 **
35802 ** * conch file to limit access to the database file to a single host
35803 ** at a time
35804 **
35805 ** * proxy file to act as a proxy for the advisory locks normally
35806 ** taken on the database
35807 **
35808 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
35809 ** by taking an sqlite-style shared lock on the conch file, reading the
35810 ** contents and comparing the host's unique host ID (see below) and lock
35811 ** proxy path against the values stored in the conch. The conch file is
35812 ** stored in the same directory as the database file and the file name
35813 ** is patterned after the database file name as ".<databasename>-conch".
35814 ** If the conch file does not exist, or its contents do not match the
35815 ** host ID and/or proxy path, then the lock is escalated to an exclusive
35816 ** lock and the conch file contents is updated with the host ID and proxy
35817 ** path and the lock is downgraded to a shared lock again. If the conch
35818 ** is held by another process (with a shared lock), the exclusive lock
35819 ** will fail and SQLITE_BUSY is returned.
35820 **
35821 ** The proxy file - a single-byte file used for all advisory file locks
35822 ** normally taken on the database file. This allows for safe sharing
35823 ** of the database file for multiple readers and writers on the same
35824 ** host (the conch ensures that they all use the same local lock file).
35825 **
35826 ** Requesting the lock proxy does not immediately take the conch, it is
35827 ** only taken when the first request to lock database file is made.
35828 ** This matches the semantics of the traditional locking behavior, where
35829 ** opening a connection to a database file does not take a lock on it.
35830 ** The shared lock and an open file descriptor are maintained until
35831 ** the connection to the database is closed.
35832 **
35833 ** The proxy file and the lock file are never deleted so they only need
35834 ** to be created the first time they are used.
35835 **
35836 ** Configuration options
35837 ** ---------------------
35838 **
35839 ** SQLITE_PREFER_PROXY_LOCKING
35840 **
35841 ** Database files accessed on non-local file systems are
35842 ** automatically configured for proxy locking, lock files are
35843 ** named automatically using the same logic as
35844 ** PRAGMA lock_proxy_file=":auto:"
35845 **
35846 ** SQLITE_PROXY_DEBUG
35847 **
35848 ** Enables the logging of error messages during host id file
35849 ** retrieval and creation
35850 **
35851 ** LOCKPROXYDIR
35852 **
35853 ** Overrides the default directory used for lock proxy files that
35854 ** are named automatically via the ":auto:" setting
35855 **
35856 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
35857 **
35858 ** Permissions to use when creating a directory for storing the
35859 ** lock proxy files, only used when LOCKPROXYDIR is not set.
35860 **
35861 **
35862 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
35863 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
35864 ** force proxy locking to be used for every database file opened, and 0
35865 ** will force automatic proxy locking to be disabled for all database
35866 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
35867 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
35868 */
35869 
35870 /*
35871 ** Proxy locking is only available on MacOSX
35872 */
35873 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35874 
35875 /*
35876 ** The proxyLockingContext has the path and file structures for the remote
35877 ** and local proxy files in it
35878 */
35879 typedef struct proxyLockingContext proxyLockingContext;
35880 struct proxyLockingContext {
35881  unixFile *conchFile; /* Open conch file */
35882  char *conchFilePath; /* Name of the conch file */
35883  unixFile *lockProxy; /* Open proxy lock file */
35884  char *lockProxyPath; /* Name of the proxy lock file */
35885  char *dbPath; /* Name of the open file */
35886  int conchHeld; /* 1 if the conch is held, -1 if lockless */
35887  int nFails; /* Number of conch taking failures */
35888  void *oldLockingContext; /* Original lockingcontext to restore on close */
35889  sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
35890 };
35891 
35892 /*
35893 ** The proxy lock file path for the database at dbPath is written into lPath,
35894 ** which must point to valid, writable memory large enough for a maxLen length
35895 ** file path.
35896 */
35897 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
35898  int len;
35899  int dbLen;
35900  int i;
35901 
35902 #ifdef LOCKPROXYDIR
35903  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
35904 #else
35905 # ifdef _CS_DARWIN_USER_TEMP_DIR
35906  {
35907  if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
35908  OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
35909  lPath, errno, osGetpid(0)));
35910  return SQLITE_IOERR_LOCK;
35911  }
35912  len = strlcat(lPath, "sqliteplocks", maxLen);
35913  }
35914 # else
35915  len = strlcpy(lPath, "/tmp/", maxLen);
35916 # endif
35917 #endif
35918 
35919  if( lPath[len-1]!='/' ){
35920  len = strlcat(lPath, "/", maxLen);
35921  }
35922 
35923  /* transform the db path to a unique cache name */
35924  dbLen = (int)strlen(dbPath);
35925  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
35926  char c = dbPath[i];
35927  lPath[i+len] = (c=='/')?'_':c;
35928  }
35929  lPath[i+len]='\0';
35930  strlcat(lPath, ":auto:", maxLen);
35931  OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
35932  return SQLITE_OK;
35933 }
35934 
35935 /*
35936  ** Creates the lock file and any missing directories in lockPath
35937  */
35938 static int proxyCreateLockPath(const char *lockPath){
35939  int i, len;
35940  char buf[MAXPATHLEN];
35941  int start = 0;
35942 
35943  assert(lockPath!=NULL);
35944  /* try to create all the intermediate directories */
35945  len = (int)strlen(lockPath);
35946  buf[0] = lockPath[0];
35947  for( i=1; i<len; i++ ){
35948  if( lockPath[i] == '/' && (i - start > 0) ){
35949  /* only mkdir if leaf dir != "." or "/" or ".." */
35950  if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
35951  || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
35952  buf[i]='\0';
35953  if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
35954  int err=errno;
35955  if( err!=EEXIST ) {
35956  OSTRACE(("CREATELOCKPATH FAILED creating %s, "
35957  "'%s' proxy lock path=%s pid=%d\n",
35958  buf, strerror(err), lockPath, osGetpid(0)));
35959  return err;
35960  }
35961  }
35962  }
35963  start=i+1;
35964  }
35965  buf[i] = lockPath[i];
35966  }
35967  OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
35968  return 0;
35969 }
35970 
35971 /*
35972 ** Create a new VFS file descriptor (stored in memory obtained from
35973 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
35974 **
35975 ** The caller is responsible not only for closing the file descriptor
35976 ** but also for freeing the memory associated with the file descriptor.
35977 */
35978 static int proxyCreateUnixFile(
35979  const char *path, /* path for the new unixFile */
35980  unixFile **ppFile, /* unixFile created and returned by ref */
35981  int islockfile /* if non zero missing dirs will be created */
35982 ) {
35983  int fd = -1;
35984  unixFile *pNew;
35985  int rc = SQLITE_OK;
35986  int openFlags = O_RDWR | O_CREAT;
35987  sqlite3_vfs dummyVfs;
35988  int terrno = 0;
35989  UnixUnusedFd *pUnused = NULL;
35990 
35991  /* 1. first try to open/create the file
35992  ** 2. if that fails, and this is a lock file (not-conch), try creating
35993  ** the parent directories and then try again.
35994  ** 3. if that fails, try to open the file read-only
35995  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
35996  */
35997  pUnused = findReusableFd(path, openFlags);
35998  if( pUnused ){
35999  fd = pUnused->fd;
36000  }else{
36001  pUnused = sqlite3_malloc64(sizeof(*pUnused));
36002  if( !pUnused ){
36003  return SQLITE_NOMEM_BKPT;
36004  }
36005  }
36006  if( fd<0 ){
36007  fd = robust_open(path, openFlags, 0);
36008  terrno = errno;
36009  if( fd<0 && errno==ENOENT && islockfile ){
36010  if( proxyCreateLockPath(path) == SQLITE_OK ){
36011  fd = robust_open(path, openFlags, 0);
36012  }
36013  }
36014  }
36015  if( fd<0 ){
36016  openFlags = O_RDONLY;
36017  fd = robust_open(path, openFlags, 0);
36018  terrno = errno;
36019  }
36020  if( fd<0 ){
36021  if( islockfile ){
36022  return SQLITE_BUSY;
36023  }
36024  switch (terrno) {
36025  case EACCES:
36026  return SQLITE_PERM;
36027  case EIO:
36028  return SQLITE_IOERR_LOCK; /* even though it is the conch */
36029  default:
36030  return SQLITE_CANTOPEN_BKPT;
36031  }
36032  }
36033 
36034  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
36035  if( pNew==NULL ){
36036  rc = SQLITE_NOMEM_BKPT;
36037  goto end_create_proxy;
36038  }
36039  memset(pNew, 0, sizeof(unixFile));
36040  pNew->openFlags = openFlags;
36041  memset(&dummyVfs, 0, sizeof(dummyVfs));
36042  dummyVfs.pAppData = (void*)&autolockIoFinder;
36043  dummyVfs.zName = "dummy";
36044  pUnused->fd = fd;
36045  pUnused->flags = openFlags;
36046  pNew->pUnused = pUnused;
36047 
36048  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
36049  if( rc==SQLITE_OK ){
36050  *ppFile = pNew;
36051  return SQLITE_OK;
36052  }
36053 end_create_proxy:
36054  robust_close(pNew, fd, __LINE__);
36055  sqlite3_free(pNew);
36056  sqlite3_free(pUnused);
36057  return rc;
36058 }
36059 
36060 #ifdef SQLITE_TEST
36061 /* simulate multiple hosts by creating unique hostid file paths */
36062 SQLITE_API int sqlite3_hostid_num = 0;
36063 #endif
36064 
36065 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
36066 
36067 #ifdef HAVE_GETHOSTUUID
36068 /* Not always defined in the headers as it ought to be */
36069 extern int gethostuuid(uuid_t id, const struct timespec *wait);
36070 #endif
36071 
36072 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
36073 ** bytes of writable memory.
36074 */
36075 static int proxyGetHostID(unsigned char *pHostID, int *pError){
36076  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
36077  memset(pHostID, 0, PROXY_HOSTIDLEN);
36078 #ifdef HAVE_GETHOSTUUID
36079  {
36080  struct timespec timeout = {1, 0}; /* 1 sec timeout */
36081  if( gethostuuid(pHostID, &timeout) ){
36082  int err = errno;
36083  if( pError ){
36084  *pError = err;
36085  }
36086  return SQLITE_IOERR;
36087  }
36088  }
36089 #else
36090  UNUSED_PARAMETER(pError);
36091 #endif
36092 #ifdef SQLITE_TEST
36093  /* simulate multiple hosts by creating unique hostid file paths */
36094  if( sqlite3_hostid_num != 0){
36095  pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
36096  }
36097 #endif
36098 
36099  return SQLITE_OK;
36100 }
36101 
36102 /* The conch file contains the header, host id and lock file path
36103  */
36104 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
36105 #define PROXY_HEADERLEN 1 /* conch file header length */
36106 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
36107 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
36108 
36109 /*
36110 ** Takes an open conch file, copies the contents to a new path and then moves
36111 ** it back. The newly created file's file descriptor is assigned to the
36112 ** conch file structure and finally the original conch file descriptor is
36113 ** closed. Returns zero if successful.
36114 */
36115 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
36116  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36117  unixFile *conchFile = pCtx->conchFile;
36118  char tPath[MAXPATHLEN];
36119  char buf[PROXY_MAXCONCHLEN];
36120  char *cPath = pCtx->conchFilePath;
36121  size_t readLen = 0;
36122  size_t pathLen = 0;
36123  char errmsg[64] = "";
36124  int fd = -1;
36125  int rc = -1;
36126  UNUSED_PARAMETER(myHostID);
36127 
36128  /* create a new path by replace the trailing '-conch' with '-break' */
36129  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
36130  if( pathLen>MAXPATHLEN || pathLen<6 ||
36131  (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
36132  sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
36133  goto end_breaklock;
36134  }
36135  /* read the conch content */
36136  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
36137  if( readLen<PROXY_PATHINDEX ){
36138  sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
36139  goto end_breaklock;
36140  }
36141  /* write it out to the temporary break file */
36142  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
36143  if( fd<0 ){
36144  sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
36145  goto end_breaklock;
36146  }
36147  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
36148  sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
36149  goto end_breaklock;
36150  }
36151  if( rename(tPath, cPath) ){
36152  sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
36153  goto end_breaklock;
36154  }
36155  rc = 0;
36156  fprintf(stderr, "broke stale lock on %s\n", cPath);
36157  robust_close(pFile, conchFile->h, __LINE__);
36158  conchFile->h = fd;
36159  conchFile->openFlags = O_RDWR | O_CREAT;
36160 
36161 end_breaklock:
36162  if( rc ){
36163  if( fd>=0 ){
36164  osUnlink(tPath);
36165  robust_close(pFile, fd, __LINE__);
36166  }
36167  fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
36168  }
36169  return rc;
36170 }
36171 
36172 /* Take the requested lock on the conch file and break a stale lock if the
36173 ** host id matches.
36174 */
36175 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
36176  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36177  unixFile *conchFile = pCtx->conchFile;
36178  int rc = SQLITE_OK;
36179  int nTries = 0;
36180  struct timespec conchModTime;
36181 
36182  memset(&conchModTime, 0, sizeof(conchModTime));
36183  do {
36184  rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36185  nTries ++;
36186  if( rc==SQLITE_BUSY ){
36187  /* If the lock failed (busy):
36188  * 1st try: get the mod time of the conch, wait 0.5s and try again.
36189  * 2nd try: fail if the mod time changed or host id is different, wait
36190  * 10 sec and try again
36191  * 3rd try: break the lock unless the mod time has changed.
36192  */
36193  struct stat buf;
36194  if( osFstat(conchFile->h, &buf) ){
36195  storeLastErrno(pFile, errno);
36196  return SQLITE_IOERR_LOCK;
36197  }
36198 
36199  if( nTries==1 ){
36200  conchModTime = buf.st_mtimespec;
36201  usleep(500000); /* wait 0.5 sec and try the lock again*/
36202  continue;
36203  }
36204 
36205  assert( nTries>1 );
36206  if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
36207  conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
36208  return SQLITE_BUSY;
36209  }
36210 
36211  if( nTries==2 ){
36212  char tBuf[PROXY_MAXCONCHLEN];
36213  int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
36214  if( len<0 ){
36215  storeLastErrno(pFile, errno);
36216  return SQLITE_IOERR_LOCK;
36217  }
36218  if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
36219  /* don't break the lock if the host id doesn't match */
36220  if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
36221  return SQLITE_BUSY;
36222  }
36223  }else{
36224  /* don't break the lock on short read or a version mismatch */
36225  return SQLITE_BUSY;
36226  }
36227  usleep(10000000); /* wait 10 sec and try the lock again */
36228  continue;
36229  }
36230 
36231  assert( nTries==3 );
36232  if( 0==proxyBreakConchLock(pFile, myHostID) ){
36233  rc = SQLITE_OK;
36234  if( lockType==EXCLUSIVE_LOCK ){
36235  rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
36236  }
36237  if( !rc ){
36238  rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36239  }
36240  }
36241  }
36242  } while( rc==SQLITE_BUSY && nTries<3 );
36243 
36244  return rc;
36245 }
36246 
36247 /* Takes the conch by taking a shared lock and read the contents conch, if
36248 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
36249 ** lockPath means that the lockPath in the conch file will be used if the
36250 ** host IDs match, or a new lock path will be generated automatically
36251 ** and written to the conch file.
36252 */
36253 static int proxyTakeConch(unixFile *pFile){
36254  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36255 
36256  if( pCtx->conchHeld!=0 ){
36257  return SQLITE_OK;
36258  }else{
36259  unixFile *conchFile = pCtx->conchFile;
36260  uuid_t myHostID;
36261  int pError = 0;
36262  char readBuf[PROXY_MAXCONCHLEN];
36263  char lockPath[MAXPATHLEN];
36264  char *tempLockPath = NULL;
36265  int rc = SQLITE_OK;
36266  int createConch = 0;
36267  int hostIdMatch = 0;
36268  int readLen = 0;
36269  int tryOldLockPath = 0;
36270  int forceNewLockPath = 0;
36271 
36272  OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
36273  (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36274  osGetpid(0)));
36275 
36276  rc = proxyGetHostID(myHostID, &pError);
36277  if( (rc&0xff)==SQLITE_IOERR ){
36278  storeLastErrno(pFile, pError);
36279  goto end_takeconch;
36280  }
36281  rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
36282  if( rc!=SQLITE_OK ){
36283  goto end_takeconch;
36284  }
36285  /* read the existing conch file */
36286  readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
36287  if( readLen<0 ){
36288  /* I/O error: lastErrno set by seekAndRead */
36289  storeLastErrno(pFile, conchFile->lastErrno);
36290  rc = SQLITE_IOERR_READ;
36291  goto end_takeconch;
36292  }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
36293  readBuf[0]!=(char)PROXY_CONCHVERSION ){
36294  /* a short read or version format mismatch means we need to create a new
36295  ** conch file.
36296  */
36297  createConch = 1;
36298  }
36299  /* if the host id matches and the lock path already exists in the conch
36300  ** we'll try to use the path there, if we can't open that path, we'll
36301  ** retry with a new auto-generated path
36302  */
36303  do { /* in case we need to try again for an :auto: named lock file */
36304 
36305  if( !createConch && !forceNewLockPath ){
36306  hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
36307  PROXY_HOSTIDLEN);
36308  /* if the conch has data compare the contents */
36309  if( !pCtx->lockProxyPath ){
36310  /* for auto-named local lock file, just check the host ID and we'll
36311  ** use the local lock file path that's already in there
36312  */
36313  if( hostIdMatch ){
36314  size_t pathLen = (readLen - PROXY_PATHINDEX);
36315 
36316  if( pathLen>=MAXPATHLEN ){
36317  pathLen=MAXPATHLEN-1;
36318  }
36319  memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
36320  lockPath[pathLen] = 0;
36321  tempLockPath = lockPath;
36322  tryOldLockPath = 1;
36323  /* create a copy of the lock path if the conch is taken */
36324  goto end_takeconch;
36325  }
36326  }else if( hostIdMatch
36327  && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
36328  readLen-PROXY_PATHINDEX)
36329  ){
36330  /* conch host and lock path match */
36331  goto end_takeconch;
36332  }
36333  }
36334 
36335  /* if the conch isn't writable and doesn't match, we can't take it */
36336  if( (conchFile->openFlags&O_RDWR) == 0 ){
36337  rc = SQLITE_BUSY;
36338  goto end_takeconch;
36339  }
36340 
36341  /* either the conch didn't match or we need to create a new one */
36342  if( !pCtx->lockProxyPath ){
36343  proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
36344  tempLockPath = lockPath;
36345  /* create a copy of the lock path _only_ if the conch is taken */
36346  }
36347 
36348  /* update conch with host and path (this will fail if other process
36349  ** has a shared lock already), if the host id matches, use the big
36350  ** stick.
36351  */
36352  futimes(conchFile->h, NULL);
36353  if( hostIdMatch && !createConch ){
36354  if( conchFile->pInode && conchFile->pInode->nShared>1 ){
36355  /* We are trying for an exclusive lock but another thread in this
36356  ** same process is still holding a shared lock. */
36357  rc = SQLITE_BUSY;
36358  } else {
36359  rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36360  }
36361  }else{
36362  rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36363  }
36364  if( rc==SQLITE_OK ){
36365  char writeBuffer[PROXY_MAXCONCHLEN];
36366  int writeSize = 0;
36367 
36368  writeBuffer[0] = (char)PROXY_CONCHVERSION;
36369  memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
36370  if( pCtx->lockProxyPath!=NULL ){
36371  strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
36372  MAXPATHLEN);
36373  }else{
36374  strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
36375  }
36376  writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
36377  robust_ftruncate(conchFile->h, writeSize);
36378  rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
36379  full_fsync(conchFile->h,0,0);
36380  /* If we created a new conch file (not just updated the contents of a
36381  ** valid conch file), try to match the permissions of the database
36382  */
36383  if( rc==SQLITE_OK && createConch ){
36384  struct stat buf;
36385  int err = osFstat(pFile->h, &buf);
36386  if( err==0 ){
36387  mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
36388  S_IROTH|S_IWOTH);
36389  /* try to match the database file R/W permissions, ignore failure */
36390 #ifndef SQLITE_PROXY_DEBUG
36391  osFchmod(conchFile->h, cmode);
36392 #else
36393  do{
36394  rc = osFchmod(conchFile->h, cmode);
36395  }while( rc==(-1) && errno==EINTR );
36396  if( rc!=0 ){
36397  int code = errno;
36398  fprintf(stderr, "fchmod %o FAILED with %d %s\n",
36399  cmode, code, strerror(code));
36400  } else {
36401  fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
36402  }
36403  }else{
36404  int code = errno;
36405  fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
36406  err, code, strerror(code));
36407 #endif
36408  }
36409  }
36410  }
36411  conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
36412 
36413  end_takeconch:
36414  OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
36415  if( rc==SQLITE_OK && pFile->openFlags ){
36416  int fd;
36417  if( pFile->h>=0 ){
36418  robust_close(pFile, pFile->h, __LINE__);
36419  }
36420  pFile->h = -1;
36421  fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
36422  OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
36423  if( fd>=0 ){
36424  pFile->h = fd;
36425  }else{
36426  rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
36427  during locking */
36428  }
36429  }
36430  if( rc==SQLITE_OK && !pCtx->lockProxy ){
36431  char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
36432  rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
36433  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
36434  /* we couldn't create the proxy lock file with the old lock file path
36435  ** so try again via auto-naming
36436  */
36437  forceNewLockPath = 1;
36438  tryOldLockPath = 0;
36439  continue; /* go back to the do {} while start point, try again */
36440  }
36441  }
36442  if( rc==SQLITE_OK ){
36443  /* Need to make a copy of path if we extracted the value
36444  ** from the conch file or the path was allocated on the stack
36445  */
36446  if( tempLockPath ){
36447  pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
36448  if( !pCtx->lockProxyPath ){
36449  rc = SQLITE_NOMEM_BKPT;
36450  }
36451  }
36452  }
36453  if( rc==SQLITE_OK ){
36454  pCtx->conchHeld = 1;
36455 
36456  if( pCtx->lockProxy->pMethod == &afpIoMethods ){
36457  afpLockingContext *afpCtx;
36458  afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
36459  afpCtx->dbPath = pCtx->lockProxyPath;
36460  }
36461  } else {
36462  conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36463  }
36464  OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
36465  rc==SQLITE_OK?"ok":"failed"));
36466  return rc;
36467  } while (1); /* in case we need to retry the :auto: lock file -
36468  ** we should never get here except via the 'continue' call. */
36469  }
36470 }
36471 
36472 /*
36473 ** If pFile holds a lock on a conch file, then release that lock.
36474 */
36475 static int proxyReleaseConch(unixFile *pFile){
36476  int rc = SQLITE_OK; /* Subroutine return code */
36477  proxyLockingContext *pCtx; /* The locking context for the proxy lock */
36478  unixFile *conchFile; /* Name of the conch file */
36479 
36480  pCtx = (proxyLockingContext *)pFile->lockingContext;
36481  conchFile = pCtx->conchFile;
36482  OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
36483  (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36484  osGetpid(0)));
36485  if( pCtx->conchHeld>0 ){
36486  rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36487  }
36488  pCtx->conchHeld = 0;
36489  OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
36490  (rc==SQLITE_OK ? "ok" : "failed")));
36491  return rc;
36492 }
36493 
36494 /*
36495 ** Given the name of a database file, compute the name of its conch file.
36496 ** Store the conch filename in memory obtained from sqlite3_malloc64().
36497 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
36498 ** or SQLITE_NOMEM if unable to obtain memory.
36499 **
36500 ** The caller is responsible for ensuring that the allocated memory
36501 ** space is eventually freed.
36502 **
36503 ** *pConchPath is set to NULL if a memory allocation error occurs.
36504 */
36505 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
36506  int i; /* Loop counter */
36507  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
36508  char *conchPath; /* buffer in which to construct conch name */
36509 
36510  /* Allocate space for the conch filename and initialize the name to
36511  ** the name of the original database file. */
36512  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
36513  if( conchPath==0 ){
36514  return SQLITE_NOMEM_BKPT;
36515  }
36516  memcpy(conchPath, dbPath, len+1);
36517 
36518  /* now insert a "." before the last / character */
36519  for( i=(len-1); i>=0; i-- ){
36520  if( conchPath[i]=='/' ){
36521  i++;
36522  break;
36523  }
36524  }
36525  conchPath[i]='.';
36526  while ( i<len ){
36527  conchPath[i+1]=dbPath[i];
36528  i++;
36529  }
36530 
36531  /* append the "-conch" suffix to the file */
36532  memcpy(&conchPath[i+1], "-conch", 7);
36533  assert( (int)strlen(conchPath) == len+7 );
36534 
36535  return SQLITE_OK;
36536 }
36537 
36538 
36539 /* Takes a fully configured proxy locking-style unix file and switches
36540 ** the local lock file path
36541 */
36542 static int switchLockProxyPath(unixFile *pFile, const char *path) {
36543  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36544  char *oldPath = pCtx->lockProxyPath;
36545  int rc = SQLITE_OK;
36546 
36547  if( pFile->eFileLock!=NO_LOCK ){
36548  return SQLITE_BUSY;
36549  }
36550 
36551  /* nothing to do if the path is NULL, :auto: or matches the existing path */
36552  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
36553  (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
36554  return SQLITE_OK;
36555  }else{
36556  unixFile *lockProxy = pCtx->lockProxy;
36557  pCtx->lockProxy=NULL;
36558  pCtx->conchHeld = 0;
36559  if( lockProxy!=NULL ){
36560  rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
36561  if( rc ) return rc;
36562  sqlite3_free(lockProxy);
36563  }
36564  sqlite3_free(oldPath);
36565  pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
36566  }
36567 
36568  return rc;
36569 }
36570 
36571 /*
36572 ** pFile is a file that has been opened by a prior xOpen call. dbPath
36573 ** is a string buffer at least MAXPATHLEN+1 characters in size.
36574 **
36575 ** This routine find the filename associated with pFile and writes it
36576 ** int dbPath.
36577 */
36578 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
36579 #if defined(__APPLE__)
36580  if( pFile->pMethod == &afpIoMethods ){
36581  /* afp style keeps a reference to the db path in the filePath field
36582  ** of the struct */
36583  assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36584  strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
36585  MAXPATHLEN);
36586  } else
36587 #endif
36588  if( pFile->pMethod == &dotlockIoMethods ){
36589  /* dot lock style uses the locking context to store the dot lock
36590  ** file path */
36591  int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
36592  memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
36593  }else{
36594  /* all other styles use the locking context to store the db file path */
36595  assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36596  strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
36597  }
36598  return SQLITE_OK;
36599 }
36600 
36601 /*
36602 ** Takes an already filled in unix file and alters it so all file locking
36603 ** will be performed on the local proxy lock file. The following fields
36604 ** are preserved in the locking context so that they can be restored and
36605 ** the unix structure properly cleaned up at close time:
36606 ** ->lockingContext
36607 ** ->pMethod
36608 */
36609 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
36610  proxyLockingContext *pCtx;
36611  char dbPath[MAXPATHLEN+1]; /* Name of the database file */
36612  char *lockPath=NULL;
36613  int rc = SQLITE_OK;
36614 
36615  if( pFile->eFileLock!=NO_LOCK ){
36616  return SQLITE_BUSY;
36617  }
36618  proxyGetDbPathForUnixFile(pFile, dbPath);
36619  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
36620  lockPath=NULL;
36621  }else{
36622  lockPath=(char *)path;
36623  }
36624 
36625  OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
36626  (lockPath ? lockPath : ":auto:"), osGetpid(0)));
36627 
36628  pCtx = sqlite3_malloc64( sizeof(*pCtx) );
36629  if( pCtx==0 ){
36630  return SQLITE_NOMEM_BKPT;
36631  }
36632  memset(pCtx, 0, sizeof(*pCtx));
36633 
36634  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
36635  if( rc==SQLITE_OK ){
36636  rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
36637  if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
36638  /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
36639  ** (c) the file system is read-only, then enable no-locking access.
36640  ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
36641  ** that openFlags will have only one of O_RDONLY or O_RDWR.
36642  */
36643  struct statfs fsInfo;
36644  struct stat conchInfo;
36645  int goLockless = 0;
36646 
36647  if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
36648  int err = errno;
36649  if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
36650  goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
36651  }
36652  }
36653  if( goLockless ){
36654  pCtx->conchHeld = -1; /* read only FS/ lockless */
36655  rc = SQLITE_OK;
36656  }
36657  }
36658  }
36659  if( rc==SQLITE_OK && lockPath ){
36660  pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
36661  }
36662 
36663  if( rc==SQLITE_OK ){
36664  pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
36665  if( pCtx->dbPath==NULL ){
36666  rc = SQLITE_NOMEM_BKPT;
36667  }
36668  }
36669  if( rc==SQLITE_OK ){
36670  /* all memory is allocated, proxys are created and assigned,
36671  ** switch the locking context and pMethod then return.
36672  */
36673  pCtx->oldLockingContext = pFile->lockingContext;
36674  pFile->lockingContext = pCtx;
36675  pCtx->pOldMethod = pFile->pMethod;
36676  pFile->pMethod = &proxyIoMethods;
36677  }else{
36678  if( pCtx->conchFile ){
36679  pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
36680  sqlite3_free(pCtx->conchFile);
36681  }
36682  sqlite3DbFree(0, pCtx->lockProxyPath);
36683  sqlite3_free(pCtx->conchFilePath);
36684  sqlite3_free(pCtx);
36685  }
36686  OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
36687  (rc==SQLITE_OK ? "ok" : "failed")));
36688  return rc;
36689 }
36690 
36691 
36692 /*
36693 ** This routine handles sqlite3_file_control() calls that are specific
36694 ** to proxy locking.
36695 */
36696 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
36697  switch( op ){
36698  case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
36699  unixFile *pFile = (unixFile*)id;
36700  if( pFile->pMethod == &proxyIoMethods ){
36701  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36702  proxyTakeConch(pFile);
36703  if( pCtx->lockProxyPath ){
36704  *(const char **)pArg = pCtx->lockProxyPath;
36705  }else{
36706  *(const char **)pArg = ":auto: (not held)";
36707  }
36708  } else {
36709  *(const char **)pArg = NULL;
36710  }
36711  return SQLITE_OK;
36712  }
36713  case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
36714  unixFile *pFile = (unixFile*)id;
36715  int rc = SQLITE_OK;
36716  int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
36717  if( pArg==NULL || (const char *)pArg==0 ){
36718  if( isProxyStyle ){
36719  /* turn off proxy locking - not supported. If support is added for
36720  ** switching proxy locking mode off then it will need to fail if
36721  ** the journal mode is WAL mode.
36722  */
36723  rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
36724  }else{
36725  /* turn off proxy locking - already off - NOOP */
36726  rc = SQLITE_OK;
36727  }
36728  }else{
36729  const char *proxyPath = (const char *)pArg;
36730  if( isProxyStyle ){
36731  proxyLockingContext *pCtx =
36732  (proxyLockingContext*)pFile->lockingContext;
36733  if( !strcmp(pArg, ":auto:")
36734  || (pCtx->lockProxyPath &&
36735  !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
36736  ){
36737  rc = SQLITE_OK;
36738  }else{
36739  rc = switchLockProxyPath(pFile, proxyPath);
36740  }
36741  }else{
36742  /* turn on proxy file locking */
36743  rc = proxyTransformUnixFile(pFile, proxyPath);
36744  }
36745  }
36746  return rc;
36747  }
36748  default: {
36749  assert( 0 ); /* The call assures that only valid opcodes are sent */
36750  }
36751  }
36752  /*NOTREACHED*/
36753  return SQLITE_ERROR;
36754 }
36755 
36756 /*
36757 ** Within this division (the proxying locking implementation) the procedures
36758 ** above this point are all utilities. The lock-related methods of the
36759 ** proxy-locking sqlite3_io_method object follow.
36760 */
36761 
36762 
36763 /*
36764 ** This routine checks if there is a RESERVED lock held on the specified
36765 ** file by this or any other process. If such a lock is held, set *pResOut
36766 ** to a non-zero value otherwise *pResOut is set to zero. The return value
36767 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
36768 */
36769 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
36770  unixFile *pFile = (unixFile*)id;
36771  int rc = proxyTakeConch(pFile);
36772  if( rc==SQLITE_OK ){
36773  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36774  if( pCtx->conchHeld>0 ){
36775  unixFile *proxy = pCtx->lockProxy;
36776  return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
36777  }else{ /* conchHeld < 0 is lockless */
36778  pResOut=0;
36779  }
36780  }
36781  return rc;
36782 }
36783 
36784 /*
36785 ** Lock the file with the lock specified by parameter eFileLock - one
36786 ** of the following:
36787 **
36788 ** (1) SHARED_LOCK
36789 ** (2) RESERVED_LOCK
36790 ** (3) PENDING_LOCK
36791 ** (4) EXCLUSIVE_LOCK
36792 **
36793 ** Sometimes when requesting one lock state, additional lock states
36794 ** are inserted in between. The locking might fail on one of the later
36795 ** transitions leaving the lock state different from what it started but
36796 ** still short of its goal. The following chart shows the allowed
36797 ** transitions and the inserted intermediate states:
36798 **
36799 ** UNLOCKED -> SHARED
36800 ** SHARED -> RESERVED
36801 ** SHARED -> (PENDING) -> EXCLUSIVE
36802 ** RESERVED -> (PENDING) -> EXCLUSIVE
36803 ** PENDING -> EXCLUSIVE
36804 **
36805 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
36806 ** routine to lower a locking level.
36807 */
36808 static int proxyLock(sqlite3_file *id, int eFileLock) {
36809  unixFile *pFile = (unixFile*)id;
36810  int rc = proxyTakeConch(pFile);
36811  if( rc==SQLITE_OK ){
36812  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36813  if( pCtx->conchHeld>0 ){
36814  unixFile *proxy = pCtx->lockProxy;
36815  rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
36816  pFile->eFileLock = proxy->eFileLock;
36817  }else{
36818  /* conchHeld < 0 is lockless */
36819  }
36820  }
36821  return rc;
36822 }
36823 
36824 
36825 /*
36826 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
36827 ** must be either NO_LOCK or SHARED_LOCK.
36828 **
36829 ** If the locking level of the file descriptor is already at or below
36830 ** the requested locking level, this routine is a no-op.
36831 */
36832 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
36833  unixFile *pFile = (unixFile*)id;
36834  int rc = proxyTakeConch(pFile);
36835  if( rc==SQLITE_OK ){
36836  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36837  if( pCtx->conchHeld>0 ){
36838  unixFile *proxy = pCtx->lockProxy;
36839  rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
36840  pFile->eFileLock = proxy->eFileLock;
36841  }else{
36842  /* conchHeld < 0 is lockless */
36843  }
36844  }
36845  return rc;
36846 }
36847 
36848 /*
36849 ** Close a file that uses proxy locks.
36850 */
36851 static int proxyClose(sqlite3_file *id) {
36852  if( ALWAYS(id) ){
36853  unixFile *pFile = (unixFile*)id;
36854  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36855  unixFile *lockProxy = pCtx->lockProxy;
36856  unixFile *conchFile = pCtx->conchFile;
36857  int rc = SQLITE_OK;
36858 
36859  if( lockProxy ){
36860  rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
36861  if( rc ) return rc;
36862  rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
36863  if( rc ) return rc;
36864  sqlite3_free(lockProxy);
36865  pCtx->lockProxy = 0;
36866  }
36867  if( conchFile ){
36868  if( pCtx->conchHeld ){
36869  rc = proxyReleaseConch(pFile);
36870  if( rc ) return rc;
36871  }
36872  rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
36873  if( rc ) return rc;
36874  sqlite3_free(conchFile);
36875  }
36876  sqlite3DbFree(0, pCtx->lockProxyPath);
36877  sqlite3_free(pCtx->conchFilePath);
36878  sqlite3DbFree(0, pCtx->dbPath);
36879  /* restore the original locking context and pMethod then close it */
36880  pFile->lockingContext = pCtx->oldLockingContext;
36881  pFile->pMethod = pCtx->pOldMethod;
36882  sqlite3_free(pCtx);
36883  return pFile->pMethod->xClose(id);
36884  }
36885  return SQLITE_OK;
36886 }
36887 
36888 
36889 
36890 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
36891 /*
36892 ** The proxy locking style is intended for use with AFP filesystems.
36893 ** And since AFP is only supported on MacOSX, the proxy locking is also
36894 ** restricted to MacOSX.
36895 **
36896 **
36897 ******************* End of the proxy lock implementation **********************
36898 ******************************************************************************/
36899 
36900 /*
36901 ** Initialize the operating system interface.
36902 **
36903 ** This routine registers all VFS implementations for unix-like operating
36904 ** systems. This routine, and the sqlite3_os_end() routine that follows,
36905 ** should be the only routines in this file that are visible from other
36906 ** files.
36907 **
36908 ** This routine is called once during SQLite initialization and by a
36909 ** single thread. The memory allocation and mutex subsystems have not
36910 ** necessarily been initialized when this routine is called, and so they
36911 ** should not be used.
36912 */
36913 SQLITE_API int sqlite3_os_init(void){
36914  /*
36915  ** The following macro defines an initializer for an sqlite3_vfs object.
36916  ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
36917  ** to the "finder" function. (pAppData is a pointer to a pointer because
36918  ** silly C90 rules prohibit a void* from being cast to a function pointer
36919  ** and so we have to go through the intermediate pointer to avoid problems
36920  ** when compiling with -pedantic-errors on GCC.)
36921  **
36922  ** The FINDER parameter to this macro is the name of the pointer to the
36923  ** finder-function. The finder-function returns a pointer to the
36924  ** sqlite_io_methods object that implements the desired locking
36925  ** behaviors. See the division above that contains the IOMETHODS
36926  ** macro for addition information on finder-functions.
36927  **
36928  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
36929  ** object. But the "autolockIoFinder" available on MacOSX does a little
36930  ** more than that; it looks at the filesystem type that hosts the
36931  ** database file and tries to choose an locking method appropriate for
36932  ** that filesystem time.
36933  */
36934  #define UNIXVFS(VFSNAME, FINDER) { \
36935  3, /* iVersion */ \
36936  sizeof(unixFile), /* szOsFile */ \
36937  MAX_PATHNAME, /* mxPathname */ \
36938  0, /* pNext */ \
36939  VFSNAME, /* zName */ \
36940  (void*)&FINDER, /* pAppData */ \
36941  unixOpen, /* xOpen */ \
36942  unixDelete, /* xDelete */ \
36943  unixAccess, /* xAccess */ \
36944  unixFullPathname, /* xFullPathname */ \
36945  unixDlOpen, /* xDlOpen */ \
36946  unixDlError, /* xDlError */ \
36947  unixDlSym, /* xDlSym */ \
36948  unixDlClose, /* xDlClose */ \
36949  unixRandomness, /* xRandomness */ \
36950  unixSleep, /* xSleep */ \
36951  unixCurrentTime, /* xCurrentTime */ \
36952  unixGetLastError, /* xGetLastError */ \
36953  unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
36954  unixSetSystemCall, /* xSetSystemCall */ \
36955  unixGetSystemCall, /* xGetSystemCall */ \
36956  unixNextSystemCall, /* xNextSystemCall */ \
36957  }
36958 
36959  /*
36960  ** All default VFSes for unix are contained in the following array.
36961  **
36962  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
36963  ** by the SQLite core when the VFS is registered. So the following
36964  ** array cannot be const.
36965  */
36966  static sqlite3_vfs aVfs[] = {
36967 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36968  UNIXVFS("unix", autolockIoFinder ),
36969 #elif OS_VXWORKS
36970  UNIXVFS("unix", vxworksIoFinder ),
36971 #else
36972  UNIXVFS("unix", posixIoFinder ),
36973 #endif
36974  UNIXVFS("unix-none", nolockIoFinder ),
36975  UNIXVFS("unix-dotfile", dotlockIoFinder ),
36976  UNIXVFS("unix-excl", posixIoFinder ),
36977 #if OS_VXWORKS
36978  UNIXVFS("unix-namedsem", semIoFinder ),
36979 #endif
36980 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
36981  UNIXVFS("unix-posix", posixIoFinder ),
36982 #endif
36983 #if SQLITE_ENABLE_LOCKING_STYLE
36984  UNIXVFS("unix-flock", flockIoFinder ),
36985 #endif
36986 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36987  UNIXVFS("unix-afp", afpIoFinder ),
36988  UNIXVFS("unix-nfs", nfsIoFinder ),
36989  UNIXVFS("unix-proxy", proxyIoFinder ),
36990 #endif
36991  };
36992  unsigned int i; /* Loop counter */
36993 
36994  /* Double-check that the aSyscall[] array has been constructed
36995  ** correctly. See ticket [bb3a86e890c8e96ab] */
36996  assert( ArraySize(aSyscall)==28 );
36997 
36998  /* Register all VFSes defined in the aVfs[] array */
36999  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
37000  sqlite3_vfs_register(&aVfs[i], i==0);
37001  }
37002  return SQLITE_OK;
37003 }
37004 
37005 /*
37006 ** Shutdown the operating system interface.
37007 **
37008 ** Some operating systems might need to do some cleanup in this routine,
37009 ** to release dynamically allocated objects. But not on unix.
37010 ** This routine is a no-op for unix.
37011 */
37012 SQLITE_API int sqlite3_os_end(void){
37013  return SQLITE_OK;
37014 }
37015 
37016 #endif /* SQLITE_OS_UNIX */
37017 
37018 /************** End of os_unix.c *********************************************/
37019 /************** Begin file os_win.c ******************************************/
37020 /*
37021 ** 2004 May 22
37022 **
37023 ** The author disclaims copyright to this source code. In place of
37024 ** a legal notice, here is a blessing:
37025 **
37026 ** May you do good and not evil.
37027 ** May you find forgiveness for yourself and forgive others.
37028 ** May you share freely, never taking more than you give.
37029 **
37030 ******************************************************************************
37031 **
37032 ** This file contains code that is specific to Windows.
37033 */
37034 /* #include "sqliteInt.h" */
37035 #if SQLITE_OS_WIN /* This file is used for Windows only */
37036 
37037 /*
37038 ** Include code that is common to all os_*.c files
37039 */
37040 /************** Include os_common.h in the middle of os_win.c ****************/
37041 /************** Begin file os_common.h ***************************************/
37042 /*
37043 ** 2004 May 22
37044 **
37045 ** The author disclaims copyright to this source code. In place of
37046 ** a legal notice, here is a blessing:
37047 **
37048 ** May you do good and not evil.
37049 ** May you find forgiveness for yourself and forgive others.
37050 ** May you share freely, never taking more than you give.
37051 **
37052 ******************************************************************************
37053 **
37054 ** This file contains macros and a little bit of code that is common to
37055 ** all of the platform-specific files (os_*.c) and is #included into those
37056 ** files.
37057 **
37058 ** This file should be #included by the os_*.c files only. It is not a
37059 ** general purpose header file.
37060 */
37061 #ifndef _OS_COMMON_H_
37062 #define _OS_COMMON_H_
37063 
37064 /*
37065 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
37066 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
37067 ** switch. The following code should catch this problem at compile-time.
37068 */
37069 #ifdef MEMORY_DEBUG
37070 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
37071 #endif
37072 
37073 /*
37074 ** Macros for performance tracing. Normally turned off. Only works
37075 ** on i486 hardware.
37076 */
37077 #ifdef SQLITE_PERFORMANCE_TRACE
37078 
37079 /*
37080 ** hwtime.h contains inline assembler code for implementing
37081 ** high-performance timing routines.
37082 */
37083 /************** Include hwtime.h in the middle of os_common.h ****************/
37084 /************** Begin file hwtime.h ******************************************/
37085 /*
37086 ** 2008 May 27
37087 **
37088 ** The author disclaims copyright to this source code. In place of
37089 ** a legal notice, here is a blessing:
37090 **
37091 ** May you do good and not evil.
37092 ** May you find forgiveness for yourself and forgive others.
37093 ** May you share freely, never taking more than you give.
37094 **
37095 ******************************************************************************
37096 **
37097 ** This file contains inline asm code for retrieving "high-performance"
37098 ** counters for x86 class CPUs.
37099 */
37100 #ifndef SQLITE_HWTIME_H
37101 #define SQLITE_HWTIME_H
37102 
37103 /*
37104 ** The following routine only works on pentium-class (or newer) processors.
37105 ** It uses the RDTSC opcode to read the cycle count value out of the
37106 ** processor and returns that value. This can be used for high-res
37107 ** profiling.
37108 */
37109 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
37110  (defined(i386) || defined(__i386__) || defined(_M_IX86))
37111 
37112  #if defined(__GNUC__)
37113 
37114  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37115  unsigned int lo, hi;
37116  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
37117  return (sqlite_uint64)hi << 32 | lo;
37118  }
37119 
37120  #elif defined(_MSC_VER)
37121 
37122  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
37123  __asm {
37124  rdtsc
37125  ret ; return value at EDX:EAX
37126  }
37127  }
37128 
37129  #endif
37130 
37131 #elif (defined(__GNUC__) && defined(__x86_64__))
37132 
37133  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37134  unsigned long val;
37135  __asm__ __volatile__ ("rdtsc" : "=A" (val));
37136  return val;
37137  }
37138 
37139 #elif (defined(__GNUC__) && defined(__ppc__))
37140 
37141  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37142  unsigned long long retval;
37143  unsigned long junk;
37144  __asm__ __volatile__ ("\n\
37145  1: mftbu %1\n\
37146  mftb %L0\n\
37147  mftbu %0\n\
37148  cmpw %0,%1\n\
37149  bne 1b"
37150  : "=r" (retval), "=r" (junk));
37151  return retval;
37152  }
37153 
37154 #else
37155 
37156  #error Need implementation of sqlite3Hwtime() for your platform.
37157 
37158  /*
37159  ** To compile without implementing sqlite3Hwtime() for your platform,
37160  ** you can remove the above #error and use the following
37161  ** stub function. You will lose timing support for many
37162  ** of the debugging and testing utilities, but it should at
37163  ** least compile and run.
37164  */
37165 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
37166 
37167 #endif
37168 
37169 #endif /* !defined(SQLITE_HWTIME_H) */
37170 
37171 /************** End of hwtime.h **********************************************/
37172 /************** Continuing where we left off in os_common.h ******************/
37173 
37174 static sqlite_uint64 g_start;
37175 static sqlite_uint64 g_elapsed;
37176 #define TIMER_START g_start=sqlite3Hwtime()
37177 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
37178 #define TIMER_ELAPSED g_elapsed
37179 #else
37180 #define TIMER_START
37181 #define TIMER_END
37182 #define TIMER_ELAPSED ((sqlite_uint64)0)
37183 #endif
37184 
37185 /*
37186 ** If we compile with the SQLITE_TEST macro set, then the following block
37187 ** of code will give us the ability to simulate a disk I/O error. This
37188 ** is used for testing the I/O recovery logic.
37189 */
37190 #if defined(SQLITE_TEST)
37191 SQLITE_API extern int sqlite3_io_error_hit;
37192 SQLITE_API extern int sqlite3_io_error_hardhit;
37193 SQLITE_API extern int sqlite3_io_error_pending;
37194 SQLITE_API extern int sqlite3_io_error_persist;
37195 SQLITE_API extern int sqlite3_io_error_benign;
37196 SQLITE_API extern int sqlite3_diskfull_pending;
37197 SQLITE_API extern int sqlite3_diskfull;
37198 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
37199 #define SimulateIOError(CODE) \
37200  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
37201  || sqlite3_io_error_pending-- == 1 ) \
37202  { local_ioerr(); CODE; }
37203 static void local_ioerr(){
37204  IOTRACE(("IOERR\n"));
37205  sqlite3_io_error_hit++;
37206  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
37207 }
37208 #define SimulateDiskfullError(CODE) \
37209  if( sqlite3_diskfull_pending ){ \
37210  if( sqlite3_diskfull_pending == 1 ){ \
37211  local_ioerr(); \
37212  sqlite3_diskfull = 1; \
37213  sqlite3_io_error_hit = 1; \
37214  CODE; \
37215  }else{ \
37216  sqlite3_diskfull_pending--; \
37217  } \
37218  }
37219 #else
37220 #define SimulateIOErrorBenign(X)
37221 #define SimulateIOError(A)
37222 #define SimulateDiskfullError(A)
37223 #endif /* defined(SQLITE_TEST) */
37224 
37225 /*
37226 ** When testing, keep a count of the number of open files.
37227 */
37228 #if defined(SQLITE_TEST)
37229 SQLITE_API extern int sqlite3_open_file_count;
37230 #define OpenCounter(X) sqlite3_open_file_count+=(X)
37231 #else
37232 #define OpenCounter(X)
37233 #endif /* defined(SQLITE_TEST) */
37234 
37235 #endif /* !defined(_OS_COMMON_H_) */
37236 
37237 /************** End of os_common.h *******************************************/
37238 /************** Continuing where we left off in os_win.c *********************/
37239 
37240 /*
37241 ** Include the header file for the Windows VFS.
37242 */
37243 /* #include "os_win.h" */
37244 
37245 /*
37246 ** Compiling and using WAL mode requires several APIs that are only
37247 ** available in Windows platforms based on the NT kernel.
37248 */
37249 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
37250 # error "WAL mode requires support from the Windows NT kernel, compile\
37251  with SQLITE_OMIT_WAL."
37252 #endif
37253 
37254 #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
37255 # error "Memory mapped files require support from the Windows NT kernel,\
37256  compile with SQLITE_MAX_MMAP_SIZE=0."
37257 #endif
37258 
37259 /*
37260 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
37261 ** based on the sub-platform)?
37262 */
37263 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
37264 # define SQLITE_WIN32_HAS_ANSI
37265 #endif
37266 
37267 /*
37268 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
37269 ** based on the sub-platform)?
37270 */
37271 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
37272  !defined(SQLITE_WIN32_NO_WIDE)
37273 # define SQLITE_WIN32_HAS_WIDE
37274 #endif
37275 
37276 /*
37277 ** Make sure at least one set of Win32 APIs is available.
37278 */
37279 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
37280 # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
37281  must be defined."
37282 #endif
37283 
37284 /*
37285 ** Define the required Windows SDK version constants if they are not
37286 ** already available.
37287 */
37288 #ifndef NTDDI_WIN8
37289 # define NTDDI_WIN8 0x06020000
37290 #endif
37291 
37292 #ifndef NTDDI_WINBLUE
37293 # define NTDDI_WINBLUE 0x06030000
37294 #endif
37295 
37296 #ifndef NTDDI_WINTHRESHOLD
37297 # define NTDDI_WINTHRESHOLD 0x06040000
37298 #endif
37299 
37300 /*
37301 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
37302 ** target system. GetVersionEx was first deprecated in Win8.1.
37303 */
37304 #ifndef SQLITE_WIN32_GETVERSIONEX
37305 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
37306 # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
37307 # else
37308 # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
37309 # endif
37310 #endif
37311 
37312 /*
37313 ** Check to see if the CreateFileMappingA function is supported on the
37314 ** target system. It is unavailable when using "mincore.lib" on Win10.
37315 ** When compiling for Windows 10, always assume "mincore.lib" is in use.
37316 */
37317 #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
37318 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
37319 # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
37320 # else
37321 # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
37322 # endif
37323 #endif
37324 
37325 /*
37326 ** This constant should already be defined (in the "WinDef.h" SDK file).
37327 */
37328 #ifndef MAX_PATH
37329 # define MAX_PATH (260)
37330 #endif
37331 
37332 /*
37333 ** Maximum pathname length (in chars) for Win32. This should normally be
37334 ** MAX_PATH.
37335 */
37336 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
37337 # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
37338 #endif
37339 
37340 /*
37341 ** This constant should already be defined (in the "WinNT.h" SDK file).
37342 */
37343 #ifndef UNICODE_STRING_MAX_CHARS
37344 # define UNICODE_STRING_MAX_CHARS (32767)
37345 #endif
37346 
37347 /*
37348 ** Maximum pathname length (in chars) for WinNT. This should normally be
37349 ** UNICODE_STRING_MAX_CHARS.
37350 */
37351 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
37352 # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
37353 #endif
37354 
37355 /*
37356 ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
37357 ** characters, so we allocate 4 bytes per character assuming worst-case of
37358 ** 4-bytes-per-character for UTF8.
37359 */
37360 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
37361 # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
37362 #endif
37363 
37364 /*
37365 ** Maximum pathname length (in bytes) for WinNT. This should normally be
37366 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
37367 */
37368 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
37369 # define SQLITE_WINNT_MAX_PATH_BYTES \
37370  (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
37371 #endif
37372 
37373 /*
37374 ** Maximum error message length (in chars) for WinRT.
37375 */
37376 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
37377 # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
37378 #endif
37379 
37380 /*
37381 ** Returns non-zero if the character should be treated as a directory
37382 ** separator.
37383 */
37384 #ifndef winIsDirSep
37385 # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
37386 #endif
37387 
37388 /*
37389 ** This macro is used when a local variable is set to a value that is
37390 ** [sometimes] not used by the code (e.g. via conditional compilation).
37391 */
37392 #ifndef UNUSED_VARIABLE_VALUE
37393 # define UNUSED_VARIABLE_VALUE(x) (void)(x)
37394 #endif
37395 
37396 /*
37397 ** Returns the character that should be used as the directory separator.
37398 */
37399 #ifndef winGetDirSep
37400 # define winGetDirSep() '\\'
37401 #endif
37402 
37403 /*
37404 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
37405 ** mode or memory mapped files (e.g. these APIs are available in the Windows
37406 ** CE SDK; however, they are not present in the header file)?
37407 */
37408 #if SQLITE_WIN32_FILEMAPPING_API && \
37409  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
37410 /*
37411 ** Two of the file mapping APIs are different under WinRT. Figure out which
37412 ** set we need.
37413 */
37414 #if SQLITE_OS_WINRT
37415 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
37416  LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
37417 
37418 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
37419 #else
37420 #if defined(SQLITE_WIN32_HAS_ANSI)
37421 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
37422  DWORD, DWORD, DWORD, LPCSTR);
37423 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
37424 
37425 #if defined(SQLITE_WIN32_HAS_WIDE)
37426 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
37427  DWORD, DWORD, DWORD, LPCWSTR);
37428 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
37429 
37430 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
37431 #endif /* SQLITE_OS_WINRT */
37432 
37433 /*
37434 ** These file mapping APIs are common to both Win32 and WinRT.
37435 */
37436 
37437 WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
37438 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
37439 #endif /* SQLITE_WIN32_FILEMAPPING_API */
37440 
37441 /*
37442 ** Some Microsoft compilers lack this definition.
37443 */
37444 #ifndef INVALID_FILE_ATTRIBUTES
37445 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
37446 #endif
37447 
37448 #ifndef FILE_FLAG_MASK
37449 # define FILE_FLAG_MASK (0xFF3C0000)
37450 #endif
37451 
37452 #ifndef FILE_ATTRIBUTE_MASK
37453 # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
37454 #endif
37455 
37456 #ifndef SQLITE_OMIT_WAL
37457 /* Forward references to structures used for WAL */
37458 typedef struct winShm winShm; /* A connection to shared-memory */
37459 typedef struct winShmNode winShmNode; /* A region of shared-memory */
37460 #endif
37461 
37462 /*
37463 ** WinCE lacks native support for file locking so we have to fake it
37464 ** with some code of our own.
37465 */
37466 #if SQLITE_OS_WINCE
37467 typedef struct winceLock {
37468  int nReaders; /* Number of reader locks obtained */
37469  BOOL bPending; /* Indicates a pending lock has been obtained */
37470  BOOL bReserved; /* Indicates a reserved lock has been obtained */
37471  BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
37472 } winceLock;
37473 #endif
37474 
37475 /*
37476 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
37477 ** portability layer.
37478 */
37479 typedef struct winFile winFile;
37480 struct winFile {
37481  const sqlite3_io_methods *pMethod; /*** Must be first ***/
37482  sqlite3_vfs *pVfs; /* The VFS used to open this file */
37483  HANDLE h; /* Handle for accessing the file */
37484  u8 locktype; /* Type of lock currently held on this file */
37485  short sharedLockByte; /* Randomly chosen byte used as a shared lock */
37486  u8 ctrlFlags; /* Flags. See WINFILE_* below */
37487  DWORD lastErrno; /* The Windows errno from the last I/O error */
37488 #ifndef SQLITE_OMIT_WAL
37489  winShm *pShm; /* Instance of shared memory on this file */
37490 #endif
37491  const char *zPath; /* Full pathname of this file */
37492  int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
37493 #if SQLITE_OS_WINCE
37494  LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
37495  HANDLE hMutex; /* Mutex used to control access to shared lock */
37496  HANDLE hShared; /* Shared memory segment used for locking */
37497  winceLock local; /* Locks obtained by this instance of winFile */
37498  winceLock *shared; /* Global shared lock memory for the file */
37499 #endif
37500 #if SQLITE_MAX_MMAP_SIZE>0
37501  int nFetchOut; /* Number of outstanding xFetch references */
37502  HANDLE hMap; /* Handle for accessing memory mapping */
37503  void *pMapRegion; /* Area memory mapped */
37504  sqlite3_int64 mmapSize; /* Usable size of mapped region */
37505  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
37506  sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
37507 #endif
37508 };
37509 
37510 /*
37511 ** The winVfsAppData structure is used for the pAppData member for all of the
37512 ** Win32 VFS variants.
37513 */
37514 typedef struct winVfsAppData winVfsAppData;
37515 struct winVfsAppData {
37516  const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
37517  void *pAppData; /* The extra pAppData, if any. */
37518  BOOL bNoLock; /* Non-zero if locking is disabled. */
37519 };
37520 
37521 /*
37522 ** Allowed values for winFile.ctrlFlags
37523 */
37524 #define WINFILE_RDONLY 0x02 /* Connection is read only */
37525 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
37526 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
37527 
37528 /*
37529  * The size of the buffer used by sqlite3_win32_write_debug().
37530  */
37531 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
37532 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
37533 #endif
37534 
37535 /*
37536  * The value used with sqlite3_win32_set_directory() to specify that
37537  * the data directory should be changed.
37538  */
37539 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
37540 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
37541 #endif
37542 
37543 /*
37544  * The value used with sqlite3_win32_set_directory() to specify that
37545  * the temporary directory should be changed.
37546  */
37547 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
37548 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
37549 #endif
37550 
37551 /*
37552  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
37553  * various Win32 API heap functions instead of our own.
37554  */
37555 #ifdef SQLITE_WIN32_MALLOC
37556 
37557 /*
37558  * If this is non-zero, an isolated heap will be created by the native Win32
37559  * allocator subsystem; otherwise, the default process heap will be used. This
37560  * setting has no effect when compiling for WinRT. By default, this is enabled
37561  * and an isolated heap will be created to store all allocated data.
37562  *
37563  ******************************************************************************
37564  * WARNING: It is important to note that when this setting is non-zero and the
37565  * winMemShutdown function is called (e.g. by the sqlite3_shutdown
37566  * function), all data that was allocated using the isolated heap will
37567  * be freed immediately and any attempt to access any of that freed
37568  * data will almost certainly result in an immediate access violation.
37569  ******************************************************************************
37570  */
37571 #ifndef SQLITE_WIN32_HEAP_CREATE
37572 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
37573 #endif
37574 
37575 /*
37576  * This is cache size used in the calculation of the initial size of the
37577  * Win32-specific heap. It cannot be negative.
37578  */
37579 #ifndef SQLITE_WIN32_CACHE_SIZE
37580 # if SQLITE_DEFAULT_CACHE_SIZE>=0
37581 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
37582 # else
37583 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
37584 # endif
37585 #endif
37586 
37587 /*
37588  * The initial size of the Win32-specific heap. This value may be zero.
37589  */
37590 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
37591 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
37592  (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
37593 #endif
37594 
37595 /*
37596  * The maximum size of the Win32-specific heap. This value may be zero.
37597  */
37598 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
37599 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
37600 #endif
37601 
37602 /*
37603  * The extra flags to use in calls to the Win32 heap APIs. This value may be
37604  * zero for the default behavior.
37605  */
37606 #ifndef SQLITE_WIN32_HEAP_FLAGS
37607 # define SQLITE_WIN32_HEAP_FLAGS (0)
37608 #endif
37609 
37610 
37611 /*
37612 ** The winMemData structure stores information required by the Win32-specific
37613 ** sqlite3_mem_methods implementation.
37614 */
37615 typedef struct winMemData winMemData;
37616 struct winMemData {
37617 #ifndef NDEBUG
37618  u32 magic1; /* Magic number to detect structure corruption. */
37619 #endif
37620  HANDLE hHeap; /* The handle to our heap. */
37621  BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
37622 #ifndef NDEBUG
37623  u32 magic2; /* Magic number to detect structure corruption. */
37624 #endif
37625 };
37626 
37627 #ifndef NDEBUG
37628 #define WINMEM_MAGIC1 0x42b2830b
37629 #define WINMEM_MAGIC2 0xbd4d7cf4
37630 #endif
37631 
37632 static struct winMemData win_mem_data = {
37633 #ifndef NDEBUG
37634  WINMEM_MAGIC1,
37635 #endif
37636  NULL, FALSE
37637 #ifndef NDEBUG
37638  ,WINMEM_MAGIC2
37639 #endif
37640 };
37641 
37642 #ifndef NDEBUG
37643 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
37644 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
37645 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
37646 #else
37647 #define winMemAssertMagic()
37648 #endif
37649 
37650 #define winMemGetDataPtr() &win_mem_data
37651 #define winMemGetHeap() win_mem_data.hHeap
37652 #define winMemGetOwned() win_mem_data.bOwned
37653 
37654 static void *winMemMalloc(int nBytes);
37655 static void winMemFree(void *pPrior);
37656 static void *winMemRealloc(void *pPrior, int nBytes);
37657 static int winMemSize(void *p);
37658 static int winMemRoundup(int n);
37659 static int winMemInit(void *pAppData);
37660 static void winMemShutdown(void *pAppData);
37661 
37662 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
37663 #endif /* SQLITE_WIN32_MALLOC */
37664 
37665 /*
37666 ** The following variable is (normally) set once and never changes
37667 ** thereafter. It records whether the operating system is Win9x
37668 ** or WinNT.
37669 **
37670 ** 0: Operating system unknown.
37671 ** 1: Operating system is Win9x.
37672 ** 2: Operating system is WinNT.
37673 **
37674 ** In order to facilitate testing on a WinNT system, the test fixture
37675 ** can manually set this value to 1 to emulate Win98 behavior.
37676 */
37677 #ifdef SQLITE_TEST
37678 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37679 #else
37680 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37681 #endif
37682 
37683 #ifndef SYSCALL
37684 # define SYSCALL sqlite3_syscall_ptr
37685 #endif
37686 
37687 /*
37688 ** This function is not available on Windows CE or WinRT.
37689  */
37690 
37691 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
37692 # define osAreFileApisANSI() 1
37693 #endif
37694 
37695 /*
37696 ** Many system calls are accessed through pointer-to-functions so that
37697 ** they may be overridden at runtime to facilitate fault injection during
37698 ** testing and sandboxing. The following array holds the names and pointers
37699 ** to all overrideable system calls.
37700 */
37701 static struct win_syscall {
37702  const char *zName; /* Name of the system call */
37703  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
37704  sqlite3_syscall_ptr pDefault; /* Default value */
37705 } aSyscall[] = {
37706 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37707  { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
37708 #else
37709  { "AreFileApisANSI", (SYSCALL)0, 0 },
37710 #endif
37711 
37712 #ifndef osAreFileApisANSI
37713 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
37714 #endif
37715 
37716 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37717  { "CharLowerW", (SYSCALL)CharLowerW, 0 },
37718 #else
37719  { "CharLowerW", (SYSCALL)0, 0 },
37720 #endif
37721 
37722 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
37723 
37724 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37725  { "CharUpperW", (SYSCALL)CharUpperW, 0 },
37726 #else
37727  { "CharUpperW", (SYSCALL)0, 0 },
37728 #endif
37729 
37730 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
37731 
37732  { "CloseHandle", (SYSCALL)CloseHandle, 0 },
37733 
37734 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
37735 
37736 #if defined(SQLITE_WIN32_HAS_ANSI)
37737  { "CreateFileA", (SYSCALL)CreateFileA, 0 },
37738 #else
37739  { "CreateFileA", (SYSCALL)0, 0 },
37740 #endif
37741 
37742 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
37743  LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
37744 
37745 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37746  { "CreateFileW", (SYSCALL)CreateFileW, 0 },
37747 #else
37748  { "CreateFileW", (SYSCALL)0, 0 },
37749 #endif
37750 
37751 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
37752  LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
37753 
37754 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
37755  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
37756  SQLITE_WIN32_CREATEFILEMAPPINGA
37757  { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
37758 #else
37759  { "CreateFileMappingA", (SYSCALL)0, 0 },
37760 #endif
37761 
37762 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37763  DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
37764 
37765 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37766  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
37767  { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
37768 #else
37769  { "CreateFileMappingW", (SYSCALL)0, 0 },
37770 #endif
37771 
37772 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37773  DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
37774 
37775 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37776  { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
37777 #else
37778  { "CreateMutexW", (SYSCALL)0, 0 },
37779 #endif
37780 
37781 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
37782  LPCWSTR))aSyscall[8].pCurrent)
37783 
37784 #if defined(SQLITE_WIN32_HAS_ANSI)
37785  { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
37786 #else
37787  { "DeleteFileA", (SYSCALL)0, 0 },
37788 #endif
37789 
37790 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
37791 
37792 #if defined(SQLITE_WIN32_HAS_WIDE)
37793  { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
37794 #else
37795  { "DeleteFileW", (SYSCALL)0, 0 },
37796 #endif
37797 
37798 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
37799 
37800 #if SQLITE_OS_WINCE
37801  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
37802 #else
37803  { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
37804 #endif
37805 
37806 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37807  LPFILETIME))aSyscall[11].pCurrent)
37808 
37809 #if SQLITE_OS_WINCE
37810  { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
37811 #else
37812  { "FileTimeToSystemTime", (SYSCALL)0, 0 },
37813 #endif
37814 
37815 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37816  LPSYSTEMTIME))aSyscall[12].pCurrent)
37817 
37818  { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
37819 
37820 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
37821 
37822 #if defined(SQLITE_WIN32_HAS_ANSI)
37823  { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
37824 #else
37825  { "FormatMessageA", (SYSCALL)0, 0 },
37826 #endif
37827 
37828 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
37829  DWORD,va_list*))aSyscall[14].pCurrent)
37830 
37831 #if defined(SQLITE_WIN32_HAS_WIDE)
37832  { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
37833 #else
37834  { "FormatMessageW", (SYSCALL)0, 0 },
37835 #endif
37836 
37837 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
37838  DWORD,va_list*))aSyscall[15].pCurrent)
37839 
37840 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37841  { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
37842 #else
37843  { "FreeLibrary", (SYSCALL)0, 0 },
37844 #endif
37845 
37846 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
37847 
37848  { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
37849 
37850 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
37851 
37852 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37853  { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
37854 #else
37855  { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
37856 #endif
37857 
37858 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
37859  LPDWORD))aSyscall[18].pCurrent)
37860 
37861 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37862  { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
37863 #else
37864  { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
37865 #endif
37866 
37867 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
37868  LPDWORD))aSyscall[19].pCurrent)
37869 
37870 #if defined(SQLITE_WIN32_HAS_ANSI)
37871  { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
37872 #else
37873  { "GetFileAttributesA", (SYSCALL)0, 0 },
37874 #endif
37875 
37876 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
37877 
37878 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37879  { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
37880 #else
37881  { "GetFileAttributesW", (SYSCALL)0, 0 },
37882 #endif
37883 
37884 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
37885 
37886 #if defined(SQLITE_WIN32_HAS_WIDE)
37887  { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
37888 #else
37889  { "GetFileAttributesExW", (SYSCALL)0, 0 },
37890 #endif
37891 
37892 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
37893  LPVOID))aSyscall[22].pCurrent)
37894 
37895 #if !SQLITE_OS_WINRT
37896  { "GetFileSize", (SYSCALL)GetFileSize, 0 },
37897 #else
37898  { "GetFileSize", (SYSCALL)0, 0 },
37899 #endif
37900 
37901 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
37902 
37903 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37904  { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
37905 #else
37906  { "GetFullPathNameA", (SYSCALL)0, 0 },
37907 #endif
37908 
37909 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
37910  LPSTR*))aSyscall[24].pCurrent)
37911 
37912 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37913  { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
37914 #else
37915  { "GetFullPathNameW", (SYSCALL)0, 0 },
37916 #endif
37917 
37918 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
37919  LPWSTR*))aSyscall[25].pCurrent)
37920 
37921  { "GetLastError", (SYSCALL)GetLastError, 0 },
37922 
37923 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
37924 
37925 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37926 #if SQLITE_OS_WINCE
37927  /* The GetProcAddressA() routine is only available on Windows CE. */
37928  { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
37929 #else
37930  /* All other Windows platforms expect GetProcAddress() to take
37931  ** an ANSI string regardless of the _UNICODE setting */
37932  { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
37933 #endif
37934 #else
37935  { "GetProcAddressA", (SYSCALL)0, 0 },
37936 #endif
37937 
37938 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
37939  LPCSTR))aSyscall[27].pCurrent)
37940 
37941 #if !SQLITE_OS_WINRT
37942  { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
37943 #else
37944  { "GetSystemInfo", (SYSCALL)0, 0 },
37945 #endif
37946 
37947 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
37948 
37949  { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
37950 
37951 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
37952 
37953 #if !SQLITE_OS_WINCE
37954  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
37955 #else
37956  { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
37957 #endif
37958 
37959 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
37960  LPFILETIME))aSyscall[30].pCurrent)
37961 
37962 #if defined(SQLITE_WIN32_HAS_ANSI)
37963  { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
37964 #else
37965  { "GetTempPathA", (SYSCALL)0, 0 },
37966 #endif
37967 
37968 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
37969 
37970 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37971  { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
37972 #else
37973  { "GetTempPathW", (SYSCALL)0, 0 },
37974 #endif
37975 
37976 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
37977 
37978 #if !SQLITE_OS_WINRT
37979  { "GetTickCount", (SYSCALL)GetTickCount, 0 },
37980 #else
37981  { "GetTickCount", (SYSCALL)0, 0 },
37982 #endif
37983 
37984 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
37985 
37986 #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
37987  { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
37988 #else
37989  { "GetVersionExA", (SYSCALL)0, 0 },
37990 #endif
37991 
37992 #define osGetVersionExA ((BOOL(WINAPI*)( \
37993  LPOSVERSIONINFOA))aSyscall[34].pCurrent)
37994 
37995 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37996  SQLITE_WIN32_GETVERSIONEX
37997  { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
37998 #else
37999  { "GetVersionExW", (SYSCALL)0, 0 },
38000 #endif
38001 
38002 #define osGetVersionExW ((BOOL(WINAPI*)( \
38003  LPOSVERSIONINFOW))aSyscall[35].pCurrent)
38004 
38005  { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
38006 
38007 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
38008  SIZE_T))aSyscall[36].pCurrent)
38009 
38010 #if !SQLITE_OS_WINRT
38011  { "HeapCreate", (SYSCALL)HeapCreate, 0 },
38012 #else
38013  { "HeapCreate", (SYSCALL)0, 0 },
38014 #endif
38015 
38016 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
38017  SIZE_T))aSyscall[37].pCurrent)
38018 
38019 #if !SQLITE_OS_WINRT
38020  { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
38021 #else
38022  { "HeapDestroy", (SYSCALL)0, 0 },
38023 #endif
38024 
38025 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
38026 
38027  { "HeapFree", (SYSCALL)HeapFree, 0 },
38028 
38029 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
38030 
38031  { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
38032 
38033 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
38034  SIZE_T))aSyscall[40].pCurrent)
38035 
38036  { "HeapSize", (SYSCALL)HeapSize, 0 },
38037 
38038 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
38039  LPCVOID))aSyscall[41].pCurrent)
38040 
38041 #if !SQLITE_OS_WINRT
38042  { "HeapValidate", (SYSCALL)HeapValidate, 0 },
38043 #else
38044  { "HeapValidate", (SYSCALL)0, 0 },
38045 #endif
38046 
38047 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
38048  LPCVOID))aSyscall[42].pCurrent)
38049 
38050 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38051  { "HeapCompact", (SYSCALL)HeapCompact, 0 },
38052 #else
38053  { "HeapCompact", (SYSCALL)0, 0 },
38054 #endif
38055 
38056 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
38057 
38058 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
38059  { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
38060 #else
38061  { "LoadLibraryA", (SYSCALL)0, 0 },
38062 #endif
38063 
38064 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
38065 
38066 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
38067  !defined(SQLITE_OMIT_LOAD_EXTENSION)
38068  { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
38069 #else
38070  { "LoadLibraryW", (SYSCALL)0, 0 },
38071 #endif
38072 
38073 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
38074 
38075 #if !SQLITE_OS_WINRT
38076  { "LocalFree", (SYSCALL)LocalFree, 0 },
38077 #else
38078  { "LocalFree", (SYSCALL)0, 0 },
38079 #endif
38080 
38081 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
38082 
38083 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38084  { "LockFile", (SYSCALL)LockFile, 0 },
38085 #else
38086  { "LockFile", (SYSCALL)0, 0 },
38087 #endif
38088 
38089 #ifndef osLockFile
38090 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38091  DWORD))aSyscall[47].pCurrent)
38092 #endif
38093 
38094 #if !SQLITE_OS_WINCE
38095  { "LockFileEx", (SYSCALL)LockFileEx, 0 },
38096 #else
38097  { "LockFileEx", (SYSCALL)0, 0 },
38098 #endif
38099 
38100 #ifndef osLockFileEx
38101 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
38102  LPOVERLAPPED))aSyscall[48].pCurrent)
38103 #endif
38104 
38105 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
38106  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
38107  { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
38108 #else
38109  { "MapViewOfFile", (SYSCALL)0, 0 },
38110 #endif
38111 
38112 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38113  SIZE_T))aSyscall[49].pCurrent)
38114 
38115  { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
38116 
38117 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
38118  int))aSyscall[50].pCurrent)
38119 
38120  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
38121 
38122 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
38123  LARGE_INTEGER*))aSyscall[51].pCurrent)
38124 
38125  { "ReadFile", (SYSCALL)ReadFile, 0 },
38126 
38127 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
38128  LPOVERLAPPED))aSyscall[52].pCurrent)
38129 
38130  { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
38131 
38132 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
38133 
38134 #if !SQLITE_OS_WINRT
38135  { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
38136 #else
38137  { "SetFilePointer", (SYSCALL)0, 0 },
38138 #endif
38139 
38140 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
38141  DWORD))aSyscall[54].pCurrent)
38142 
38143 #if !SQLITE_OS_WINRT
38144  { "Sleep", (SYSCALL)Sleep, 0 },
38145 #else
38146  { "Sleep", (SYSCALL)0, 0 },
38147 #endif
38148 
38149 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
38150 
38151  { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
38152 
38153 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
38154  LPFILETIME))aSyscall[56].pCurrent)
38155 
38156 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38157  { "UnlockFile", (SYSCALL)UnlockFile, 0 },
38158 #else
38159  { "UnlockFile", (SYSCALL)0, 0 },
38160 #endif
38161 
38162 #ifndef osUnlockFile
38163 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38164  DWORD))aSyscall[57].pCurrent)
38165 #endif
38166 
38167 #if !SQLITE_OS_WINCE
38168  { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
38169 #else
38170  { "UnlockFileEx", (SYSCALL)0, 0 },
38171 #endif
38172 
38173 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38174  LPOVERLAPPED))aSyscall[58].pCurrent)
38175 
38176 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
38177  { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
38178 #else
38179  { "UnmapViewOfFile", (SYSCALL)0, 0 },
38180 #endif
38181 
38182 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
38183 
38184  { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
38185 
38186 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
38187  LPCSTR,LPBOOL))aSyscall[60].pCurrent)
38188 
38189  { "WriteFile", (SYSCALL)WriteFile, 0 },
38190 
38191 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
38192  LPOVERLAPPED))aSyscall[61].pCurrent)
38193 
38194 #if SQLITE_OS_WINRT
38195  { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
38196 #else
38197  { "CreateEventExW", (SYSCALL)0, 0 },
38198 #endif
38199 
38200 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
38201  DWORD,DWORD))aSyscall[62].pCurrent)
38202 
38203 #if !SQLITE_OS_WINRT
38204  { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
38205 #else
38206  { "WaitForSingleObject", (SYSCALL)0, 0 },
38207 #endif
38208 
38209 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
38210  DWORD))aSyscall[63].pCurrent)
38211 
38212 #if !SQLITE_OS_WINCE
38213  { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
38214 #else
38215  { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
38216 #endif
38217 
38218 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
38219  BOOL))aSyscall[64].pCurrent)
38220 
38221 #if SQLITE_OS_WINRT
38222  { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
38223 #else
38224  { "SetFilePointerEx", (SYSCALL)0, 0 },
38225 #endif
38226 
38227 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
38228  PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
38229 
38230 #if SQLITE_OS_WINRT
38231  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
38232 #else
38233  { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
38234 #endif
38235 
38236 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
38237  FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
38238 
38239 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38240  { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
38241 #else
38242  { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
38243 #endif
38244 
38245 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
38246  SIZE_T))aSyscall[67].pCurrent)
38247 
38248 #if SQLITE_OS_WINRT
38249  { "CreateFile2", (SYSCALL)CreateFile2, 0 },
38250 #else
38251  { "CreateFile2", (SYSCALL)0, 0 },
38252 #endif
38253 
38254 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
38255  LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
38256 
38257 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
38258  { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
38259 #else
38260  { "LoadPackagedLibrary", (SYSCALL)0, 0 },
38261 #endif
38262 
38263 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
38264  DWORD))aSyscall[69].pCurrent)
38265 
38266 #if SQLITE_OS_WINRT
38267  { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
38268 #else
38269  { "GetTickCount64", (SYSCALL)0, 0 },
38270 #endif
38271 
38272 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
38273 
38274 #if SQLITE_OS_WINRT
38275  { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
38276 #else
38277  { "GetNativeSystemInfo", (SYSCALL)0, 0 },
38278 #endif
38279 
38280 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
38281  LPSYSTEM_INFO))aSyscall[71].pCurrent)
38282 
38283 #if defined(SQLITE_WIN32_HAS_ANSI)
38284  { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
38285 #else
38286  { "OutputDebugStringA", (SYSCALL)0, 0 },
38287 #endif
38288 
38289 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
38290 
38291 #if defined(SQLITE_WIN32_HAS_WIDE)
38292  { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
38293 #else
38294  { "OutputDebugStringW", (SYSCALL)0, 0 },
38295 #endif
38296 
38297 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
38298 
38299  { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
38300 
38301 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
38302 
38303 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38304  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
38305 #else
38306  { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
38307 #endif
38308 
38309 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
38310  LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
38311 
38312 /*
38313 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
38314 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
38315 ** So do not try to make this is into a redefinable interface.
38316 */
38317 #if defined(InterlockedCompareExchange)
38318  { "InterlockedCompareExchange", (SYSCALL)0, 0 },
38319 
38320 #define osInterlockedCompareExchange InterlockedCompareExchange
38321 #else
38322  { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
38323 
38324 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
38325  SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
38326 #endif /* defined(InterlockedCompareExchange) */
38327 
38328 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38329  { "UuidCreate", (SYSCALL)UuidCreate, 0 },
38330 #else
38331  { "UuidCreate", (SYSCALL)0, 0 },
38332 #endif
38333 
38334 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
38335 
38336 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38337  { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
38338 #else
38339  { "UuidCreateSequential", (SYSCALL)0, 0 },
38340 #endif
38341 
38342 #define osUuidCreateSequential \
38343  ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
38344 
38345 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
38346  { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
38347 #else
38348  { "FlushViewOfFile", (SYSCALL)0, 0 },
38349 #endif
38350 
38351 #define osFlushViewOfFile \
38352  ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
38353 
38354 }; /* End of the overrideable system calls */
38355 
38356 /*
38357 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
38358 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
38359 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
38360 ** system call named zName.
38361 */
38362 static int winSetSystemCall(
38363  sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
38364  const char *zName, /* Name of system call to override */
38365  sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
38366 ){
38367  unsigned int i;
38368  int rc = SQLITE_NOTFOUND;
38369 
38370  UNUSED_PARAMETER(pNotUsed);
38371  if( zName==0 ){
38372  /* If no zName is given, restore all system calls to their default
38373  ** settings and return NULL
38374  */
38375  rc = SQLITE_OK;
38376  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38377  if( aSyscall[i].pDefault ){
38378  aSyscall[i].pCurrent = aSyscall[i].pDefault;
38379  }
38380  }
38381  }else{
38382  /* If zName is specified, operate on only the one system call
38383  ** specified.
38384  */
38385  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38386  if( strcmp(zName, aSyscall[i].zName)==0 ){
38387  if( aSyscall[i].pDefault==0 ){
38388  aSyscall[i].pDefault = aSyscall[i].pCurrent;
38389  }
38390  rc = SQLITE_OK;
38391  if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
38392  aSyscall[i].pCurrent = pNewFunc;
38393  break;
38394  }
38395  }
38396  }
38397  return rc;
38398 }
38399 
38400 /*
38401 ** Return the value of a system call. Return NULL if zName is not a
38402 ** recognized system call name. NULL is also returned if the system call
38403 ** is currently undefined.
38404 */
38405 static sqlite3_syscall_ptr winGetSystemCall(
38406  sqlite3_vfs *pNotUsed,
38407  const char *zName
38408 ){
38409  unsigned int i;
38410 
38411  UNUSED_PARAMETER(pNotUsed);
38412  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38413  if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
38414  }
38415  return 0;
38416 }
38417 
38418 /*
38419 ** Return the name of the first system call after zName. If zName==NULL
38420 ** then return the name of the first system call. Return NULL if zName
38421 ** is the last system call or if zName is not the name of a valid
38422 ** system call.
38423 */
38424 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
38425  int i = -1;
38426 
38427  UNUSED_PARAMETER(p);
38428  if( zName ){
38429  for(i=0; i<ArraySize(aSyscall)-1; i++){
38430  if( strcmp(zName, aSyscall[i].zName)==0 ) break;
38431  }
38432  }
38433  for(i++; i<ArraySize(aSyscall); i++){
38434  if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
38435  }
38436  return 0;
38437 }
38438 
38439 #ifdef SQLITE_WIN32_MALLOC
38440 /*
38441 ** If a Win32 native heap has been configured, this function will attempt to
38442 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
38443 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
38444 ** "pnLargest" argument, if non-zero, will be used to return the size of the
38445 ** largest committed free block in the heap, in bytes.
38446 */
38447 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
38448  int rc = SQLITE_OK;
38449  UINT nLargest = 0;
38450  HANDLE hHeap;
38451 
38452  winMemAssertMagic();
38453  hHeap = winMemGetHeap();
38454  assert( hHeap!=0 );
38455  assert( hHeap!=INVALID_HANDLE_VALUE );
38456 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38457  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38458 #endif
38459 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38460  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
38461  DWORD lastErrno = osGetLastError();
38462  if( lastErrno==NO_ERROR ){
38463  sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
38464  (void*)hHeap);
38465  rc = SQLITE_NOMEM_BKPT;
38466  }else{
38467  sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
38468  osGetLastError(), (void*)hHeap);
38469  rc = SQLITE_ERROR;
38470  }
38471  }
38472 #else
38473  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
38474  (void*)hHeap);
38475  rc = SQLITE_NOTFOUND;
38476 #endif
38477  if( pnLargest ) *pnLargest = nLargest;
38478  return rc;
38479 }
38480 
38481 /*
38482 ** If a Win32 native heap has been configured, this function will attempt to
38483 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
38484 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
38485 ** be returned and no changes will be made to the Win32 native heap.
38486 */
38487 SQLITE_API int sqlite3_win32_reset_heap(){
38488  int rc;
38489  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
38490  MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
38491  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
38492  MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
38493  sqlite3_mutex_enter(pMaster);
38494  sqlite3_mutex_enter(pMem);
38495  winMemAssertMagic();
38496  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
38497  /*
38498  ** At this point, there should be no outstanding memory allocations on
38499  ** the heap. Also, since both the master and memsys locks are currently
38500  ** being held by us, no other function (i.e. from another thread) should
38501  ** be able to even access the heap. Attempt to destroy and recreate our
38502  ** isolated Win32 native heap now.
38503  */
38504  assert( winMemGetHeap()!=NULL );
38505  assert( winMemGetOwned() );
38506  assert( sqlite3_memory_used()==0 );
38507  winMemShutdown(winMemGetDataPtr());
38508  assert( winMemGetHeap()==NULL );
38509  assert( !winMemGetOwned() );
38510  assert( sqlite3_memory_used()==0 );
38511  rc = winMemInit(winMemGetDataPtr());
38512  assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
38513  assert( rc!=SQLITE_OK || winMemGetOwned() );
38514  assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
38515  }else{
38516  /*
38517  ** The Win32 native heap cannot be modified because it may be in use.
38518  */
38519  rc = SQLITE_BUSY;
38520  }
38521  sqlite3_mutex_leave(pMem);
38522  sqlite3_mutex_leave(pMaster);
38523  return rc;
38524 }
38525 #endif /* SQLITE_WIN32_MALLOC */
38526 
38527 /*
38528 ** This function outputs the specified (ANSI) string to the Win32 debugger
38529 ** (if available).
38530 */
38531 
38532 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
38533  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
38534  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
38535  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
38536  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
38537 #ifdef SQLITE_ENABLE_API_ARMOR
38538  if( !zBuf ){
38539  (void)SQLITE_MISUSE_BKPT;
38540  return;
38541  }
38542 #endif
38543 #if defined(SQLITE_WIN32_HAS_ANSI)
38544  if( nMin>0 ){
38545  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38546  memcpy(zDbgBuf, zBuf, nMin);
38547  osOutputDebugStringA(zDbgBuf);
38548  }else{
38549  osOutputDebugStringA(zBuf);
38550  }
38551 #elif defined(SQLITE_WIN32_HAS_WIDE)
38552  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38553  if ( osMultiByteToWideChar(
38554  osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
38555  nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
38556  return;
38557  }
38558  osOutputDebugStringW((LPCWSTR)zDbgBuf);
38559 #else
38560  if( nMin>0 ){
38561  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38562  memcpy(zDbgBuf, zBuf, nMin);
38563  fprintf(stderr, "%s", zDbgBuf);
38564  }else{
38565  fprintf(stderr, "%s", zBuf);
38566  }
38567 #endif
38568 }
38569 
38570 /*
38571 ** The following routine suspends the current thread for at least ms
38572 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
38573 */
38574 #if SQLITE_OS_WINRT
38575 static HANDLE sleepObj = NULL;
38576 #endif
38577 
38578 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
38579 #if SQLITE_OS_WINRT
38580  if ( sleepObj==NULL ){
38581  sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
38582  SYNCHRONIZE);
38583  }
38584  assert( sleepObj!=NULL );
38585  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
38586 #else
38587  osSleep(milliseconds);
38588 #endif
38589 }
38590 
38591 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
38592  SQLITE_THREADSAFE>0
38593 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
38594  DWORD rc;
38595  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
38596  TRUE))==WAIT_IO_COMPLETION ){}
38597  return rc;
38598 }
38599 #endif
38600 
38601 /*
38602 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
38603 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
38604 **
38605 ** Here is an interesting observation: Win95, Win98, and WinME lack
38606 ** the LockFileEx() API. But we can still statically link against that
38607 ** API as long as we don't call it when running Win95/98/ME. A call to
38608 ** this routine is used to determine if the host is Win95/98/ME or
38609 ** WinNT/2K/XP so that we will know whether or not we can safely call
38610 ** the LockFileEx() API.
38611 */
38612 
38613 #if !SQLITE_WIN32_GETVERSIONEX
38614 # define osIsNT() (1)
38615 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
38616 # define osIsNT() (1)
38617 #elif !defined(SQLITE_WIN32_HAS_WIDE)
38618 # define osIsNT() (0)
38619 #else
38620 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
38621 #endif
38622 
38623 /*
38624 ** This function determines if the machine is running a version of Windows
38625 ** based on the NT kernel.
38626 */
38627 SQLITE_API int sqlite3_win32_is_nt(void){
38628 #if SQLITE_OS_WINRT
38629  /*
38630  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
38631  ** kernel.
38632  */
38633  return 1;
38634 #elif SQLITE_WIN32_GETVERSIONEX
38635  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
38636 #if defined(SQLITE_WIN32_HAS_ANSI)
38637  OSVERSIONINFOA sInfo;
38638  sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38639  osGetVersionExA(&sInfo);
38640  osInterlockedCompareExchange(&sqlite3_os_type,
38641  (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38642 #elif defined(SQLITE_WIN32_HAS_WIDE)
38643  OSVERSIONINFOW sInfo;
38644  sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38645  osGetVersionExW(&sInfo);
38646  osInterlockedCompareExchange(&sqlite3_os_type,
38647  (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38648 #endif
38649  }
38650  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38651 #elif SQLITE_TEST
38652  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38653 #else
38654  /*
38655  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
38656  ** deprecated are always assumed to be based on the NT kernel.
38657  */
38658  return 1;
38659 #endif
38660 }
38661 
38662 #ifdef SQLITE_WIN32_MALLOC
38663 /*
38664 ** Allocate nBytes of memory.
38665 */
38666 static void *winMemMalloc(int nBytes){
38667  HANDLE hHeap;
38668  void *p;
38669 
38670  winMemAssertMagic();
38671  hHeap = winMemGetHeap();
38672  assert( hHeap!=0 );
38673  assert( hHeap!=INVALID_HANDLE_VALUE );
38674 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38675  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38676 #endif
38677  assert( nBytes>=0 );
38678  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38679  if( !p ){
38680  sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
38681  nBytes, osGetLastError(), (void*)hHeap);
38682  }
38683  return p;
38684 }
38685 
38686 /*
38687 ** Free memory.
38688 */
38689 static void winMemFree(void *pPrior){
38690  HANDLE hHeap;
38691 
38692  winMemAssertMagic();
38693  hHeap = winMemGetHeap();
38694  assert( hHeap!=0 );
38695  assert( hHeap!=INVALID_HANDLE_VALUE );
38696 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38697  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38698 #endif
38699  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
38700  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
38701  sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
38702  pPrior, osGetLastError(), (void*)hHeap);
38703  }
38704 }
38705 
38706 /*
38707 ** Change the size of an existing memory allocation
38708 */
38709 static void *winMemRealloc(void *pPrior, int nBytes){
38710  HANDLE hHeap;
38711  void *p;
38712 
38713  winMemAssertMagic();
38714  hHeap = winMemGetHeap();
38715  assert( hHeap!=0 );
38716  assert( hHeap!=INVALID_HANDLE_VALUE );
38717 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38718  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38719 #endif
38720  assert( nBytes>=0 );
38721  if( !pPrior ){
38722  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38723  }else{
38724  p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
38725  }
38726  if( !p ){
38727  sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
38728  pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
38729  (void*)hHeap);
38730  }
38731  return p;
38732 }
38733 
38734 /*
38735 ** Return the size of an outstanding allocation, in bytes.
38736 */
38737 static int winMemSize(void *p){
38738  HANDLE hHeap;
38739  SIZE_T n;
38740 
38741  winMemAssertMagic();
38742  hHeap = winMemGetHeap();
38743  assert( hHeap!=0 );
38744  assert( hHeap!=INVALID_HANDLE_VALUE );
38745 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38746  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
38747 #endif
38748  if( !p ) return 0;
38749  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
38750  if( n==(SIZE_T)-1 ){
38751  sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
38752  p, osGetLastError(), (void*)hHeap);
38753  return 0;
38754  }
38755  return (int)n;
38756 }
38757 
38758 /*
38759 ** Round up a request size to the next valid allocation size.
38760 */
38761 static int winMemRoundup(int n){
38762  return n;
38763 }
38764 
38765 /*
38766 ** Initialize this module.
38767 */
38768 static int winMemInit(void *pAppData){
38769  winMemData *pWinMemData = (winMemData *)pAppData;
38770 
38771  if( !pWinMemData ) return SQLITE_ERROR;
38772  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38773  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38774 
38775 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
38776  if( !pWinMemData->hHeap ){
38777  DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
38778  DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
38779  if( dwMaximumSize==0 ){
38780  dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
38781  }else if( dwInitialSize>dwMaximumSize ){
38782  dwInitialSize = dwMaximumSize;
38783  }
38784  pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
38785  dwInitialSize, dwMaximumSize);
38786  if( !pWinMemData->hHeap ){
38787  sqlite3_log(SQLITE_NOMEM,
38788  "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
38789  osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
38790  dwMaximumSize);
38791  return SQLITE_NOMEM_BKPT;
38792  }
38793  pWinMemData->bOwned = TRUE;
38794  assert( pWinMemData->bOwned );
38795  }
38796 #else
38797  pWinMemData->hHeap = osGetProcessHeap();
38798  if( !pWinMemData->hHeap ){
38799  sqlite3_log(SQLITE_NOMEM,
38800  "failed to GetProcessHeap (%lu)", osGetLastError());
38801  return SQLITE_NOMEM_BKPT;
38802  }
38803  pWinMemData->bOwned = FALSE;
38804  assert( !pWinMemData->bOwned );
38805 #endif
38806  assert( pWinMemData->hHeap!=0 );
38807  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38808 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38809  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38810 #endif
38811  return SQLITE_OK;
38812 }
38813 
38814 /*
38815 ** Deinitialize this module.
38816 */
38817 static void winMemShutdown(void *pAppData){
38818  winMemData *pWinMemData = (winMemData *)pAppData;
38819 
38820  if( !pWinMemData ) return;
38821  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38822  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38823 
38824  if( pWinMemData->hHeap ){
38825  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38826 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38827  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38828 #endif
38829  if( pWinMemData->bOwned ){
38830  if( !osHeapDestroy(pWinMemData->hHeap) ){
38831  sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
38832  osGetLastError(), (void*)pWinMemData->hHeap);
38833  }
38834  pWinMemData->bOwned = FALSE;
38835  }
38836  pWinMemData->hHeap = NULL;
38837  }
38838 }
38839 
38840 /*
38841 ** Populate the low-level memory allocation function pointers in
38842 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
38843 ** arguments specify the block of memory to manage.
38844 **
38845 ** This routine is only called by sqlite3_config(), and therefore
38846 ** is not required to be threadsafe (it is not).
38847 */
38848 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
38849  static const sqlite3_mem_methods winMemMethods = {
38850  winMemMalloc,
38851  winMemFree,
38852  winMemRealloc,
38853  winMemSize,
38854  winMemRoundup,
38855  winMemInit,
38856  winMemShutdown,
38857  &win_mem_data
38858  };
38859  return &winMemMethods;
38860 }
38861 
38862 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
38863  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
38864 }
38865 #endif /* SQLITE_WIN32_MALLOC */
38866 
38867 /*
38868 ** Convert a UTF-8 string to Microsoft Unicode.
38869 **
38870 ** Space to hold the returned string is obtained from sqlite3_malloc().
38871 */
38872 static LPWSTR winUtf8ToUnicode(const char *zText){
38873  int nChar;
38874  LPWSTR zWideText;
38875 
38876  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
38877  if( nChar==0 ){
38878  return 0;
38879  }
38880  zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
38881  if( zWideText==0 ){
38882  return 0;
38883  }
38884  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
38885  nChar);
38886  if( nChar==0 ){
38887  sqlite3_free(zWideText);
38888  zWideText = 0;
38889  }
38890  return zWideText;
38891 }
38892 
38893 /*
38894 ** Convert a Microsoft Unicode string to UTF-8.
38895 **
38896 ** Space to hold the returned string is obtained from sqlite3_malloc().
38897 */
38898 static char *winUnicodeToUtf8(LPCWSTR zWideText){
38899  int nByte;
38900  char *zText;
38901 
38902  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
38903  if( nByte == 0 ){
38904  return 0;
38905  }
38906  zText = sqlite3MallocZero( nByte );
38907  if( zText==0 ){
38908  return 0;
38909  }
38910  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
38911  0, 0);
38912  if( nByte == 0 ){
38913  sqlite3_free(zText);
38914  zText = 0;
38915  }
38916  return zText;
38917 }
38918 
38919 /*
38920 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
38921 ** code page.
38922 **
38923 ** Space to hold the returned string is obtained from sqlite3_malloc().
38924 */
38925 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
38926  int nByte;
38927  LPWSTR zMbcsText;
38928  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38929 
38930  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
38931  0)*sizeof(WCHAR);
38932  if( nByte==0 ){
38933  return 0;
38934  }
38935  zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
38936  if( zMbcsText==0 ){
38937  return 0;
38938  }
38939  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
38940  nByte);
38941  if( nByte==0 ){
38942  sqlite3_free(zMbcsText);
38943  zMbcsText = 0;
38944  }
38945  return zMbcsText;
38946 }
38947 
38948 /*
38949 ** Convert a Microsoft Unicode string to a multi-byte character string,
38950 ** using the ANSI or OEM code page.
38951 **
38952 ** Space to hold the returned string is obtained from sqlite3_malloc().
38953 */
38954 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
38955  int nByte;
38956  char *zText;
38957  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38958 
38959  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
38960  if( nByte == 0 ){
38961  return 0;
38962  }
38963  zText = sqlite3MallocZero( nByte );
38964  if( zText==0 ){
38965  return 0;
38966  }
38967  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
38968  nByte, 0, 0);
38969  if( nByte == 0 ){
38970  sqlite3_free(zText);
38971  zText = 0;
38972  }
38973  return zText;
38974 }
38975 
38976 /*
38977 ** Convert a multi-byte character string to UTF-8.
38978 **
38979 ** Space to hold the returned string is obtained from sqlite3_malloc().
38980 */
38981 static char *winMbcsToUtf8(const char *zText, int useAnsi){
38982  char *zTextUtf8;
38983  LPWSTR zTmpWide;
38984 
38985  zTmpWide = winMbcsToUnicode(zText, useAnsi);
38986  if( zTmpWide==0 ){
38987  return 0;
38988  }
38989  zTextUtf8 = winUnicodeToUtf8(zTmpWide);
38990  sqlite3_free(zTmpWide);
38991  return zTextUtf8;
38992 }
38993 
38994 /*
38995 ** Convert a UTF-8 string to a multi-byte character string.
38996 **
38997 ** Space to hold the returned string is obtained from sqlite3_malloc().
38998 */
38999 static char *winUtf8ToMbcs(const char *zText, int useAnsi){
39000  char *zTextMbcs;
39001  LPWSTR zTmpWide;
39002 
39003  zTmpWide = winUtf8ToUnicode(zText);
39004  if( zTmpWide==0 ){
39005  return 0;
39006  }
39007  zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
39008  sqlite3_free(zTmpWide);
39009  return zTextMbcs;
39010 }
39011 
39012 /*
39013 ** This is a public wrapper for the winUtf8ToUnicode() function.
39014 */
39015 SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
39016 #ifdef SQLITE_ENABLE_API_ARMOR
39017  if( !zText ){
39018  (void)SQLITE_MISUSE_BKPT;
39019  return 0;
39020  }
39021 #endif
39022 #ifndef SQLITE_OMIT_AUTOINIT
39023  if( sqlite3_initialize() ) return 0;
39024 #endif
39025  return winUtf8ToUnicode(zText);
39026 }
39027 
39028 /*
39029 ** This is a public wrapper for the winUnicodeToUtf8() function.
39030 */
39031 SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
39032 #ifdef SQLITE_ENABLE_API_ARMOR
39033  if( !zWideText ){
39034  (void)SQLITE_MISUSE_BKPT;
39035  return 0;
39036  }
39037 #endif
39038 #ifndef SQLITE_OMIT_AUTOINIT
39039  if( sqlite3_initialize() ) return 0;
39040 #endif
39041  return winUnicodeToUtf8(zWideText);
39042 }
39043 
39044 /*
39045 ** This is a public wrapper for the winMbcsToUtf8() function.
39046 */
39047 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
39048 #ifdef SQLITE_ENABLE_API_ARMOR
39049  if( !zText ){
39050  (void)SQLITE_MISUSE_BKPT;
39051  return 0;
39052  }
39053 #endif
39054 #ifndef SQLITE_OMIT_AUTOINIT
39055  if( sqlite3_initialize() ) return 0;
39056 #endif
39057  return winMbcsToUtf8(zText, osAreFileApisANSI());
39058 }
39059 
39060 /*
39061 ** This is a public wrapper for the winMbcsToUtf8() function.
39062 */
39063 SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
39064 #ifdef SQLITE_ENABLE_API_ARMOR
39065  if( !zText ){
39066  (void)SQLITE_MISUSE_BKPT;
39067  return 0;
39068  }
39069 #endif
39070 #ifndef SQLITE_OMIT_AUTOINIT
39071  if( sqlite3_initialize() ) return 0;
39072 #endif
39073  return winMbcsToUtf8(zText, useAnsi);
39074 }
39075 
39076 /*
39077 ** This is a public wrapper for the winUtf8ToMbcs() function.
39078 */
39079 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
39080 #ifdef SQLITE_ENABLE_API_ARMOR
39081  if( !zText ){
39082  (void)SQLITE_MISUSE_BKPT;
39083  return 0;
39084  }
39085 #endif
39086 #ifndef SQLITE_OMIT_AUTOINIT
39087  if( sqlite3_initialize() ) return 0;
39088 #endif
39089  return winUtf8ToMbcs(zText, osAreFileApisANSI());
39090 }
39091 
39092 /*
39093 ** This is a public wrapper for the winUtf8ToMbcs() function.
39094 */
39095 SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
39096 #ifdef SQLITE_ENABLE_API_ARMOR
39097  if( !zText ){
39098  (void)SQLITE_MISUSE_BKPT;
39099  return 0;
39100  }
39101 #endif
39102 #ifndef SQLITE_OMIT_AUTOINIT
39103  if( sqlite3_initialize() ) return 0;
39104 #endif
39105  return winUtf8ToMbcs(zText, useAnsi);
39106 }
39107 
39108 /*
39109 ** This function sets the data directory or the temporary directory based on
39110 ** the provided arguments. The type argument must be 1 in order to set the
39111 ** data directory or 2 in order to set the temporary directory. The zValue
39112 ** argument is the name of the directory to use. The return value will be
39113 ** SQLITE_OK if successful.
39114 */
39115 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
39116  char **ppDirectory = 0;
39117 #ifndef SQLITE_OMIT_AUTOINIT
39118  int rc = sqlite3_initialize();
39119  if( rc ) return rc;
39120 #endif
39121  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
39122  ppDirectory = &sqlite3_data_directory;
39123  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
39124  ppDirectory = &sqlite3_temp_directory;
39125  }
39126  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
39127  || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
39128  );
39129  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
39130  if( ppDirectory ){
39131  char *zValueUtf8 = 0;
39132  if( zValue && zValue[0] ){
39133  zValueUtf8 = winUnicodeToUtf8(zValue);
39134  if ( zValueUtf8==0 ){
39135  return SQLITE_NOMEM_BKPT;
39136  }
39137  }
39138  sqlite3_free(*ppDirectory);
39139  *ppDirectory = zValueUtf8;
39140  return SQLITE_OK;
39141  }
39142  return SQLITE_ERROR;
39143 }
39144 
39145 /*
39146 ** The return value of winGetLastErrorMsg
39147 ** is zero if the error message fits in the buffer, or non-zero
39148 ** otherwise (if the message was truncated).
39149 */
39150 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
39151  /* FormatMessage returns 0 on failure. Otherwise it
39152  ** returns the number of TCHARs written to the output
39153  ** buffer, excluding the terminating null char.
39154  */
39155  DWORD dwLen = 0;
39156  char *zOut = 0;
39157 
39158  if( osIsNT() ){
39159 #if SQLITE_OS_WINRT
39160  WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
39161  dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
39162  FORMAT_MESSAGE_IGNORE_INSERTS,
39163  NULL,
39164  lastErrno,
39165  0,
39166  zTempWide,
39167  SQLITE_WIN32_MAX_ERRMSG_CHARS,
39168  0);
39169 #else
39170  LPWSTR zTempWide = NULL;
39171  dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39172  FORMAT_MESSAGE_FROM_SYSTEM |
39173  FORMAT_MESSAGE_IGNORE_INSERTS,
39174  NULL,
39175  lastErrno,
39176  0,
39177  (LPWSTR) &zTempWide,
39178  0,
39179  0);
39180 #endif
39181  if( dwLen > 0 ){
39182  /* allocate a buffer and convert to UTF8 */
39183  sqlite3BeginBenignMalloc();
39184  zOut = winUnicodeToUtf8(zTempWide);
39185  sqlite3EndBenignMalloc();
39186 #if !SQLITE_OS_WINRT
39187  /* free the system buffer allocated by FormatMessage */
39188  osLocalFree(zTempWide);
39189 #endif
39190  }
39191  }
39192 #ifdef SQLITE_WIN32_HAS_ANSI
39193  else{
39194  char *zTemp = NULL;
39195  dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39196  FORMAT_MESSAGE_FROM_SYSTEM |
39197  FORMAT_MESSAGE_IGNORE_INSERTS,
39198  NULL,
39199  lastErrno,
39200  0,
39201  (LPSTR) &zTemp,
39202  0,
39203  0);
39204  if( dwLen > 0 ){
39205  /* allocate a buffer and convert to UTF8 */
39206  sqlite3BeginBenignMalloc();
39207  zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
39208  sqlite3EndBenignMalloc();
39209  /* free the system buffer allocated by FormatMessage */
39210  osLocalFree(zTemp);
39211  }
39212  }
39213 #endif
39214  if( 0 == dwLen ){
39215  sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
39216  }else{
39217  /* copy a maximum of nBuf chars to output buffer */
39218  sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
39219  /* free the UTF8 buffer */
39220  sqlite3_free(zOut);
39221  }
39222  return 0;
39223 }
39224 
39225 /*
39226 **
39227 ** This function - winLogErrorAtLine() - is only ever called via the macro
39228 ** winLogError().
39229 **
39230 ** This routine is invoked after an error occurs in an OS function.
39231 ** It logs a message using sqlite3_log() containing the current value of
39232 ** error code and, if possible, the human-readable equivalent from
39233 ** FormatMessage.
39234 **
39235 ** The first argument passed to the macro should be the error code that
39236 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
39237 ** The two subsequent arguments should be the name of the OS function that
39238 ** failed and the associated file-system path, if any.
39239 */
39240 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
39241 static int winLogErrorAtLine(
39242  int errcode, /* SQLite error code */
39243  DWORD lastErrno, /* Win32 last error */
39244  const char *zFunc, /* Name of OS function that failed */
39245  const char *zPath, /* File path associated with error */
39246  int iLine /* Source line number where error occurred */
39247 ){
39248  char zMsg[500]; /* Human readable error text */
39249  int i; /* Loop counter */
39250 
39251  zMsg[0] = 0;
39252  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
39253  assert( errcode!=SQLITE_OK );
39254  if( zPath==0 ) zPath = "";
39255  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
39256  zMsg[i] = 0;
39257  sqlite3_log(errcode,
39258  "os_win.c:%d: (%lu) %s(%s) - %s",
39259  iLine, lastErrno, zFunc, zPath, zMsg
39260  );
39261 
39262  return errcode;
39263 }
39264 
39265 /*
39266 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
39267 ** will be retried following a locking error - probably caused by
39268 ** antivirus software. Also the initial delay before the first retry.
39269 ** The delay increases linearly with each retry.
39270 */
39271 #ifndef SQLITE_WIN32_IOERR_RETRY
39272 # define SQLITE_WIN32_IOERR_RETRY 10
39273 #endif
39274 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
39275 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
39276 #endif
39277 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
39278 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
39279 
39280 /*
39281 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
39282 ** error code obtained via GetLastError() is eligible to be retried. It
39283 ** must accept the error code DWORD as its only argument and should return
39284 ** non-zero if the error code is transient in nature and the operation
39285 ** responsible for generating the original error might succeed upon being
39286 ** retried. The argument to this macro should be a variable.
39287 **
39288 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
39289 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
39290 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
39291 ** may be used to include additional error codes in the set that should
39292 ** result in the failing I/O operation being retried by the caller. If
39293 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
39294 ** identical to those of the "winIoerrCanRetry1" macro.
39295 */
39296 #if !defined(winIoerrCanRetry1)
39297 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
39298  ((a)==ERROR_SHARING_VIOLATION) || \
39299  ((a)==ERROR_LOCK_VIOLATION) || \
39300  ((a)==ERROR_DEV_NOT_EXIST) || \
39301  ((a)==ERROR_NETNAME_DELETED) || \
39302  ((a)==ERROR_SEM_TIMEOUT) || \
39303  ((a)==ERROR_NETWORK_UNREACHABLE))
39304 #endif
39305 
39306 /*
39307 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
39308 ** to see if it should be retried. Return TRUE to retry. Return FALSE
39309 ** to give up with an error.
39310 */
39311 static int winRetryIoerr(int *pnRetry, DWORD *pError){
39312  DWORD e = osGetLastError();
39313  if( *pnRetry>=winIoerrRetry ){
39314  if( pError ){
39315  *pError = e;
39316  }
39317  return 0;
39318  }
39319  if( winIoerrCanRetry1(e) ){
39320  sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39321  ++*pnRetry;
39322  return 1;
39323  }
39324 #if defined(winIoerrCanRetry2)
39325  else if( winIoerrCanRetry2(e) ){
39326  sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39327  ++*pnRetry;
39328  return 1;
39329  }
39330 #endif
39331  if( pError ){
39332  *pError = e;
39333  }
39334  return 0;
39335 }
39336 
39337 /*
39338 ** Log a I/O error retry episode.
39339 */
39340 static void winLogIoerr(int nRetry, int lineno){
39341  if( nRetry ){
39342  sqlite3_log(SQLITE_NOTICE,
39343  "delayed %dms for lock/sharing conflict at line %d",
39344  winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
39345  );
39346  }
39347 }
39348 
39349 /*
39350 ** This #if does not rely on the SQLITE_OS_WINCE define because the
39351 ** corresponding section in "date.c" cannot use it.
39352 */
39353 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
39354  (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
39355 /*
39356 ** The MSVC CRT on Windows CE may not have a localtime() function.
39357 ** So define a substitute.
39358 */
39359 /* # include <time.h> */
39360 struct tm *__cdecl localtime(const time_t *t)
39361 {
39362  static struct tm y;
39363  FILETIME uTm, lTm;
39364  SYSTEMTIME pTm;
39365  sqlite3_int64 t64;
39366  t64 = *t;
39367  t64 = (t64 + 11644473600)*10000000;
39368  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
39369  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
39370  osFileTimeToLocalFileTime(&uTm,&lTm);
39371  osFileTimeToSystemTime(&lTm,&pTm);
39372  y.tm_year = pTm.wYear - 1900;
39373  y.tm_mon = pTm.wMonth - 1;
39374  y.tm_wday = pTm.wDayOfWeek;
39375  y.tm_mday = pTm.wDay;
39376  y.tm_hour = pTm.wHour;
39377  y.tm_min = pTm.wMinute;
39378  y.tm_sec = pTm.wSecond;
39379  return &y;
39380 }
39381 #endif
39382 
39383 #if SQLITE_OS_WINCE
39384 /*************************************************************************
39385 ** This section contains code for WinCE only.
39386 */
39387 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
39388 
39389 /*
39390 ** Acquire a lock on the handle h
39391 */
39392 static void winceMutexAcquire(HANDLE h){
39393  DWORD dwErr;
39394  do {
39395  dwErr = osWaitForSingleObject(h, INFINITE);
39396  } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
39397 }
39398 /*
39399 ** Release a lock acquired by winceMutexAcquire()
39400 */
39401 #define winceMutexRelease(h) ReleaseMutex(h)
39402 
39403 /*
39404 ** Create the mutex and shared memory used for locking in the file
39405 ** descriptor pFile
39406 */
39407 static int winceCreateLock(const char *zFilename, winFile *pFile){
39408  LPWSTR zTok;
39409  LPWSTR zName;
39410  DWORD lastErrno;
39411  BOOL bLogged = FALSE;
39412  BOOL bInit = TRUE;
39413 
39414  zName = winUtf8ToUnicode(zFilename);
39415  if( zName==0 ){
39416  /* out of memory */
39417  return SQLITE_IOERR_NOMEM_BKPT;
39418  }
39419 
39420  /* Initialize the local lockdata */
39421  memset(&pFile->local, 0, sizeof(pFile->local));
39422 
39423  /* Replace the backslashes from the filename and lowercase it
39424  ** to derive a mutex name. */
39425  zTok = osCharLowerW(zName);
39426  for (;*zTok;zTok++){
39427  if (*zTok == '\\') *zTok = '_';
39428  }
39429 
39430  /* Create/open the named mutex */
39431  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
39432  if (!pFile->hMutex){
39433  pFile->lastErrno = osGetLastError();
39434  sqlite3_free(zName);
39435  return winLogError(SQLITE_IOERR, pFile->lastErrno,
39436  "winceCreateLock1", zFilename);
39437  }
39438 
39439  /* Acquire the mutex before continuing */
39440  winceMutexAcquire(pFile->hMutex);
39441 
39442  /* Since the names of named mutexes, semaphores, file mappings etc are
39443  ** case-sensitive, take advantage of that by uppercasing the mutex name
39444  ** and using that as the shared filemapping name.
39445  */
39446  osCharUpperW(zName);
39447  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
39448  PAGE_READWRITE, 0, sizeof(winceLock),
39449  zName);
39450 
39451  /* Set a flag that indicates we're the first to create the memory so it
39452  ** must be zero-initialized */
39453  lastErrno = osGetLastError();
39454  if (lastErrno == ERROR_ALREADY_EXISTS){
39455  bInit = FALSE;
39456  }
39457 
39458  sqlite3_free(zName);
39459 
39460  /* If we succeeded in making the shared memory handle, map it. */
39461  if( pFile->hShared ){
39462  pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
39463  FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
39464  /* If mapping failed, close the shared memory handle and erase it */
39465  if( !pFile->shared ){
39466  pFile->lastErrno = osGetLastError();
39467  winLogError(SQLITE_IOERR, pFile->lastErrno,
39468  "winceCreateLock2", zFilename);
39469  bLogged = TRUE;
39470  osCloseHandle(pFile->hShared);
39471  pFile->hShared = NULL;
39472  }
39473  }
39474 
39475  /* If shared memory could not be created, then close the mutex and fail */
39476  if( pFile->hShared==NULL ){
39477  if( !bLogged ){
39478  pFile->lastErrno = lastErrno;
39479  winLogError(SQLITE_IOERR, pFile->lastErrno,
39480  "winceCreateLock3", zFilename);
39481  bLogged = TRUE;
39482  }
39483  winceMutexRelease(pFile->hMutex);
39484  osCloseHandle(pFile->hMutex);
39485  pFile->hMutex = NULL;
39486  return SQLITE_IOERR;
39487  }
39488 
39489  /* Initialize the shared memory if we're supposed to */
39490  if( bInit ){
39491  memset(pFile->shared, 0, sizeof(winceLock));
39492  }
39493 
39494  winceMutexRelease(pFile->hMutex);
39495  return SQLITE_OK;
39496 }
39497 
39498 /*
39499 ** Destroy the part of winFile that deals with wince locks
39500 */
39501 static void winceDestroyLock(winFile *pFile){
39502  if (pFile->hMutex){
39503  /* Acquire the mutex */
39504  winceMutexAcquire(pFile->hMutex);
39505 
39506  /* The following blocks should probably assert in debug mode, but they
39507  are to cleanup in case any locks remained open */
39508  if (pFile->local.nReaders){
39509  pFile->shared->nReaders --;
39510  }
39511  if (pFile->local.bReserved){
39512  pFile->shared->bReserved = FALSE;
39513  }
39514  if (pFile->local.bPending){
39515  pFile->shared->bPending = FALSE;
39516  }
39517  if (pFile->local.bExclusive){
39518  pFile->shared->bExclusive = FALSE;
39519  }
39520 
39521  /* De-reference and close our copy of the shared memory handle */
39522  osUnmapViewOfFile(pFile->shared);
39523  osCloseHandle(pFile->hShared);
39524 
39525  /* Done with the mutex */
39526  winceMutexRelease(pFile->hMutex);
39527  osCloseHandle(pFile->hMutex);
39528  pFile->hMutex = NULL;
39529  }
39530 }
39531 
39532 /*
39533 ** An implementation of the LockFile() API of Windows for CE
39534 */
39535 static BOOL winceLockFile(
39536  LPHANDLE phFile,
39537  DWORD dwFileOffsetLow,
39538  DWORD dwFileOffsetHigh,
39539  DWORD nNumberOfBytesToLockLow,
39540  DWORD nNumberOfBytesToLockHigh
39541 ){
39542  winFile *pFile = HANDLE_TO_WINFILE(phFile);
39543  BOOL bReturn = FALSE;
39544 
39545  UNUSED_PARAMETER(dwFileOffsetHigh);
39546  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
39547 
39548  if (!pFile->hMutex) return TRUE;
39549  winceMutexAcquire(pFile->hMutex);
39550 
39551  /* Wanting an exclusive lock? */
39552  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
39553  && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
39554  if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
39555  pFile->shared->bExclusive = TRUE;
39556  pFile->local.bExclusive = TRUE;
39557  bReturn = TRUE;
39558  }
39559  }
39560 
39561  /* Want a read-only lock? */
39562  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
39563  nNumberOfBytesToLockLow == 1){
39564  if (pFile->shared->bExclusive == 0){
39565  pFile->local.nReaders ++;
39566  if (pFile->local.nReaders == 1){
39567  pFile->shared->nReaders ++;
39568  }
39569  bReturn = TRUE;
39570  }
39571  }
39572 
39573  /* Want a pending lock? */
39574  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39575  && nNumberOfBytesToLockLow == 1){
39576  /* If no pending lock has been acquired, then acquire it */
39577  if (pFile->shared->bPending == 0) {
39578  pFile->shared->bPending = TRUE;
39579  pFile->local.bPending = TRUE;
39580  bReturn = TRUE;
39581  }
39582  }
39583 
39584  /* Want a reserved lock? */
39585  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39586  && nNumberOfBytesToLockLow == 1){
39587  if (pFile->shared->bReserved == 0) {
39588  pFile->shared->bReserved = TRUE;
39589  pFile->local.bReserved = TRUE;
39590  bReturn = TRUE;
39591  }
39592  }
39593 
39594  winceMutexRelease(pFile->hMutex);
39595  return bReturn;
39596 }
39597 
39598 /*
39599 ** An implementation of the UnlockFile API of Windows for CE
39600 */
39601 static BOOL winceUnlockFile(
39602  LPHANDLE phFile,
39603  DWORD dwFileOffsetLow,
39604  DWORD dwFileOffsetHigh,
39605  DWORD nNumberOfBytesToUnlockLow,
39606  DWORD nNumberOfBytesToUnlockHigh
39607 ){
39608  winFile *pFile = HANDLE_TO_WINFILE(phFile);
39609  BOOL bReturn = FALSE;
39610 
39611  UNUSED_PARAMETER(dwFileOffsetHigh);
39612  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
39613 
39614  if (!pFile->hMutex) return TRUE;
39615  winceMutexAcquire(pFile->hMutex);
39616 
39617  /* Releasing a reader lock or an exclusive lock */
39618  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
39619  /* Did we have an exclusive lock? */
39620  if (pFile->local.bExclusive){
39621  assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
39622  pFile->local.bExclusive = FALSE;
39623  pFile->shared->bExclusive = FALSE;
39624  bReturn = TRUE;
39625  }
39626 
39627  /* Did we just have a reader lock? */
39628  else if (pFile->local.nReaders){
39629  assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
39630  || nNumberOfBytesToUnlockLow == 1);
39631  pFile->local.nReaders --;
39632  if (pFile->local.nReaders == 0)
39633  {
39634  pFile->shared->nReaders --;
39635  }
39636  bReturn = TRUE;
39637  }
39638  }
39639 
39640  /* Releasing a pending lock */
39641  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39642  && nNumberOfBytesToUnlockLow == 1){
39643  if (pFile->local.bPending){
39644  pFile->local.bPending = FALSE;
39645  pFile->shared->bPending = FALSE;
39646  bReturn = TRUE;
39647  }
39648  }
39649  /* Releasing a reserved lock */
39650  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39651  && nNumberOfBytesToUnlockLow == 1){
39652  if (pFile->local.bReserved) {
39653  pFile->local.bReserved = FALSE;
39654  pFile->shared->bReserved = FALSE;
39655  bReturn = TRUE;
39656  }
39657  }
39658 
39659  winceMutexRelease(pFile->hMutex);
39660  return bReturn;
39661 }
39662 /*
39663 ** End of the special code for wince
39664 *****************************************************************************/
39665 #endif /* SQLITE_OS_WINCE */
39666 
39667 /*
39668 ** Lock a file region.
39669 */
39670 static BOOL winLockFile(
39671  LPHANDLE phFile,
39672  DWORD flags,
39673  DWORD offsetLow,
39674  DWORD offsetHigh,
39675  DWORD numBytesLow,
39676  DWORD numBytesHigh
39677 ){
39678 #if SQLITE_OS_WINCE
39679  /*
39680  ** NOTE: Windows CE is handled differently here due its lack of the Win32
39681  ** API LockFile.
39682  */
39683  return winceLockFile(phFile, offsetLow, offsetHigh,
39684  numBytesLow, numBytesHigh);
39685 #else
39686  if( osIsNT() ){
39687  OVERLAPPED ovlp;
39688  memset(&ovlp, 0, sizeof(OVERLAPPED));
39689  ovlp.Offset = offsetLow;
39690  ovlp.OffsetHigh = offsetHigh;
39691  return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
39692  }else{
39693  return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39694  numBytesHigh);
39695  }
39696 #endif
39697 }
39698 
39699 /*
39700 ** Unlock a file region.
39701  */
39702 static BOOL winUnlockFile(
39703  LPHANDLE phFile,
39704  DWORD offsetLow,
39705  DWORD offsetHigh,
39706  DWORD numBytesLow,
39707  DWORD numBytesHigh
39708 ){
39709 #if SQLITE_OS_WINCE
39710  /*
39711  ** NOTE: Windows CE is handled differently here due its lack of the Win32
39712  ** API UnlockFile.
39713  */
39714  return winceUnlockFile(phFile, offsetLow, offsetHigh,
39715  numBytesLow, numBytesHigh);
39716 #else
39717  if( osIsNT() ){
39718  OVERLAPPED ovlp;
39719  memset(&ovlp, 0, sizeof(OVERLAPPED));
39720  ovlp.Offset = offsetLow;
39721  ovlp.OffsetHigh = offsetHigh;
39722  return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
39723  }else{
39724  return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39725  numBytesHigh);
39726  }
39727 #endif
39728 }
39729 
39730 /*****************************************************************************
39731 ** The next group of routines implement the I/O methods specified
39732 ** by the sqlite3_io_methods object.
39733 ******************************************************************************/
39734 
39735 /*
39736 ** Some Microsoft compilers lack this definition.
39737 */
39738 #ifndef INVALID_SET_FILE_POINTER
39739 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
39740 #endif
39741 
39742 /*
39743 ** Move the current position of the file handle passed as the first
39744 ** argument to offset iOffset within the file. If successful, return 0.
39745 ** Otherwise, set pFile->lastErrno and return non-zero.
39746 */
39747 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
39748 #if !SQLITE_OS_WINRT
39749  LONG upperBits; /* Most sig. 32 bits of new offset */
39750  LONG lowerBits; /* Least sig. 32 bits of new offset */
39751  DWORD dwRet; /* Value returned by SetFilePointer() */
39752  DWORD lastErrno; /* Value returned by GetLastError() */
39753 
39754  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
39755 
39756  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
39757  lowerBits = (LONG)(iOffset & 0xffffffff);
39758 
39759  /* API oddity: If successful, SetFilePointer() returns a dword
39760  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
39761  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
39762  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
39763  ** whether an error has actually occurred, it is also necessary to call
39764  ** GetLastError().
39765  */
39766  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
39767 
39768  if( (dwRet==INVALID_SET_FILE_POINTER
39769  && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
39770  pFile->lastErrno = lastErrno;
39771  winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39772  "winSeekFile", pFile->zPath);
39773  OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39774  return 1;
39775  }
39776 
39777  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39778  return 0;
39779 #else
39780  /*
39781  ** Same as above, except that this implementation works for WinRT.
39782  */
39783 
39784  LARGE_INTEGER x; /* The new offset */
39785  BOOL bRet; /* Value returned by SetFilePointerEx() */
39786 
39787  x.QuadPart = iOffset;
39788  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
39789 
39790  if(!bRet){
39791  pFile->lastErrno = osGetLastError();
39792  winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39793  "winSeekFile", pFile->zPath);
39794  OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39795  return 1;
39796  }
39797 
39798  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39799  return 0;
39800 #endif
39801 }
39802 
39803 #if SQLITE_MAX_MMAP_SIZE>0
39804 /* Forward references to VFS helper methods used for memory mapped files */
39805 static int winMapfile(winFile*, sqlite3_int64);
39806 static int winUnmapfile(winFile*);
39807 #endif
39808 
39809 /*
39810 ** Close a file.
39811 **
39812 ** It is reported that an attempt to close a handle might sometimes
39813 ** fail. This is a very unreasonable result, but Windows is notorious
39814 ** for being unreasonable so I do not doubt that it might happen. If
39815 ** the close fails, we pause for 100 milliseconds and try again. As
39816 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
39817 ** giving up and returning an error.
39818 */
39819 #define MX_CLOSE_ATTEMPT 3
39820 static int winClose(sqlite3_file *id){
39821  int rc, cnt = 0;
39822  winFile *pFile = (winFile*)id;
39823 
39824  assert( id!=0 );
39825 #ifndef SQLITE_OMIT_WAL
39826  assert( pFile->pShm==0 );
39827 #endif
39828  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
39829  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
39830  osGetCurrentProcessId(), pFile, pFile->h));
39831 
39832 #if SQLITE_MAX_MMAP_SIZE>0
39833  winUnmapfile(pFile);
39834 #endif
39835 
39836  do{
39837  rc = osCloseHandle(pFile->h);
39838  /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
39839  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
39840 #if SQLITE_OS_WINCE
39841 #define WINCE_DELETION_ATTEMPTS 3
39842  {
39843  winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
39844  if( pAppData==NULL || !pAppData->bNoLock ){
39845  winceDestroyLock(pFile);
39846  }
39847  }
39848  if( pFile->zDeleteOnClose ){
39849  int cnt = 0;
39850  while(
39851  osDeleteFileW(pFile->zDeleteOnClose)==0
39852  && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
39853  && cnt++ < WINCE_DELETION_ATTEMPTS
39854  ){
39855  sqlite3_win32_sleep(100); /* Wait a little before trying again */
39856  }
39857  sqlite3_free(pFile->zDeleteOnClose);
39858  }
39859 #endif
39860  if( rc ){
39861  pFile->h = NULL;
39862  }
39863  OpenCounter(-1);
39864  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
39865  osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
39866  return rc ? SQLITE_OK
39867  : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
39868  "winClose", pFile->zPath);
39869 }
39870 
39871 /*
39872 ** Read data from a file into a buffer. Return SQLITE_OK if all
39873 ** bytes were read successfully and SQLITE_IOERR if anything goes
39874 ** wrong.
39875 */
39876 static int winRead(
39877  sqlite3_file *id, /* File to read from */
39878  void *pBuf, /* Write content into this buffer */
39879  int amt, /* Number of bytes to read */
39880  sqlite3_int64 offset /* Begin reading at this offset */
39881 ){
39882 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39883  OVERLAPPED overlapped; /* The offset for ReadFile. */
39884 #endif
39885  winFile *pFile = (winFile*)id; /* file handle */
39886  DWORD nRead; /* Number of bytes actually read from file */
39887  int nRetry = 0; /* Number of retrys */
39888 
39889  assert( id!=0 );
39890  assert( amt>0 );
39891  assert( offset>=0 );
39892  SimulateIOError(return SQLITE_IOERR_READ);
39893  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39894  "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39895  pFile->h, pBuf, amt, offset, pFile->locktype));
39896 
39897 #if SQLITE_MAX_MMAP_SIZE>0
39898  /* Deal with as much of this read request as possible by transfering
39899  ** data from the memory mapping using memcpy(). */
39900  if( offset<pFile->mmapSize ){
39901  if( offset+amt <= pFile->mmapSize ){
39902  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
39903  OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39904  osGetCurrentProcessId(), pFile, pFile->h));
39905  return SQLITE_OK;
39906  }else{
39907  int nCopy = (int)(pFile->mmapSize - offset);
39908  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
39909  pBuf = &((u8 *)pBuf)[nCopy];
39910  amt -= nCopy;
39911  offset += nCopy;
39912  }
39913  }
39914 #endif
39915 
39916 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39917  if( winSeekFile(pFile, offset) ){
39918  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
39919  osGetCurrentProcessId(), pFile, pFile->h));
39920  return SQLITE_FULL;
39921  }
39922  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
39923 #else
39924  memset(&overlapped, 0, sizeof(OVERLAPPED));
39925  overlapped.Offset = (LONG)(offset & 0xffffffff);
39926  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39927  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
39928  osGetLastError()!=ERROR_HANDLE_EOF ){
39929 #endif
39930  DWORD lastErrno;
39931  if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
39932  pFile->lastErrno = lastErrno;
39933  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
39934  osGetCurrentProcessId(), pFile, pFile->h));
39935  return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
39936  "winRead", pFile->zPath);
39937  }
39938  winLogIoerr(nRetry, __LINE__);
39939  if( nRead<(DWORD)amt ){
39940  /* Unread parts of the buffer must be zero-filled */
39941  memset(&((char*)pBuf)[nRead], 0, amt-nRead);
39942  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
39943  osGetCurrentProcessId(), pFile, pFile->h));
39944  return SQLITE_IOERR_SHORT_READ;
39945  }
39946 
39947  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39948  osGetCurrentProcessId(), pFile, pFile->h));
39949  return SQLITE_OK;
39950 }
39951 
39952 /*
39953 ** Write data from a buffer into a file. Return SQLITE_OK on success
39954 ** or some other error code on failure.
39955 */
39956 static int winWrite(
39957  sqlite3_file *id, /* File to write into */
39958  const void *pBuf, /* The bytes to be written */
39959  int amt, /* Number of bytes to write */
39960  sqlite3_int64 offset /* Offset into the file to begin writing at */
39961 ){
39962  int rc = 0; /* True if error has occurred, else false */
39963  winFile *pFile = (winFile*)id; /* File handle */
39964  int nRetry = 0; /* Number of retries */
39965 
39966  assert( amt>0 );
39967  assert( pFile );
39968  SimulateIOError(return SQLITE_IOERR_WRITE);
39969  SimulateDiskfullError(return SQLITE_FULL);
39970 
39971  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39972  "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39973  pFile->h, pBuf, amt, offset, pFile->locktype));
39974 
39975 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
39976  /* Deal with as much of this write request as possible by transfering
39977  ** data from the memory mapping using memcpy(). */
39978  if( offset<pFile->mmapSize ){
39979  if( offset+amt <= pFile->mmapSize ){
39980  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
39981  OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39982  osGetCurrentProcessId(), pFile, pFile->h));
39983  return SQLITE_OK;
39984  }else{
39985  int nCopy = (int)(pFile->mmapSize - offset);
39986  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
39987  pBuf = &((u8 *)pBuf)[nCopy];
39988  amt -= nCopy;
39989  offset += nCopy;
39990  }
39991  }
39992 #endif
39993 
39994 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39995  rc = winSeekFile(pFile, offset);
39996  if( rc==0 ){
39997 #else
39998  {
39999 #endif
40000 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40001  OVERLAPPED overlapped; /* The offset for WriteFile. */
40002 #endif
40003  u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
40004  int nRem = amt; /* Number of bytes yet to be written */
40005  DWORD nWrite; /* Bytes written by each WriteFile() call */
40006  DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
40007 
40008 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40009  memset(&overlapped, 0, sizeof(OVERLAPPED));
40010  overlapped.Offset = (LONG)(offset & 0xffffffff);
40011  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
40012 #endif
40013 
40014  while( nRem>0 ){
40015 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
40016  if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
40017 #else
40018  if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
40019 #endif
40020  if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
40021  break;
40022  }
40023  assert( nWrite==0 || nWrite<=(DWORD)nRem );
40024  if( nWrite==0 || nWrite>(DWORD)nRem ){
40025  lastErrno = osGetLastError();
40026  break;
40027  }
40028 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40029  offset += nWrite;
40030  overlapped.Offset = (LONG)(offset & 0xffffffff);
40031  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
40032 #endif
40033  aRem += nWrite;
40034  nRem -= nWrite;
40035  }
40036  if( nRem>0 ){
40037  pFile->lastErrno = lastErrno;
40038  rc = 1;
40039  }
40040  }
40041 
40042  if( rc ){
40043  if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
40044  || ( pFile->lastErrno==ERROR_DISK_FULL )){
40045  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
40046  osGetCurrentProcessId(), pFile, pFile->h));
40047  return winLogError(SQLITE_FULL, pFile->lastErrno,
40048  "winWrite1", pFile->zPath);
40049  }
40050  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
40051  osGetCurrentProcessId(), pFile, pFile->h));
40052  return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
40053  "winWrite2", pFile->zPath);
40054  }else{
40055  winLogIoerr(nRetry, __LINE__);
40056  }
40057  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40058  osGetCurrentProcessId(), pFile, pFile->h));
40059  return SQLITE_OK;
40060 }
40061 
40062 /*
40063 ** Truncate an open file to a specified size
40064 */
40065 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
40066  winFile *pFile = (winFile*)id; /* File handle object */
40067  int rc = SQLITE_OK; /* Return code for this function */
40068  DWORD lastErrno;
40069 
40070  assert( pFile );
40071  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
40072  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
40073  osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
40074 
40075  /* If the user has configured a chunk-size for this file, truncate the
40076  ** file so that it consists of an integer number of chunks (i.e. the
40077  ** actual file size after the operation may be larger than the requested
40078  ** size).
40079  */
40080  if( pFile->szChunk>0 ){
40081  nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
40082  }
40083 
40084  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
40085  if( winSeekFile(pFile, nByte) ){
40086  rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
40087  "winTruncate1", pFile->zPath);
40088  }else if( 0==osSetEndOfFile(pFile->h) &&
40089  ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
40090  pFile->lastErrno = lastErrno;
40091  rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
40092  "winTruncate2", pFile->zPath);
40093  }
40094 
40095 #if SQLITE_MAX_MMAP_SIZE>0
40096  /* If the file was truncated to a size smaller than the currently
40097  ** mapped region, reduce the effective mapping size as well. SQLite will
40098  ** use read() and write() to access data beyond this point from now on.
40099  */
40100  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
40101  pFile->mmapSize = nByte;
40102  }
40103 #endif
40104 
40105  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
40106  osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
40107  return rc;
40108 }
40109 
40110 #ifdef SQLITE_TEST
40111 /*
40112 ** Count the number of fullsyncs and normal syncs. This is used to test
40113 ** that syncs and fullsyncs are occuring at the right times.
40114 */
40115 SQLITE_API int sqlite3_sync_count = 0;
40116 SQLITE_API int sqlite3_fullsync_count = 0;
40117 #endif
40118 
40119 /*
40120 ** Make sure all writes to a particular file are committed to disk.
40121 */
40122 static int winSync(sqlite3_file *id, int flags){
40123 #ifndef SQLITE_NO_SYNC
40124  /*
40125  ** Used only when SQLITE_NO_SYNC is not defined.
40126  */
40127  BOOL rc;
40128 #endif
40129 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
40130  defined(SQLITE_HAVE_OS_TRACE)
40131  /*
40132  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
40133  ** OSTRACE() macros.
40134  */
40135  winFile *pFile = (winFile*)id;
40136 #else
40137  UNUSED_PARAMETER(id);
40138 #endif
40139 
40140  assert( pFile );
40141  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
40142  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
40143  || (flags&0x0F)==SQLITE_SYNC_FULL
40144  );
40145 
40146  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
40147  ** line is to test that doing so does not cause any problems.
40148  */
40149  SimulateDiskfullError( return SQLITE_FULL );
40150 
40151  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
40152  osGetCurrentProcessId(), pFile, pFile->h, flags,
40153  pFile->locktype));
40154 
40155 #ifndef SQLITE_TEST
40156  UNUSED_PARAMETER(flags);
40157 #else
40158  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
40159  sqlite3_fullsync_count++;
40160  }
40161  sqlite3_sync_count++;
40162 #endif
40163 
40164  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
40165  ** no-op
40166  */
40167 #ifdef SQLITE_NO_SYNC
40168  OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40169  osGetCurrentProcessId(), pFile, pFile->h));
40170  return SQLITE_OK;
40171 #else
40172 #if SQLITE_MAX_MMAP_SIZE>0
40173  if( pFile->pMapRegion ){
40174  if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
40175  OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40176  "rc=SQLITE_OK\n", osGetCurrentProcessId(),
40177  pFile, pFile->pMapRegion));
40178  }else{
40179  pFile->lastErrno = osGetLastError();
40180  OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40181  "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
40182  pFile, pFile->pMapRegion));
40183  return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
40184  "winSync1", pFile->zPath);
40185  }
40186  }
40187 #endif
40188  rc = osFlushFileBuffers(pFile->h);
40189  SimulateIOError( rc=FALSE );
40190  if( rc ){
40191  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40192  osGetCurrentProcessId(), pFile, pFile->h));
40193  return SQLITE_OK;
40194  }else{
40195  pFile->lastErrno = osGetLastError();
40196  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
40197  osGetCurrentProcessId(), pFile, pFile->h));
40198  return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
40199  "winSync2", pFile->zPath);
40200  }
40201 #endif
40202 }
40203 
40204 /*
40205 ** Determine the current size of a file in bytes
40206 */
40207 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
40208  winFile *pFile = (winFile*)id;
40209  int rc = SQLITE_OK;
40210 
40211  assert( id!=0 );
40212  assert( pSize!=0 );
40213  SimulateIOError(return SQLITE_IOERR_FSTAT);
40214  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
40215 
40216 #if SQLITE_OS_WINRT
40217  {
40218  FILE_STANDARD_INFO info;
40219  if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
40220  &info, sizeof(info)) ){
40221  *pSize = info.EndOfFile.QuadPart;
40222  }else{
40223  pFile->lastErrno = osGetLastError();
40224  rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40225  "winFileSize", pFile->zPath);
40226  }
40227  }
40228 #else
40229  {
40230  DWORD upperBits;
40231  DWORD lowerBits;
40232  DWORD lastErrno;
40233 
40234  lowerBits = osGetFileSize(pFile->h, &upperBits);
40235  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
40236  if( (lowerBits == INVALID_FILE_SIZE)
40237  && ((lastErrno = osGetLastError())!=NO_ERROR) ){
40238  pFile->lastErrno = lastErrno;
40239  rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40240  "winFileSize", pFile->zPath);
40241  }
40242  }
40243 #endif
40244  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
40245  pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
40246  return rc;
40247 }
40248 
40249 /*
40250 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
40251 */
40252 #ifndef LOCKFILE_FAIL_IMMEDIATELY
40253 # define LOCKFILE_FAIL_IMMEDIATELY 1
40254 #endif
40255 
40256 #ifndef LOCKFILE_EXCLUSIVE_LOCK
40257 # define LOCKFILE_EXCLUSIVE_LOCK 2
40258 #endif
40259 
40260 /*
40261 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
40262 ** When the LockFile function was used, it was always expected to fail
40263 ** immediately if the lock could not be obtained. Also, it always expected to
40264 ** obtain an exclusive lock. These flags are used with the LockFileEx function
40265 ** and reflect those expectations; therefore, they should not be changed.
40266 */
40267 #ifndef SQLITE_LOCKFILE_FLAGS
40268 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
40269  LOCKFILE_EXCLUSIVE_LOCK)
40270 #endif
40271 
40272 /*
40273 ** Currently, SQLite never calls the LockFileEx function without wanting the
40274 ** call to fail immediately if the lock cannot be obtained.
40275 */
40276 #ifndef SQLITE_LOCKFILEEX_FLAGS
40277 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
40278 #endif
40279 
40280 /*
40281 ** Acquire a reader lock.
40282 ** Different API routines are called depending on whether or not this
40283 ** is Win9x or WinNT.
40284 */
40285 static int winGetReadLock(winFile *pFile){
40286  int res;
40287  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40288  if( osIsNT() ){
40289 #if SQLITE_OS_WINCE
40290  /*
40291  ** NOTE: Windows CE is handled differently here due its lack of the Win32
40292  ** API LockFileEx.
40293  */
40294  res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
40295 #else
40296  res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
40297  SHARED_SIZE, 0);
40298 #endif
40299  }
40300 #ifdef SQLITE_WIN32_HAS_ANSI
40301  else{
40302  int lk;
40303  sqlite3_randomness(sizeof(lk), &lk);
40304  pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
40305  res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40306  SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40307  }
40308 #endif
40309  if( res == 0 ){
40310  pFile->lastErrno = osGetLastError();
40311  /* No need to log a failure to lock */
40312  }
40313  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
40314  return res;
40315 }
40316 
40317 /*
40318 ** Undo a readlock
40319 */
40320 static int winUnlockReadLock(winFile *pFile){
40321  int res;
40322  DWORD lastErrno;
40323  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40324  if( osIsNT() ){
40325  res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40326  }
40327 #ifdef SQLITE_WIN32_HAS_ANSI
40328  else{
40329  res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40330  }
40331 #endif
40332  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
40333  pFile->lastErrno = lastErrno;
40334  winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
40335  "winUnlockReadLock", pFile->zPath);
40336  }
40337  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
40338  return res;
40339 }
40340 
40341 /*
40342 ** Lock the file with the lock specified by parameter locktype - one
40343 ** of the following:
40344 **
40345 ** (1) SHARED_LOCK
40346 ** (2) RESERVED_LOCK
40347 ** (3) PENDING_LOCK
40348 ** (4) EXCLUSIVE_LOCK
40349 **
40350 ** Sometimes when requesting one lock state, additional lock states
40351 ** are inserted in between. The locking might fail on one of the later
40352 ** transitions leaving the lock state different from what it started but
40353 ** still short of its goal. The following chart shows the allowed
40354 ** transitions and the inserted intermediate states:
40355 **
40356 ** UNLOCKED -> SHARED
40357 ** SHARED -> RESERVED
40358 ** SHARED -> (PENDING) -> EXCLUSIVE
40359 ** RESERVED -> (PENDING) -> EXCLUSIVE
40360 ** PENDING -> EXCLUSIVE
40361 **
40362 ** This routine will only increase a lock. The winUnlock() routine
40363 ** erases all locks at once and returns us immediately to locking level 0.
40364 ** It is not possible to lower the locking level one step at a time. You
40365 ** must go straight to locking level 0.
40366 */
40367 static int winLock(sqlite3_file *id, int locktype){
40368  int rc = SQLITE_OK; /* Return code from subroutines */
40369  int res = 1; /* Result of a Windows lock call */
40370  int newLocktype; /* Set pFile->locktype to this value before exiting */
40371  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
40372  winFile *pFile = (winFile*)id;
40373  DWORD lastErrno = NO_ERROR;
40374 
40375  assert( id!=0 );
40376  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40377  pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40378 
40379  /* If there is already a lock of this type or more restrictive on the
40380  ** OsFile, do nothing. Don't use the end_lock: exit path, as
40381  ** sqlite3OsEnterMutex() hasn't been called yet.
40382  */
40383  if( pFile->locktype>=locktype ){
40384  OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
40385  return SQLITE_OK;
40386  }
40387 
40388  /* Do not allow any kind of write-lock on a read-only database
40389  */
40390  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
40391  return SQLITE_IOERR_LOCK;
40392  }
40393 
40394  /* Make sure the locking sequence is correct
40395  */
40396  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
40397  assert( locktype!=PENDING_LOCK );
40398  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
40399 
40400  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
40401  ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
40402  ** the PENDING_LOCK byte is temporary.
40403  */
40404  newLocktype = pFile->locktype;
40405  if( pFile->locktype==NO_LOCK
40406  || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
40407  ){
40408  int cnt = 3;
40409  while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40410  PENDING_BYTE, 0, 1, 0))==0 ){
40411  /* Try 3 times to get the pending lock. This is needed to work
40412  ** around problems caused by indexing and/or anti-virus software on
40413  ** Windows systems.
40414  ** If you are using this code as a model for alternative VFSes, do not
40415  ** copy this retry logic. It is a hack intended for Windows only.
40416  */
40417  lastErrno = osGetLastError();
40418  OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
40419  pFile->h, cnt, res));
40420  if( lastErrno==ERROR_INVALID_HANDLE ){
40421  pFile->lastErrno = lastErrno;
40422  rc = SQLITE_IOERR_LOCK;
40423  OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
40424  pFile->h, cnt, sqlite3ErrName(rc)));
40425  return rc;
40426  }
40427  if( cnt ) sqlite3_win32_sleep(1);
40428  }
40429  gotPendingLock = res;
40430  if( !res ){
40431  lastErrno = osGetLastError();
40432  }
40433  }
40434 
40435  /* Acquire a shared lock
40436  */
40437  if( locktype==SHARED_LOCK && res ){
40438  assert( pFile->locktype==NO_LOCK );
40439  res = winGetReadLock(pFile);
40440  if( res ){
40441  newLocktype = SHARED_LOCK;
40442  }else{
40443  lastErrno = osGetLastError();
40444  }
40445  }
40446 
40447  /* Acquire a RESERVED lock
40448  */
40449  if( locktype==RESERVED_LOCK && res ){
40450  assert( pFile->locktype==SHARED_LOCK );
40451  res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
40452  if( res ){
40453  newLocktype = RESERVED_LOCK;
40454  }else{
40455  lastErrno = osGetLastError();
40456  }
40457  }
40458 
40459  /* Acquire a PENDING lock
40460  */
40461  if( locktype==EXCLUSIVE_LOCK && res ){
40462  newLocktype = PENDING_LOCK;
40463  gotPendingLock = 0;
40464  }
40465 
40466  /* Acquire an EXCLUSIVE lock
40467  */
40468  if( locktype==EXCLUSIVE_LOCK && res ){
40469  assert( pFile->locktype>=SHARED_LOCK );
40470  res = winUnlockReadLock(pFile);
40471  res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
40472  SHARED_SIZE, 0);
40473  if( res ){
40474  newLocktype = EXCLUSIVE_LOCK;
40475  }else{
40476  lastErrno = osGetLastError();
40477  winGetReadLock(pFile);
40478  }
40479  }
40480 
40481  /* If we are holding a PENDING lock that ought to be released, then
40482  ** release it now.
40483  */
40484  if( gotPendingLock && locktype==SHARED_LOCK ){
40485  winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40486  }
40487 
40488  /* Update the state of the lock has held in the file descriptor then
40489  ** return the appropriate result code.
40490  */
40491  if( res ){
40492  rc = SQLITE_OK;
40493  }else{
40494  pFile->lastErrno = lastErrno;
40495  rc = SQLITE_BUSY;
40496  OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
40497  pFile->h, locktype, newLocktype));
40498  }
40499  pFile->locktype = (u8)newLocktype;
40500  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
40501  pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40502  return rc;
40503 }
40504 
40505 /*
40506 ** This routine checks if there is a RESERVED lock held on the specified
40507 ** file by this or any other process. If such a lock is held, return
40508 ** non-zero, otherwise zero.
40509 */
40510 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
40511  int res;
40512  winFile *pFile = (winFile*)id;
40513 
40514  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
40515  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
40516 
40517  assert( id!=0 );
40518  if( pFile->locktype>=RESERVED_LOCK ){
40519  res = 1;
40520  OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
40521  }else{
40522  res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
40523  if( res ){
40524  winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40525  }
40526  res = !res;
40527  OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
40528  }
40529  *pResOut = res;
40530  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
40531  pFile->h, pResOut, *pResOut));
40532  return SQLITE_OK;
40533 }
40534 
40535 /*
40536 ** Lower the locking level on file descriptor id to locktype. locktype
40537 ** must be either NO_LOCK or SHARED_LOCK.
40538 **
40539 ** If the locking level of the file descriptor is already at or below
40540 ** the requested locking level, this routine is a no-op.
40541 **
40542 ** It is not possible for this routine to fail if the second argument
40543 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
40544 ** might return SQLITE_IOERR;
40545 */
40546 static int winUnlock(sqlite3_file *id, int locktype){
40547  int type;
40548  winFile *pFile = (winFile*)id;
40549  int rc = SQLITE_OK;
40550  assert( pFile!=0 );
40551  assert( locktype<=SHARED_LOCK );
40552  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40553  pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40554  type = pFile->locktype;
40555  if( type>=EXCLUSIVE_LOCK ){
40556  winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40557  if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
40558  /* This should never happen. We should always be able to
40559  ** reacquire the read lock */
40560  rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
40561  "winUnlock", pFile->zPath);
40562  }
40563  }
40564  if( type>=RESERVED_LOCK ){
40565  winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40566  }
40567  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
40568  winUnlockReadLock(pFile);
40569  }
40570  if( type>=PENDING_LOCK ){
40571  winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40572  }
40573  pFile->locktype = (u8)locktype;
40574  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
40575  pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40576  return rc;
40577 }
40578 
40579 /******************************************************************************
40580 ****************************** No-op Locking **********************************
40581 **
40582 ** Of the various locking implementations available, this is by far the
40583 ** simplest: locking is ignored. No attempt is made to lock the database
40584 ** file for reading or writing.
40585 **
40586 ** This locking mode is appropriate for use on read-only databases
40587 ** (ex: databases that are burned into CD-ROM, for example.) It can
40588 ** also be used if the application employs some external mechanism to
40589 ** prevent simultaneous access of the same database by two or more
40590 ** database connections. But there is a serious risk of database
40591 ** corruption if this locking mode is used in situations where multiple
40592 ** database connections are accessing the same database file at the same
40593 ** time and one or more of those connections are writing.
40594 */
40595 
40596 static int winNolockLock(sqlite3_file *id, int locktype){
40597  UNUSED_PARAMETER(id);
40598  UNUSED_PARAMETER(locktype);
40599  return SQLITE_OK;
40600 }
40601 
40602 static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
40603  UNUSED_PARAMETER(id);
40604  UNUSED_PARAMETER(pResOut);
40605  return SQLITE_OK;
40606 }
40607 
40608 static int winNolockUnlock(sqlite3_file *id, int locktype){
40609  UNUSED_PARAMETER(id);
40610  UNUSED_PARAMETER(locktype);
40611  return SQLITE_OK;
40612 }
40613 
40614 /******************* End of the no-op lock implementation *********************
40615 ******************************************************************************/
40616 
40617 /*
40618 ** If *pArg is initially negative then this is a query. Set *pArg to
40619 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
40620 **
40621 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
40622 */
40623 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
40624  if( *pArg<0 ){
40625  *pArg = (pFile->ctrlFlags & mask)!=0;
40626  }else if( (*pArg)==0 ){
40627  pFile->ctrlFlags &= ~mask;
40628  }else{
40629  pFile->ctrlFlags |= mask;
40630  }
40631 }
40632 
40633 /* Forward references to VFS helper methods used for temporary files */
40634 static int winGetTempname(sqlite3_vfs *, char **);
40635 static int winIsDir(const void *);
40636 static BOOL winIsDriveLetterAndColon(const char *);
40637 
40638 /*
40639 ** Control and query of the open file handle.
40640 */
40641 static int winFileControl(sqlite3_file *id, int op, void *pArg){
40642  winFile *pFile = (winFile*)id;
40643  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
40644  switch( op ){
40645  case SQLITE_FCNTL_LOCKSTATE: {
40646  *(int*)pArg = pFile->locktype;
40647  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40648  return SQLITE_OK;
40649  }
40650  case SQLITE_FCNTL_LAST_ERRNO: {
40651  *(int*)pArg = (int)pFile->lastErrno;
40652  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40653  return SQLITE_OK;
40654  }
40655  case SQLITE_FCNTL_CHUNK_SIZE: {
40656  pFile->szChunk = *(int *)pArg;
40657  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40658  return SQLITE_OK;
40659  }
40660  case SQLITE_FCNTL_SIZE_HINT: {
40661  if( pFile->szChunk>0 ){
40662  sqlite3_int64 oldSz;
40663  int rc = winFileSize(id, &oldSz);
40664  if( rc==SQLITE_OK ){
40665  sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
40666  if( newSz>oldSz ){
40667  SimulateIOErrorBenign(1);
40668  rc = winTruncate(id, newSz);
40669  SimulateIOErrorBenign(0);
40670  }
40671  }
40672  OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40673  return rc;
40674  }
40675  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40676  return SQLITE_OK;
40677  }
40678  case SQLITE_FCNTL_PERSIST_WAL: {
40679  winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
40680  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40681  return SQLITE_OK;
40682  }
40683  case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
40684  winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
40685  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40686  return SQLITE_OK;
40687  }
40688  case SQLITE_FCNTL_VFSNAME: {
40689  *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
40690  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40691  return SQLITE_OK;
40692  }
40693  case SQLITE_FCNTL_WIN32_AV_RETRY: {
40694  int *a = (int*)pArg;
40695  if( a[0]>0 ){
40696  winIoerrRetry = a[0];
40697  }else{
40698  a[0] = winIoerrRetry;
40699  }
40700  if( a[1]>0 ){
40701  winIoerrRetryDelay = a[1];
40702  }else{
40703  a[1] = winIoerrRetryDelay;
40704  }
40705  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40706  return SQLITE_OK;
40707  }
40708  case SQLITE_FCNTL_WIN32_GET_HANDLE: {
40709  LPHANDLE phFile = (LPHANDLE)pArg;
40710  *phFile = pFile->h;
40711  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40712  return SQLITE_OK;
40713  }
40714 #ifdef SQLITE_TEST
40715  case SQLITE_FCNTL_WIN32_SET_HANDLE: {
40716  LPHANDLE phFile = (LPHANDLE)pArg;
40717  HANDLE hOldFile = pFile->h;
40718  pFile->h = *phFile;
40719  *phFile = hOldFile;
40720  OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
40721  hOldFile, pFile->h));
40722  return SQLITE_OK;
40723  }
40724 #endif
40725  case SQLITE_FCNTL_TEMPFILENAME: {
40726  char *zTFile = 0;
40727  int rc = winGetTempname(pFile->pVfs, &zTFile);
40728  if( rc==SQLITE_OK ){
40729  *(char**)pArg = zTFile;
40730  }
40731  OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40732  return rc;
40733  }
40734 #if SQLITE_MAX_MMAP_SIZE>0
40735  case SQLITE_FCNTL_MMAP_SIZE: {
40736  i64 newLimit = *(i64*)pArg;
40737  int rc = SQLITE_OK;
40738  if( newLimit>sqlite3GlobalConfig.mxMmap ){
40739  newLimit = sqlite3GlobalConfig.mxMmap;
40740  }
40741  *(i64*)pArg = pFile->mmapSizeMax;
40742  if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
40743  pFile->mmapSizeMax = newLimit;
40744  if( pFile->mmapSize>0 ){
40745  winUnmapfile(pFile);
40746  rc = winMapfile(pFile, -1);
40747  }
40748  }
40749  OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40750  return rc;
40751  }
40752 #endif
40753  }
40754  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
40755  return SQLITE_NOTFOUND;
40756 }
40757 
40758 /*
40759 ** Return the sector size in bytes of the underlying block device for
40760 ** the specified file. This is almost always 512 bytes, but may be
40761 ** larger for some devices.
40762 **
40763 ** SQLite code assumes this function cannot fail. It also assumes that
40764 ** if two files are created in the same file-system directory (i.e.
40765 ** a database and its journal file) that the sector size will be the
40766 ** same for both.
40767 */
40768 static int winSectorSize(sqlite3_file *id){
40769  (void)id;
40770  return SQLITE_DEFAULT_SECTOR_SIZE;
40771 }
40772 
40773 /*
40774 ** Return a vector of device characteristics.
40775 */
40776 static int winDeviceCharacteristics(sqlite3_file *id){
40777  winFile *p = (winFile*)id;
40778  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
40779  ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
40780 }
40781 
40782 /*
40783 ** Windows will only let you create file view mappings
40784 ** on allocation size granularity boundaries.
40785 ** During sqlite3_os_init() we do a GetSystemInfo()
40786 ** to get the granularity size.
40787 */
40788 static SYSTEM_INFO winSysInfo;
40789 
40790 #ifndef SQLITE_OMIT_WAL
40791 
40792 /*
40793 ** Helper functions to obtain and relinquish the global mutex. The
40794 ** global mutex is used to protect the winLockInfo objects used by
40795 ** this file, all of which may be shared by multiple threads.
40796 **
40797 ** Function winShmMutexHeld() is used to assert() that the global mutex
40798 ** is held when required. This function is only used as part of assert()
40799 ** statements. e.g.
40800 **
40801 ** winShmEnterMutex()
40802 ** assert( winShmMutexHeld() );
40803 ** winShmLeaveMutex()
40804 */
40805 static void winShmEnterMutex(void){
40806  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
40807 }
40808 static void winShmLeaveMutex(void){
40809  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
40810 }
40811 #ifndef NDEBUG
40812 static int winShmMutexHeld(void) {
40813  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
40814 }
40815 #endif
40816 
40817 /*
40818 ** Object used to represent a single file opened and mmapped to provide
40819 ** shared memory. When multiple threads all reference the same
40820 ** log-summary, each thread has its own winFile object, but they all
40821 ** point to a single instance of this object. In other words, each
40822 ** log-summary is opened only once per process.
40823 **
40824 ** winShmMutexHeld() must be true when creating or destroying
40825 ** this object or while reading or writing the following fields:
40826 **
40827 ** nRef
40828 ** pNext
40829 **
40830 ** The following fields are read-only after the object is created:
40831 **
40832 ** fid
40833 ** zFilename
40834 **
40835 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
40836 ** winShmMutexHeld() is true when reading or writing any other field
40837 ** in this structure.
40838 **
40839 */
40840 struct winShmNode {
40841  sqlite3_mutex *mutex; /* Mutex to access this object */
40842  char *zFilename; /* Name of the file */
40843  winFile hFile; /* File handle from winOpen */
40844 
40845  int szRegion; /* Size of shared-memory regions */
40846  int nRegion; /* Size of array apRegion */
40847  struct ShmRegion {
40848  HANDLE hMap; /* File handle from CreateFileMapping */
40849  void *pMap;
40850  } *aRegion;
40851  DWORD lastErrno; /* The Windows errno from the last I/O error */
40852 
40853  int nRef; /* Number of winShm objects pointing to this */
40854  winShm *pFirst; /* All winShm objects pointing to this */
40855  winShmNode *pNext; /* Next in list of all winShmNode objects */
40856 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40857  u8 nextShmId; /* Next available winShm.id value */
40858 #endif
40859 };
40860 
40861 /*
40862 ** A global array of all winShmNode objects.
40863 **
40864 ** The winShmMutexHeld() must be true while reading or writing this list.
40865 */
40866 static winShmNode *winShmNodeList = 0;
40867 
40868 /*
40869 ** Structure used internally by this VFS to record the state of an
40870 ** open shared memory connection.
40871 **
40872 ** The following fields are initialized when this object is created and
40873 ** are read-only thereafter:
40874 **
40875 ** winShm.pShmNode
40876 ** winShm.id
40877 **
40878 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
40879 ** while accessing any read/write fields.
40880 */
40881 struct winShm {
40882  winShmNode *pShmNode; /* The underlying winShmNode object */
40883  winShm *pNext; /* Next winShm with the same winShmNode */
40884  u8 hasMutex; /* True if holding the winShmNode mutex */
40885  u16 sharedMask; /* Mask of shared locks held */
40886  u16 exclMask; /* Mask of exclusive locks held */
40887 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40888  u8 id; /* Id of this connection with its winShmNode */
40889 #endif
40890 };
40891 
40892 /*
40893 ** Constants used for locking
40894 */
40895 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
40896 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
40897 
40898 /*
40899 ** Apply advisory locks for all n bytes beginning at ofst.
40900 */
40901 #define WINSHM_UNLCK 1
40902 #define WINSHM_RDLCK 2
40903 #define WINSHM_WRLCK 3
40904 static int winShmSystemLock(
40905  winShmNode *pFile, /* Apply locks to this open shared-memory segment */
40906  int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
40907  int ofst, /* Offset to first byte to be locked/unlocked */
40908  int nByte /* Number of bytes to lock or unlock */
40909 ){
40910  int rc = 0; /* Result code form Lock/UnlockFileEx() */
40911 
40912  /* Access to the winShmNode object is serialized by the caller */
40913  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
40914 
40915  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
40916  pFile->hFile.h, lockType, ofst, nByte));
40917 
40918  /* Release/Acquire the system-level lock */
40919  if( lockType==WINSHM_UNLCK ){
40920  rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
40921  }else{
40922  /* Initialize the locking parameters */
40923  DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
40924  if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
40925  rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
40926  }
40927 
40928  if( rc!= 0 ){
40929  rc = SQLITE_OK;
40930  }else{
40931  pFile->lastErrno = osGetLastError();
40932  rc = SQLITE_BUSY;
40933  }
40934 
40935  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
40936  pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
40937  "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
40938 
40939  return rc;
40940 }
40941 
40942 /* Forward references to VFS methods */
40943 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
40944 static int winDelete(sqlite3_vfs *,const char*,int);
40945 
40946 /*
40947 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
40948 **
40949 ** This is not a VFS shared-memory method; it is a utility function called
40950 ** by VFS shared-memory methods.
40951 */
40952 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
40953  winShmNode **pp;
40954  winShmNode *p;
40955  assert( winShmMutexHeld() );
40956  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
40957  osGetCurrentProcessId(), deleteFlag));
40958  pp = &winShmNodeList;
40959  while( (p = *pp)!=0 ){
40960  if( p->nRef==0 ){
40961  int i;
40962  if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
40963  for(i=0; i<p->nRegion; i++){
40964  BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
40965  OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
40966  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40967  UNUSED_VARIABLE_VALUE(bRc);
40968  bRc = osCloseHandle(p->aRegion[i].hMap);
40969  OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
40970  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40971  UNUSED_VARIABLE_VALUE(bRc);
40972  }
40973  if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
40974  SimulateIOErrorBenign(1);
40975  winClose((sqlite3_file *)&p->hFile);
40976  SimulateIOErrorBenign(0);
40977  }
40978  if( deleteFlag ){
40979  SimulateIOErrorBenign(1);
40980  sqlite3BeginBenignMalloc();
40981  winDelete(pVfs, p->zFilename, 0);
40982  sqlite3EndBenignMalloc();
40983  SimulateIOErrorBenign(0);
40984  }
40985  *pp = p->pNext;
40986  sqlite3_free(p->aRegion);
40987  sqlite3_free(p);
40988  }else{
40989  pp = &p->pNext;
40990  }
40991  }
40992 }
40993 
40994 /*
40995 ** Open the shared-memory area associated with database file pDbFd.
40996 **
40997 ** When opening a new shared-memory file, if no other instances of that
40998 ** file are currently open, in this process or in other processes, then
40999 ** the file must be truncated to zero length or have its header cleared.
41000 */
41001 static int winOpenSharedMemory(winFile *pDbFd){
41002  struct winShm *p; /* The connection to be opened */
41003  struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
41004  int rc; /* Result code */
41005  struct winShmNode *pNew; /* Newly allocated winShmNode */
41006  int nName; /* Size of zName in bytes */
41007 
41008  assert( pDbFd->pShm==0 ); /* Not previously opened */
41009 
41010  /* Allocate space for the new sqlite3_shm object. Also speculatively
41011  ** allocate space for a new winShmNode and filename.
41012  */
41013  p = sqlite3MallocZero( sizeof(*p) );
41014  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
41015  nName = sqlite3Strlen30(pDbFd->zPath);
41016  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
41017  if( pNew==0 ){
41018  sqlite3_free(p);
41019  return SQLITE_IOERR_NOMEM_BKPT;
41020  }
41021  pNew->zFilename = (char*)&pNew[1];
41022  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
41023  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
41024 
41025  /* Look to see if there is an existing winShmNode that can be used.
41026  ** If no matching winShmNode currently exists, create a new one.
41027  */
41028  winShmEnterMutex();
41029  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
41030  /* TBD need to come up with better match here. Perhaps
41031  ** use FILE_ID_BOTH_DIR_INFO Structure.
41032  */
41033  if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
41034  }
41035  if( pShmNode ){
41036  sqlite3_free(pNew);
41037  }else{
41038  pShmNode = pNew;
41039  pNew = 0;
41040  ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
41041  pShmNode->pNext = winShmNodeList;
41042  winShmNodeList = pShmNode;
41043 
41044  if( sqlite3GlobalConfig.bCoreMutex ){
41045  pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
41046  if( pShmNode->mutex==0 ){
41047  rc = SQLITE_IOERR_NOMEM_BKPT;
41048  goto shm_open_err;
41049  }
41050  }
41051 
41052  rc = winOpen(pDbFd->pVfs,
41053  pShmNode->zFilename, /* Name of the file (UTF-8) */
41054  (sqlite3_file*)&pShmNode->hFile, /* File handle here */
41055  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
41056  0);
41057  if( SQLITE_OK!=rc ){
41058  goto shm_open_err;
41059  }
41060 
41061  /* Check to see if another process is holding the dead-man switch.
41062  ** If not, truncate the file to zero length.
41063  */
41064  if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
41065  rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
41066  if( rc!=SQLITE_OK ){
41067  rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
41068  "winOpenShm", pDbFd->zPath);
41069  }
41070  }
41071  if( rc==SQLITE_OK ){
41072  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
41073  rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
41074  }
41075  if( rc ) goto shm_open_err;
41076  }
41077 
41078  /* Make the new connection a child of the winShmNode */
41079  p->pShmNode = pShmNode;
41080 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
41081  p->id = pShmNode->nextShmId++;
41082 #endif
41083  pShmNode->nRef++;
41084  pDbFd->pShm = p;
41085  winShmLeaveMutex();
41086 
41087  /* The reference count on pShmNode has already been incremented under
41088  ** the cover of the winShmEnterMutex() mutex and the pointer from the
41089  ** new (struct winShm) object to the pShmNode has been set. All that is
41090  ** left to do is to link the new object into the linked list starting
41091  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
41092  ** mutex.
41093  */
41094  sqlite3_mutex_enter(pShmNode->mutex);
41095  p->pNext = pShmNode->pFirst;
41096  pShmNode->pFirst = p;
41097  sqlite3_mutex_leave(pShmNode->mutex);
41098  return SQLITE_OK;
41099 
41100  /* Jump here on any error */
41101 shm_open_err:
41102  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
41103  winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
41104  sqlite3_free(p);
41105  sqlite3_free(pNew);
41106  winShmLeaveMutex();
41107  return rc;
41108 }
41109 
41110 /*
41111 ** Close a connection to shared-memory. Delete the underlying
41112 ** storage if deleteFlag is true.
41113 */
41114 static int winShmUnmap(
41115  sqlite3_file *fd, /* Database holding shared memory */
41116  int deleteFlag /* Delete after closing if true */
41117 ){
41118  winFile *pDbFd; /* Database holding shared-memory */
41119  winShm *p; /* The connection to be closed */
41120  winShmNode *pShmNode; /* The underlying shared-memory file */
41121  winShm **pp; /* For looping over sibling connections */
41122 
41123  pDbFd = (winFile*)fd;
41124  p = pDbFd->pShm;
41125  if( p==0 ) return SQLITE_OK;
41126  pShmNode = p->pShmNode;
41127 
41128  /* Remove connection p from the set of connections associated
41129  ** with pShmNode */
41130  sqlite3_mutex_enter(pShmNode->mutex);
41131  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
41132  *pp = p->pNext;
41133 
41134  /* Free the connection p */
41135  sqlite3_free(p);
41136  pDbFd->pShm = 0;
41137  sqlite3_mutex_leave(pShmNode->mutex);
41138 
41139  /* If pShmNode->nRef has reached 0, then close the underlying
41140  ** shared-memory file, too */
41141  winShmEnterMutex();
41142  assert( pShmNode->nRef>0 );
41143  pShmNode->nRef--;
41144  if( pShmNode->nRef==0 ){
41145  winShmPurge(pDbFd->pVfs, deleteFlag);
41146  }
41147  winShmLeaveMutex();
41148 
41149  return SQLITE_OK;
41150 }
41151 
41152 /*
41153 ** Change the lock state for a shared-memory segment.
41154 */
41155 static int winShmLock(
41156  sqlite3_file *fd, /* Database file holding the shared memory */
41157  int ofst, /* First lock to acquire or release */
41158  int n, /* Number of locks to acquire or release */
41159  int flags /* What to do with the lock */
41160 ){
41161  winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
41162  winShm *p = pDbFd->pShm; /* The shared memory being locked */
41163  winShm *pX; /* For looping over all siblings */
41164  winShmNode *pShmNode = p->pShmNode;
41165  int rc = SQLITE_OK; /* Result code */
41166  u16 mask; /* Mask of locks to take or release */
41167 
41168  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
41169  assert( n>=1 );
41170  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
41171  || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
41172  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
41173  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
41174  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
41175 
41176  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
41177  assert( n>1 || mask==(1<<ofst) );
41178  sqlite3_mutex_enter(pShmNode->mutex);
41179  if( flags & SQLITE_SHM_UNLOCK ){
41180  u16 allMask = 0; /* Mask of locks held by siblings */
41181 
41182  /* See if any siblings hold this same lock */
41183  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41184  if( pX==p ) continue;
41185  assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
41186  allMask |= pX->sharedMask;
41187  }
41188 
41189  /* Unlock the system-level locks */
41190  if( (mask & allMask)==0 ){
41191  rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
41192  }else{
41193  rc = SQLITE_OK;
41194  }
41195 
41196  /* Undo the local locks */
41197  if( rc==SQLITE_OK ){
41198  p->exclMask &= ~mask;
41199  p->sharedMask &= ~mask;
41200  }
41201  }else if( flags & SQLITE_SHM_SHARED ){
41202  u16 allShared = 0; /* Union of locks held by connections other than "p" */
41203 
41204  /* Find out which shared locks are already held by sibling connections.
41205  ** If any sibling already holds an exclusive lock, go ahead and return
41206  ** SQLITE_BUSY.
41207  */
41208  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41209  if( (pX->exclMask & mask)!=0 ){
41210  rc = SQLITE_BUSY;
41211  break;
41212  }
41213  allShared |= pX->sharedMask;
41214  }
41215 
41216  /* Get shared locks at the system level, if necessary */
41217  if( rc==SQLITE_OK ){
41218  if( (allShared & mask)==0 ){
41219  rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
41220  }else{
41221  rc = SQLITE_OK;
41222  }
41223  }
41224 
41225  /* Get the local shared locks */
41226  if( rc==SQLITE_OK ){
41227  p->sharedMask |= mask;
41228  }
41229  }else{
41230  /* Make sure no sibling connections hold locks that will block this
41231  ** lock. If any do, return SQLITE_BUSY right away.
41232  */
41233  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41234  if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
41235  rc = SQLITE_BUSY;
41236  break;
41237  }
41238  }
41239 
41240  /* Get the exclusive locks at the system level. Then if successful
41241  ** also mark the local connection as being locked.
41242  */
41243  if( rc==SQLITE_OK ){
41244  rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
41245  if( rc==SQLITE_OK ){
41246  assert( (p->sharedMask & mask)==0 );
41247  p->exclMask |= mask;
41248  }
41249  }
41250  }
41251  sqlite3_mutex_leave(pShmNode->mutex);
41252  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
41253  osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
41254  sqlite3ErrName(rc)));
41255  return rc;
41256 }
41257 
41258 /*
41259 ** Implement a memory barrier or memory fence on shared memory.
41260 **
41261 ** All loads and stores begun before the barrier must complete before
41262 ** any load or store begun after the barrier.
41263 */
41264 static void winShmBarrier(
41265  sqlite3_file *fd /* Database holding the shared memory */
41266 ){
41267  UNUSED_PARAMETER(fd);
41268  sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
41269  winShmEnterMutex(); /* Also mutex, for redundancy */
41270  winShmLeaveMutex();
41271 }
41272 
41273 /*
41274 ** This function is called to obtain a pointer to region iRegion of the
41275 ** shared-memory associated with the database file fd. Shared-memory regions
41276 ** are numbered starting from zero. Each shared-memory region is szRegion
41277 ** bytes in size.
41278 **
41279 ** If an error occurs, an error code is returned and *pp is set to NULL.
41280 **
41281 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
41282 ** region has not been allocated (by any client, including one running in a
41283 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
41284 ** isWrite is non-zero and the requested shared-memory region has not yet
41285 ** been allocated, it is allocated by this function.
41286 **
41287 ** If the shared-memory region has already been allocated or is allocated by
41288 ** this call as described above, then it is mapped into this processes
41289 ** address space (if it is not already), *pp is set to point to the mapped
41290 ** memory and SQLITE_OK returned.
41291 */
41292 static int winShmMap(
41293  sqlite3_file *fd, /* Handle open on database file */
41294  int iRegion, /* Region to retrieve */
41295  int szRegion, /* Size of regions */
41296  int isWrite, /* True to extend file if necessary */
41297  void volatile **pp /* OUT: Mapped memory */
41298 ){
41299  winFile *pDbFd = (winFile*)fd;
41300  winShm *pShm = pDbFd->pShm;
41301  winShmNode *pShmNode;
41302  int rc = SQLITE_OK;
41303 
41304  if( !pShm ){
41305  rc = winOpenSharedMemory(pDbFd);
41306  if( rc!=SQLITE_OK ) return rc;
41307  pShm = pDbFd->pShm;
41308  }
41309  pShmNode = pShm->pShmNode;
41310 
41311  sqlite3_mutex_enter(pShmNode->mutex);
41312  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
41313 
41314  if( pShmNode->nRegion<=iRegion ){
41315  struct ShmRegion *apNew; /* New aRegion[] array */
41316  int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
41317  sqlite3_int64 sz; /* Current size of wal-index file */
41318 
41319  pShmNode->szRegion = szRegion;
41320 
41321  /* The requested region is not mapped into this processes address space.
41322  ** Check to see if it has been allocated (i.e. if the wal-index file is
41323  ** large enough to contain the requested region).
41324  */
41325  rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
41326  if( rc!=SQLITE_OK ){
41327  rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41328  "winShmMap1", pDbFd->zPath);
41329  goto shmpage_out;
41330  }
41331 
41332  if( sz<nByte ){
41333  /* The requested memory region does not exist. If isWrite is set to
41334  ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
41335  **
41336  ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
41337  ** the requested memory region.
41338  */
41339  if( !isWrite ) goto shmpage_out;
41340  rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
41341  if( rc!=SQLITE_OK ){
41342  rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41343  "winShmMap2", pDbFd->zPath);
41344  goto shmpage_out;
41345  }
41346  }
41347 
41348  /* Map the requested memory region into this processes address space. */
41349  apNew = (struct ShmRegion *)sqlite3_realloc64(
41350  pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
41351  );
41352  if( !apNew ){
41353  rc = SQLITE_IOERR_NOMEM_BKPT;
41354  goto shmpage_out;
41355  }
41356  pShmNode->aRegion = apNew;
41357 
41358  while( pShmNode->nRegion<=iRegion ){
41359  HANDLE hMap = NULL; /* file-mapping handle */
41360  void *pMap = 0; /* Mapped memory region */
41361 
41362 #if SQLITE_OS_WINRT
41363  hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
41364  NULL, PAGE_READWRITE, nByte, NULL
41365  );
41366 #elif defined(SQLITE_WIN32_HAS_WIDE)
41367  hMap = osCreateFileMappingW(pShmNode->hFile.h,
41368  NULL, PAGE_READWRITE, 0, nByte, NULL
41369  );
41370 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41371  hMap = osCreateFileMappingA(pShmNode->hFile.h,
41372  NULL, PAGE_READWRITE, 0, nByte, NULL
41373  );
41374 #endif
41375  OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
41376  osGetCurrentProcessId(), pShmNode->nRegion, nByte,
41377  hMap ? "ok" : "failed"));
41378  if( hMap ){
41379  int iOffset = pShmNode->nRegion*szRegion;
41380  int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41381 #if SQLITE_OS_WINRT
41382  pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41383  iOffset - iOffsetShift, szRegion + iOffsetShift
41384  );
41385 #else
41386  pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41387  0, iOffset - iOffsetShift, szRegion + iOffsetShift
41388  );
41389 #endif
41390  OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
41391  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
41392  szRegion, pMap ? "ok" : "failed"));
41393  }
41394  if( !pMap ){
41395  pShmNode->lastErrno = osGetLastError();
41396  rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
41397  "winShmMap3", pDbFd->zPath);
41398  if( hMap ) osCloseHandle(hMap);
41399  goto shmpage_out;
41400  }
41401 
41402  pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
41403  pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
41404  pShmNode->nRegion++;
41405  }
41406  }
41407 
41408 shmpage_out:
41409  if( pShmNode->nRegion>iRegion ){
41410  int iOffset = iRegion*szRegion;
41411  int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41412  char *p = (char *)pShmNode->aRegion[iRegion].pMap;
41413  *pp = (void *)&p[iOffsetShift];
41414  }else{
41415  *pp = 0;
41416  }
41417  sqlite3_mutex_leave(pShmNode->mutex);
41418  return rc;
41419 }
41420 
41421 #else
41422 # define winShmMap 0
41423 # define winShmLock 0
41424 # define winShmBarrier 0
41425 # define winShmUnmap 0
41426 #endif /* #ifndef SQLITE_OMIT_WAL */
41427 
41428 /*
41429 ** Cleans up the mapped region of the specified file, if any.
41430 */
41431 #if SQLITE_MAX_MMAP_SIZE>0
41432 static int winUnmapfile(winFile *pFile){
41433  assert( pFile!=0 );
41434  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
41435  "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
41436  osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
41437  pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
41438  if( pFile->pMapRegion ){
41439  if( !osUnmapViewOfFile(pFile->pMapRegion) ){
41440  pFile->lastErrno = osGetLastError();
41441  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
41442  "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
41443  pFile->pMapRegion));
41444  return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41445  "winUnmapfile1", pFile->zPath);
41446  }
41447  pFile->pMapRegion = 0;
41448  pFile->mmapSize = 0;
41449  pFile->mmapSizeActual = 0;
41450  }
41451  if( pFile->hMap!=NULL ){
41452  if( !osCloseHandle(pFile->hMap) ){
41453  pFile->lastErrno = osGetLastError();
41454  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
41455  osGetCurrentProcessId(), pFile, pFile->hMap));
41456  return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41457  "winUnmapfile2", pFile->zPath);
41458  }
41459  pFile->hMap = NULL;
41460  }
41461  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41462  osGetCurrentProcessId(), pFile));
41463  return SQLITE_OK;
41464 }
41465 
41466 /*
41467 ** Memory map or remap the file opened by file-descriptor pFd (if the file
41468 ** is already mapped, the existing mapping is replaced by the new). Or, if
41469 ** there already exists a mapping for this file, and there are still
41470 ** outstanding xFetch() references to it, this function is a no-op.
41471 **
41472 ** If parameter nByte is non-negative, then it is the requested size of
41473 ** the mapping to create. Otherwise, if nByte is less than zero, then the
41474 ** requested size is the size of the file on disk. The actual size of the
41475 ** created mapping is either the requested size or the value configured
41476 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
41477 **
41478 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
41479 ** recreated as a result of outstanding references) or an SQLite error
41480 ** code otherwise.
41481 */
41482 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
41483  sqlite3_int64 nMap = nByte;
41484  int rc;
41485 
41486  assert( nMap>=0 || pFd->nFetchOut==0 );
41487  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
41488  osGetCurrentProcessId(), pFd, nByte));
41489 
41490  if( pFd->nFetchOut>0 ) return SQLITE_OK;
41491 
41492  if( nMap<0 ){
41493  rc = winFileSize((sqlite3_file*)pFd, &nMap);
41494  if( rc ){
41495  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
41496  osGetCurrentProcessId(), pFd));
41497  return SQLITE_IOERR_FSTAT;
41498  }
41499  }
41500  if( nMap>pFd->mmapSizeMax ){
41501  nMap = pFd->mmapSizeMax;
41502  }
41503  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
41504 
41505  if( nMap==0 && pFd->mmapSize>0 ){
41506  winUnmapfile(pFd);
41507  }
41508  if( nMap!=pFd->mmapSize ){
41509  void *pNew = 0;
41510  DWORD protect = PAGE_READONLY;
41511  DWORD flags = FILE_MAP_READ;
41512 
41513  winUnmapfile(pFd);
41514 #ifdef SQLITE_MMAP_READWRITE
41515  if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
41516  protect = PAGE_READWRITE;
41517  flags |= FILE_MAP_WRITE;
41518  }
41519 #endif
41520 #if SQLITE_OS_WINRT
41521  pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
41522 #elif defined(SQLITE_WIN32_HAS_WIDE)
41523  pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
41524  (DWORD)((nMap>>32) & 0xffffffff),
41525  (DWORD)(nMap & 0xffffffff), NULL);
41526 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41527  pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
41528  (DWORD)((nMap>>32) & 0xffffffff),
41529  (DWORD)(nMap & 0xffffffff), NULL);
41530 #endif
41531  if( pFd->hMap==NULL ){
41532  pFd->lastErrno = osGetLastError();
41533  rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41534  "winMapfile1", pFd->zPath);
41535  /* Log the error, but continue normal operation using xRead/xWrite */
41536  OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
41537  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41538  return SQLITE_OK;
41539  }
41540  assert( (nMap % winSysInfo.dwPageSize)==0 );
41541  assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
41542 #if SQLITE_OS_WINRT
41543  pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
41544 #else
41545  pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
41546 #endif
41547  if( pNew==NULL ){
41548  osCloseHandle(pFd->hMap);
41549  pFd->hMap = NULL;
41550  pFd->lastErrno = osGetLastError();
41551  rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41552  "winMapfile2", pFd->zPath);
41553  /* Log the error, but continue normal operation using xRead/xWrite */
41554  OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
41555  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41556  return SQLITE_OK;
41557  }
41558  pFd->pMapRegion = pNew;
41559  pFd->mmapSize = nMap;
41560  pFd->mmapSizeActual = nMap;
41561  }
41562 
41563  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41564  osGetCurrentProcessId(), pFd));
41565  return SQLITE_OK;
41566 }
41567 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
41568 
41569 /*
41570 ** If possible, return a pointer to a mapping of file fd starting at offset
41571 ** iOff. The mapping must be valid for at least nAmt bytes.
41572 **
41573 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
41574 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
41575 ** Finally, if an error does occur, return an SQLite error code. The final
41576 ** value of *pp is undefined in this case.
41577 **
41578 ** If this function does return a pointer, the caller must eventually
41579 ** release the reference by calling winUnfetch().
41580 */
41581 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
41582 #if SQLITE_MAX_MMAP_SIZE>0
41583  winFile *pFd = (winFile*)fd; /* The underlying database file */
41584 #endif
41585  *pp = 0;
41586 
41587  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
41588  osGetCurrentProcessId(), fd, iOff, nAmt, pp));
41589 
41590 #if SQLITE_MAX_MMAP_SIZE>0
41591  if( pFd->mmapSizeMax>0 ){
41592  if( pFd->pMapRegion==0 ){
41593  int rc = winMapfile(pFd, -1);
41594  if( rc!=SQLITE_OK ){
41595  OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
41596  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41597  return rc;
41598  }
41599  }
41600  if( pFd->mmapSize >= iOff+nAmt ){
41601  *pp = &((u8 *)pFd->pMapRegion)[iOff];
41602  pFd->nFetchOut++;
41603  }
41604  }
41605 #endif
41606 
41607  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
41608  osGetCurrentProcessId(), fd, pp, *pp));
41609  return SQLITE_OK;
41610 }
41611 
41612 /*
41613 ** If the third argument is non-NULL, then this function releases a
41614 ** reference obtained by an earlier call to winFetch(). The second
41615 ** argument passed to this function must be the same as the corresponding
41616 ** argument that was passed to the winFetch() invocation.
41617 **
41618 ** Or, if the third argument is NULL, then this function is being called
41619 ** to inform the VFS layer that, according to POSIX, any existing mapping
41620 ** may now be invalid and should be unmapped.
41621 */
41622 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
41623 #if SQLITE_MAX_MMAP_SIZE>0
41624  winFile *pFd = (winFile*)fd; /* The underlying database file */
41625 
41626  /* If p==0 (unmap the entire file) then there must be no outstanding
41627  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
41628  ** then there must be at least one outstanding. */
41629  assert( (p==0)==(pFd->nFetchOut==0) );
41630 
41631  /* If p!=0, it must match the iOff value. */
41632  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
41633 
41634  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
41635  osGetCurrentProcessId(), pFd, iOff, p));
41636 
41637  if( p ){
41638  pFd->nFetchOut--;
41639  }else{
41640  /* FIXME: If Windows truly always prevents truncating or deleting a
41641  ** file while a mapping is held, then the following winUnmapfile() call
41642  ** is unnecessary can be omitted - potentially improving
41643  ** performance. */
41644  winUnmapfile(pFd);
41645  }
41646 
41647  assert( pFd->nFetchOut>=0 );
41648 #endif
41649 
41650  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41651  osGetCurrentProcessId(), fd));
41652  return SQLITE_OK;
41653 }
41654 
41655 /*
41656 ** Here ends the implementation of all sqlite3_file methods.
41657 **
41658 ********************** End sqlite3_file Methods *******************************
41659 ******************************************************************************/
41660 
41661 /*
41662 ** This vector defines all the methods that can operate on an
41663 ** sqlite3_file for win32.
41664 */
41665 static const sqlite3_io_methods winIoMethod = {
41666  3, /* iVersion */
41667  winClose, /* xClose */
41668  winRead, /* xRead */
41669  winWrite, /* xWrite */
41670  winTruncate, /* xTruncate */
41671  winSync, /* xSync */
41672  winFileSize, /* xFileSize */
41673  winLock, /* xLock */
41674  winUnlock, /* xUnlock */
41675  winCheckReservedLock, /* xCheckReservedLock */
41676  winFileControl, /* xFileControl */
41677  winSectorSize, /* xSectorSize */
41678  winDeviceCharacteristics, /* xDeviceCharacteristics */
41679  winShmMap, /* xShmMap */
41680  winShmLock, /* xShmLock */
41681  winShmBarrier, /* xShmBarrier */
41682  winShmUnmap, /* xShmUnmap */
41683  winFetch, /* xFetch */
41684  winUnfetch /* xUnfetch */
41685 };
41686 
41687 /*
41688 ** This vector defines all the methods that can operate on an
41689 ** sqlite3_file for win32 without performing any locking.
41690 */
41691 static const sqlite3_io_methods winIoNolockMethod = {
41692  3, /* iVersion */
41693  winClose, /* xClose */
41694  winRead, /* xRead */
41695  winWrite, /* xWrite */
41696  winTruncate, /* xTruncate */
41697  winSync, /* xSync */
41698  winFileSize, /* xFileSize */
41699  winNolockLock, /* xLock */
41700  winNolockUnlock, /* xUnlock */
41701  winNolockCheckReservedLock, /* xCheckReservedLock */
41702  winFileControl, /* xFileControl */
41703  winSectorSize, /* xSectorSize */
41704  winDeviceCharacteristics, /* xDeviceCharacteristics */
41705  winShmMap, /* xShmMap */
41706  winShmLock, /* xShmLock */
41707  winShmBarrier, /* xShmBarrier */
41708  winShmUnmap, /* xShmUnmap */
41709  winFetch, /* xFetch */
41710  winUnfetch /* xUnfetch */
41711 };
41712 
41713 static winVfsAppData winAppData = {
41714  &winIoMethod, /* pMethod */
41715  0, /* pAppData */
41716  0 /* bNoLock */
41717 };
41718 
41719 static winVfsAppData winNolockAppData = {
41720  &winIoNolockMethod, /* pMethod */
41721  0, /* pAppData */
41722  1 /* bNoLock */
41723 };
41724 
41725 /****************************************************************************
41726 **************************** sqlite3_vfs methods ****************************
41727 **
41728 ** This division contains the implementation of methods on the
41729 ** sqlite3_vfs object.
41730 */
41731 
41732 #if defined(__CYGWIN__)
41733 /*
41734 ** Convert a filename from whatever the underlying operating system
41735 ** supports for filenames into UTF-8. Space to hold the result is
41736 ** obtained from malloc and must be freed by the calling function.
41737 */
41738 static char *winConvertToUtf8Filename(const void *zFilename){
41739  char *zConverted = 0;
41740  if( osIsNT() ){
41741  zConverted = winUnicodeToUtf8(zFilename);
41742  }
41743 #ifdef SQLITE_WIN32_HAS_ANSI
41744  else{
41745  zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
41746  }
41747 #endif
41748  /* caller will handle out of memory */
41749  return zConverted;
41750 }
41751 #endif
41752 
41753 /*
41754 ** Convert a UTF-8 filename into whatever form the underlying
41755 ** operating system wants filenames in. Space to hold the result
41756 ** is obtained from malloc and must be freed by the calling
41757 ** function.
41758 */
41759 static void *winConvertFromUtf8Filename(const char *zFilename){
41760  void *zConverted = 0;
41761  if( osIsNT() ){
41762  zConverted = winUtf8ToUnicode(zFilename);
41763  }
41764 #ifdef SQLITE_WIN32_HAS_ANSI
41765  else{
41766  zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
41767  }
41768 #endif
41769  /* caller will handle out of memory */
41770  return zConverted;
41771 }
41772 
41773 /*
41774 ** This function returns non-zero if the specified UTF-8 string buffer
41775 ** ends with a directory separator character or one was successfully
41776 ** added to it.
41777 */
41778 static int winMakeEndInDirSep(int nBuf, char *zBuf){
41779  if( zBuf ){
41780  int nLen = sqlite3Strlen30(zBuf);
41781  if( nLen>0 ){
41782  if( winIsDirSep(zBuf[nLen-1]) ){
41783  return 1;
41784  }else if( nLen+1<nBuf ){
41785  zBuf[nLen] = winGetDirSep();
41786  zBuf[nLen+1] = '\0';
41787  return 1;
41788  }
41789  }
41790  }
41791  return 0;
41792 }
41793 
41794 /*
41795 ** Create a temporary file name and store the resulting pointer into pzBuf.
41796 ** The pointer returned in pzBuf must be freed via sqlite3_free().
41797 */
41798 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
41799  static char zChars[] =
41800  "abcdefghijklmnopqrstuvwxyz"
41801  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
41802  "0123456789";
41803  size_t i, j;
41804  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
41805  int nMax, nBuf, nDir, nLen;
41806  char *zBuf;
41807 
41808  /* It's odd to simulate an io-error here, but really this is just
41809  ** using the io-error infrastructure to test that SQLite handles this
41810  ** function failing.
41811  */
41812  SimulateIOError( return SQLITE_IOERR );
41813 
41814  /* Allocate a temporary buffer to store the fully qualified file
41815  ** name for the temporary file. If this fails, we cannot continue.
41816  */
41817  nMax = pVfs->mxPathname; nBuf = nMax + 2;
41818  zBuf = sqlite3MallocZero( nBuf );
41819  if( !zBuf ){
41820  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41821  return SQLITE_IOERR_NOMEM_BKPT;
41822  }
41823 
41824  /* Figure out the effective temporary directory. First, check if one
41825  ** has been explicitly set by the application; otherwise, use the one
41826  ** configured by the operating system.
41827  */
41828  nDir = nMax - (nPre + 15);
41829  assert( nDir>0 );
41830  if( sqlite3_temp_directory ){
41831  int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
41832  if( nDirLen>0 ){
41833  if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
41834  nDirLen++;
41835  }
41836  if( nDirLen>nDir ){
41837  sqlite3_free(zBuf);
41838  OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41839  return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
41840  }
41841  sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
41842  }
41843  }
41844 #if defined(__CYGWIN__)
41845  else{
41846  static const char *azDirs[] = {
41847  0, /* getenv("SQLITE_TMPDIR") */
41848  0, /* getenv("TMPDIR") */
41849  0, /* getenv("TMP") */
41850  0, /* getenv("TEMP") */
41851  0, /* getenv("USERPROFILE") */
41852  "/var/tmp",
41853  "/usr/tmp",
41854  "/tmp",
41855  ".",
41856  0 /* List terminator */
41857  };
41858  unsigned int i;
41859  const char *zDir = 0;
41860 
41861  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
41862  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
41863  if( !azDirs[2] ) azDirs[2] = getenv("TMP");
41864  if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
41865  if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
41866  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
41867  void *zConverted;
41868  if( zDir==0 ) continue;
41869  /* If the path starts with a drive letter followed by the colon
41870  ** character, assume it is already a native Win32 path; otherwise,
41871  ** it must be converted to a native Win32 path via the Cygwin API
41872  ** prior to using it.
41873  */
41874  if( winIsDriveLetterAndColon(zDir) ){
41875  zConverted = winConvertFromUtf8Filename(zDir);
41876  if( !zConverted ){
41877  sqlite3_free(zBuf);
41878  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41879  return SQLITE_IOERR_NOMEM_BKPT;
41880  }
41881  if( winIsDir(zConverted) ){
41882  sqlite3_snprintf(nMax, zBuf, "%s", zDir);
41883  sqlite3_free(zConverted);
41884  break;
41885  }
41886  sqlite3_free(zConverted);
41887  }else{
41888  zConverted = sqlite3MallocZero( nMax+1 );
41889  if( !zConverted ){
41890  sqlite3_free(zBuf);
41891  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41892  return SQLITE_IOERR_NOMEM_BKPT;
41893  }
41894  if( cygwin_conv_path(
41895  osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
41896  zConverted, nMax+1)<0 ){
41897  sqlite3_free(zConverted);
41898  sqlite3_free(zBuf);
41899  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
41900  return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
41901  "winGetTempname2", zDir);
41902  }
41903  if( winIsDir(zConverted) ){
41904  /* At this point, we know the candidate directory exists and should
41905  ** be used. However, we may need to convert the string containing
41906  ** its name into UTF-8 (i.e. if it is UTF-16 right now).
41907  */
41908  char *zUtf8 = winConvertToUtf8Filename(zConverted);
41909  if( !zUtf8 ){
41910  sqlite3_free(zConverted);
41911  sqlite3_free(zBuf);
41912  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41913  return SQLITE_IOERR_NOMEM_BKPT;
41914  }
41915  sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41916  sqlite3_free(zUtf8);
41917  sqlite3_free(zConverted);
41918  break;
41919  }
41920  sqlite3_free(zConverted);
41921  }
41922  }
41923  }
41924 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
41925  else if( osIsNT() ){
41926  char *zMulti;
41927  LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
41928  if( !zWidePath ){
41929  sqlite3_free(zBuf);
41930  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41931  return SQLITE_IOERR_NOMEM_BKPT;
41932  }
41933  if( osGetTempPathW(nMax, zWidePath)==0 ){
41934  sqlite3_free(zWidePath);
41935  sqlite3_free(zBuf);
41936  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41937  return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41938  "winGetTempname2", 0);
41939  }
41940  zMulti = winUnicodeToUtf8(zWidePath);
41941  if( zMulti ){
41942  sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
41943  sqlite3_free(zMulti);
41944  sqlite3_free(zWidePath);
41945  }else{
41946  sqlite3_free(zWidePath);
41947  sqlite3_free(zBuf);
41948  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41949  return SQLITE_IOERR_NOMEM_BKPT;
41950  }
41951  }
41952 #ifdef SQLITE_WIN32_HAS_ANSI
41953  else{
41954  char *zUtf8;
41955  char *zMbcsPath = sqlite3MallocZero( nMax );
41956  if( !zMbcsPath ){
41957  sqlite3_free(zBuf);
41958  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41959  return SQLITE_IOERR_NOMEM_BKPT;
41960  }
41961  if( osGetTempPathA(nMax, zMbcsPath)==0 ){
41962  sqlite3_free(zBuf);
41963  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41964  return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41965  "winGetTempname3", 0);
41966  }
41967  zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
41968  if( zUtf8 ){
41969  sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41970  sqlite3_free(zUtf8);
41971  }else{
41972  sqlite3_free(zBuf);
41973  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41974  return SQLITE_IOERR_NOMEM_BKPT;
41975  }
41976  }
41977 #endif /* SQLITE_WIN32_HAS_ANSI */
41978 #endif /* !SQLITE_OS_WINRT */
41979 
41980  /*
41981  ** Check to make sure the temporary directory ends with an appropriate
41982  ** separator. If it does not and there is not enough space left to add
41983  ** one, fail.
41984  */
41985  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
41986  sqlite3_free(zBuf);
41987  OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41988  return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
41989  }
41990 
41991  /*
41992  ** Check that the output buffer is large enough for the temporary file
41993  ** name in the following format:
41994  **
41995  ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
41996  **
41997  ** If not, return SQLITE_ERROR. The number 17 is used here in order to
41998  ** account for the space used by the 15 character random suffix and the
41999  ** two trailing NUL characters. The final directory separator character
42000  ** has already added if it was not already present.
42001  */
42002  nLen = sqlite3Strlen30(zBuf);
42003  if( (nLen + nPre + 17) > nBuf ){
42004  sqlite3_free(zBuf);
42005  OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
42006  return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
42007  }
42008 
42009  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
42010 
42011  j = sqlite3Strlen30(zBuf);
42012  sqlite3_randomness(15, &zBuf[j]);
42013  for(i=0; i<15; i++, j++){
42014  zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
42015  }
42016  zBuf[j] = 0;
42017  zBuf[j+1] = 0;
42018  *pzBuf = zBuf;
42019 
42020  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
42021  return SQLITE_OK;
42022 }
42023 
42024 /*
42025 ** Return TRUE if the named file is really a directory. Return false if
42026 ** it is something other than a directory, or if there is any kind of memory
42027 ** allocation failure.
42028 */
42029 static int winIsDir(const void *zConverted){
42030  DWORD attr;
42031  int rc = 0;
42032  DWORD lastErrno;
42033 
42034  if( osIsNT() ){
42035  int cnt = 0;
42036  WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42037  memset(&sAttrData, 0, sizeof(sAttrData));
42038  while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
42039  GetFileExInfoStandard,
42040  &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
42041  if( !rc ){
42042  return 0; /* Invalid name? */
42043  }
42044  attr = sAttrData.dwFileAttributes;
42045 #if SQLITE_OS_WINCE==0
42046  }else{
42047  attr = osGetFileAttributesA((char*)zConverted);
42048 #endif
42049  }
42050  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
42051 }
42052 
42053 /*
42054 ** Open a file.
42055 */
42056 static int winOpen(
42057  sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
42058  const char *zName, /* Name of the file (UTF-8) */
42059  sqlite3_file *id, /* Write the SQLite file handle here */
42060  int flags, /* Open mode flags */
42061  int *pOutFlags /* Status return flags */
42062 ){
42063  HANDLE h;
42064  DWORD lastErrno = 0;
42065  DWORD dwDesiredAccess;
42066  DWORD dwShareMode;
42067  DWORD dwCreationDisposition;
42068  DWORD dwFlagsAndAttributes = 0;
42069 #if SQLITE_OS_WINCE
42070  int isTemp = 0;
42071 #endif
42072  winVfsAppData *pAppData;
42073  winFile *pFile = (winFile*)id;
42074  void *zConverted; /* Filename in OS encoding */
42075  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
42076  int cnt = 0;
42077 
42078  /* If argument zPath is a NULL pointer, this function is required to open
42079  ** a temporary file. Use this buffer to store the file name in.
42080  */
42081  char *zTmpname = 0; /* For temporary filename, if necessary. */
42082 
42083  int rc = SQLITE_OK; /* Function Return Code */
42084 #if !defined(NDEBUG) || SQLITE_OS_WINCE
42085  int eType = flags&0xFFFFFF00; /* Type of file to open */
42086 #endif
42087 
42088  int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
42089  int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
42090  int isCreate = (flags & SQLITE_OPEN_CREATE);
42091  int isReadonly = (flags & SQLITE_OPEN_READONLY);
42092  int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
42093 
42094 #ifndef NDEBUG
42095  int isOpenJournal = (isCreate && (
42096  eType==SQLITE_OPEN_MASTER_JOURNAL
42097  || eType==SQLITE_OPEN_MAIN_JOURNAL
42098  || eType==SQLITE_OPEN_WAL
42099  ));
42100 #endif
42101 
42102  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
42103  zUtf8Name, id, flags, pOutFlags));
42104 
42105  /* Check the following statements are true:
42106  **
42107  ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
42108  ** (b) if CREATE is set, then READWRITE must also be set, and
42109  ** (c) if EXCLUSIVE is set, then CREATE must also be set.
42110  ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
42111  */
42112  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
42113  assert(isCreate==0 || isReadWrite);
42114  assert(isExclusive==0 || isCreate);
42115  assert(isDelete==0 || isCreate);
42116 
42117  /* The main DB, main journal, WAL file and master journal are never
42118  ** automatically deleted. Nor are they ever temporary files. */
42119  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
42120  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
42121  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
42122  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
42123 
42124  /* Assert that the upper layer has set one of the "file-type" flags. */
42125  assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
42126  || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
42127  || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
42128  || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
42129  );
42130 
42131  assert( pFile!=0 );
42132  memset(pFile, 0, sizeof(winFile));
42133  pFile->h = INVALID_HANDLE_VALUE;
42134 
42135 #if SQLITE_OS_WINRT
42136  if( !zUtf8Name && !sqlite3_temp_directory ){
42137  sqlite3_log(SQLITE_ERROR,
42138  "sqlite3_temp_directory variable should be set for WinRT");
42139  }
42140 #endif
42141 
42142  /* If the second argument to this function is NULL, generate a
42143  ** temporary file name to use
42144  */
42145  if( !zUtf8Name ){
42146  assert( isDelete && !isOpenJournal );
42147  rc = winGetTempname(pVfs, &zTmpname);
42148  if( rc!=SQLITE_OK ){
42149  OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
42150  return rc;
42151  }
42152  zUtf8Name = zTmpname;
42153  }
42154 
42155  /* Database filenames are double-zero terminated if they are not
42156  ** URIs with parameters. Hence, they can always be passed into
42157  ** sqlite3_uri_parameter().
42158  */
42159  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
42160  zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
42161 
42162  /* Convert the filename to the system encoding. */
42163  zConverted = winConvertFromUtf8Filename(zUtf8Name);
42164  if( zConverted==0 ){
42165  sqlite3_free(zTmpname);
42166  OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
42167  return SQLITE_IOERR_NOMEM_BKPT;
42168  }
42169 
42170  if( winIsDir(zConverted) ){
42171  sqlite3_free(zConverted);
42172  sqlite3_free(zTmpname);
42173  OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
42174  return SQLITE_CANTOPEN_ISDIR;
42175  }
42176 
42177  if( isReadWrite ){
42178  dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
42179  }else{
42180  dwDesiredAccess = GENERIC_READ;
42181  }
42182 
42183  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
42184  ** created. SQLite doesn't use it to indicate "exclusive access"
42185  ** as it is usually understood.
42186  */
42187  if( isExclusive ){
42188  /* Creates a new file, only if it does not already exist. */
42189  /* If the file exists, it fails. */
42190  dwCreationDisposition = CREATE_NEW;
42191  }else if( isCreate ){
42192  /* Open existing file, or create if it doesn't exist */
42193  dwCreationDisposition = OPEN_ALWAYS;
42194  }else{
42195  /* Opens a file, only if it exists. */
42196  dwCreationDisposition = OPEN_EXISTING;
42197  }
42198 
42199  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
42200 
42201  if( isDelete ){
42202 #if SQLITE_OS_WINCE
42203  dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
42204  isTemp = 1;
42205 #else
42206  dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
42207  | FILE_ATTRIBUTE_HIDDEN
42208  | FILE_FLAG_DELETE_ON_CLOSE;
42209 #endif
42210  }else{
42211  dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
42212  }
42213  /* Reports from the internet are that performance is always
42214  ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
42215 #if SQLITE_OS_WINCE
42216  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
42217 #endif
42218 
42219  if( osIsNT() ){
42220 #if SQLITE_OS_WINRT
42221  CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
42222  extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
42223  extendedParameters.dwFileAttributes =
42224  dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
42225  extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
42226  extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
42227  extendedParameters.lpSecurityAttributes = NULL;
42228  extendedParameters.hTemplateFile = NULL;
42229  while( (h = osCreateFile2((LPCWSTR)zConverted,
42230  dwDesiredAccess,
42231  dwShareMode,
42232  dwCreationDisposition,
42233  &extendedParameters))==INVALID_HANDLE_VALUE &&
42234  winRetryIoerr(&cnt, &lastErrno) ){
42235  /* Noop */
42236  }
42237 #else
42238  while( (h = osCreateFileW((LPCWSTR)zConverted,
42239  dwDesiredAccess,
42240  dwShareMode, NULL,
42241  dwCreationDisposition,
42242  dwFlagsAndAttributes,
42243  NULL))==INVALID_HANDLE_VALUE &&
42244  winRetryIoerr(&cnt, &lastErrno) ){
42245  /* Noop */
42246  }
42247 #endif
42248  }
42249 #ifdef SQLITE_WIN32_HAS_ANSI
42250  else{
42251  while( (h = osCreateFileA((LPCSTR)zConverted,
42252  dwDesiredAccess,
42253  dwShareMode, NULL,
42254  dwCreationDisposition,
42255  dwFlagsAndAttributes,
42256  NULL))==INVALID_HANDLE_VALUE &&
42257  winRetryIoerr(&cnt, &lastErrno) ){
42258  /* Noop */
42259  }
42260  }
42261 #endif
42262  winLogIoerr(cnt, __LINE__);
42263 
42264  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
42265  dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42266 
42267  if( h==INVALID_HANDLE_VALUE ){
42268  pFile->lastErrno = lastErrno;
42269  winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
42270  sqlite3_free(zConverted);
42271  sqlite3_free(zTmpname);
42272  if( isReadWrite && !isExclusive ){
42273  return winOpen(pVfs, zName, id,
42274  ((flags|SQLITE_OPEN_READONLY) &
42275  ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
42276  pOutFlags);
42277  }else{
42278  return SQLITE_CANTOPEN_BKPT;
42279  }
42280  }
42281 
42282  if( pOutFlags ){
42283  if( isReadWrite ){
42284  *pOutFlags = SQLITE_OPEN_READWRITE;
42285  }else{
42286  *pOutFlags = SQLITE_OPEN_READONLY;
42287  }
42288  }
42289 
42290  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
42291  "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
42292  *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42293 
42294  pAppData = (winVfsAppData*)pVfs->pAppData;
42295 
42296 #if SQLITE_OS_WINCE
42297  {
42298  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
42299  && ((pAppData==NULL) || !pAppData->bNoLock)
42300  && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
42301  ){
42302  osCloseHandle(h);
42303  sqlite3_free(zConverted);
42304  sqlite3_free(zTmpname);
42305  OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
42306  return rc;
42307  }
42308  }
42309  if( isTemp ){
42310  pFile->zDeleteOnClose = zConverted;
42311  }else
42312 #endif
42313  {
42314  sqlite3_free(zConverted);
42315  }
42316 
42317  sqlite3_free(zTmpname);
42318  pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
42319  pFile->pVfs = pVfs;
42320  pFile->h = h;
42321  if( isReadonly ){
42322  pFile->ctrlFlags |= WINFILE_RDONLY;
42323  }
42324  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
42325  pFile->ctrlFlags |= WINFILE_PSOW;
42326  }
42327  pFile->lastErrno = NO_ERROR;
42328  pFile->zPath = zName;
42329 #if SQLITE_MAX_MMAP_SIZE>0
42330  pFile->hMap = NULL;
42331  pFile->pMapRegion = 0;
42332  pFile->mmapSize = 0;
42333  pFile->mmapSizeActual = 0;
42334  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
42335 #endif
42336 
42337  OpenCounter(+1);
42338  return rc;
42339 }
42340 
42341 /*
42342 ** Delete the named file.
42343 **
42344 ** Note that Windows does not allow a file to be deleted if some other
42345 ** process has it open. Sometimes a virus scanner or indexing program
42346 ** will open a journal file shortly after it is created in order to do
42347 ** whatever it does. While this other process is holding the
42348 ** file open, we will be unable to delete it. To work around this
42349 ** problem, we delay 100 milliseconds and try to delete again. Up
42350 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
42351 ** up and returning an error.
42352 */
42353 static int winDelete(
42354  sqlite3_vfs *pVfs, /* Not used on win32 */
42355  const char *zFilename, /* Name of file to delete */
42356  int syncDir /* Not used on win32 */
42357 ){
42358  int cnt = 0;
42359  int rc;
42360  DWORD attr;
42361  DWORD lastErrno = 0;
42362  void *zConverted;
42363  UNUSED_PARAMETER(pVfs);
42364  UNUSED_PARAMETER(syncDir);
42365 
42366  SimulateIOError(return SQLITE_IOERR_DELETE);
42367  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
42368 
42369  zConverted = winConvertFromUtf8Filename(zFilename);
42370  if( zConverted==0 ){
42371  OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42372  return SQLITE_IOERR_NOMEM_BKPT;
42373  }
42374  if( osIsNT() ){
42375  do {
42376 #if SQLITE_OS_WINRT
42377  WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42378  memset(&sAttrData, 0, sizeof(sAttrData));
42379  if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
42380  &sAttrData) ){
42381  attr = sAttrData.dwFileAttributes;
42382  }else{
42383  lastErrno = osGetLastError();
42384  if( lastErrno==ERROR_FILE_NOT_FOUND
42385  || lastErrno==ERROR_PATH_NOT_FOUND ){
42386  rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42387  }else{
42388  rc = SQLITE_ERROR;
42389  }
42390  break;
42391  }
42392 #else
42393  attr = osGetFileAttributesW(zConverted);
42394 #endif
42395  if ( attr==INVALID_FILE_ATTRIBUTES ){
42396  lastErrno = osGetLastError();
42397  if( lastErrno==ERROR_FILE_NOT_FOUND
42398  || lastErrno==ERROR_PATH_NOT_FOUND ){
42399  rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42400  }else{
42401  rc = SQLITE_ERROR;
42402  }
42403  break;
42404  }
42405  if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42406  rc = SQLITE_ERROR; /* Files only. */
42407  break;
42408  }
42409  if ( osDeleteFileW(zConverted) ){
42410  rc = SQLITE_OK; /* Deleted OK. */
42411  break;
42412  }
42413  if ( !winRetryIoerr(&cnt, &lastErrno) ){
42414  rc = SQLITE_ERROR; /* No more retries. */
42415  break;
42416  }
42417  } while(1);
42418  }
42419 #ifdef SQLITE_WIN32_HAS_ANSI
42420  else{
42421  do {
42422  attr = osGetFileAttributesA(zConverted);
42423  if ( attr==INVALID_FILE_ATTRIBUTES ){
42424  lastErrno = osGetLastError();
42425  if( lastErrno==ERROR_FILE_NOT_FOUND
42426  || lastErrno==ERROR_PATH_NOT_FOUND ){
42427  rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42428  }else{
42429  rc = SQLITE_ERROR;
42430  }
42431  break;
42432  }
42433  if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42434  rc = SQLITE_ERROR; /* Files only. */
42435  break;
42436  }
42437  if ( osDeleteFileA(zConverted) ){
42438  rc = SQLITE_OK; /* Deleted OK. */
42439  break;
42440  }
42441  if ( !winRetryIoerr(&cnt, &lastErrno) ){
42442  rc = SQLITE_ERROR; /* No more retries. */
42443  break;
42444  }
42445  } while(1);
42446  }
42447 #endif
42448  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
42449  rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
42450  }else{
42451  winLogIoerr(cnt, __LINE__);
42452  }
42453  sqlite3_free(zConverted);
42454  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
42455  return rc;
42456 }
42457 
42458 /*
42459 ** Check the existence and status of a file.
42460 */
42461 static int winAccess(
42462  sqlite3_vfs *pVfs, /* Not used on win32 */
42463  const char *zFilename, /* Name of file to check */
42464  int flags, /* Type of test to make on this file */
42465  int *pResOut /* OUT: Result */
42466 ){
42467  DWORD attr;
42468  int rc = 0;
42469  DWORD lastErrno = 0;
42470  void *zConverted;
42471  UNUSED_PARAMETER(pVfs);
42472 
42473  SimulateIOError( return SQLITE_IOERR_ACCESS; );
42474  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
42475  zFilename, flags, pResOut));
42476 
42477  zConverted = winConvertFromUtf8Filename(zFilename);
42478  if( zConverted==0 ){
42479  OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42480  return SQLITE_IOERR_NOMEM_BKPT;
42481  }
42482  if( osIsNT() ){
42483  int cnt = 0;
42484  WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42485  memset(&sAttrData, 0, sizeof(sAttrData));
42486  while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
42487  GetFileExInfoStandard,
42488  &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
42489  if( rc ){
42490  /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
42491  ** as if it does not exist.
42492  */
42493  if( flags==SQLITE_ACCESS_EXISTS
42494  && sAttrData.nFileSizeHigh==0
42495  && sAttrData.nFileSizeLow==0 ){
42496  attr = INVALID_FILE_ATTRIBUTES;
42497  }else{
42498  attr = sAttrData.dwFileAttributes;
42499  }
42500  }else{
42501  winLogIoerr(cnt, __LINE__);
42502  if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
42503  sqlite3_free(zConverted);
42504  return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
42505  zFilename);
42506  }else{
42507  attr = INVALID_FILE_ATTRIBUTES;
42508  }
42509  }
42510  }
42511 #ifdef SQLITE_WIN32_HAS_ANSI
42512  else{
42513  attr = osGetFileAttributesA((char*)zConverted);
42514  }
42515 #endif
42516  sqlite3_free(zConverted);
42517  switch( flags ){
42518  case SQLITE_ACCESS_READ:
42519  case SQLITE_ACCESS_EXISTS:
42520  rc = attr!=INVALID_FILE_ATTRIBUTES;
42521  break;
42522  case SQLITE_ACCESS_READWRITE:
42523  rc = attr!=INVALID_FILE_ATTRIBUTES &&
42524  (attr & FILE_ATTRIBUTE_READONLY)==0;
42525  break;
42526  default:
42527  assert(!"Invalid flags argument");
42528  }
42529  *pResOut = rc;
42530  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
42531  zFilename, pResOut, *pResOut));
42532  return SQLITE_OK;
42533 }
42534 
42535 /*
42536 ** Returns non-zero if the specified path name starts with a drive letter
42537 ** followed by a colon character.
42538 */
42539 static BOOL winIsDriveLetterAndColon(
42540  const char *zPathname
42541 ){
42542  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
42543 }
42544 
42545 /*
42546 ** Returns non-zero if the specified path name should be used verbatim. If
42547 ** non-zero is returned from this function, the calling function must simply
42548 ** use the provided path name verbatim -OR- resolve it into a full path name
42549 ** using the GetFullPathName Win32 API function (if available).
42550 */
42551 static BOOL winIsVerbatimPathname(
42552  const char *zPathname
42553 ){
42554  /*
42555  ** If the path name starts with a forward slash or a backslash, it is either
42556  ** a legal UNC name, a volume relative path, or an absolute path name in the
42557  ** "Unix" format on Windows. There is no easy way to differentiate between
42558  ** the final two cases; therefore, we return the safer return value of TRUE
42559  ** so that callers of this function will simply use it verbatim.
42560  */
42561  if ( winIsDirSep(zPathname[0]) ){
42562  return TRUE;
42563  }
42564 
42565  /*
42566  ** If the path name starts with a letter and a colon it is either a volume
42567  ** relative path or an absolute path. Callers of this function must not
42568  ** attempt to treat it as a relative path name (i.e. they should simply use
42569  ** it verbatim).
42570  */
42571  if ( winIsDriveLetterAndColon(zPathname) ){
42572  return TRUE;
42573  }
42574 
42575  /*
42576  ** If we get to this point, the path name should almost certainly be a purely
42577  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
42578  */
42579  return FALSE;
42580 }
42581 
42582 /*
42583 ** Turn a relative pathname into a full pathname. Write the full
42584 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
42585 ** bytes in size.
42586 */
42587 static int winFullPathname(
42588  sqlite3_vfs *pVfs, /* Pointer to vfs object */
42589  const char *zRelative, /* Possibly relative input path */
42590  int nFull, /* Size of output buffer in bytes */
42591  char *zFull /* Output buffer */
42592 ){
42593 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42594  DWORD nByte;
42595  void *zConverted;
42596  char *zOut;
42597 #endif
42598 
42599  /* If this path name begins with "/X:", where "X" is any alphabetic
42600  ** character, discard the initial "/" from the pathname.
42601  */
42602  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
42603  zRelative++;
42604  }
42605 
42606 #if defined(__CYGWIN__)
42607  SimulateIOError( return SQLITE_ERROR );
42608  UNUSED_PARAMETER(nFull);
42609  assert( nFull>=pVfs->mxPathname );
42610  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42611  /*
42612  ** NOTE: We are dealing with a relative path name and the data
42613  ** directory has been set. Therefore, use it as the basis
42614  ** for converting the relative path name to an absolute
42615  ** one by prepending the data directory and a slash.
42616  */
42617  char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42618  if( !zOut ){
42619  return SQLITE_IOERR_NOMEM_BKPT;
42620  }
42621  if( cygwin_conv_path(
42622  (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
42623  CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
42624  sqlite3_free(zOut);
42625  return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42626  "winFullPathname1", zRelative);
42627  }else{
42628  char *zUtf8 = winConvertToUtf8Filename(zOut);
42629  if( !zUtf8 ){
42630  sqlite3_free(zOut);
42631  return SQLITE_IOERR_NOMEM_BKPT;
42632  }
42633  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42634  sqlite3_data_directory, winGetDirSep(), zUtf8);
42635  sqlite3_free(zUtf8);
42636  sqlite3_free(zOut);
42637  }
42638  }else{
42639  char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42640  if( !zOut ){
42641  return SQLITE_IOERR_NOMEM_BKPT;
42642  }
42643  if( cygwin_conv_path(
42644  (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
42645  zRelative, zOut, pVfs->mxPathname+1)<0 ){
42646  sqlite3_free(zOut);
42647  return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42648  "winFullPathname2", zRelative);
42649  }else{
42650  char *zUtf8 = winConvertToUtf8Filename(zOut);
42651  if( !zUtf8 ){
42652  sqlite3_free(zOut);
42653  return SQLITE_IOERR_NOMEM_BKPT;
42654  }
42655  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
42656  sqlite3_free(zUtf8);
42657  sqlite3_free(zOut);
42658  }
42659  }
42660  return SQLITE_OK;
42661 #endif
42662 
42663 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
42664  SimulateIOError( return SQLITE_ERROR );
42665  /* WinCE has no concept of a relative pathname, or so I am told. */
42666  /* WinRT has no way to convert a relative path to an absolute one. */
42667  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42668  /*
42669  ** NOTE: We are dealing with a relative path name and the data
42670  ** directory has been set. Therefore, use it as the basis
42671  ** for converting the relative path name to an absolute
42672  ** one by prepending the data directory and a backslash.
42673  */
42674  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42675  sqlite3_data_directory, winGetDirSep(), zRelative);
42676  }else{
42677  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
42678  }
42679  return SQLITE_OK;
42680 #endif
42681 
42682 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42683  /* It's odd to simulate an io-error here, but really this is just
42684  ** using the io-error infrastructure to test that SQLite handles this
42685  ** function failing. This function could fail if, for example, the
42686  ** current working directory has been unlinked.
42687  */
42688  SimulateIOError( return SQLITE_ERROR );
42689  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42690  /*
42691  ** NOTE: We are dealing with a relative path name and the data
42692  ** directory has been set. Therefore, use it as the basis
42693  ** for converting the relative path name to an absolute
42694  ** one by prepending the data directory and a backslash.
42695  */
42696  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42697  sqlite3_data_directory, winGetDirSep(), zRelative);
42698  return SQLITE_OK;
42699  }
42700  zConverted = winConvertFromUtf8Filename(zRelative);
42701  if( zConverted==0 ){
42702  return SQLITE_IOERR_NOMEM_BKPT;
42703  }
42704  if( osIsNT() ){
42705  LPWSTR zTemp;
42706  nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
42707  if( nByte==0 ){
42708  sqlite3_free(zConverted);
42709  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42710  "winFullPathname1", zRelative);
42711  }
42712  nByte += 3;
42713  zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42714  if( zTemp==0 ){
42715  sqlite3_free(zConverted);
42716  return SQLITE_IOERR_NOMEM_BKPT;
42717  }
42718  nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
42719  if( nByte==0 ){
42720  sqlite3_free(zConverted);
42721  sqlite3_free(zTemp);
42722  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42723  "winFullPathname2", zRelative);
42724  }
42725  sqlite3_free(zConverted);
42726  zOut = winUnicodeToUtf8(zTemp);
42727  sqlite3_free(zTemp);
42728  }
42729 #ifdef SQLITE_WIN32_HAS_ANSI
42730  else{
42731  char *zTemp;
42732  nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
42733  if( nByte==0 ){
42734  sqlite3_free(zConverted);
42735  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42736  "winFullPathname3", zRelative);
42737  }
42738  nByte += 3;
42739  zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42740  if( zTemp==0 ){
42741  sqlite3_free(zConverted);
42742  return SQLITE_IOERR_NOMEM_BKPT;
42743  }
42744  nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
42745  if( nByte==0 ){
42746  sqlite3_free(zConverted);
42747  sqlite3_free(zTemp);
42748  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42749  "winFullPathname4", zRelative);
42750  }
42751  sqlite3_free(zConverted);
42752  zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
42753  sqlite3_free(zTemp);
42754  }
42755 #endif
42756  if( zOut ){
42757  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
42758  sqlite3_free(zOut);
42759  return SQLITE_OK;
42760  }else{
42761  return SQLITE_IOERR_NOMEM_BKPT;
42762  }
42763 #endif
42764 }
42765 
42766 #ifndef SQLITE_OMIT_LOAD_EXTENSION
42767 /*
42768 ** Interfaces for opening a shared library, finding entry points
42769 ** within the shared library, and closing the shared library.
42770 */
42771 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
42772  HANDLE h;
42773 #if defined(__CYGWIN__)
42774  int nFull = pVfs->mxPathname+1;
42775  char *zFull = sqlite3MallocZero( nFull );
42776  void *zConverted = 0;
42777  if( zFull==0 ){
42778  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42779  return 0;
42780  }
42781  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
42782  sqlite3_free(zFull);
42783  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42784  return 0;
42785  }
42786  zConverted = winConvertFromUtf8Filename(zFull);
42787  sqlite3_free(zFull);
42788 #else
42789  void *zConverted = winConvertFromUtf8Filename(zFilename);
42790  UNUSED_PARAMETER(pVfs);
42791 #endif
42792  if( zConverted==0 ){
42793  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42794  return 0;
42795  }
42796  if( osIsNT() ){
42797 #if SQLITE_OS_WINRT
42798  h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
42799 #else
42800  h = osLoadLibraryW((LPCWSTR)zConverted);
42801 #endif
42802  }
42803 #ifdef SQLITE_WIN32_HAS_ANSI
42804  else{
42805  h = osLoadLibraryA((char*)zConverted);
42806  }
42807 #endif
42808  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
42809  sqlite3_free(zConverted);
42810  return (void*)h;
42811 }
42812 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
42813  UNUSED_PARAMETER(pVfs);
42814  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
42815 }
42816 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
42817  FARPROC proc;
42818  UNUSED_PARAMETER(pVfs);
42819  proc = osGetProcAddressA((HANDLE)pH, zSym);
42820  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
42821  (void*)pH, zSym, (void*)proc));
42822  return (void(*)(void))proc;
42823 }
42824 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
42825  UNUSED_PARAMETER(pVfs);
42826  osFreeLibrary((HANDLE)pHandle);
42827  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
42828 }
42829 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
42830  #define winDlOpen 0
42831  #define winDlError 0
42832  #define winDlSym 0
42833  #define winDlClose 0
42834 #endif
42835 
42836 /* State information for the randomness gatherer. */
42837 typedef struct EntropyGatherer EntropyGatherer;
42838 struct EntropyGatherer {
42839  unsigned char *a; /* Gather entropy into this buffer */
42840  int na; /* Size of a[] in bytes */
42841  int i; /* XOR next input into a[i] */
42842  int nXor; /* Number of XOR operations done */
42843 };
42844 
42845 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
42846 /* Mix sz bytes of entropy into p. */
42847 static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
42848  int j, k;
42849  for(j=0, k=p->i; j<sz; j++){
42850  p->a[k++] ^= x[j];
42851  if( k>=p->na ) k = 0;
42852  }
42853  p->i = k;
42854  p->nXor += sz;
42855 }
42856 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
42857 
42858 /*
42859 ** Write up to nBuf bytes of randomness into zBuf.
42860 */
42861 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42862 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
42863  UNUSED_PARAMETER(pVfs);
42864  memset(zBuf, 0, nBuf);
42865  return nBuf;
42866 #else
42867  EntropyGatherer e;
42868  UNUSED_PARAMETER(pVfs);
42869  memset(zBuf, 0, nBuf);
42870 #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
42871  rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
42872 #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
42873  e.a = (unsigned char*)zBuf;
42874  e.na = nBuf;
42875  e.nXor = 0;
42876  e.i = 0;
42877  {
42878  SYSTEMTIME x;
42879  osGetSystemTime(&x);
42880  xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
42881  }
42882  {
42883  DWORD pid = osGetCurrentProcessId();
42884  xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
42885  }
42886 #if SQLITE_OS_WINRT
42887  {
42888  ULONGLONG cnt = osGetTickCount64();
42889  xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
42890  }
42891 #else
42892  {
42893  DWORD cnt = osGetTickCount();
42894  xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
42895  }
42896 #endif /* SQLITE_OS_WINRT */
42897  {
42898  LARGE_INTEGER i;
42899  osQueryPerformanceCounter(&i);
42900  xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
42901  }
42902 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
42903  {
42904  UUID id;
42905  memset(&id, 0, sizeof(UUID));
42906  osUuidCreate(&id);
42907  xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42908  memset(&id, 0, sizeof(UUID));
42909  osUuidCreateSequential(&id);
42910  xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42911  }
42912 #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
42913  return e.nXor>nBuf ? nBuf : e.nXor;
42914 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
42915 }
42916 
42917 
42918 /*
42919 ** Sleep for a little while. Return the amount of time slept.
42920 */
42921 static int winSleep(sqlite3_vfs *pVfs, int microsec){
42922  sqlite3_win32_sleep((microsec+999)/1000);
42923  UNUSED_PARAMETER(pVfs);
42924  return ((microsec+999)/1000)*1000;
42925 }
42926 
42927 /*
42928 ** The following variable, if set to a non-zero value, is interpreted as
42929 ** the number of seconds since 1970 and is used to set the result of
42930 ** sqlite3OsCurrentTime() during testing.
42931 */
42932 #ifdef SQLITE_TEST
42933 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
42934 #endif
42935 
42936 /*
42937 ** Find the current time (in Universal Coordinated Time). Write into *piNow
42938 ** the current time and date as a Julian Day number times 86_400_000. In
42939 ** other words, write into *piNow the number of milliseconds since the Julian
42940 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
42941 ** proleptic Gregorian calendar.
42942 **
42943 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
42944 ** cannot be found.
42945 */
42946 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
42947  /* FILETIME structure is a 64-bit value representing the number of
42948  100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
42949  */
42950  FILETIME ft;
42951  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
42952 #ifdef SQLITE_TEST
42953  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
42954 #endif
42955  /* 2^32 - to avoid use of LL and warnings in gcc */
42956  static const sqlite3_int64 max32BitValue =
42957  (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
42958  (sqlite3_int64)294967296;
42959 
42960 #if SQLITE_OS_WINCE
42961  SYSTEMTIME time;
42962  osGetSystemTime(&time);
42963  /* if SystemTimeToFileTime() fails, it returns zero. */
42964  if (!osSystemTimeToFileTime(&time,&ft)){
42965  return SQLITE_ERROR;
42966  }
42967 #else
42968  osGetSystemTimeAsFileTime( &ft );
42969 #endif
42970 
42971  *piNow = winFiletimeEpoch +
42972  ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
42973  (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
42974 
42975 #ifdef SQLITE_TEST
42976  if( sqlite3_current_time ){
42977  *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
42978  }
42979 #endif
42980  UNUSED_PARAMETER(pVfs);
42981  return SQLITE_OK;
42982 }
42983 
42984 /*
42985 ** Find the current time (in Universal Coordinated Time). Write the
42986 ** current time and date as a Julian Day number into *prNow and
42987 ** return 0. Return 1 if the time and date cannot be found.
42988 */
42989 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
42990  int rc;
42991  sqlite3_int64 i;
42992  rc = winCurrentTimeInt64(pVfs, &i);
42993  if( !rc ){
42994  *prNow = i/86400000.0;
42995  }
42996  return rc;
42997 }
42998 
42999 /*
43000 ** The idea is that this function works like a combination of
43001 ** GetLastError() and FormatMessage() on Windows (or errno and
43002 ** strerror_r() on Unix). After an error is returned by an OS
43003 ** function, SQLite calls this function with zBuf pointing to
43004 ** a buffer of nBuf bytes. The OS layer should populate the
43005 ** buffer with a nul-terminated UTF-8 encoded error message
43006 ** describing the last IO error to have occurred within the calling
43007 ** thread.
43008 **
43009 ** If the error message is too large for the supplied buffer,
43010 ** it should be truncated. The return value of xGetLastError
43011 ** is zero if the error message fits in the buffer, or non-zero
43012 ** otherwise (if the message was truncated). If non-zero is returned,
43013 ** then it is not necessary to include the nul-terminator character
43014 ** in the output buffer.
43015 **
43016 ** Not supplying an error message will have no adverse effect
43017 ** on SQLite. It is fine to have an implementation that never
43018 ** returns an error message:
43019 **
43020 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
43021 ** assert(zBuf[0]=='\0');
43022 ** return 0;
43023 ** }
43024 **
43025 ** However if an error message is supplied, it will be incorporated
43026 ** by sqlite into the error message available to the user using
43027 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
43028 */
43029 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
43030  DWORD e = osGetLastError();
43031  UNUSED_PARAMETER(pVfs);
43032  if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
43033  return e;
43034 }
43035 
43036 /*
43037 ** Initialize and deinitialize the operating system interface.
43038 */
43039 SQLITE_API int sqlite3_os_init(void){
43040  static sqlite3_vfs winVfs = {
43041  3, /* iVersion */
43042  sizeof(winFile), /* szOsFile */
43043  SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
43044  0, /* pNext */
43045  "win32", /* zName */
43046  &winAppData, /* pAppData */
43047  winOpen, /* xOpen */
43048  winDelete, /* xDelete */
43049  winAccess, /* xAccess */
43050  winFullPathname, /* xFullPathname */
43051  winDlOpen, /* xDlOpen */
43052  winDlError, /* xDlError */
43053  winDlSym, /* xDlSym */
43054  winDlClose, /* xDlClose */
43055  winRandomness, /* xRandomness */
43056  winSleep, /* xSleep */
43057  winCurrentTime, /* xCurrentTime */
43058  winGetLastError, /* xGetLastError */
43059  winCurrentTimeInt64, /* xCurrentTimeInt64 */
43060  winSetSystemCall, /* xSetSystemCall */
43061  winGetSystemCall, /* xGetSystemCall */
43062  winNextSystemCall, /* xNextSystemCall */
43063  };
43064 #if defined(SQLITE_WIN32_HAS_WIDE)
43065  static sqlite3_vfs winLongPathVfs = {
43066  3, /* iVersion */
43067  sizeof(winFile), /* szOsFile */
43068  SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
43069  0, /* pNext */
43070  "win32-longpath", /* zName */
43071  &winAppData, /* pAppData */
43072  winOpen, /* xOpen */
43073  winDelete, /* xDelete */
43074  winAccess, /* xAccess */
43075  winFullPathname, /* xFullPathname */
43076  winDlOpen, /* xDlOpen */
43077  winDlError, /* xDlError */
43078  winDlSym, /* xDlSym */
43079  winDlClose, /* xDlClose */
43080  winRandomness, /* xRandomness */
43081  winSleep, /* xSleep */
43082  winCurrentTime, /* xCurrentTime */
43083  winGetLastError, /* xGetLastError */
43084  winCurrentTimeInt64, /* xCurrentTimeInt64 */
43085  winSetSystemCall, /* xSetSystemCall */
43086  winGetSystemCall, /* xGetSystemCall */
43087  winNextSystemCall, /* xNextSystemCall */
43088  };
43089 #endif
43090  static sqlite3_vfs winNolockVfs = {
43091  3, /* iVersion */
43092  sizeof(winFile), /* szOsFile */
43093  SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
43094  0, /* pNext */
43095  "win32-none", /* zName */
43096  &winNolockAppData, /* pAppData */
43097  winOpen, /* xOpen */
43098  winDelete, /* xDelete */
43099  winAccess, /* xAccess */
43100  winFullPathname, /* xFullPathname */
43101  winDlOpen, /* xDlOpen */
43102  winDlError, /* xDlError */
43103  winDlSym, /* xDlSym */
43104  winDlClose, /* xDlClose */
43105  winRandomness, /* xRandomness */
43106  winSleep, /* xSleep */
43107  winCurrentTime, /* xCurrentTime */
43108  winGetLastError, /* xGetLastError */
43109  winCurrentTimeInt64, /* xCurrentTimeInt64 */
43110  winSetSystemCall, /* xSetSystemCall */
43111  winGetSystemCall, /* xGetSystemCall */
43112  winNextSystemCall, /* xNextSystemCall */
43113  };
43114 #if defined(SQLITE_WIN32_HAS_WIDE)
43115  static sqlite3_vfs winLongPathNolockVfs = {
43116  3, /* iVersion */
43117  sizeof(winFile), /* szOsFile */
43118  SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
43119  0, /* pNext */
43120  "win32-longpath-none", /* zName */
43121  &winNolockAppData, /* pAppData */
43122  winOpen, /* xOpen */
43123  winDelete, /* xDelete */
43124  winAccess, /* xAccess */
43125  winFullPathname, /* xFullPathname */
43126  winDlOpen, /* xDlOpen */
43127  winDlError, /* xDlError */
43128  winDlSym, /* xDlSym */
43129  winDlClose, /* xDlClose */
43130  winRandomness, /* xRandomness */
43131  winSleep, /* xSleep */
43132  winCurrentTime, /* xCurrentTime */
43133  winGetLastError, /* xGetLastError */
43134  winCurrentTimeInt64, /* xCurrentTimeInt64 */
43135  winSetSystemCall, /* xSetSystemCall */
43136  winGetSystemCall, /* xGetSystemCall */
43137  winNextSystemCall, /* xNextSystemCall */
43138  };
43139 #endif
43140 
43141  /* Double-check that the aSyscall[] array has been constructed
43142  ** correctly. See ticket [bb3a86e890c8e96ab] */
43143  assert( ArraySize(aSyscall)==80 );
43144 
43145  /* get memory map allocation granularity */
43146  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
43147 #if SQLITE_OS_WINRT
43148  osGetNativeSystemInfo(&winSysInfo);
43149 #else
43150  osGetSystemInfo(&winSysInfo);
43151 #endif
43152  assert( winSysInfo.dwAllocationGranularity>0 );
43153  assert( winSysInfo.dwPageSize>0 );
43154 
43155  sqlite3_vfs_register(&winVfs, 1);
43156 
43157 #if defined(SQLITE_WIN32_HAS_WIDE)
43158  sqlite3_vfs_register(&winLongPathVfs, 0);
43159 #endif
43160 
43161  sqlite3_vfs_register(&winNolockVfs, 0);
43162 
43163 #if defined(SQLITE_WIN32_HAS_WIDE)
43164  sqlite3_vfs_register(&winLongPathNolockVfs, 0);
43165 #endif
43166 
43167  return SQLITE_OK;
43168 }
43169 
43170 SQLITE_API int sqlite3_os_end(void){
43171 #if SQLITE_OS_WINRT
43172  if( sleepObj!=NULL ){
43173  osCloseHandle(sleepObj);
43174  sleepObj = NULL;
43175  }
43176 #endif
43177  return SQLITE_OK;
43178 }
43179 
43180 #endif /* SQLITE_OS_WIN */
43181 
43182 /************** End of os_win.c **********************************************/
43183 /************** Begin file bitvec.c ******************************************/
43184 /*
43185 ** 2008 February 16
43186 **
43187 ** The author disclaims copyright to this source code. In place of
43188 ** a legal notice, here is a blessing:
43189 **
43190 ** May you do good and not evil.
43191 ** May you find forgiveness for yourself and forgive others.
43192 ** May you share freely, never taking more than you give.
43193 **
43194 *************************************************************************
43195 ** This file implements an object that represents a fixed-length
43196 ** bitmap. Bits are numbered starting with 1.
43197 **
43198 ** A bitmap is used to record which pages of a database file have been
43199 ** journalled during a transaction, or which pages have the "dont-write"
43200 ** property. Usually only a few pages are meet either condition.
43201 ** So the bitmap is usually sparse and has low cardinality.
43202 ** But sometimes (for example when during a DROP of a large table) most
43203 ** or all of the pages in a database can get journalled. In those cases,
43204 ** the bitmap becomes dense with high cardinality. The algorithm needs
43205 ** to handle both cases well.
43206 **
43207 ** The size of the bitmap is fixed when the object is created.
43208 **
43209 ** All bits are clear when the bitmap is created. Individual bits
43210 ** may be set or cleared one at a time.
43211 **
43212 ** Test operations are about 100 times more common that set operations.
43213 ** Clear operations are exceedingly rare. There are usually between
43214 ** 5 and 500 set operations per Bitvec object, though the number of sets can
43215 ** sometimes grow into tens of thousands or larger. The size of the
43216 ** Bitvec object is the number of pages in the database file at the
43217 ** start of a transaction, and is thus usually less than a few thousand,
43218 ** but can be as large as 2 billion for a really big database.
43219 */
43220 /* #include "sqliteInt.h" */
43221 
43222 /* Size of the Bitvec structure in bytes. */
43223 #define BITVEC_SZ 512
43224 
43225 /* Round the union size down to the nearest pointer boundary, since that's how
43226 ** it will be aligned within the Bitvec struct. */
43227 #define BITVEC_USIZE \
43228  (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
43229 
43230 /* Type of the array "element" for the bitmap representation.
43231 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
43232 ** Setting this to the "natural word" size of your CPU may improve
43233 ** performance. */
43234 #define BITVEC_TELEM u8
43235 /* Size, in bits, of the bitmap element. */
43236 #define BITVEC_SZELEM 8
43237 /* Number of elements in a bitmap array. */
43238 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
43239 /* Number of bits in the bitmap array. */
43240 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
43241 
43242 /* Number of u32 values in hash table. */
43243 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
43244 /* Maximum number of entries in hash table before
43245 ** sub-dividing and re-hashing. */
43246 #define BITVEC_MXHASH (BITVEC_NINT/2)
43247 /* Hashing function for the aHash representation.
43248 ** Empirical testing showed that the *37 multiplier
43249 ** (an arbitrary prime)in the hash function provided
43250 ** no fewer collisions than the no-op *1. */
43251 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
43252 
43253 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
43254 
43255 
43256 /*
43257 ** A bitmap is an instance of the following structure.
43258 **
43259 ** This bitmap records the existence of zero or more bits
43260 ** with values between 1 and iSize, inclusive.
43261 **
43262 ** There are three possible representations of the bitmap.
43263 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
43264 ** bitmap. The least significant bit is bit 1.
43265 **
43266 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
43267 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
43268 **
43269 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
43270 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
43271 ** handles up to iDivisor separate values of i. apSub[0] holds
43272 ** values between 1 and iDivisor. apSub[1] holds values between
43273 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
43274 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
43275 ** to hold deal with values between 1 and iDivisor.
43276 */
43277 struct Bitvec {
43278  u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
43279  u32 nSet; /* Number of bits that are set - only valid for aHash
43280  ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
43281  ** this would be 125. */
43282  u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
43283  /* Should >=0 for apSub element. */
43284  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
43285  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
43286  union {
43287  BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
43288  u32 aHash[BITVEC_NINT]; /* Hash table representation */
43289  Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
43290  } u;
43291 };
43292 
43293 /*
43294 ** Create a new bitmap object able to handle bits between 0 and iSize,
43295 ** inclusive. Return a pointer to the new object. Return NULL if
43296 ** malloc fails.
43297 */
43298 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
43299  Bitvec *p;
43300  assert( sizeof(*p)==BITVEC_SZ );
43301  p = sqlite3MallocZero( sizeof(*p) );
43302  if( p ){
43303  p->iSize = iSize;
43304  }
43305  return p;
43306 }
43307 
43308 /*
43309 ** Check to see if the i-th bit is set. Return true or false.
43310 ** If p is NULL (if the bitmap has not been created) or if
43311 ** i is out of range, then return false.
43312 */
43313 SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
43314  assert( p!=0 );
43315  i--;
43316  if( i>=p->iSize ) return 0;
43317  while( p->iDivisor ){
43318  u32 bin = i/p->iDivisor;
43319  i = i%p->iDivisor;
43320  p = p->u.apSub[bin];
43321  if (!p) {
43322  return 0;
43323  }
43324  }
43325  if( p->iSize<=BITVEC_NBIT ){
43326  return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
43327  } else{
43328  u32 h = BITVEC_HASH(i++);
43329  while( p->u.aHash[h] ){
43330  if( p->u.aHash[h]==i ) return 1;
43331  h = (h+1) % BITVEC_NINT;
43332  }
43333  return 0;
43334  }
43335 }
43336 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
43337  return p!=0 && sqlite3BitvecTestNotNull(p,i);
43338 }
43339 
43340 /*
43341 ** Set the i-th bit. Return 0 on success and an error code if
43342 ** anything goes wrong.
43343 **
43344 ** This routine might cause sub-bitmaps to be allocated. Failing
43345 ** to get the memory needed to hold the sub-bitmap is the only
43346 ** that can go wrong with an insert, assuming p and i are valid.
43347 **
43348 ** The calling function must ensure that p is a valid Bitvec object
43349 ** and that the value for "i" is within range of the Bitvec object.
43350 ** Otherwise the behavior is undefined.
43351 */
43352 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
43353  u32 h;
43354  if( p==0 ) return SQLITE_OK;
43355  assert( i>0 );
43356  assert( i<=p->iSize );
43357  i--;
43358  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
43359  u32 bin = i/p->iDivisor;
43360  i = i%p->iDivisor;
43361  if( p->u.apSub[bin]==0 ){
43362  p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
43363  if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
43364  }
43365  p = p->u.apSub[bin];
43366  }
43367  if( p->iSize<=BITVEC_NBIT ){
43368  p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
43369  return SQLITE_OK;
43370  }
43371  h = BITVEC_HASH(i++);
43372  /* if there wasn't a hash collision, and this doesn't */
43373  /* completely fill the hash, then just add it without */
43374  /* worring about sub-dividing and re-hashing. */
43375  if( !p->u.aHash[h] ){
43376  if (p->nSet<(BITVEC_NINT-1)) {
43377  goto bitvec_set_end;
43378  } else {
43379  goto bitvec_set_rehash;
43380  }
43381  }
43382  /* there was a collision, check to see if it's already */
43383  /* in hash, if not, try to find a spot for it */
43384  do {
43385  if( p->u.aHash[h]==i ) return SQLITE_OK;
43386  h++;
43387  if( h>=BITVEC_NINT ) h = 0;
43388  } while( p->u.aHash[h] );
43389  /* we didn't find it in the hash. h points to the first */
43390  /* available free spot. check to see if this is going to */
43391  /* make our hash too "full". */
43392 bitvec_set_rehash:
43393  if( p->nSet>=BITVEC_MXHASH ){
43394  unsigned int j;
43395  int rc;
43396  u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
43397  if( aiValues==0 ){
43398  return SQLITE_NOMEM_BKPT;
43399  }else{
43400  memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43401  memset(p->u.apSub, 0, sizeof(p->u.apSub));
43402  p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
43403  rc = sqlite3BitvecSet(p, i);
43404  for(j=0; j<BITVEC_NINT; j++){
43405  if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
43406  }
43407  sqlite3StackFree(0, aiValues);
43408  return rc;
43409  }
43410  }
43411 bitvec_set_end:
43412  p->nSet++;
43413  p->u.aHash[h] = i;
43414  return SQLITE_OK;
43415 }
43416 
43417 /*
43418 ** Clear the i-th bit.
43419 **
43420 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
43421 ** that BitvecClear can use to rebuilt its hash table.
43422 */
43423 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
43424  if( p==0 ) return;
43425  assert( i>0 );
43426  i--;
43427  while( p->iDivisor ){
43428  u32 bin = i/p->iDivisor;
43429  i = i%p->iDivisor;
43430  p = p->u.apSub[bin];
43431  if (!p) {
43432  return;
43433  }
43434  }
43435  if( p->iSize<=BITVEC_NBIT ){
43436  p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
43437  }else{
43438  unsigned int j;
43439  u32 *aiValues = pBuf;
43440  memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43441  memset(p->u.aHash, 0, sizeof(p->u.aHash));
43442  p->nSet = 0;
43443  for(j=0; j<BITVEC_NINT; j++){
43444  if( aiValues[j] && aiValues[j]!=(i+1) ){
43445  u32 h = BITVEC_HASH(aiValues[j]-1);
43446  p->nSet++;
43447  while( p->u.aHash[h] ){
43448  h++;
43449  if( h>=BITVEC_NINT ) h = 0;
43450  }
43451  p->u.aHash[h] = aiValues[j];
43452  }
43453  }
43454  }
43455 }
43456 
43457 /*
43458 ** Destroy a bitmap object. Reclaim all memory used.
43459 */
43460 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
43461  if( p==0 ) return;
43462  if( p->iDivisor ){
43463  unsigned int i;
43464  for(i=0; i<BITVEC_NPTR; i++){
43465  sqlite3BitvecDestroy(p->u.apSub[i]);
43466  }
43467  }
43468  sqlite3_free(p);
43469 }
43470 
43471 /*
43472 ** Return the value of the iSize parameter specified when Bitvec *p
43473 ** was created.
43474 */
43475 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
43476  return p->iSize;
43477 }
43478 
43479 #ifndef SQLITE_OMIT_BUILTIN_TEST
43480 /*
43481 ** Let V[] be an array of unsigned characters sufficient to hold
43482 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
43483 ** Then the following macros can be used to set, clear, or test
43484 ** individual bits within V.
43485 */
43486 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
43487 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
43488 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
43489 
43490 /*
43491 ** This routine runs an extensive test of the Bitvec code.
43492 **
43493 ** The input is an array of integers that acts as a program
43494 ** to test the Bitvec. The integers are opcodes followed
43495 ** by 0, 1, or 3 operands, depending on the opcode. Another
43496 ** opcode follows immediately after the last operand.
43497 **
43498 ** There are 6 opcodes numbered from 0 through 5. 0 is the
43499 ** "halt" opcode and causes the test to end.
43500 **
43501 ** 0 Halt and return the number of errors
43502 ** 1 N S X Set N bits beginning with S and incrementing by X
43503 ** 2 N S X Clear N bits beginning with S and incrementing by X
43504 ** 3 N Set N randomly chosen bits
43505 ** 4 N Clear N randomly chosen bits
43506 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
43507 **
43508 ** The opcodes 1 through 4 perform set and clear operations are performed
43509 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
43510 ** Opcode 5 works on the linear array only, not on the Bitvec.
43511 ** Opcode 5 is used to deliberately induce a fault in order to
43512 ** confirm that error detection works.
43513 **
43514 ** At the conclusion of the test the linear array is compared
43515 ** against the Bitvec object. If there are any differences,
43516 ** an error is returned. If they are the same, zero is returned.
43517 **
43518 ** If a memory allocation error occurs, return -1.
43519 */
43520 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
43521  Bitvec *pBitvec = 0;
43522  unsigned char *pV = 0;
43523  int rc = -1;
43524  int i, nx, pc, op;
43525  void *pTmpSpace;
43526 
43527  /* Allocate the Bitvec to be tested and a linear array of
43528  ** bits to act as the reference */
43529  pBitvec = sqlite3BitvecCreate( sz );
43530  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
43531  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
43532  if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
43533 
43534  /* NULL pBitvec tests */
43535  sqlite3BitvecSet(0, 1);
43536  sqlite3BitvecClear(0, 1, pTmpSpace);
43537 
43538  /* Run the program */
43539  pc = 0;
43540  while( (op = aOp[pc])!=0 ){
43541  switch( op ){
43542  case 1:
43543  case 2:
43544  case 5: {
43545  nx = 4;
43546  i = aOp[pc+2] - 1;
43547  aOp[pc+2] += aOp[pc+3];
43548  break;
43549  }
43550  case 3:
43551  case 4:
43552  default: {
43553  nx = 2;
43554  sqlite3_randomness(sizeof(i), &i);
43555  break;
43556  }
43557  }
43558  if( (--aOp[pc+1]) > 0 ) nx = 0;
43559  pc += nx;
43560  i = (i & 0x7fffffff)%sz;
43561  if( (op & 1)!=0 ){
43562  SETBIT(pV, (i+1));
43563  if( op!=5 ){
43564  if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
43565  }
43566  }else{
43567  CLEARBIT(pV, (i+1));
43568  sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
43569  }
43570  }
43571 
43572  /* Test to make sure the linear array exactly matches the
43573  ** Bitvec object. Start with the assumption that they do
43574  ** match (rc==0). Change rc to non-zero if a discrepancy
43575  ** is found.
43576  */
43577  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
43578  + sqlite3BitvecTest(pBitvec, 0)
43579  + (sqlite3BitvecSize(pBitvec) - sz);
43580  for(i=1; i<=sz; i++){
43581  if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
43582  rc = i;
43583  break;
43584  }
43585  }
43586 
43587  /* Free allocated structure */
43588 bitvec_end:
43589  sqlite3_free(pTmpSpace);
43590  sqlite3_free(pV);
43591  sqlite3BitvecDestroy(pBitvec);
43592  return rc;
43593 }
43594 #endif /* SQLITE_OMIT_BUILTIN_TEST */
43595 
43596 /************** End of bitvec.c **********************************************/
43597 /************** Begin file pcache.c ******************************************/
43598 /*
43599 ** 2008 August 05
43600 **
43601 ** The author disclaims copyright to this source code. In place of
43602 ** a legal notice, here is a blessing:
43603 **
43604 ** May you do good and not evil.
43605 ** May you find forgiveness for yourself and forgive others.
43606 ** May you share freely, never taking more than you give.
43607 **
43608 *************************************************************************
43609 ** This file implements that page cache.
43610 */
43611 /* #include "sqliteInt.h" */
43612 
43613 /*
43614 ** A complete page cache is an instance of this structure. Every
43615 ** entry in the cache holds a single page of the database file. The
43616 ** btree layer only operates on the cached copy of the database pages.
43617 **
43618 ** A page cache entry is "clean" if it exactly matches what is currently
43619 ** on disk. A page is "dirty" if it has been modified and needs to be
43620 ** persisted to disk.
43621 **
43622 ** pDirty, pDirtyTail, pSynced:
43623 ** All dirty pages are linked into the doubly linked list using
43624 ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
43625 ** such that p was added to the list more recently than p->pDirtyNext.
43626 ** PCache.pDirty points to the first (newest) element in the list and
43627 ** pDirtyTail to the last (oldest).
43628 **
43629 ** The PCache.pSynced variable is used to optimize searching for a dirty
43630 ** page to eject from the cache mid-transaction. It is better to eject
43631 ** a page that does not require a journal sync than one that does.
43632 ** Therefore, pSynced is maintained to that it *almost* always points
43633 ** to either the oldest page in the pDirty/pDirtyTail list that has a
43634 ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
43635 ** (so that the right page to eject can be found by following pDirtyPrev
43636 ** pointers).
43637 */
43638 struct PCache {
43639  PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
43640  PgHdr *pSynced; /* Last synced page in dirty page list */
43641  int nRefSum; /* Sum of ref counts over all pages */
43642  int szCache; /* Configured cache size */
43643  int szSpill; /* Size before spilling occurs */
43644  int szPage; /* Size of every page in this cache */
43645  int szExtra; /* Size of extra space for each page */
43646  u8 bPurgeable; /* True if pages are on backing store */
43647  u8 eCreate; /* eCreate value for for xFetch() */
43648  int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
43649  void *pStress; /* Argument to xStress */
43650  sqlite3_pcache *pCache; /* Pluggable cache module */
43651 };
43652 
43653 /********************************** Test and Debug Logic **********************/
43654 /*
43655 ** Debug tracing macros. Enable by by changing the "0" to "1" and
43656 ** recompiling.
43657 **
43658 ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
43659 ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
43660 ** is displayed for many operations, resulting in a lot of output.
43661 */
43662 #if defined(SQLITE_DEBUG) && 0
43663  int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
43664  int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
43665 # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
43666  void pcacheDump(PCache *pCache){
43667  int N;
43668  int i, j;
43669  sqlite3_pcache_page *pLower;
43670  PgHdr *pPg;
43671  unsigned char *a;
43672 
43673  if( sqlite3PcacheTrace<2 ) return;
43674  if( pCache->pCache==0 ) return;
43675  N = sqlite3PcachePagecount(pCache);
43676  if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
43677  for(i=1; i<=N; i++){
43678  pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
43679  if( pLower==0 ) continue;
43680  pPg = (PgHdr*)pLower->pExtra;
43681  printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
43682  a = (unsigned char *)pLower->pBuf;
43683  for(j=0; j<12; j++) printf("%02x", a[j]);
43684  printf("\n");
43685  if( pPg->pPage==0 ){
43686  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
43687  }
43688  }
43689  }
43690  #else
43691 # define pcacheTrace(X)
43692 # define pcacheDump(X)
43693 #endif
43694 
43695 /*
43696 ** Check invariants on a PgHdr entry. Return true if everything is OK.
43697 ** Return false if any invariant is violated.
43698 **
43699 ** This routine is for use inside of assert() statements only. For
43700 ** example:
43701 **
43702 ** assert( sqlite3PcachePageSanity(pPg) );
43703 */
43704 #if SQLITE_DEBUG
43705 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
43706  PCache *pCache;
43707  assert( pPg!=0 );
43708  assert( pPg->pgno>0 ); /* Page number is 1 or more */
43709  pCache = pPg->pCache;
43710  assert( pCache!=0 ); /* Every page has an associated PCache */
43711  if( pPg->flags & PGHDR_CLEAN ){
43712  assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
43713  assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
43714  assert( pCache->pDirtyTail!=pPg );
43715  }
43716  /* WRITEABLE pages must also be DIRTY */
43717  if( pPg->flags & PGHDR_WRITEABLE ){
43718  assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
43719  }
43720  /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
43721  ** for example, when using the sqlite3PagerDontWrite() optimization:
43722  ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
43723  ** (2) Page X moved to freelist, WRITEABLE is cleared
43724  ** (3) Page X reused, WRITEABLE is set again
43725  ** If NEED_SYNC had been cleared in step 2, then it would not be reset
43726  ** in step 3, and page might be written into the database without first
43727  ** syncing the rollback journal, which might cause corruption on a power
43728  ** loss.
43729  **
43730  ** Another example is when the database page size is smaller than the
43731  ** disk sector size. When any page of a sector is journalled, all pages
43732  ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
43733  ** in case they are later modified, since all pages in the same sector
43734  ** must be journalled and synced before any of those pages can be safely
43735  ** written.
43736  */
43737  return 1;
43738 }
43739 #endif /* SQLITE_DEBUG */
43740 
43741 
43742 /********************************** Linked List Management ********************/
43743 
43744 /* Allowed values for second argument to pcacheManageDirtyList() */
43745 #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
43746 #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
43747 #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
43748 
43749 /*
43750 ** Manage pPage's participation on the dirty list. Bits of the addRemove
43751 ** argument determines what operation to do. The 0x01 bit means first
43752 ** remove pPage from the dirty list. The 0x02 means add pPage back to
43753 ** the dirty list. Doing both moves pPage to the front of the dirty list.
43754 */
43755 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
43756  PCache *p = pPage->pCache;
43757 
43758  pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
43759  addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
43760  pPage->pgno));
43761  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
43762  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
43763  assert( pPage->pDirtyPrev || pPage==p->pDirty );
43764 
43765  /* Update the PCache1.pSynced variable if necessary. */
43766  if( p->pSynced==pPage ){
43767  p->pSynced = pPage->pDirtyPrev;
43768  }
43769 
43770  if( pPage->pDirtyNext ){
43771  pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
43772  }else{
43773  assert( pPage==p->pDirtyTail );
43774  p->pDirtyTail = pPage->pDirtyPrev;
43775  }
43776  if( pPage->pDirtyPrev ){
43777  pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
43778  }else{
43779  /* If there are now no dirty pages in the cache, set eCreate to 2.
43780  ** This is an optimization that allows sqlite3PcacheFetch() to skip
43781  ** searching for a dirty page to eject from the cache when it might
43782  ** otherwise have to. */
43783  assert( pPage==p->pDirty );
43784  p->pDirty = pPage->pDirtyNext;
43785  assert( p->bPurgeable || p->eCreate==2 );
43786  if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
43787  assert( p->bPurgeable==0 || p->eCreate==1 );
43788  p->eCreate = 2;
43789  }
43790  }
43791  pPage->pDirtyNext = 0;
43792  pPage->pDirtyPrev = 0;
43793  }
43794  if( addRemove & PCACHE_DIRTYLIST_ADD ){
43795  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
43796 
43797  pPage->pDirtyNext = p->pDirty;
43798  if( pPage->pDirtyNext ){
43799  assert( pPage->pDirtyNext->pDirtyPrev==0 );
43800  pPage->pDirtyNext->pDirtyPrev = pPage;
43801  }else{
43802  p->pDirtyTail = pPage;
43803  if( p->bPurgeable ){
43804  assert( p->eCreate==2 );
43805  p->eCreate = 1;
43806  }
43807  }
43808  p->pDirty = pPage;
43809 
43810  /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
43811  ** pSynced to point to it. Checking the NEED_SYNC flag is an
43812  ** optimization, as if pSynced points to a page with the NEED_SYNC
43813  ** flag set sqlite3PcacheFetchStress() searches through all newer
43814  ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
43815  if( !p->pSynced
43816  && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
43817  ){
43818  p->pSynced = pPage;
43819  }
43820  }
43821  pcacheDump(p);
43822 }
43823 
43824 /*
43825 ** Wrapper around the pluggable caches xUnpin method. If the cache is
43826 ** being used for an in-memory database, this function is a no-op.
43827 */
43828 static void pcacheUnpin(PgHdr *p){
43829  if( p->pCache->bPurgeable ){
43830  pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
43831  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
43832  pcacheDump(p->pCache);
43833  }
43834 }
43835 
43836 /*
43837 ** Compute the number of pages of cache requested. p->szCache is the
43838 ** cache size requested by the "PRAGMA cache_size" statement.
43839 */
43840 static int numberOfCachePages(PCache *p){
43841  if( p->szCache>=0 ){
43842  /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
43843  ** suggested cache size is set to N. */
43844  return p->szCache;
43845  }else{
43846  /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
43847  ** the number of cache pages is adjusted to use approximately abs(N*1024)
43848  ** bytes of memory. */
43849  return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
43850  }
43851 }
43852 
43853 /*************************************************** General Interfaces ******
43854 **
43855 ** Initialize and shutdown the page cache subsystem. Neither of these
43856 ** functions are threadsafe.
43857 */
43858 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
43859  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
43860  /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
43861  ** built-in default page cache is used instead of the application defined
43862  ** page cache. */
43863  sqlite3PCacheSetDefault();
43864  }
43865  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
43866 }
43867 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
43868  if( sqlite3GlobalConfig.pcache2.xShutdown ){
43869  /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
43870  sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
43871  }
43872 }
43873 
43874 /*
43875 ** Return the size in bytes of a PCache object.
43876 */
43877 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
43878 
43879 /*
43880 ** Create a new PCache object. Storage space to hold the object
43881 ** has already been allocated and is passed in as the p pointer.
43882 ** The caller discovers how much space needs to be allocated by
43883 ** calling sqlite3PcacheSize().
43884 */
43885 SQLITE_PRIVATE int sqlite3PcacheOpen(
43886  int szPage, /* Size of every page */
43887  int szExtra, /* Extra space associated with each page */
43888  int bPurgeable, /* True if pages are on backing store */
43889  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
43890  void *pStress, /* Argument to xStress */
43891  PCache *p /* Preallocated space for the PCache */
43892 ){
43893  memset(p, 0, sizeof(PCache));
43894  p->szPage = 1;
43895  p->szExtra = szExtra;
43896  p->bPurgeable = bPurgeable;
43897  p->eCreate = 2;
43898  p->xStress = xStress;
43899  p->pStress = pStress;
43900  p->szCache = 100;
43901  p->szSpill = 1;
43902  pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
43903  return sqlite3PcacheSetPageSize(p, szPage);
43904 }
43905 
43906 /*
43907 ** Change the page size for PCache object. The caller must ensure that there
43908 ** are no outstanding page references when this function is called.
43909 */
43910 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
43911  assert( pCache->nRefSum==0 && pCache->pDirty==0 );
43912  if( pCache->szPage ){
43913  sqlite3_pcache *pNew;
43914  pNew = sqlite3GlobalConfig.pcache2.xCreate(
43915  szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
43916  pCache->bPurgeable
43917  );
43918  if( pNew==0 ) return SQLITE_NOMEM_BKPT;
43919  sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
43920  if( pCache->pCache ){
43921  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
43922  }
43923  pCache->pCache = pNew;
43924  pCache->szPage = szPage;
43925  pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
43926  }
43927  return SQLITE_OK;
43928 }
43929 
43930 /*
43931 ** Try to obtain a page from the cache.
43932 **
43933 ** This routine returns a pointer to an sqlite3_pcache_page object if
43934 ** such an object is already in cache, or if a new one is created.
43935 ** This routine returns a NULL pointer if the object was not in cache
43936 ** and could not be created.
43937 **
43938 ** The createFlags should be 0 to check for existing pages and should
43939 ** be 3 (not 1, but 3) to try to create a new page.
43940 **
43941 ** If the createFlag is 0, then NULL is always returned if the page
43942 ** is not already in the cache. If createFlag is 1, then a new page
43943 ** is created only if that can be done without spilling dirty pages
43944 ** and without exceeding the cache size limit.
43945 **
43946 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
43947 ** initialize the sqlite3_pcache_page object and convert it into a
43948 ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
43949 ** routines are split this way for performance reasons. When separated
43950 ** they can both (usually) operate without having to push values to
43951 ** the stack on entry and pop them back off on exit, which saves a
43952 ** lot of pushing and popping.
43953 */
43954 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
43955  PCache *pCache, /* Obtain the page from this cache */
43956  Pgno pgno, /* Page number to obtain */
43957  int createFlag /* If true, create page if it does not exist already */
43958 ){
43959  int eCreate;
43960  sqlite3_pcache_page *pRes;
43961 
43962  assert( pCache!=0 );
43963  assert( pCache->pCache!=0 );
43964  assert( createFlag==3 || createFlag==0 );
43965  assert( pgno>0 );
43966  assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
43967 
43968  /* eCreate defines what to do if the page does not exist.
43969  ** 0 Do not allocate a new page. (createFlag==0)
43970  ** 1 Allocate a new page if doing so is inexpensive.
43971  ** (createFlag==1 AND bPurgeable AND pDirty)
43972  ** 2 Allocate a new page even it doing so is difficult.
43973  ** (createFlag==1 AND !(bPurgeable AND pDirty)
43974  */
43975  eCreate = createFlag & pCache->eCreate;
43976  assert( eCreate==0 || eCreate==1 || eCreate==2 );
43977  assert( createFlag==0 || pCache->eCreate==eCreate );
43978  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
43979  pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
43980  pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
43981  createFlag?" create":"",pRes));
43982  return pRes;
43983 }
43984 
43985 /*
43986 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
43987 ** page because no clean pages are available for reuse and the cache
43988 ** size limit has been reached, then this routine can be invoked to
43989 ** try harder to allocate a page. This routine might invoke the stress
43990 ** callback to spill dirty pages to the journal. It will then try to
43991 ** allocate the new page and will only fail to allocate a new page on
43992 ** an OOM error.
43993 **
43994 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
43995 */
43996 SQLITE_PRIVATE int sqlite3PcacheFetchStress(
43997  PCache *pCache, /* Obtain the page from this cache */
43998  Pgno pgno, /* Page number to obtain */
43999  sqlite3_pcache_page **ppPage /* Write result here */
44000 ){
44001  PgHdr *pPg;
44002  if( pCache->eCreate==2 ) return 0;
44003 
44004  if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
44005  /* Find a dirty page to write-out and recycle. First try to find a
44006  ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
44007  ** cleared), but if that is not possible settle for any other
44008  ** unreferenced dirty page.
44009  **
44010  ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
44011  ** flag is currently referenced, then the following may leave pSynced
44012  ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
44013  ** cleared). This is Ok, as pSynced is just an optimization. */
44014  for(pPg=pCache->pSynced;
44015  pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
44016  pPg=pPg->pDirtyPrev
44017  );
44018  pCache->pSynced = pPg;
44019  if( !pPg ){
44020  for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
44021  }
44022  if( pPg ){
44023  int rc;
44024 #ifdef SQLITE_LOG_CACHE_SPILL
44025  sqlite3_log(SQLITE_FULL,
44026  "spill page %d making room for %d - cache used: %d/%d",
44027  pPg->pgno, pgno,
44028  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
44029  numberOfCachePages(pCache));
44030 #endif
44031  pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
44032  rc = pCache->xStress(pCache->pStress, pPg);
44033  pcacheDump(pCache);
44034  if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
44035  return rc;
44036  }
44037  }
44038  }
44039  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
44040  return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
44041 }
44042 
44043 /*
44044 ** This is a helper routine for sqlite3PcacheFetchFinish()
44045 **
44046 ** In the uncommon case where the page being fetched has not been
44047 ** initialized, this routine is invoked to do the initialization.
44048 ** This routine is broken out into a separate function since it
44049 ** requires extra stack manipulation that can be avoided in the common
44050 ** case.
44051 */
44052 static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
44053  PCache *pCache, /* Obtain the page from this cache */
44054  Pgno pgno, /* Page number obtained */
44055  sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
44056 ){
44057  PgHdr *pPgHdr;
44058  assert( pPage!=0 );
44059  pPgHdr = (PgHdr*)pPage->pExtra;
44060  assert( pPgHdr->pPage==0 );
44061  memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
44062  pPgHdr->pPage = pPage;
44063  pPgHdr->pData = pPage->pBuf;
44064  pPgHdr->pExtra = (void *)&pPgHdr[1];
44065  memset(pPgHdr->pExtra, 0, pCache->szExtra);
44066  pPgHdr->pCache = pCache;
44067  pPgHdr->pgno = pgno;
44068  pPgHdr->flags = PGHDR_CLEAN;
44069  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
44070 }
44071 
44072 /*
44073 ** This routine converts the sqlite3_pcache_page object returned by
44074 ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
44075 ** must be called after sqlite3PcacheFetch() in order to get a usable
44076 ** result.
44077 */
44078 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
44079  PCache *pCache, /* Obtain the page from this cache */
44080  Pgno pgno, /* Page number obtained */
44081  sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
44082 ){
44083  PgHdr *pPgHdr;
44084 
44085  assert( pPage!=0 );
44086  pPgHdr = (PgHdr *)pPage->pExtra;
44087 
44088  if( !pPgHdr->pPage ){
44089  return pcacheFetchFinishWithInit(pCache, pgno, pPage);
44090  }
44091  pCache->nRefSum++;
44092  pPgHdr->nRef++;
44093  assert( sqlite3PcachePageSanity(pPgHdr) );
44094  return pPgHdr;
44095 }
44096 
44097 /*
44098 ** Decrement the reference count on a page. If the page is clean and the
44099 ** reference count drops to 0, then it is made eligible for recycling.
44100 */
44101 SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
44102  assert( p->nRef>0 );
44103  p->pCache->nRefSum--;
44104  if( (--p->nRef)==0 ){
44105  if( p->flags&PGHDR_CLEAN ){
44106  pcacheUnpin(p);
44107  }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
44108  /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
44109  ** then page p is already at the head of the dirty list and the
44110  ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
44111  ** tag above. */
44112  pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
44113  }
44114  }
44115 }
44116 
44117 /*
44118 ** Increase the reference count of a supplied page by 1.
44119 */
44120 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
44121  assert(p->nRef>0);
44122  assert( sqlite3PcachePageSanity(p) );
44123  p->nRef++;
44124  p->pCache->nRefSum++;
44125 }
44126 
44127 /*
44128 ** Drop a page from the cache. There must be exactly one reference to the
44129 ** page. This function deletes that reference, so after it returns the
44130 ** page pointed to by p is invalid.
44131 */
44132 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
44133  assert( p->nRef==1 );
44134  assert( sqlite3PcachePageSanity(p) );
44135  if( p->flags&PGHDR_DIRTY ){
44136  pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
44137  }
44138  p->pCache->nRefSum--;
44139  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
44140 }
44141 
44142 /*
44143 ** Make sure the page is marked as dirty. If it isn't dirty already,
44144 ** make it so.
44145 */
44146 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
44147  assert( p->nRef>0 );
44148  assert( sqlite3PcachePageSanity(p) );
44149  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
44150  p->flags &= ~PGHDR_DONT_WRITE;
44151  if( p->flags & PGHDR_CLEAN ){
44152  p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
44153  pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
44154  assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
44155  pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
44156  }
44157  assert( sqlite3PcachePageSanity(p) );
44158  }
44159 }
44160 
44161 /*
44162 ** Make sure the page is marked as clean. If it isn't clean already,
44163 ** make it so.
44164 */
44165 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
44166  assert( sqlite3PcachePageSanity(p) );
44167  if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
44168  assert( (p->flags & PGHDR_CLEAN)==0 );
44169  pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
44170  p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
44171  p->flags |= PGHDR_CLEAN;
44172  pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
44173  assert( sqlite3PcachePageSanity(p) );
44174  if( p->nRef==0 ){
44175  pcacheUnpin(p);
44176  }
44177  }
44178 }
44179 
44180 /*
44181 ** Make every page in the cache clean.
44182 */
44183 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
44184  PgHdr *p;
44185  pcacheTrace(("%p.CLEAN-ALL\n",pCache));
44186  while( (p = pCache->pDirty)!=0 ){
44187  sqlite3PcacheMakeClean(p);
44188  }
44189 }
44190 
44191 /*
44192 ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
44193 */
44194 SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
44195  PgHdr *p;
44196  pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
44197  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44198  p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
44199  }
44200  pCache->pSynced = pCache->pDirtyTail;
44201 }
44202 
44203 /*
44204 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
44205 */
44206 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
44207  PgHdr *p;
44208  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44209  p->flags &= ~PGHDR_NEED_SYNC;
44210  }
44211  pCache->pSynced = pCache->pDirtyTail;
44212 }
44213 
44214 /*
44215 ** Change the page number of page p to newPgno.
44216 */
44217 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
44218  PCache *pCache = p->pCache;
44219  assert( p->nRef>0 );
44220  assert( newPgno>0 );
44221  assert( sqlite3PcachePageSanity(p) );
44222  pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
44223  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
44224  p->pgno = newPgno;
44225  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
44226  pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
44227  }
44228 }
44229 
44230 /*
44231 ** Drop every cache entry whose page number is greater than "pgno". The
44232 ** caller must ensure that there are no outstanding references to any pages
44233 ** other than page 1 with a page number greater than pgno.
44234 **
44235 ** If there is a reference to page 1 and the pgno parameter passed to this
44236 ** function is 0, then the data area associated with page 1 is zeroed, but
44237 ** the page object is not dropped.
44238 */
44239 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
44240  if( pCache->pCache ){
44241  PgHdr *p;
44242  PgHdr *pNext;
44243  pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
44244  for(p=pCache->pDirty; p; p=pNext){
44245  pNext = p->pDirtyNext;
44246  /* This routine never gets call with a positive pgno except right
44247  ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
44248  ** it must be that pgno==0.
44249  */
44250  assert( p->pgno>0 );
44251  if( p->pgno>pgno ){
44252  assert( p->flags&PGHDR_DIRTY );
44253  sqlite3PcacheMakeClean(p);
44254  }
44255  }
44256  if( pgno==0 && pCache->nRefSum ){
44257  sqlite3_pcache_page *pPage1;
44258  pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
44259  if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
44260  ** pCache->nRefSum>0 */
44261  memset(pPage1->pBuf, 0, pCache->szPage);
44262  pgno = 1;
44263  }
44264  }
44265  sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
44266  }
44267 }
44268 
44269 /*
44270 ** Close a cache.
44271 */
44272 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
44273  assert( pCache->pCache!=0 );
44274  pcacheTrace(("%p.CLOSE\n",pCache));
44275  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
44276 }
44277 
44278 /*
44279 ** Discard the contents of the cache.
44280 */
44281 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
44282  sqlite3PcacheTruncate(pCache, 0);
44283 }
44284 
44285 /*
44286 ** Merge two lists of pages connected by pDirty and in pgno order.
44287 ** Do not bother fixing the pDirtyPrev pointers.
44288 */
44289 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
44290  PgHdr result, *pTail;
44291  pTail = &result;
44292  assert( pA!=0 && pB!=0 );
44293  for(;;){
44294  if( pA->pgno<pB->pgno ){
44295  pTail->pDirty = pA;
44296  pTail = pA;
44297  pA = pA->pDirty;
44298  if( pA==0 ){
44299  pTail->pDirty = pB;
44300  break;
44301  }
44302  }else{
44303  pTail->pDirty = pB;
44304  pTail = pB;
44305  pB = pB->pDirty;
44306  if( pB==0 ){
44307  pTail->pDirty = pA;
44308  break;
44309  }
44310  }
44311  }
44312  return result.pDirty;
44313 }
44314 
44315 /*
44316 ** Sort the list of pages in accending order by pgno. Pages are
44317 ** connected by pDirty pointers. The pDirtyPrev pointers are
44318 ** corrupted by this sort.
44319 **
44320 ** Since there cannot be more than 2^31 distinct pages in a database,
44321 ** there cannot be more than 31 buckets required by the merge sorter.
44322 ** One extra bucket is added to catch overflow in case something
44323 ** ever changes to make the previous sentence incorrect.
44324 */
44325 #define N_SORT_BUCKET 32
44326 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
44327  PgHdr *a[N_SORT_BUCKET], *p;
44328  int i;
44329  memset(a, 0, sizeof(a));
44330  while( pIn ){
44331  p = pIn;
44332  pIn = p->pDirty;
44333  p->pDirty = 0;
44334  for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
44335  if( a[i]==0 ){
44336  a[i] = p;
44337  break;
44338  }else{
44339  p = pcacheMergeDirtyList(a[i], p);
44340  a[i] = 0;
44341  }
44342  }
44343  if( NEVER(i==N_SORT_BUCKET-1) ){
44344  /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
44345  ** the input list. But that is impossible.
44346  */
44347  a[i] = pcacheMergeDirtyList(a[i], p);
44348  }
44349  }
44350  p = a[0];
44351  for(i=1; i<N_SORT_BUCKET; i++){
44352  if( a[i]==0 ) continue;
44353  p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
44354  }
44355  return p;
44356 }
44357 
44358 /*
44359 ** Return a list of all dirty pages in the cache, sorted by page number.
44360 */
44361 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
44362  PgHdr *p;
44363  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44364  p->pDirty = p->pDirtyNext;
44365  }
44366  return pcacheSortDirtyList(pCache->pDirty);
44367 }
44368 
44369 /*
44370 ** Return the total number of references to all pages held by the cache.
44371 **
44372 ** This is not the total number of pages referenced, but the sum of the
44373 ** reference count for all pages.
44374 */
44375 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
44376  return pCache->nRefSum;
44377 }
44378 
44379 /*
44380 ** Return the number of references to the page supplied as an argument.
44381 */
44382 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
44383  return p->nRef;
44384 }
44385 
44386 /*
44387 ** Return the total number of pages in the cache.
44388 */
44389 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
44390  assert( pCache->pCache!=0 );
44391  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
44392 }
44393 
44394 #ifdef SQLITE_TEST
44395 /*
44396 ** Get the suggested cache-size value.
44397 */
44398 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
44399  return numberOfCachePages(pCache);
44400 }
44401 #endif
44402 
44403 /*
44404 ** Set the suggested cache-size value.
44405 */
44406 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
44407  assert( pCache->pCache!=0 );
44408  pCache->szCache = mxPage;
44409  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
44410  numberOfCachePages(pCache));
44411 }
44412 
44413 /*
44414 ** Set the suggested cache-spill value. Make no changes if if the
44415 ** argument is zero. Return the effective cache-spill size, which will
44416 ** be the larger of the szSpill and szCache.
44417 */
44418 SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
44419  int res;
44420  assert( p->pCache!=0 );
44421  if( mxPage ){
44422  if( mxPage<0 ){
44423  mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
44424  }
44425  p->szSpill = mxPage;
44426  }
44427  res = numberOfCachePages(p);
44428  if( res<p->szSpill ) res = p->szSpill;
44429  return res;
44430 }
44431 
44432 /*
44433 ** Free up as much memory as possible from the page cache.
44434 */
44435 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
44436  assert( pCache->pCache!=0 );
44437  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
44438 }
44439 
44440 /*
44441 ** Return the size of the header added by this middleware layer
44442 ** in the page-cache hierarchy.
44443 */
44444 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
44445 
44446 /*
44447 ** Return the number of dirty pages currently in the cache, as a percentage
44448 ** of the configured cache size.
44449 */
44450 SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
44451  PgHdr *pDirty;
44452  int nDirty = 0;
44453  int nCache = numberOfCachePages(pCache);
44454  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
44455  return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
44456 }
44457 
44458 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
44459 /*
44460 ** For all dirty pages currently in the cache, invoke the specified
44461 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
44462 ** defined.
44463 */
44464 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
44465  PgHdr *pDirty;
44466  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
44467  xIter(pDirty);
44468  }
44469 }
44470 #endif
44471 
44472 /************** End of pcache.c **********************************************/
44473 /************** Begin file pcache1.c *****************************************/
44474 /*
44475 ** 2008 November 05
44476 **
44477 ** The author disclaims copyright to this source code. In place of
44478 ** a legal notice, here is a blessing:
44479 **
44480 ** May you do good and not evil.
44481 ** May you find forgiveness for yourself and forgive others.
44482 ** May you share freely, never taking more than you give.
44483 **
44484 *************************************************************************
44485 **
44486 ** This file implements the default page cache implementation (the
44487 ** sqlite3_pcache interface). It also contains part of the implementation
44488 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
44489 ** If the default page cache implementation is overridden, then neither of
44490 ** these two features are available.
44491 **
44492 ** A Page cache line looks like this:
44493 **
44494 ** -------------------------------------------------------------
44495 ** | database page content | PgHdr1 | MemPage | PgHdr |
44496 ** -------------------------------------------------------------
44497 **
44498 ** The database page content is up front (so that buffer overreads tend to
44499 ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
44500 ** is the extension added by the btree.c module containing information such
44501 ** as the database page number and how that database page is used. PgHdr
44502 ** is added by the pcache.c layer and contains information used to keep track
44503 ** of which pages are "dirty". PgHdr1 is an extension added by this
44504 ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
44505 ** PgHdr1 contains information needed to look up a page by its page number.
44506 ** The superclass sqlite3_pcache_page.pBuf points to the start of the
44507 ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
44508 **
44509 ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
44510 ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
44511 ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
44512 ** size can vary according to architecture, compile-time options, and
44513 ** SQLite library version number.
44514 **
44515 ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
44516 ** using a separate memory allocation from the database page content. This
44517 ** seeks to overcome the "clownshoe" problem (also called "internal
44518 ** fragmentation" in academic literature) of allocating a few bytes more
44519 ** than a power of two with the memory allocator rounding up to the next
44520 ** power of two, and leaving the rounded-up space unused.
44521 **
44522 ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
44523 ** with this module. Information is passed back and forth as PgHdr1 pointers.
44524 **
44525 ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
44526 ** The btree.c module deals with pointers to MemPage objects.
44527 **
44528 ** SOURCE OF PAGE CACHE MEMORY:
44529 **
44530 ** Memory for a page might come from any of three sources:
44531 **
44532 ** (1) The general-purpose memory allocator - sqlite3Malloc()
44533 ** (2) Global page-cache memory provided using sqlite3_config() with
44534 ** SQLITE_CONFIG_PAGECACHE.
44535 ** (3) PCache-local bulk allocation.
44536 **
44537 ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
44538 ** that is allocated when the page cache is created. The size of the local
44539 ** bulk allocation can be adjusted using
44540 **
44541 ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
44542 **
44543 ** If N is positive, then N pages worth of memory are allocated using a single
44544 ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
44545 ** Or if N is negative, then -1024*N bytes of memory are allocated and used
44546 ** for as many pages as can be accomodated.
44547 **
44548 ** Only one of (2) or (3) can be used. Once the memory available to (2) or
44549 ** (3) is exhausted, subsequent allocations fail over to the general-purpose
44550 ** memory allocator (1).
44551 **
44552 ** Earlier versions of SQLite used only methods (1) and (2). But experiments
44553 ** show that method (3) with N==100 provides about a 5% performance boost for
44554 ** common workloads.
44555 */
44556 /* #include "sqliteInt.h" */
44557 
44558 typedef struct PCache1 PCache1;
44559 typedef struct PgHdr1 PgHdr1;
44560 typedef struct PgFreeslot PgFreeslot;
44561 typedef struct PGroup PGroup;
44562 
44563 /*
44564 ** Each cache entry is represented by an instance of the following
44565 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
44566 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
44567 ** in memory.
44568 */
44569 struct PgHdr1 {
44570  sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
44571  unsigned int iKey; /* Key value (page number) */
44572  u8 isPinned; /* Page in use, not on the LRU list */
44573  u8 isBulkLocal; /* This page from bulk local storage */
44574  u8 isAnchor; /* This is the PGroup.lru element */
44575  PgHdr1 *pNext; /* Next in hash table chain */
44576  PCache1 *pCache; /* Cache that currently owns this page */
44577  PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
44578  PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
44579 };
44580 
44581 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
44582 ** of one or more PCaches that are able to recycle each other's unpinned
44583 ** pages when they are under memory pressure. A PGroup is an instance of
44584 ** the following object.
44585 **
44586 ** This page cache implementation works in one of two modes:
44587 **
44588 ** (1) Every PCache is the sole member of its own PGroup. There is
44589 ** one PGroup per PCache.
44590 **
44591 ** (2) There is a single global PGroup that all PCaches are a member
44592 ** of.
44593 **
44594 ** Mode 1 uses more memory (since PCache instances are not able to rob
44595 ** unused pages from other PCaches) but it also operates without a mutex,
44596 ** and is therefore often faster. Mode 2 requires a mutex in order to be
44597 ** threadsafe, but recycles pages more efficiently.
44598 **
44599 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
44600 ** PGroup which is the pcache1.grp global variable and its mutex is
44601 ** SQLITE_MUTEX_STATIC_LRU.
44602 */
44603 struct PGroup {
44604  sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
44605  unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
44606  unsigned int nMinPage; /* Sum of nMin for purgeable caches */
44607  unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
44608  unsigned int nCurrentPage; /* Number of purgeable pages allocated */
44609  PgHdr1 lru; /* The beginning and end of the LRU list */
44610 };
44611 
44612 /* Each page cache is an instance of the following object. Every
44613 ** open database file (including each in-memory database and each
44614 ** temporary or transient database) has a single page cache which
44615 ** is an instance of this object.
44616 **
44617 ** Pointers to structures of this type are cast and returned as
44618 ** opaque sqlite3_pcache* handles.
44619 */
44620 struct PCache1 {
44621  /* Cache configuration parameters. Page size (szPage) and the purgeable
44622  ** flag (bPurgeable) are set when the cache is created. nMax may be
44623  ** modified at any time by a call to the pcache1Cachesize() method.
44624  ** The PGroup mutex must be held when accessing nMax.
44625  */
44626  PGroup *pGroup; /* PGroup this cache belongs to */
44627  int szPage; /* Size of database content section */
44628  int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
44629  int szAlloc; /* Total size of one pcache line */
44630  int bPurgeable; /* True if cache is purgeable */
44631  unsigned int nMin; /* Minimum number of pages reserved */
44632  unsigned int nMax; /* Configured "cache_size" value */
44633  unsigned int n90pct; /* nMax*9/10 */
44634  unsigned int iMaxKey; /* Largest key seen since xTruncate() */
44635 
44636  /* Hash table of all pages. The following variables may only be accessed
44637  ** when the accessor is holding the PGroup mutex.
44638  */
44639  unsigned int nRecyclable; /* Number of pages in the LRU list */
44640  unsigned int nPage; /* Total number of pages in apHash */
44641  unsigned int nHash; /* Number of slots in apHash[] */
44642  PgHdr1 **apHash; /* Hash table for fast lookup by key */
44643  PgHdr1 *pFree; /* List of unused pcache-local pages */
44644  void *pBulk; /* Bulk memory used by pcache-local */
44645 };
44646 
44647 /*
44648 ** Free slots in the allocator used to divide up the global page cache
44649 ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
44650 */
44651 struct PgFreeslot {
44652  PgFreeslot *pNext; /* Next free slot */
44653 };
44654 
44655 /*
44656 ** Global data used by this cache.
44657 */
44658 static SQLITE_WSD struct PCacheGlobal {
44659  PGroup grp; /* The global PGroup for mode (2) */
44660 
44661  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
44662  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
44663  ** fixed at sqlite3_initialize() time and do not require mutex protection.
44664  ** The nFreeSlot and pFree values do require mutex protection.
44665  */
44666  int isInit; /* True if initialized */
44667  int separateCache; /* Use a new PGroup for each PCache */
44668  int nInitPage; /* Initial bulk allocation size */
44669  int szSlot; /* Size of each free slot */
44670  int nSlot; /* The number of pcache slots */
44671  int nReserve; /* Try to keep nFreeSlot above this */
44672  void *pStart, *pEnd; /* Bounds of global page cache memory */
44673  /* Above requires no mutex. Use mutex below for variable that follow. */
44674  sqlite3_mutex *mutex; /* Mutex for accessing the following: */
44675  PgFreeslot *pFree; /* Free page blocks */
44676  int nFreeSlot; /* Number of unused pcache slots */
44677  /* The following value requires a mutex to change. We skip the mutex on
44678  ** reading because (1) most platforms read a 32-bit integer atomically and
44679  ** (2) even if an incorrect value is read, no great harm is done since this
44680  ** is really just an optimization. */
44681  int bUnderPressure; /* True if low on PAGECACHE memory */
44682 } pcache1_g;
44683 
44684 /*
44685 ** All code in this file should access the global structure above via the
44686 ** alias "pcache1". This ensures that the WSD emulation is used when
44687 ** compiling for systems that do not support real WSD.
44688 */
44689 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
44690 
44691 /*
44692 ** Macros to enter and leave the PCache LRU mutex.
44693 */
44694 #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
44695 # define pcache1EnterMutex(X) assert((X)->mutex==0)
44696 # define pcache1LeaveMutex(X) assert((X)->mutex==0)
44697 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
44698 #else
44699 # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
44700 # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
44701 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
44702 #endif
44703 
44704 /******************************************************************************/
44705 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
44706 
44707 
44708 /*
44709 ** This function is called during initialization if a static buffer is
44710 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
44711 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
44712 ** enough to contain 'n' buffers of 'sz' bytes each.
44713 **
44714 ** This routine is called from sqlite3_initialize() and so it is guaranteed
44715 ** to be serialized already. There is no need for further mutexing.
44716 */
44717 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
44718  if( pcache1.isInit ){
44719  PgFreeslot *p;
44720  if( pBuf==0 ) sz = n = 0;
44721  sz = ROUNDDOWN8(sz);
44722  pcache1.szSlot = sz;
44723  pcache1.nSlot = pcache1.nFreeSlot = n;
44724  pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
44725  pcache1.pStart = pBuf;
44726  pcache1.pFree = 0;
44727  pcache1.bUnderPressure = 0;
44728  while( n-- ){
44729  p = (PgFreeslot*)pBuf;
44730  p->pNext = pcache1.pFree;
44731  pcache1.pFree = p;
44732  pBuf = (void*)&((char*)pBuf)[sz];
44733  }
44734  pcache1.pEnd = pBuf;
44735  }
44736 }
44737 
44738 /*
44739 ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
44740 ** true if pCache->pFree ends up containing one or more free pages.
44741 */
44742 static int pcache1InitBulk(PCache1 *pCache){
44743  i64 szBulk;
44744  char *zBulk;
44745  if( pcache1.nInitPage==0 ) return 0;
44746  /* Do not bother with a bulk allocation if the cache size very small */
44747  if( pCache->nMax<3 ) return 0;
44748  sqlite3BeginBenignMalloc();
44749  if( pcache1.nInitPage>0 ){
44750  szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
44751  }else{
44752  szBulk = -1024 * (i64)pcache1.nInitPage;
44753  }
44754  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
44755  szBulk = pCache->szAlloc*(i64)pCache->nMax;
44756  }
44757  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
44758  sqlite3EndBenignMalloc();
44759  if( zBulk ){
44760  int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
44761  int i;
44762  for(i=0; i<nBulk; i++){
44763  PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
44764  pX->page.pBuf = zBulk;
44765  pX->page.pExtra = &pX[1];
44766  pX->isBulkLocal = 1;
44767  pX->isAnchor = 0;
44768  pX->pNext = pCache->pFree;
44769  pCache->pFree = pX;
44770  zBulk += pCache->szAlloc;
44771  }
44772  }
44773  return pCache->pFree!=0;
44774 }
44775 
44776 /*
44777 ** Malloc function used within this file to allocate space from the buffer
44778 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
44779 ** such buffer exists or there is no space left in it, this function falls
44780 ** back to sqlite3Malloc().
44781 **
44782 ** Multiple threads can run this routine at the same time. Global variables
44783 ** in pcache1 need to be protected via mutex.
44784 */
44785 static void *pcache1Alloc(int nByte){
44786  void *p = 0;
44787  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
44788  if( nByte<=pcache1.szSlot ){
44789  sqlite3_mutex_enter(pcache1.mutex);
44790  p = (PgHdr1 *)pcache1.pFree;
44791  if( p ){
44792  pcache1.pFree = pcache1.pFree->pNext;
44793  pcache1.nFreeSlot--;
44794  pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44795  assert( pcache1.nFreeSlot>=0 );
44796  sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
44797  sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
44798  }
44799  sqlite3_mutex_leave(pcache1.mutex);
44800  }
44801  if( p==0 ){
44802  /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
44803  ** it from sqlite3Malloc instead.
44804  */
44805  p = sqlite3Malloc(nByte);
44806 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44807  if( p ){
44808  int sz = sqlite3MallocSize(p);
44809  sqlite3_mutex_enter(pcache1.mutex);
44810  sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
44811  sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
44812  sqlite3_mutex_leave(pcache1.mutex);
44813  }
44814 #endif
44815  sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
44816  }
44817  return p;
44818 }
44819 
44820 /*
44821 ** Free an allocated buffer obtained from pcache1Alloc().
44822 */
44823 static void pcache1Free(void *p){
44824  if( p==0 ) return;
44825  if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
44826  PgFreeslot *pSlot;
44827  sqlite3_mutex_enter(pcache1.mutex);
44828  sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
44829  pSlot = (PgFreeslot*)p;
44830  pSlot->pNext = pcache1.pFree;
44831  pcache1.pFree = pSlot;
44832  pcache1.nFreeSlot++;
44833  pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44834  assert( pcache1.nFreeSlot<=pcache1.nSlot );
44835  sqlite3_mutex_leave(pcache1.mutex);
44836  }else{
44837  assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
44838  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
44839 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44840  {
44841  int nFreed = 0;
44842  nFreed = sqlite3MallocSize(p);
44843  sqlite3_mutex_enter(pcache1.mutex);
44844  sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
44845  sqlite3_mutex_leave(pcache1.mutex);
44846  }
44847 #endif
44848  sqlite3_free(p);
44849  }
44850 }
44851 
44852 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44853 /*
44854 ** Return the size of a pcache allocation
44855 */
44856 static int pcache1MemSize(void *p){
44857  if( p>=pcache1.pStart && p<pcache1.pEnd ){
44858  return pcache1.szSlot;
44859  }else{
44860  int iSize;
44861  assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
44862  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
44863  iSize = sqlite3MallocSize(p);
44864  sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
44865  return iSize;
44866  }
44867 }
44868 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
44869 
44870 /*
44871 ** Allocate a new page object initially associated with cache pCache.
44872 */
44873 static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
44874  PgHdr1 *p = 0;
44875  void *pPg;
44876 
44877  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44878  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
44879  p = pCache->pFree;
44880  pCache->pFree = p->pNext;
44881  p->pNext = 0;
44882  }else{
44883 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44884  /* The group mutex must be released before pcache1Alloc() is called. This
44885  ** is because it might call sqlite3_release_memory(), which assumes that
44886  ** this mutex is not held. */
44887  assert( pcache1.separateCache==0 );
44888  assert( pCache->pGroup==&pcache1.grp );
44889  pcache1LeaveMutex(pCache->pGroup);
44890 #endif
44891  if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
44892 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
44893  pPg = pcache1Alloc(pCache->szPage);
44894  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
44895  if( !pPg || !p ){
44896  pcache1Free(pPg);
44897  sqlite3_free(p);
44898  pPg = 0;
44899  }
44900 #else
44901  pPg = pcache1Alloc(pCache->szAlloc);
44902  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
44903 #endif
44904  if( benignMalloc ){ sqlite3EndBenignMalloc(); }
44905 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44906  pcache1EnterMutex(pCache->pGroup);
44907 #endif
44908  if( pPg==0 ) return 0;
44909  p->page.pBuf = pPg;
44910  p->page.pExtra = &p[1];
44911  p->isBulkLocal = 0;
44912  p->isAnchor = 0;
44913  }
44914  if( pCache->bPurgeable ){
44915  pCache->pGroup->nCurrentPage++;
44916  }
44917  return p;
44918 }
44919 
44920 /*
44921 ** Free a page object allocated by pcache1AllocPage().
44922 */
44923 static void pcache1FreePage(PgHdr1 *p){
44924  PCache1 *pCache;
44925  assert( p!=0 );
44926  pCache = p->pCache;
44927  assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
44928  if( p->isBulkLocal ){
44929  p->pNext = pCache->pFree;
44930  pCache->pFree = p;
44931  }else{
44932  pcache1Free(p->page.pBuf);
44933 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
44934  sqlite3_free(p);
44935 #endif
44936  }
44937  if( pCache->bPurgeable ){
44938  pCache->pGroup->nCurrentPage--;
44939  }
44940 }
44941 
44942 /*
44943 ** Malloc function used by SQLite to obtain space from the buffer configured
44944 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
44945 ** exists, this function falls back to sqlite3Malloc().
44946 */
44947 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
44948  return pcache1Alloc(sz);
44949 }
44950 
44951 /*
44952 ** Free an allocated buffer obtained from sqlite3PageMalloc().
44953 */
44954 SQLITE_PRIVATE void sqlite3PageFree(void *p){
44955  pcache1Free(p);
44956 }
44957 
44958 
44959 /*
44960 ** Return true if it desirable to avoid allocating a new page cache
44961 ** entry.
44962 **
44963 ** If memory was allocated specifically to the page cache using
44964 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
44965 ** it is desirable to avoid allocating a new page cache entry because
44966 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
44967 ** for all page cache needs and we should not need to spill the
44968 ** allocation onto the heap.
44969 **
44970 ** Or, the heap is used for all page cache memory but the heap is
44971 ** under memory pressure, then again it is desirable to avoid
44972 ** allocating a new page cache entry in order to avoid stressing
44973 ** the heap even further.
44974 */
44975 static int pcache1UnderMemoryPressure(PCache1 *pCache){
44976  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
44977  return pcache1.bUnderPressure;
44978  }else{
44979  return sqlite3HeapNearlyFull();
44980  }
44981 }
44982 
44983 /******************************************************************************/
44984 /******** General Implementation Functions ************************************/
44985 
44986 /*
44987 ** This function is used to resize the hash table used by the cache passed
44988 ** as the first argument.
44989 **
44990 ** The PCache mutex must be held when this function is called.
44991 */
44992 static void pcache1ResizeHash(PCache1 *p){
44993  PgHdr1 **apNew;
44994  unsigned int nNew;
44995  unsigned int i;
44996 
44997  assert( sqlite3_mutex_held(p->pGroup->mutex) );
44998 
44999  nNew = p->nHash*2;
45000  if( nNew<256 ){
45001  nNew = 256;
45002  }
45003 
45004  pcache1LeaveMutex(p->pGroup);
45005  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
45006  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
45007  if( p->nHash ){ sqlite3EndBenignMalloc(); }
45008  pcache1EnterMutex(p->pGroup);
45009  if( apNew ){
45010  for(i=0; i<p->nHash; i++){
45011  PgHdr1 *pPage;
45012  PgHdr1 *pNext = p->apHash[i];
45013  while( (pPage = pNext)!=0 ){
45014  unsigned int h = pPage->iKey % nNew;
45015  pNext = pPage->pNext;
45016  pPage->pNext = apNew[h];
45017  apNew[h] = pPage;
45018  }
45019  }
45020  sqlite3_free(p->apHash);
45021  p->apHash = apNew;
45022  p->nHash = nNew;
45023  }
45024 }
45025 
45026 /*
45027 ** This function is used internally to remove the page pPage from the
45028 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
45029 ** LRU list, then this function is a no-op.
45030 **
45031 ** The PGroup mutex must be held when this function is called.
45032 */
45033 static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
45034  PCache1 *pCache;
45035 
45036  assert( pPage!=0 );
45037  assert( pPage->isPinned==0 );
45038  pCache = pPage->pCache;
45039  assert( pPage->pLruNext );
45040  assert( pPage->pLruPrev );
45041  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45042  pPage->pLruPrev->pLruNext = pPage->pLruNext;
45043  pPage->pLruNext->pLruPrev = pPage->pLruPrev;
45044  pPage->pLruNext = 0;
45045  pPage->pLruPrev = 0;
45046  pPage->isPinned = 1;
45047  assert( pPage->isAnchor==0 );
45048  assert( pCache->pGroup->lru.isAnchor==1 );
45049  pCache->nRecyclable--;
45050  return pPage;
45051 }
45052 
45053 
45054 /*
45055 ** Remove the page supplied as an argument from the hash table
45056 ** (PCache1.apHash structure) that it is currently stored in.
45057 ** Also free the page if freePage is true.
45058 **
45059 ** The PGroup mutex must be held when this function is called.
45060 */
45061 static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
45062  unsigned int h;
45063  PCache1 *pCache = pPage->pCache;
45064  PgHdr1 **pp;
45065 
45066  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45067  h = pPage->iKey % pCache->nHash;
45068  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
45069  *pp = (*pp)->pNext;
45070 
45071  pCache->nPage--;
45072  if( freeFlag ) pcache1FreePage(pPage);
45073 }
45074 
45075 /*
45076 ** If there are currently more than nMaxPage pages allocated, try
45077 ** to recycle pages to reduce the number allocated to nMaxPage.
45078 */
45079 static void pcache1EnforceMaxPage(PCache1 *pCache){
45080  PGroup *pGroup = pCache->pGroup;
45081  PgHdr1 *p;
45082  assert( sqlite3_mutex_held(pGroup->mutex) );
45083  while( pGroup->nCurrentPage>pGroup->nMaxPage
45084  && (p=pGroup->lru.pLruPrev)->isAnchor==0
45085  ){
45086  assert( p->pCache->pGroup==pGroup );
45087  assert( p->isPinned==0 );
45088  pcache1PinPage(p);
45089  pcache1RemoveFromHash(p, 1);
45090  }
45091  if( pCache->nPage==0 && pCache->pBulk ){
45092  sqlite3_free(pCache->pBulk);
45093  pCache->pBulk = pCache->pFree = 0;
45094  }
45095 }
45096 
45097 /*
45098 ** Discard all pages from cache pCache with a page number (key value)
45099 ** greater than or equal to iLimit. Any pinned pages that meet this
45100 ** criteria are unpinned before they are discarded.
45101 **
45102 ** The PCache mutex must be held when this function is called.
45103 */
45104 static void pcache1TruncateUnsafe(
45105  PCache1 *pCache, /* The cache to truncate */
45106  unsigned int iLimit /* Drop pages with this pgno or larger */
45107 ){
45108  TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
45109  unsigned int h, iStop;
45110  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45111  assert( pCache->iMaxKey >= iLimit );
45112  assert( pCache->nHash > 0 );
45113  if( pCache->iMaxKey - iLimit < pCache->nHash ){
45114  /* If we are just shaving the last few pages off the end of the
45115  ** cache, then there is no point in scanning the entire hash table.
45116  ** Only scan those hash slots that might contain pages that need to
45117  ** be removed. */
45118  h = iLimit % pCache->nHash;
45119  iStop = pCache->iMaxKey % pCache->nHash;
45120  TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
45121  }else{
45122  /* This is the general case where many pages are being removed.
45123  ** It is necessary to scan the entire hash table */
45124  h = pCache->nHash/2;
45125  iStop = h - 1;
45126  }
45127  for(;;){
45128  PgHdr1 **pp;
45129  PgHdr1 *pPage;
45130  assert( h<pCache->nHash );
45131  pp = &pCache->apHash[h];
45132  while( (pPage = *pp)!=0 ){
45133  if( pPage->iKey>=iLimit ){
45134  pCache->nPage--;
45135  *pp = pPage->pNext;
45136  if( !pPage->isPinned ) pcache1PinPage(pPage);
45137  pcache1FreePage(pPage);
45138  }else{
45139  pp = &pPage->pNext;
45140  TESTONLY( if( nPage>=0 ) nPage++; )
45141  }
45142  }
45143  if( h==iStop ) break;
45144  h = (h+1) % pCache->nHash;
45145  }
45146  assert( nPage<0 || pCache->nPage==(unsigned)nPage );
45147 }
45148 
45149 /******************************************************************************/
45150 /******** sqlite3_pcache Methods **********************************************/
45151 
45152 /*
45153 ** Implementation of the sqlite3_pcache.xInit method.
45154 */
45155 static int pcache1Init(void *NotUsed){
45156  UNUSED_PARAMETER(NotUsed);
45157  assert( pcache1.isInit==0 );
45158  memset(&pcache1, 0, sizeof(pcache1));
45159 
45160 
45161  /*
45162  ** The pcache1.separateCache variable is true if each PCache has its own
45163  ** private PGroup (mode-1). pcache1.separateCache is false if the single
45164  ** PGroup in pcache1.grp is used for all page caches (mode-2).
45165  **
45166  ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
45167  **
45168  ** * Use a unified cache in single-threaded applications that have
45169  ** configured a start-time buffer for use as page-cache memory using
45170  ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
45171  ** pBuf argument.
45172  **
45173  ** * Otherwise use separate caches (mode-1)
45174  */
45175 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
45176  pcache1.separateCache = 0;
45177 #elif SQLITE_THREADSAFE
45178  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
45179  || sqlite3GlobalConfig.bCoreMutex>0;
45180 #else
45181  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
45182 #endif
45183 
45184 #if SQLITE_THREADSAFE
45185  if( sqlite3GlobalConfig.bCoreMutex ){
45186  pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
45187  pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
45188  }
45189 #endif
45190  if( pcache1.separateCache
45191  && sqlite3GlobalConfig.nPage!=0
45192  && sqlite3GlobalConfig.pPage==0
45193  ){
45194  pcache1.nInitPage = sqlite3GlobalConfig.nPage;
45195  }else{
45196  pcache1.nInitPage = 0;
45197  }
45198  pcache1.grp.mxPinned = 10;
45199  pcache1.isInit = 1;
45200  return SQLITE_OK;
45201 }
45202 
45203 /*
45204 ** Implementation of the sqlite3_pcache.xShutdown method.
45205 ** Note that the static mutex allocated in xInit does
45206 ** not need to be freed.
45207 */
45208 static void pcache1Shutdown(void *NotUsed){
45209  UNUSED_PARAMETER(NotUsed);
45210  assert( pcache1.isInit!=0 );
45211  memset(&pcache1, 0, sizeof(pcache1));
45212 }
45213 
45214 /* forward declaration */
45215 static void pcache1Destroy(sqlite3_pcache *p);
45216 
45217 /*
45218 ** Implementation of the sqlite3_pcache.xCreate method.
45219 **
45220 ** Allocate a new cache.
45221 */
45222 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
45223  PCache1 *pCache; /* The newly created page cache */
45224  PGroup *pGroup; /* The group the new page cache will belong to */
45225  int sz; /* Bytes of memory required to allocate the new cache */
45226 
45227  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
45228  assert( szExtra < 300 );
45229 
45230  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
45231  pCache = (PCache1 *)sqlite3MallocZero(sz);
45232  if( pCache ){
45233  if( pcache1.separateCache ){
45234  pGroup = (PGroup*)&pCache[1];
45235  pGroup->mxPinned = 10;
45236  }else{
45237  pGroup = &pcache1.grp;
45238  }
45239  if( pGroup->lru.isAnchor==0 ){
45240  pGroup->lru.isAnchor = 1;
45241  pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
45242  }
45243  pCache->pGroup = pGroup;
45244  pCache->szPage = szPage;
45245  pCache->szExtra = szExtra;
45246  pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
45247  pCache->bPurgeable = (bPurgeable ? 1 : 0);
45248  pcache1EnterMutex(pGroup);
45249  pcache1ResizeHash(pCache);
45250  if( bPurgeable ){
45251  pCache->nMin = 10;
45252  pGroup->nMinPage += pCache->nMin;
45253  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45254  }
45255  pcache1LeaveMutex(pGroup);
45256  if( pCache->nHash==0 ){
45257  pcache1Destroy((sqlite3_pcache*)pCache);
45258  pCache = 0;
45259  }
45260  }
45261  return (sqlite3_pcache *)pCache;
45262 }
45263 
45264 /*
45265 ** Implementation of the sqlite3_pcache.xCachesize method.
45266 **
45267 ** Configure the cache_size limit for a cache.
45268 */
45269 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
45270  PCache1 *pCache = (PCache1 *)p;
45271  if( pCache->bPurgeable ){
45272  PGroup *pGroup = pCache->pGroup;
45273  pcache1EnterMutex(pGroup);
45274  pGroup->nMaxPage += (nMax - pCache->nMax);
45275  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45276  pCache->nMax = nMax;
45277  pCache->n90pct = pCache->nMax*9/10;
45278  pcache1EnforceMaxPage(pCache);
45279  pcache1LeaveMutex(pGroup);
45280  }
45281 }
45282 
45283 /*
45284 ** Implementation of the sqlite3_pcache.xShrink method.
45285 **
45286 ** Free up as much memory as possible.
45287 */
45288 static void pcache1Shrink(sqlite3_pcache *p){
45289  PCache1 *pCache = (PCache1*)p;
45290  if( pCache->bPurgeable ){
45291  PGroup *pGroup = pCache->pGroup;
45292  int savedMaxPage;
45293  pcache1EnterMutex(pGroup);
45294  savedMaxPage = pGroup->nMaxPage;
45295  pGroup->nMaxPage = 0;
45296  pcache1EnforceMaxPage(pCache);
45297  pGroup->nMaxPage = savedMaxPage;
45298  pcache1LeaveMutex(pGroup);
45299  }
45300 }
45301 
45302 /*
45303 ** Implementation of the sqlite3_pcache.xPagecount method.
45304 */
45305 static int pcache1Pagecount(sqlite3_pcache *p){
45306  int n;
45307  PCache1 *pCache = (PCache1*)p;
45308  pcache1EnterMutex(pCache->pGroup);
45309  n = pCache->nPage;
45310  pcache1LeaveMutex(pCache->pGroup);
45311  return n;
45312 }
45313 
45314 
45315 /*
45316 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
45317 ** in the header of the pcache1Fetch() procedure.
45318 **
45319 ** This steps are broken out into a separate procedure because they are
45320 ** usually not needed, and by avoiding the stack initialization required
45321 ** for these steps, the main pcache1Fetch() procedure can run faster.
45322 */
45323 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
45324  PCache1 *pCache,
45325  unsigned int iKey,
45326  int createFlag
45327 ){
45328  unsigned int nPinned;
45329  PGroup *pGroup = pCache->pGroup;
45330  PgHdr1 *pPage = 0;
45331 
45332  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
45333  assert( pCache->nPage >= pCache->nRecyclable );
45334  nPinned = pCache->nPage - pCache->nRecyclable;
45335  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
45336  assert( pCache->n90pct == pCache->nMax*9/10 );
45337  if( createFlag==1 && (
45338  nPinned>=pGroup->mxPinned
45339  || nPinned>=pCache->n90pct
45340  || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
45341  )){
45342  return 0;
45343  }
45344 
45345  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
45346  assert( pCache->nHash>0 && pCache->apHash );
45347 
45348  /* Step 4. Try to recycle a page. */
45349  if( pCache->bPurgeable
45350  && !pGroup->lru.pLruPrev->isAnchor
45351  && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
45352  ){
45353  PCache1 *pOther;
45354  pPage = pGroup->lru.pLruPrev;
45355  assert( pPage->isPinned==0 );
45356  pcache1RemoveFromHash(pPage, 0);
45357  pcache1PinPage(pPage);
45358  pOther = pPage->pCache;
45359  if( pOther->szAlloc != pCache->szAlloc ){
45360  pcache1FreePage(pPage);
45361  pPage = 0;
45362  }else{
45363  pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
45364  }
45365  }
45366 
45367  /* Step 5. If a usable page buffer has still not been found,
45368  ** attempt to allocate a new one.
45369  */
45370  if( !pPage ){
45371  pPage = pcache1AllocPage(pCache, createFlag==1);
45372  }
45373 
45374  if( pPage ){
45375  unsigned int h = iKey % pCache->nHash;
45376  pCache->nPage++;
45377  pPage->iKey = iKey;
45378  pPage->pNext = pCache->apHash[h];
45379  pPage->pCache = pCache;
45380  pPage->pLruPrev = 0;
45381  pPage->pLruNext = 0;
45382  pPage->isPinned = 1;
45383  *(void **)pPage->page.pExtra = 0;
45384  pCache->apHash[h] = pPage;
45385  if( iKey>pCache->iMaxKey ){
45386  pCache->iMaxKey = iKey;
45387  }
45388  }
45389  return pPage;
45390 }
45391 
45392 /*
45393 ** Implementation of the sqlite3_pcache.xFetch method.
45394 **
45395 ** Fetch a page by key value.
45396 **
45397 ** Whether or not a new page may be allocated by this function depends on
45398 ** the value of the createFlag argument. 0 means do not allocate a new
45399 ** page. 1 means allocate a new page if space is easily available. 2
45400 ** means to try really hard to allocate a new page.
45401 **
45402 ** For a non-purgeable cache (a cache used as the storage for an in-memory
45403 ** database) there is really no difference between createFlag 1 and 2. So
45404 ** the calling function (pcache.c) will never have a createFlag of 1 on
45405 ** a non-purgeable cache.
45406 **
45407 ** There are three different approaches to obtaining space for a page,
45408 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
45409 **
45410 ** 1. Regardless of the value of createFlag, the cache is searched for a
45411 ** copy of the requested page. If one is found, it is returned.
45412 **
45413 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
45414 ** returned.
45415 **
45416 ** 3. If createFlag is 1, and the page is not already in the cache, then
45417 ** return NULL (do not allocate a new page) if any of the following
45418 ** conditions are true:
45419 **
45420 ** (a) the number of pages pinned by the cache is greater than
45421 ** PCache1.nMax, or
45422 **
45423 ** (b) the number of pages pinned by the cache is greater than
45424 ** the sum of nMax for all purgeable caches, less the sum of
45425 ** nMin for all other purgeable caches, or
45426 **
45427 ** 4. If none of the first three conditions apply and the cache is marked
45428 ** as purgeable, and if one of the following is true:
45429 **
45430 ** (a) The number of pages allocated for the cache is already
45431 ** PCache1.nMax, or
45432 **
45433 ** (b) The number of pages allocated for all purgeable caches is
45434 ** already equal to or greater than the sum of nMax for all
45435 ** purgeable caches,
45436 **
45437 ** (c) The system is under memory pressure and wants to avoid
45438 ** unnecessary pages cache entry allocations
45439 **
45440 ** then attempt to recycle a page from the LRU list. If it is the right
45441 ** size, return the recycled buffer. Otherwise, free the buffer and
45442 ** proceed to step 5.
45443 **
45444 ** 5. Otherwise, allocate and return a new page buffer.
45445 **
45446 ** There are two versions of this routine. pcache1FetchWithMutex() is
45447 ** the general case. pcache1FetchNoMutex() is a faster implementation for
45448 ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
45449 ** invokes the appropriate routine.
45450 */
45451 static PgHdr1 *pcache1FetchNoMutex(
45452  sqlite3_pcache *p,
45453  unsigned int iKey,
45454  int createFlag
45455 ){
45456  PCache1 *pCache = (PCache1 *)p;
45457  PgHdr1 *pPage = 0;
45458 
45459  /* Step 1: Search the hash table for an existing entry. */
45460  pPage = pCache->apHash[iKey % pCache->nHash];
45461  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
45462 
45463  /* Step 2: If the page was found in the hash table, then return it.
45464  ** If the page was not in the hash table and createFlag is 0, abort.
45465  ** Otherwise (page not in hash and createFlag!=0) continue with
45466  ** subsequent steps to try to create the page. */
45467  if( pPage ){
45468  if( !pPage->isPinned ){
45469  return pcache1PinPage(pPage);
45470  }else{
45471  return pPage;
45472  }
45473  }else if( createFlag ){
45474  /* Steps 3, 4, and 5 implemented by this subroutine */
45475  return pcache1FetchStage2(pCache, iKey, createFlag);
45476  }else{
45477  return 0;
45478  }
45479 }
45480 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
45481 static PgHdr1 *pcache1FetchWithMutex(
45482  sqlite3_pcache *p,
45483  unsigned int iKey,
45484  int createFlag
45485 ){
45486  PCache1 *pCache = (PCache1 *)p;
45487  PgHdr1 *pPage;
45488 
45489  pcache1EnterMutex(pCache->pGroup);
45490  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
45491  assert( pPage==0 || pCache->iMaxKey>=iKey );
45492  pcache1LeaveMutex(pCache->pGroup);
45493  return pPage;
45494 }
45495 #endif
45496 static sqlite3_pcache_page *pcache1Fetch(
45497  sqlite3_pcache *p,
45498  unsigned int iKey,
45499  int createFlag
45500 ){
45501 #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
45502  PCache1 *pCache = (PCache1 *)p;
45503 #endif
45504 
45505  assert( offsetof(PgHdr1,page)==0 );
45506  assert( pCache->bPurgeable || createFlag!=1 );
45507  assert( pCache->bPurgeable || pCache->nMin==0 );
45508  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
45509  assert( pCache->nMin==0 || pCache->bPurgeable );
45510  assert( pCache->nHash>0 );
45511 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
45512  if( pCache->pGroup->mutex ){
45513  return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
45514  }else
45515 #endif
45516  {
45517  return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
45518  }
45519 }
45520 
45521 
45522 /*
45523 ** Implementation of the sqlite3_pcache.xUnpin method.
45524 **
45525 ** Mark a page as unpinned (eligible for asynchronous recycling).
45526 */
45527 static void pcache1Unpin(
45528  sqlite3_pcache *p,
45529  sqlite3_pcache_page *pPg,
45530  int reuseUnlikely
45531 ){
45532  PCache1 *pCache = (PCache1 *)p;
45533  PgHdr1 *pPage = (PgHdr1 *)pPg;
45534  PGroup *pGroup = pCache->pGroup;
45535 
45536  assert( pPage->pCache==pCache );
45537  pcache1EnterMutex(pGroup);
45538 
45539  /* It is an error to call this function if the page is already
45540  ** part of the PGroup LRU list.
45541  */
45542  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
45543  assert( pPage->isPinned==1 );
45544 
45545  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
45546  pcache1RemoveFromHash(pPage, 1);
45547  }else{
45548  /* Add the page to the PGroup LRU list. */
45549  PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
45550  pPage->pLruPrev = &pGroup->lru;
45551  (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
45552  *ppFirst = pPage;
45553  pCache->nRecyclable++;
45554  pPage->isPinned = 0;
45555  }
45556 
45557  pcache1LeaveMutex(pCache->pGroup);
45558 }
45559 
45560 /*
45561 ** Implementation of the sqlite3_pcache.xRekey method.
45562 */
45563 static void pcache1Rekey(
45564  sqlite3_pcache *p,
45565  sqlite3_pcache_page *pPg,
45566  unsigned int iOld,
45567  unsigned int iNew
45568 ){
45569  PCache1 *pCache = (PCache1 *)p;
45570  PgHdr1 *pPage = (PgHdr1 *)pPg;
45571  PgHdr1 **pp;
45572  unsigned int h;
45573  assert( pPage->iKey==iOld );
45574  assert( pPage->pCache==pCache );
45575 
45576  pcache1EnterMutex(pCache->pGroup);
45577 
45578  h = iOld%pCache->nHash;
45579  pp = &pCache->apHash[h];
45580  while( (*pp)!=pPage ){
45581  pp = &(*pp)->pNext;
45582  }
45583  *pp = pPage->pNext;
45584 
45585  h = iNew%pCache->nHash;
45586  pPage->iKey = iNew;
45587  pPage->pNext = pCache->apHash[h];
45588  pCache->apHash[h] = pPage;
45589  if( iNew>pCache->iMaxKey ){
45590  pCache->iMaxKey = iNew;
45591  }
45592 
45593  pcache1LeaveMutex(pCache->pGroup);
45594 }
45595 
45596 /*
45597 ** Implementation of the sqlite3_pcache.xTruncate method.
45598 **
45599 ** Discard all unpinned pages in the cache with a page number equal to
45600 ** or greater than parameter iLimit. Any pinned pages with a page number
45601 ** equal to or greater than iLimit are implicitly unpinned.
45602 */
45603 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
45604  PCache1 *pCache = (PCache1 *)p;
45605  pcache1EnterMutex(pCache->pGroup);
45606  if( iLimit<=pCache->iMaxKey ){
45607  pcache1TruncateUnsafe(pCache, iLimit);
45608  pCache->iMaxKey = iLimit-1;
45609  }
45610  pcache1LeaveMutex(pCache->pGroup);
45611 }
45612 
45613 /*
45614 ** Implementation of the sqlite3_pcache.xDestroy method.
45615 **
45616 ** Destroy a cache allocated using pcache1Create().
45617 */
45618 static void pcache1Destroy(sqlite3_pcache *p){
45619  PCache1 *pCache = (PCache1 *)p;
45620  PGroup *pGroup = pCache->pGroup;
45621  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
45622  pcache1EnterMutex(pGroup);
45623  if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
45624  assert( pGroup->nMaxPage >= pCache->nMax );
45625  pGroup->nMaxPage -= pCache->nMax;
45626  assert( pGroup->nMinPage >= pCache->nMin );
45627  pGroup->nMinPage -= pCache->nMin;
45628  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45629  pcache1EnforceMaxPage(pCache);
45630  pcache1LeaveMutex(pGroup);
45631  sqlite3_free(pCache->pBulk);
45632  sqlite3_free(pCache->apHash);
45633  sqlite3_free(pCache);
45634 }
45635 
45636 /*
45637 ** This function is called during initialization (sqlite3_initialize()) to
45638 ** install the default pluggable cache module, assuming the user has not
45639 ** already provided an alternative.
45640 */
45641 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
45642  static const sqlite3_pcache_methods2 defaultMethods = {
45643  1, /* iVersion */
45644  0, /* pArg */
45645  pcache1Init, /* xInit */
45646  pcache1Shutdown, /* xShutdown */
45647  pcache1Create, /* xCreate */
45648  pcache1Cachesize, /* xCachesize */
45649  pcache1Pagecount, /* xPagecount */
45650  pcache1Fetch, /* xFetch */
45651  pcache1Unpin, /* xUnpin */
45652  pcache1Rekey, /* xRekey */
45653  pcache1Truncate, /* xTruncate */
45654  pcache1Destroy, /* xDestroy */
45655  pcache1Shrink /* xShrink */
45656  };
45657  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
45658 }
45659 
45660 /*
45661 ** Return the size of the header on each page of this PCACHE implementation.
45662 */
45663 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
45664 
45665 /*
45666 ** Return the global mutex used by this PCACHE implementation. The
45667 ** sqlite3_status() routine needs access to this mutex.
45668 */
45669 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
45670  return pcache1.mutex;
45671 }
45672 
45673 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45674 /*
45675 ** This function is called to free superfluous dynamically allocated memory
45676 ** held by the pager system. Memory in use by any SQLite pager allocated
45677 ** by the current thread may be sqlite3_free()ed.
45678 **
45679 ** nReq is the number of bytes of memory required. Once this much has
45680 ** been released, the function returns. The return value is the total number
45681 ** of bytes of memory released.
45682 */
45683 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
45684  int nFree = 0;
45685  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
45686  assert( sqlite3_mutex_notheld(pcache1.mutex) );
45687  if( sqlite3GlobalConfig.nPage==0 ){
45688  PgHdr1 *p;
45689  pcache1EnterMutex(&pcache1.grp);
45690  while( (nReq<0 || nFree<nReq)
45691  && (p=pcache1.grp.lru.pLruPrev)!=0
45692  && p->isAnchor==0
45693  ){
45694  nFree += pcache1MemSize(p->page.pBuf);
45695 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
45696  nFree += sqlite3MemSize(p);
45697 #endif
45698  assert( p->isPinned==0 );
45699  pcache1PinPage(p);
45700  pcache1RemoveFromHash(p, 1);
45701  }
45702  pcache1LeaveMutex(&pcache1.grp);
45703  }
45704  return nFree;
45705 }
45706 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
45707 
45708 #ifdef SQLITE_TEST
45709 /*
45710 ** This function is used by test procedures to inspect the internal state
45711 ** of the global cache.
45712 */
45713 SQLITE_PRIVATE void sqlite3PcacheStats(
45714  int *pnCurrent, /* OUT: Total number of pages cached */
45715  int *pnMax, /* OUT: Global maximum cache size */
45716  int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
45717  int *pnRecyclable /* OUT: Total number of pages available for recycling */
45718 ){
45719  PgHdr1 *p;
45720  int nRecyclable = 0;
45721  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
45722  assert( p->isPinned==0 );
45723  nRecyclable++;
45724  }
45725  *pnCurrent = pcache1.grp.nCurrentPage;
45726  *pnMax = (int)pcache1.grp.nMaxPage;
45727  *pnMin = (int)pcache1.grp.nMinPage;
45728  *pnRecyclable = nRecyclable;
45729 }
45730 #endif
45731 
45732 /************** End of pcache1.c *********************************************/
45733 /************** Begin file rowset.c ******************************************/
45734 /*
45735 ** 2008 December 3
45736 **
45737 ** The author disclaims copyright to this source code. In place of
45738 ** a legal notice, here is a blessing:
45739 **
45740 ** May you do good and not evil.
45741 ** May you find forgiveness for yourself and forgive others.
45742 ** May you share freely, never taking more than you give.
45743 **
45744 *************************************************************************
45745 **
45746 ** This module implements an object we call a "RowSet".
45747 **
45748 ** The RowSet object is a collection of rowids. Rowids
45749 ** are inserted into the RowSet in an arbitrary order. Inserts
45750 ** can be intermixed with tests to see if a given rowid has been
45751 ** previously inserted into the RowSet.
45752 **
45753 ** After all inserts are finished, it is possible to extract the
45754 ** elements of the RowSet in sorted order. Once this extraction
45755 ** process has started, no new elements may be inserted.
45756 **
45757 ** Hence, the primitive operations for a RowSet are:
45758 **
45759 ** CREATE
45760 ** INSERT
45761 ** TEST
45762 ** SMALLEST
45763 ** DESTROY
45764 **
45765 ** The CREATE and DESTROY primitives are the constructor and destructor,
45766 ** obviously. The INSERT primitive adds a new element to the RowSet.
45767 ** TEST checks to see if an element is already in the RowSet. SMALLEST
45768 ** extracts the least value from the RowSet.
45769 **
45770 ** The INSERT primitive might allocate additional memory. Memory is
45771 ** allocated in chunks so most INSERTs do no allocation. There is an
45772 ** upper bound on the size of allocated memory. No memory is freed
45773 ** until DESTROY.
45774 **
45775 ** The TEST primitive includes a "batch" number. The TEST primitive
45776 ** will only see elements that were inserted before the last change
45777 ** in the batch number. In other words, if an INSERT occurs between
45778 ** two TESTs where the TESTs have the same batch nubmer, then the
45779 ** value added by the INSERT will not be visible to the second TEST.
45780 ** The initial batch number is zero, so if the very first TEST contains
45781 ** a non-zero batch number, it will see all prior INSERTs.
45782 **
45783 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
45784 ** that is attempted.
45785 **
45786 ** The cost of an INSERT is roughly constant. (Sometimes new memory
45787 ** has to be allocated on an INSERT.) The cost of a TEST with a new
45788 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
45789 ** The cost of a TEST using the same batch number is O(logN). The cost
45790 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
45791 ** primitives are constant time. The cost of DESTROY is O(N).
45792 **
45793 ** TEST and SMALLEST may not be used by the same RowSet. This used to
45794 ** be possible, but the feature was not used, so it was removed in order
45795 ** to simplify the code.
45796 */
45797 /* #include "sqliteInt.h" */
45798 
45799 
45800 /*
45801 ** Target size for allocation chunks.
45802 */
45803 #define ROWSET_ALLOCATION_SIZE 1024
45804 
45805 /*
45806 ** The number of rowset entries per allocation chunk.
45807 */
45808 #define ROWSET_ENTRY_PER_CHUNK \
45809  ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
45810 
45811 /*
45812 ** Each entry in a RowSet is an instance of the following object.
45813 **
45814 ** This same object is reused to store a linked list of trees of RowSetEntry
45815 ** objects. In that alternative use, pRight points to the next entry
45816 ** in the list, pLeft points to the tree, and v is unused. The
45817 ** RowSet.pForest value points to the head of this forest list.
45818 */
45819 struct RowSetEntry {
45820  i64 v; /* ROWID value for this entry */
45821  struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
45822  struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
45823 };
45824 
45825 /*
45826 ** RowSetEntry objects are allocated in large chunks (instances of the
45827 ** following structure) to reduce memory allocation overhead. The
45828 ** chunks are kept on a linked list so that they can be deallocated
45829 ** when the RowSet is destroyed.
45830 */
45831 struct RowSetChunk {
45832  struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
45833  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
45834 };
45835 
45836 /*
45837 ** A RowSet in an instance of the following structure.
45838 **
45839 ** A typedef of this structure if found in sqliteInt.h.
45840 */
45841 struct RowSet {
45842  struct RowSetChunk *pChunk; /* List of all chunk allocations */
45843  sqlite3 *db; /* The database connection */
45844  struct RowSetEntry *pEntry; /* List of entries using pRight */
45845  struct RowSetEntry *pLast; /* Last entry on the pEntry list */
45846  struct RowSetEntry *pFresh; /* Source of new entry objects */
45847  struct RowSetEntry *pForest; /* List of binary trees of entries */
45848  u16 nFresh; /* Number of objects on pFresh */
45849  u16 rsFlags; /* Various flags */
45850  int iBatch; /* Current insert batch */
45851 };
45852 
45853 /*
45854 ** Allowed values for RowSet.rsFlags
45855 */
45856 #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
45857 #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
45858 
45859 /*
45860 ** Turn bulk memory into a RowSet object. N bytes of memory
45861 ** are available at pSpace. The db pointer is used as a memory context
45862 ** for any subsequent allocations that need to occur.
45863 ** Return a pointer to the new RowSet object.
45864 **
45865 ** It must be the case that N is sufficient to make a Rowset. If not
45866 ** an assertion fault occurs.
45867 **
45868 ** If N is larger than the minimum, use the surplus as an initial
45869 ** allocation of entries available to be filled.
45870 */
45871 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
45872  RowSet *p;
45873  assert( N >= ROUND8(sizeof(*p)) );
45874  p = pSpace;
45875  p->pChunk = 0;
45876  p->db = db;
45877  p->pEntry = 0;
45878  p->pLast = 0;
45879  p->pForest = 0;
45880  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
45881  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
45882  p->rsFlags = ROWSET_SORTED;
45883  p->iBatch = 0;
45884  return p;
45885 }
45886 
45887 /*
45888 ** Deallocate all chunks from a RowSet. This frees all memory that
45889 ** the RowSet has allocated over its lifetime. This routine is
45890 ** the destructor for the RowSet.
45891 */
45892 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
45893  struct RowSetChunk *pChunk, *pNextChunk;
45894  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
45895  pNextChunk = pChunk->pNextChunk;
45896  sqlite3DbFree(p->db, pChunk);
45897  }
45898  p->pChunk = 0;
45899  p->nFresh = 0;
45900  p->pEntry = 0;
45901  p->pLast = 0;
45902  p->pForest = 0;
45903  p->rsFlags = ROWSET_SORTED;
45904 }
45905 
45906 /*
45907 ** Allocate a new RowSetEntry object that is associated with the
45908 ** given RowSet. Return a pointer to the new and completely uninitialized
45909 ** objected.
45910 **
45911 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
45912 ** routine returns NULL.
45913 */
45914 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
45915  assert( p!=0 );
45916  if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
45917  /* We could allocate a fresh RowSetEntry each time one is needed, but it
45918  ** is more efficient to pull a preallocated entry from the pool */
45919  struct RowSetChunk *pNew;
45920  pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
45921  if( pNew==0 ){
45922  return 0;
45923  }
45924  pNew->pNextChunk = p->pChunk;
45925  p->pChunk = pNew;
45926  p->pFresh = pNew->aEntry;
45927  p->nFresh = ROWSET_ENTRY_PER_CHUNK;
45928  }
45929  p->nFresh--;
45930  return p->pFresh++;
45931 }
45932 
45933 /*
45934 ** Insert a new value into a RowSet.
45935 **
45936 ** The mallocFailed flag of the database connection is set if a
45937 ** memory allocation fails.
45938 */
45939 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
45940  struct RowSetEntry *pEntry; /* The new entry */
45941  struct RowSetEntry *pLast; /* The last prior entry */
45942 
45943  /* This routine is never called after sqlite3RowSetNext() */
45944  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
45945 
45946  pEntry = rowSetEntryAlloc(p);
45947  if( pEntry==0 ) return;
45948  pEntry->v = rowid;
45949  pEntry->pRight = 0;
45950  pLast = p->pLast;
45951  if( pLast ){
45952  if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
45953  /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
45954  ** where possible */
45955  p->rsFlags &= ~ROWSET_SORTED;
45956  }
45957  pLast->pRight = pEntry;
45958  }else{
45959  p->pEntry = pEntry;
45960  }
45961  p->pLast = pEntry;
45962 }
45963 
45964 /*
45965 ** Merge two lists of RowSetEntry objects. Remove duplicates.
45966 **
45967 ** The input lists are connected via pRight pointers and are
45968 ** assumed to each already be in sorted order.
45969 */
45970 static struct RowSetEntry *rowSetEntryMerge(
45971  struct RowSetEntry *pA, /* First sorted list to be merged */
45972  struct RowSetEntry *pB /* Second sorted list to be merged */
45973 ){
45974  struct RowSetEntry head;
45975  struct RowSetEntry *pTail;
45976 
45977  pTail = &head;
45978  assert( pA!=0 && pB!=0 );
45979  for(;;){
45980  assert( pA->pRight==0 || pA->v<=pA->pRight->v );
45981  assert( pB->pRight==0 || pB->v<=pB->pRight->v );
45982  if( pA->v<=pB->v ){
45983  if( pA->v<pB->v ) pTail = pTail->pRight = pA;
45984  pA = pA->pRight;
45985  if( pA==0 ){
45986  pTail->pRight = pB;
45987  break;
45988  }
45989  }else{
45990  pTail = pTail->pRight = pB;
45991  pB = pB->pRight;
45992  if( pB==0 ){
45993  pTail->pRight = pA;
45994  break;
45995  }
45996  }
45997  }
45998  return head.pRight;
45999 }
46000 
46001 /*
46002 ** Sort all elements on the list of RowSetEntry objects into order of
46003 ** increasing v.
46004 */
46005 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
46006  unsigned int i;
46007  struct RowSetEntry *pNext, *aBucket[40];
46008 
46009  memset(aBucket, 0, sizeof(aBucket));
46010  while( pIn ){
46011  pNext = pIn->pRight;
46012  pIn->pRight = 0;
46013  for(i=0; aBucket[i]; i++){
46014  pIn = rowSetEntryMerge(aBucket[i], pIn);
46015  aBucket[i] = 0;
46016  }
46017  aBucket[i] = pIn;
46018  pIn = pNext;
46019  }
46020  pIn = aBucket[0];
46021  for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
46022  if( aBucket[i]==0 ) continue;
46023  pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
46024  }
46025  return pIn;
46026 }
46027 
46028 
46029 /*
46030 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
46031 ** Convert this tree into a linked list connected by the pRight pointers
46032 ** and return pointers to the first and last elements of the new list.
46033 */
46034 static void rowSetTreeToList(
46035  struct RowSetEntry *pIn, /* Root of the input tree */
46036  struct RowSetEntry **ppFirst, /* Write head of the output list here */
46037  struct RowSetEntry **ppLast /* Write tail of the output list here */
46038 ){
46039  assert( pIn!=0 );
46040  if( pIn->pLeft ){
46041  struct RowSetEntry *p;
46042  rowSetTreeToList(pIn->pLeft, ppFirst, &p);
46043  p->pRight = pIn;
46044  }else{
46045  *ppFirst = pIn;
46046  }
46047  if( pIn->pRight ){
46048  rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
46049  }else{
46050  *ppLast = pIn;
46051  }
46052  assert( (*ppLast)->pRight==0 );
46053 }
46054 
46055 
46056 /*
46057 ** Convert a sorted list of elements (connected by pRight) into a binary
46058 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
46059 ** node taken from the head of *ppList. A depth of 2 means a tree with
46060 ** three nodes. And so forth.
46061 **
46062 ** Use as many entries from the input list as required and update the
46063 ** *ppList to point to the unused elements of the list. If the input
46064 ** list contains too few elements, then construct an incomplete tree
46065 ** and leave *ppList set to NULL.
46066 **
46067 ** Return a pointer to the root of the constructed binary tree.
46068 */
46069 static struct RowSetEntry *rowSetNDeepTree(
46070  struct RowSetEntry **ppList,
46071  int iDepth
46072 ){
46073  struct RowSetEntry *p; /* Root of the new tree */
46074  struct RowSetEntry *pLeft; /* Left subtree */
46075  if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
46076  /* Prevent unnecessary deep recursion when we run out of entries */
46077  return 0;
46078  }
46079  if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
46080  /* This branch causes a *balanced* tree to be generated. A valid tree
46081  ** is still generated without this branch, but the tree is wildly
46082  ** unbalanced and inefficient. */
46083  pLeft = rowSetNDeepTree(ppList, iDepth-1);
46084  p = *ppList;
46085  if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
46086  /* It is safe to always return here, but the resulting tree
46087  ** would be unbalanced */
46088  return pLeft;
46089  }
46090  p->pLeft = pLeft;
46091  *ppList = p->pRight;
46092  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
46093  }else{
46094  p = *ppList;
46095  *ppList = p->pRight;
46096  p->pLeft = p->pRight = 0;
46097  }
46098  return p;
46099 }
46100 
46101 /*
46102 ** Convert a sorted list of elements into a binary tree. Make the tree
46103 ** as deep as it needs to be in order to contain the entire list.
46104 */
46105 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
46106  int iDepth; /* Depth of the tree so far */
46107  struct RowSetEntry *p; /* Current tree root */
46108  struct RowSetEntry *pLeft; /* Left subtree */
46109 
46110  assert( pList!=0 );
46111  p = pList;
46112  pList = p->pRight;
46113  p->pLeft = p->pRight = 0;
46114  for(iDepth=1; pList; iDepth++){
46115  pLeft = p;
46116  p = pList;
46117  pList = p->pRight;
46118  p->pLeft = pLeft;
46119  p->pRight = rowSetNDeepTree(&pList, iDepth);
46120  }
46121  return p;
46122 }
46123 
46124 /*
46125 ** Extract the smallest element from the RowSet.
46126 ** Write the element into *pRowid. Return 1 on success. Return
46127 ** 0 if the RowSet is already empty.
46128 **
46129 ** After this routine has been called, the sqlite3RowSetInsert()
46130 ** routine may not be called again.
46131 **
46132 ** This routine may not be called after sqlite3RowSetTest() has
46133 ** been used. Older versions of RowSet allowed that, but as the
46134 ** capability was not used by the code generator, it was removed
46135 ** for code economy.
46136 */
46137 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
46138  assert( p!=0 );
46139  assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
46140 
46141  /* Merge the forest into a single sorted list on first call */
46142  if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46143  if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46144  p->pEntry = rowSetEntrySort(p->pEntry);
46145  }
46146  p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
46147  }
46148 
46149  /* Return the next entry on the list */
46150  if( p->pEntry ){
46151  *pRowid = p->pEntry->v;
46152  p->pEntry = p->pEntry->pRight;
46153  if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
46154  /* Free memory immediately, rather than waiting on sqlite3_finalize() */
46155  sqlite3RowSetClear(p);
46156  }
46157  return 1;
46158  }else{
46159  return 0;
46160  }
46161 }
46162 
46163 /*
46164 ** Check to see if element iRowid was inserted into the rowset as
46165 ** part of any insert batch prior to iBatch. Return 1 or 0.
46166 **
46167 ** If this is the first test of a new batch and if there exist entries
46168 ** on pRowSet->pEntry, then sort those entries into the forest at
46169 ** pRowSet->pForest so that they can be tested.
46170 */
46171 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
46172  struct RowSetEntry *p, *pTree;
46173 
46174  /* This routine is never called after sqlite3RowSetNext() */
46175  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
46176 
46177  /* Sort entries into the forest on the first test of a new batch.
46178  ** To save unnecessary work, only do this when the batch number changes.
46179  */
46180  if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
46181  p = pRowSet->pEntry;
46182  if( p ){
46183  struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
46184  if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46185  /* Only sort the current set of entiries if they need it */
46186  p = rowSetEntrySort(p);
46187  }
46188  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46189  ppPrevTree = &pTree->pRight;
46190  if( pTree->pLeft==0 ){
46191  pTree->pLeft = rowSetListToTree(p);
46192  break;
46193  }else{
46194  struct RowSetEntry *pAux, *pTail;
46195  rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
46196  pTree->pLeft = 0;
46197  p = rowSetEntryMerge(pAux, p);
46198  }
46199  }
46200  if( pTree==0 ){
46201  *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
46202  if( pTree ){
46203  pTree->v = 0;
46204  pTree->pRight = 0;
46205  pTree->pLeft = rowSetListToTree(p);
46206  }
46207  }
46208  pRowSet->pEntry = 0;
46209  pRowSet->pLast = 0;
46210  pRowSet->rsFlags |= ROWSET_SORTED;
46211  }
46212  pRowSet->iBatch = iBatch;
46213  }
46214 
46215  /* Test to see if the iRowid value appears anywhere in the forest.
46216  ** Return 1 if it does and 0 if not.
46217  */
46218  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46219  p = pTree->pLeft;
46220  while( p ){
46221  if( p->v<iRowid ){
46222  p = p->pRight;
46223  }else if( p->v>iRowid ){
46224  p = p->pLeft;
46225  }else{
46226  return 1;
46227  }
46228  }
46229  }
46230  return 0;
46231 }
46232 
46233 /************** End of rowset.c **********************************************/
46234 /************** Begin file pager.c *******************************************/
46235 /*
46236 ** 2001 September 15
46237 **
46238 ** The author disclaims copyright to this source code. In place of
46239 ** a legal notice, here is a blessing:
46240 **
46241 ** May you do good and not evil.
46242 ** May you find forgiveness for yourself and forgive others.
46243 ** May you share freely, never taking more than you give.
46244 **
46245 *************************************************************************
46246 ** This is the implementation of the page cache subsystem or "pager".
46247 **
46248 ** The pager is used to access a database disk file. It implements
46249 ** atomic commit and rollback through the use of a journal file that
46250 ** is separate from the database file. The pager also implements file
46251 ** locking to prevent two processes from writing the same database
46252 ** file simultaneously, or one process from reading the database while
46253 ** another is writing.
46254 */
46255 #ifndef SQLITE_OMIT_DISKIO
46256 /* #include "sqliteInt.h" */
46257 /************** Include wal.h in the middle of pager.c ***********************/
46258 /************** Begin file wal.h *********************************************/
46259 /*
46260 ** 2010 February 1
46261 **
46262 ** The author disclaims copyright to this source code. In place of
46263 ** a legal notice, here is a blessing:
46264 **
46265 ** May you do good and not evil.
46266 ** May you find forgiveness for yourself and forgive others.
46267 ** May you share freely, never taking more than you give.
46268 **
46269 *************************************************************************
46270 ** This header file defines the interface to the write-ahead logging
46271 ** system. Refer to the comments below and the header comment attached to
46272 ** the implementation of each function in log.c for further details.
46273 */
46274 
46275 #ifndef SQLITE_WAL_H
46276 #define SQLITE_WAL_H
46277 
46278 /* #include "sqliteInt.h" */
46279 
46280 /* Additional values that can be added to the sync_flags argument of
46281 ** sqlite3WalFrames():
46282 */
46283 #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
46284 #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
46285 
46286 #ifdef SQLITE_OMIT_WAL
46287 # define sqlite3WalOpen(x,y,z) 0
46288 # define sqlite3WalLimit(x,y)
46289 # define sqlite3WalClose(w,x,y,z) 0
46290 # define sqlite3WalBeginReadTransaction(y,z) 0
46291 # define sqlite3WalEndReadTransaction(z)
46292 # define sqlite3WalDbsize(y) 0
46293 # define sqlite3WalBeginWriteTransaction(y) 0
46294 # define sqlite3WalEndWriteTransaction(x) 0
46295 # define sqlite3WalUndo(x,y,z) 0
46296 # define sqlite3WalSavepoint(y,z)
46297 # define sqlite3WalSavepointUndo(y,z) 0
46298 # define sqlite3WalFrames(u,v,w,x,y,z) 0
46299 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
46300 # define sqlite3WalCallback(z) 0
46301 # define sqlite3WalExclusiveMode(y,z) 0
46302 # define sqlite3WalHeapMemory(z) 0
46303 # define sqlite3WalFramesize(z) 0
46304 # define sqlite3WalFindFrame(x,y,z) 0
46305 # define sqlite3WalFile(x) 0
46306 #else
46307 
46308 #define WAL_SAVEPOINT_NDATA 4
46309 
46310 /* Connection to a write-ahead log (WAL) file.
46311 ** There is one object of this type for each pager.
46312 */
46313 typedef struct Wal Wal;
46314 
46315 /* Open and close a connection to a write-ahead log. */
46316 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
46317 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
46318 
46319 /* Set the limiting size of a WAL file. */
46320 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
46321 
46322 /* Used by readers to open (lock) and close (unlock) a snapshot. A
46323 ** snapshot is like a read-transaction. It is the state of the database
46324 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
46325 ** preserves the current state even if the other threads or processes
46326 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
46327 ** transaction and releases the lock.
46328 */
46329 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
46330 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
46331 
46332 /* Read a page from the write-ahead log, if it is present. */
46333 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
46334 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
46335 
46336 /* If the WAL is not empty, return the size of the database. */
46337 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
46338 
46339 /* Obtain or release the WRITER lock. */
46340 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
46341 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
46342 
46343 /* Undo any frames written (but not committed) to the log */
46344 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
46345 
46346 /* Return an integer that records the current (uncommitted) write
46347 ** position in the WAL */
46348 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
46349 
46350 /* Move the write position of the WAL back to iFrame. Called in
46351 ** response to a ROLLBACK TO command. */
46352 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
46353 
46354 /* Write a frame or frames to the log. */
46355 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
46356 
46357 /* Copy pages from the log to the database file */
46358 SQLITE_PRIVATE int sqlite3WalCheckpoint(
46359  Wal *pWal, /* Write-ahead log connection */
46360  int eMode, /* One of PASSIVE, FULL and RESTART */
46361  int (*xBusy)(void*), /* Function to call when busy */
46362  void *pBusyArg, /* Context argument for xBusyHandler */
46363  int sync_flags, /* Flags to sync db file with (or 0) */
46364  int nBuf, /* Size of buffer nBuf */
46365  u8 *zBuf, /* Temporary buffer to use */
46366  int *pnLog, /* OUT: Number of frames in WAL */
46367  int *pnCkpt /* OUT: Number of backfilled frames in WAL */
46368 );
46369 
46370 /* Return the value to pass to a sqlite3_wal_hook callback, the
46371 ** number of frames in the WAL at the point of the last commit since
46372 ** sqlite3WalCallback() was called. If no commits have occurred since
46373 ** the last call, then return 0.
46374 */
46375 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
46376 
46377 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
46378 ** by the pager layer on the database file.
46379 */
46380 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
46381 
46382 /* Return true if the argument is non-NULL and the WAL module is using
46383 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46384 ** WAL module is using shared-memory, return false.
46385 */
46386 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
46387 
46388 #ifdef SQLITE_ENABLE_SNAPSHOT
46389 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
46390 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
46391 #endif
46392 
46393 #ifdef SQLITE_ENABLE_ZIPVFS
46394 /* If the WAL file is not empty, return the number of bytes of content
46395 ** stored in each frame (i.e. the db page-size when the WAL was created).
46396 */
46397 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
46398 #endif
46399 
46400 /* Return the sqlite3_file object for the WAL file */
46401 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
46402 
46403 #endif /* ifndef SQLITE_OMIT_WAL */
46404 #endif /* SQLITE_WAL_H */
46405 
46406 /************** End of wal.h *************************************************/
46407 /************** Continuing where we left off in pager.c **********************/
46408 
46409 
46410 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
46411 **
46412 ** This comment block describes invariants that hold when using a rollback
46413 ** journal. These invariants do not apply for journal_mode=WAL,
46414 ** journal_mode=MEMORY, or journal_mode=OFF.
46415 **
46416 ** Within this comment block, a page is deemed to have been synced
46417 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
46418 ** Otherwise, the page is not synced until the xSync method of the VFS
46419 ** is called successfully on the file containing the page.
46420 **
46421 ** Definition: A page of the database file is said to be "overwriteable" if
46422 ** one or more of the following are true about the page:
46423 **
46424 ** (a) The original content of the page as it was at the beginning of
46425 ** the transaction has been written into the rollback journal and
46426 ** synced.
46427 **
46428 ** (b) The page was a freelist leaf page at the start of the transaction.
46429 **
46430 ** (c) The page number is greater than the largest page that existed in
46431 ** the database file at the start of the transaction.
46432 **
46433 ** (1) A page of the database file is never overwritten unless one of the
46434 ** following are true:
46435 **
46436 ** (a) The page and all other pages on the same sector are overwriteable.
46437 **
46438 ** (b) The atomic page write optimization is enabled, and the entire
46439 ** transaction other than the update of the transaction sequence
46440 ** number consists of a single page change.
46441 **
46442 ** (2) The content of a page written into the rollback journal exactly matches
46443 ** both the content in the database when the rollback journal was written
46444 ** and the content in the database at the beginning of the current
46445 ** transaction.
46446 **
46447 ** (3) Writes to the database file are an integer multiple of the page size
46448 ** in length and are aligned on a page boundary.
46449 **
46450 ** (4) Reads from the database file are either aligned on a page boundary and
46451 ** an integer multiple of the page size in length or are taken from the
46452 ** first 100 bytes of the database file.
46453 **
46454 ** (5) All writes to the database file are synced prior to the rollback journal
46455 ** being deleted, truncated, or zeroed.
46456 **
46457 ** (6) If a master journal file is used, then all writes to the database file
46458 ** are synced prior to the master journal being deleted.
46459 **
46460 ** Definition: Two databases (or the same database at two points it time)
46461 ** are said to be "logically equivalent" if they give the same answer to
46462 ** all queries. Note in particular the content of freelist leaf
46463 ** pages can be changed arbitrarily without affecting the logical equivalence
46464 ** of the database.
46465 **
46466 ** (7) At any time, if any subset, including the empty set and the total set,
46467 ** of the unsynced changes to a rollback journal are removed and the
46468 ** journal is rolled back, the resulting database file will be logically
46469 ** equivalent to the database file at the beginning of the transaction.
46470 **
46471 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
46472 ** is called to restore the database file to the same size it was at
46473 ** the beginning of the transaction. (In some VFSes, the xTruncate
46474 ** method is a no-op, but that does not change the fact the SQLite will
46475 ** invoke it.)
46476 **
46477 ** (9) Whenever the database file is modified, at least one bit in the range
46478 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
46479 ** the EXCLUSIVE lock, thus signaling other connections on the same
46480 ** database to flush their caches.
46481 **
46482 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
46483 ** than one billion transactions.
46484 **
46485 ** (11) A database file is well-formed at the beginning and at the conclusion
46486 ** of every transaction.
46487 **
46488 ** (12) An EXCLUSIVE lock is held on the database file when writing to
46489 ** the database file.
46490 **
46491 ** (13) A SHARED lock is held on the database file while reading any
46492 ** content out of the database file.
46493 **
46494 ******************************************************************************/
46495 
46496 /*
46497 ** Macros for troubleshooting. Normally turned off
46498 */
46499 #if 0
46500 int sqlite3PagerTrace=1; /* True to enable tracing */
46501 #define sqlite3DebugPrintf printf
46502 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
46503 #else
46504 #define PAGERTRACE(X)
46505 #endif
46506 
46507 /*
46508 ** The following two macros are used within the PAGERTRACE() macros above
46509 ** to print out file-descriptors.
46510 **
46511 ** PAGERID() takes a pointer to a Pager struct as its argument. The
46512 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
46513 ** struct as its argument.
46514 */
46515 #define PAGERID(p) ((int)(p->fd))
46516 #define FILEHANDLEID(fd) ((int)fd)
46517 
46518 /*
46519 ** The Pager.eState variable stores the current 'state' of a pager. A
46520 ** pager may be in any one of the seven states shown in the following
46521 ** state diagram.
46522 **
46523 ** OPEN <------+------+
46524 ** | | |
46525 ** V | |
46526 ** +---------> READER-------+ |
46527 ** | | |
46528 ** | V |
46529 ** |<-------WRITER_LOCKED------> ERROR
46530 ** | | ^
46531 ** | V |
46532 ** |<------WRITER_CACHEMOD-------->|
46533 ** | | |
46534 ** | V |
46535 ** |<-------WRITER_DBMOD---------->|
46536 ** | | |
46537 ** | V |
46538 ** +<------WRITER_FINISHED-------->+
46539 **
46540 **
46541 ** List of state transitions and the C [function] that performs each:
46542 **
46543 ** OPEN -> READER [sqlite3PagerSharedLock]
46544 ** READER -> OPEN [pager_unlock]
46545 **
46546 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
46547 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
46548 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
46549 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
46550 ** WRITER_*** -> READER [pager_end_transaction]
46551 **
46552 ** WRITER_*** -> ERROR [pager_error]
46553 ** ERROR -> OPEN [pager_unlock]
46554 **
46555 **
46556 ** OPEN:
46557 **
46558 ** The pager starts up in this state. Nothing is guaranteed in this
46559 ** state - the file may or may not be locked and the database size is
46560 ** unknown. The database may not be read or written.
46561 **
46562 ** * No read or write transaction is active.
46563 ** * Any lock, or no lock at all, may be held on the database file.
46564 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
46565 **
46566 ** READER:
46567 **
46568 ** In this state all the requirements for reading the database in
46569 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
46570 ** was) in exclusive-locking mode, a user-level read transaction is
46571 ** open. The database size is known in this state.
46572 **
46573 ** A connection running with locking_mode=normal enters this state when
46574 ** it opens a read-transaction on the database and returns to state
46575 ** OPEN after the read-transaction is completed. However a connection
46576 ** running in locking_mode=exclusive (including temp databases) remains in
46577 ** this state even after the read-transaction is closed. The only way
46578 ** a locking_mode=exclusive connection can transition from READER to OPEN
46579 ** is via the ERROR state (see below).
46580 **
46581 ** * A read transaction may be active (but a write-transaction cannot).
46582 ** * A SHARED or greater lock is held on the database file.
46583 ** * The dbSize variable may be trusted (even if a user-level read
46584 ** transaction is not active). The dbOrigSize and dbFileSize variables
46585 ** may not be trusted at this point.
46586 ** * If the database is a WAL database, then the WAL connection is open.
46587 ** * Even if a read-transaction is not open, it is guaranteed that
46588 ** there is no hot-journal in the file-system.
46589 **
46590 ** WRITER_LOCKED:
46591 **
46592 ** The pager moves to this state from READER when a write-transaction
46593 ** is first opened on the database. In WRITER_LOCKED state, all locks
46594 ** required to start a write-transaction are held, but no actual
46595 ** modifications to the cache or database have taken place.
46596 **
46597 ** In rollback mode, a RESERVED or (if the transaction was opened with
46598 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
46599 ** moving to this state, but the journal file is not written to or opened
46600 ** to in this state. If the transaction is committed or rolled back while
46601 ** in WRITER_LOCKED state, all that is required is to unlock the database
46602 ** file.
46603 **
46604 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
46605 ** If the connection is running with locking_mode=exclusive, an attempt
46606 ** is made to obtain an EXCLUSIVE lock on the database file.
46607 **
46608 ** * A write transaction is active.
46609 ** * If the connection is open in rollback-mode, a RESERVED or greater
46610 ** lock is held on the database file.
46611 ** * If the connection is open in WAL-mode, a WAL write transaction
46612 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
46613 ** called).
46614 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
46615 ** * The contents of the pager cache have not been modified.
46616 ** * The journal file may or may not be open.
46617 ** * Nothing (not even the first header) has been written to the journal.
46618 **
46619 ** WRITER_CACHEMOD:
46620 **
46621 ** A pager moves from WRITER_LOCKED state to this state when a page is
46622 ** first modified by the upper layer. In rollback mode the journal file
46623 ** is opened (if it is not already open) and a header written to the
46624 ** start of it. The database file on disk has not been modified.
46625 **
46626 ** * A write transaction is active.
46627 ** * A RESERVED or greater lock is held on the database file.
46628 ** * The journal file is open and the first header has been written
46629 ** to it, but the header has not been synced to disk.
46630 ** * The contents of the page cache have been modified.
46631 **
46632 ** WRITER_DBMOD:
46633 **
46634 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
46635 ** when it modifies the contents of the database file. WAL connections
46636 ** never enter this state (since they do not modify the database file,
46637 ** just the log file).
46638 **
46639 ** * A write transaction is active.
46640 ** * An EXCLUSIVE or greater lock is held on the database file.
46641 ** * The journal file is open and the first header has been written
46642 ** and synced to disk.
46643 ** * The contents of the page cache have been modified (and possibly
46644 ** written to disk).
46645 **
46646 ** WRITER_FINISHED:
46647 **
46648 ** It is not possible for a WAL connection to enter this state.
46649 **
46650 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
46651 ** state after the entire transaction has been successfully written into the
46652 ** database file. In this state the transaction may be committed simply
46653 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
46654 ** not possible to modify the database further. At this point, the upper
46655 ** layer must either commit or rollback the transaction.
46656 **
46657 ** * A write transaction is active.
46658 ** * An EXCLUSIVE or greater lock is held on the database file.
46659 ** * All writing and syncing of journal and database data has finished.
46660 ** If no error occurred, all that remains is to finalize the journal to
46661 ** commit the transaction. If an error did occur, the caller will need
46662 ** to rollback the transaction.
46663 **
46664 ** ERROR:
46665 **
46666 ** The ERROR state is entered when an IO or disk-full error (including
46667 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
46668 ** difficult to be sure that the in-memory pager state (cache contents,
46669 ** db size etc.) are consistent with the contents of the file-system.
46670 **
46671 ** Temporary pager files may enter the ERROR state, but in-memory pagers
46672 ** cannot.
46673 **
46674 ** For example, if an IO error occurs while performing a rollback,
46675 ** the contents of the page-cache may be left in an inconsistent state.
46676 ** At this point it would be dangerous to change back to READER state
46677 ** (as usually happens after a rollback). Any subsequent readers might
46678 ** report database corruption (due to the inconsistent cache), and if
46679 ** they upgrade to writers, they may inadvertently corrupt the database
46680 ** file. To avoid this hazard, the pager switches into the ERROR state
46681 ** instead of READER following such an error.
46682 **
46683 ** Once it has entered the ERROR state, any attempt to use the pager
46684 ** to read or write data returns an error. Eventually, once all
46685 ** outstanding transactions have been abandoned, the pager is able to
46686 ** transition back to OPEN state, discarding the contents of the
46687 ** page-cache and any other in-memory state at the same time. Everything
46688 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
46689 ** when a read-transaction is next opened on the pager (transitioning
46690 ** the pager into READER state). At that point the system has recovered
46691 ** from the error.
46692 **
46693 ** Specifically, the pager jumps into the ERROR state if:
46694 **
46695 ** 1. An error occurs while attempting a rollback. This happens in
46696 ** function sqlite3PagerRollback().
46697 **
46698 ** 2. An error occurs while attempting to finalize a journal file
46699 ** following a commit in function sqlite3PagerCommitPhaseTwo().
46700 **
46701 ** 3. An error occurs while attempting to write to the journal or
46702 ** database file in function pagerStress() in order to free up
46703 ** memory.
46704 **
46705 ** In other cases, the error is returned to the b-tree layer. The b-tree
46706 ** layer then attempts a rollback operation. If the error condition
46707 ** persists, the pager enters the ERROR state via condition (1) above.
46708 **
46709 ** Condition (3) is necessary because it can be triggered by a read-only
46710 ** statement executed within a transaction. In this case, if the error
46711 ** code were simply returned to the user, the b-tree layer would not
46712 ** automatically attempt a rollback, as it assumes that an error in a
46713 ** read-only statement cannot leave the pager in an internally inconsistent
46714 ** state.
46715 **
46716 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
46717 ** * There are one or more outstanding references to pages (after the
46718 ** last reference is dropped the pager should move back to OPEN state).
46719 ** * The pager is not an in-memory pager.
46720 **
46721 **
46722 ** Notes:
46723 **
46724 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
46725 ** connection is open in WAL mode. A WAL connection is always in one
46726 ** of the first four states.
46727 **
46728 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
46729 ** state. There are two exceptions: immediately after exclusive-mode has
46730 ** been turned on (and before any read or write transactions are
46731 ** executed), and when the pager is leaving the "error state".
46732 **
46733 ** * See also: assert_pager_state().
46734 */
46735 #define PAGER_OPEN 0
46736 #define PAGER_READER 1
46737 #define PAGER_WRITER_LOCKED 2
46738 #define PAGER_WRITER_CACHEMOD 3
46739 #define PAGER_WRITER_DBMOD 4
46740 #define PAGER_WRITER_FINISHED 5
46741 #define PAGER_ERROR 6
46742 
46743 /*
46744 ** The Pager.eLock variable is almost always set to one of the
46745 ** following locking-states, according to the lock currently held on
46746 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46747 ** This variable is kept up to date as locks are taken and released by
46748 ** the pagerLockDb() and pagerUnlockDb() wrappers.
46749 **
46750 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
46751 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
46752 ** the operation was successful. In these circumstances pagerLockDb() and
46753 ** pagerUnlockDb() take a conservative approach - eLock is always updated
46754 ** when unlocking the file, and only updated when locking the file if the
46755 ** VFS call is successful. This way, the Pager.eLock variable may be set
46756 ** to a less exclusive (lower) value than the lock that is actually held
46757 ** at the system level, but it is never set to a more exclusive value.
46758 **
46759 ** This is usually safe. If an xUnlock fails or appears to fail, there may
46760 ** be a few redundant xLock() calls or a lock may be held for longer than
46761 ** required, but nothing really goes wrong.
46762 **
46763 ** The exception is when the database file is unlocked as the pager moves
46764 ** from ERROR to OPEN state. At this point there may be a hot-journal file
46765 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
46766 ** transition, by the same pager or any other). If the call to xUnlock()
46767 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
46768 ** can confuse the call to xCheckReservedLock() call made later as part
46769 ** of hot-journal detection.
46770 **
46771 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
46772 ** lock held by this process or any others". So xCheckReservedLock may
46773 ** return true because the caller itself is holding an EXCLUSIVE lock (but
46774 ** doesn't know it because of a previous error in xUnlock). If this happens
46775 ** a hot-journal may be mistaken for a journal being created by an active
46776 ** transaction in another process, causing SQLite to read from the database
46777 ** without rolling it back.
46778 **
46779 ** To work around this, if a call to xUnlock() fails when unlocking the
46780 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
46781 ** is only changed back to a real locking state after a successful call
46782 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
46783 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
46784 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
46785 ** lock on the database file before attempting to roll it back. See function
46786 ** PagerSharedLock() for more detail.
46787 **
46788 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
46789 ** PAGER_OPEN state.
46790 */
46791 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
46792 
46793 /*
46794 ** A macro used for invoking the codec if there is one
46795 */
46796 #ifdef SQLITE_HAS_CODEC
46797 # define CODEC1(P,D,N,X,E) \
46798  if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
46799 # define CODEC2(P,D,N,X,E,O) \
46800  if( P->xCodec==0 ){ O=(char*)D; }else \
46801  if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
46802 #else
46803 # define CODEC1(P,D,N,X,E) /* NO-OP */
46804 # define CODEC2(P,D,N,X,E,O) O=(char*)D
46805 #endif
46806 
46807 /*
46808 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
46809 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
46810 ** This could conceivably cause corruption following a power failure on
46811 ** such a system. This is currently an undocumented limit.
46812 */
46813 #define MAX_SECTOR_SIZE 0x10000
46814 
46815 
46816 /*
46817 ** An instance of the following structure is allocated for each active
46818 ** savepoint and statement transaction in the system. All such structures
46819 ** are stored in the Pager.aSavepoint[] array, which is allocated and
46820 ** resized using sqlite3Realloc().
46821 **
46822 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
46823 ** set to 0. If a journal-header is written into the main journal while
46824 ** the savepoint is active, then iHdrOffset is set to the byte offset
46825 ** immediately following the last journal record written into the main
46826 ** journal before the journal-header. This is required during savepoint
46827 ** rollback (see pagerPlaybackSavepoint()).
46828 */
46829 typedef struct PagerSavepoint PagerSavepoint;
46830 struct PagerSavepoint {
46831  i64 iOffset; /* Starting offset in main journal */
46832  i64 iHdrOffset; /* See above */
46833  Bitvec *pInSavepoint; /* Set of pages in this savepoint */
46834  Pgno nOrig; /* Original number of pages in file */
46835  Pgno iSubRec; /* Index of first record in sub-journal */
46836 #ifndef SQLITE_OMIT_WAL
46837  u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
46838 #endif
46839 };
46840 
46841 /*
46842 ** Bits of the Pager.doNotSpill flag. See further description below.
46843 */
46844 #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
46845 #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
46846 #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
46847 
46848 /*
46849 ** An open page cache is an instance of struct Pager. A description of
46850 ** some of the more important member variables follows:
46851 **
46852 ** eState
46853 **
46854 ** The current 'state' of the pager object. See the comment and state
46855 ** diagram above for a description of the pager state.
46856 **
46857 ** eLock
46858 **
46859 ** For a real on-disk database, the current lock held on the database file -
46860 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46861 **
46862 ** For a temporary or in-memory database (neither of which require any
46863 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
46864 ** databases always have Pager.exclusiveMode==1, this tricks the pager
46865 ** logic into thinking that it already has all the locks it will ever
46866 ** need (and no reason to release them).
46867 **
46868 ** In some (obscure) circumstances, this variable may also be set to
46869 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
46870 ** details.
46871 **
46872 ** changeCountDone
46873 **
46874 ** This boolean variable is used to make sure that the change-counter
46875 ** (the 4-byte header field at byte offset 24 of the database file) is
46876 ** not updated more often than necessary.
46877 **
46878 ** It is set to true when the change-counter field is updated, which
46879 ** can only happen if an exclusive lock is held on the database file.
46880 ** It is cleared (set to false) whenever an exclusive lock is
46881 ** relinquished on the database file. Each time a transaction is committed,
46882 ** The changeCountDone flag is inspected. If it is true, the work of
46883 ** updating the change-counter is omitted for the current transaction.
46884 **
46885 ** This mechanism means that when running in exclusive mode, a connection
46886 ** need only update the change-counter once, for the first transaction
46887 ** committed.
46888 **
46889 ** setMaster
46890 **
46891 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
46892 ** (or may not) specify a master-journal name to be written into the
46893 ** journal file before it is synced to disk.
46894 **
46895 ** Whether or not a journal file contains a master-journal pointer affects
46896 ** the way in which the journal file is finalized after the transaction is
46897 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
46898 ** If a journal file does not contain a master-journal pointer, it is
46899 ** finalized by overwriting the first journal header with zeroes. If
46900 ** it does contain a master-journal pointer the journal file is finalized
46901 ** by truncating it to zero bytes, just as if the connection were
46902 ** running in "journal_mode=truncate" mode.
46903 **
46904 ** Journal files that contain master journal pointers cannot be finalized
46905 ** simply by overwriting the first journal-header with zeroes, as the
46906 ** master journal pointer could interfere with hot-journal rollback of any
46907 ** subsequently interrupted transaction that reuses the journal file.
46908 **
46909 ** The flag is cleared as soon as the journal file is finalized (either
46910 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
46911 ** journal file from being successfully finalized, the setMaster flag
46912 ** is cleared anyway (and the pager will move to ERROR state).
46913 **
46914 ** doNotSpill
46915 **
46916 ** This variables control the behavior of cache-spills (calls made by
46917 ** the pcache module to the pagerStress() routine to write cached data
46918 ** to the file-system in order to free up memory).
46919 **
46920 ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
46921 ** writing to the database from pagerStress() is disabled altogether.
46922 ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
46923 ** comes up during savepoint rollback that requires the pcache module
46924 ** to allocate a new page to prevent the journal file from being written
46925 ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
46926 ** case is a user preference.
46927 **
46928 ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
46929 ** pagerStress() is permitted, but syncing the journal file is not.
46930 ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
46931 ** is larger than the database page-size in order to prevent a journal sync
46932 ** from happening in between the journalling of two pages on the same sector.
46933 **
46934 ** subjInMemory
46935 **
46936 ** This is a boolean variable. If true, then any required sub-journal
46937 ** is opened as an in-memory journal file. If false, then in-memory
46938 ** sub-journals are only used for in-memory pager files.
46939 **
46940 ** This variable is updated by the upper layer each time a new
46941 ** write-transaction is opened.
46942 **
46943 ** dbSize, dbOrigSize, dbFileSize
46944 **
46945 ** Variable dbSize is set to the number of pages in the database file.
46946 ** It is valid in PAGER_READER and higher states (all states except for
46947 ** OPEN and ERROR).
46948 **
46949 ** dbSize is set based on the size of the database file, which may be
46950 ** larger than the size of the database (the value stored at offset
46951 ** 28 of the database header by the btree). If the size of the file
46952 ** is not an integer multiple of the page-size, the value stored in
46953 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
46954 ** Except, any file that is greater than 0 bytes in size is considered
46955 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
46956 ** to dbSize==1).
46957 **
46958 ** During a write-transaction, if pages with page-numbers greater than
46959 ** dbSize are modified in the cache, dbSize is updated accordingly.
46960 ** Similarly, if the database is truncated using PagerTruncateImage(),
46961 ** dbSize is updated.
46962 **
46963 ** Variables dbOrigSize and dbFileSize are valid in states
46964 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
46965 ** variable at the start of the transaction. It is used during rollback,
46966 ** and to determine whether or not pages need to be journalled before
46967 ** being modified.
46968 **
46969 ** Throughout a write-transaction, dbFileSize contains the size of
46970 ** the file on disk in pages. It is set to a copy of dbSize when the
46971 ** write-transaction is first opened, and updated when VFS calls are made
46972 ** to write or truncate the database file on disk.
46973 **
46974 ** The only reason the dbFileSize variable is required is to suppress
46975 ** unnecessary calls to xTruncate() after committing a transaction. If,
46976 ** when a transaction is committed, the dbFileSize variable indicates
46977 ** that the database file is larger than the database image (Pager.dbSize),
46978 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
46979 ** to measure the database file on disk, and then truncates it if required.
46980 ** dbFileSize is not used when rolling back a transaction. In this case
46981 ** pager_truncate() is called unconditionally (which means there may be
46982 ** a call to xFilesize() that is not strictly required). In either case,
46983 ** pager_truncate() may cause the file to become smaller or larger.
46984 **
46985 ** dbHintSize
46986 **
46987 ** The dbHintSize variable is used to limit the number of calls made to
46988 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
46989 **
46990 ** dbHintSize is set to a copy of the dbSize variable when a
46991 ** write-transaction is opened (at the same time as dbFileSize and
46992 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
46993 ** dbHintSize is increased to the number of pages that correspond to the
46994 ** size-hint passed to the method call. See pager_write_pagelist() for
46995 ** details.
46996 **
46997 ** errCode
46998 **
46999 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
47000 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
47001 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
47002 ** sub-codes.
47003 */
47004 struct Pager {
47005  sqlite3_vfs *pVfs; /* OS functions to use for IO */
47006  u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
47007  u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
47008  u8 useJournal; /* Use a rollback journal on this file */
47009  u8 noSync; /* Do not sync the journal if true */
47010  u8 fullSync; /* Do extra syncs of the journal for robustness */
47011  u8 extraSync; /* sync directory after journal delete */
47012  u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
47013  u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
47014  u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
47015  u8 tempFile; /* zFilename is a temporary or immutable file */
47016  u8 noLock; /* Do not lock (except in WAL mode) */
47017  u8 readOnly; /* True for a read-only database */
47018  u8 memDb; /* True to inhibit all file I/O */
47019 
47020  /**************************************************************************
47021  ** The following block contains those class members that change during
47022  ** routine operation. Class members not in this block are either fixed
47023  ** when the pager is first created or else only change when there is a
47024  ** significant mode change (such as changing the page_size, locking_mode,
47025  ** or the journal_mode). From another view, these class members describe
47026  ** the "state" of the pager, while other class members describe the
47027  ** "configuration" of the pager.
47028  */
47029  u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
47030  u8 eLock; /* Current lock held on database file */
47031  u8 changeCountDone; /* Set after incrementing the change-counter */
47032  u8 setMaster; /* True if a m-j name has been written to jrnl */
47033  u8 doNotSpill; /* Do not spill the cache when non-zero */
47034  u8 subjInMemory; /* True to use in-memory sub-journals */
47035  u8 bUseFetch; /* True to use xFetch() */
47036  u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
47037  Pgno dbSize; /* Number of pages in the database */
47038  Pgno dbOrigSize; /* dbSize before the current transaction */
47039  Pgno dbFileSize; /* Number of pages in the database file */
47040  Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
47041  int errCode; /* One of several kinds of errors */
47042  int nRec; /* Pages journalled since last j-header written */
47043  u32 cksumInit; /* Quasi-random value added to every checksum */
47044  u32 nSubRec; /* Number of records written to sub-journal */
47045  Bitvec *pInJournal; /* One bit for each page in the database file */
47046  sqlite3_file *fd; /* File descriptor for database */
47047  sqlite3_file *jfd; /* File descriptor for main journal */
47048  sqlite3_file *sjfd; /* File descriptor for sub-journal */
47049  i64 journalOff; /* Current write offset in the journal file */
47050  i64 journalHdr; /* Byte offset to previous journal header */
47051  sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
47052  PagerSavepoint *aSavepoint; /* Array of active savepoints */
47053  int nSavepoint; /* Number of elements in aSavepoint[] */
47054  u32 iDataVersion; /* Changes whenever database content changes */
47055  char dbFileVers[16]; /* Changes whenever database file changes */
47056 
47057  int nMmapOut; /* Number of mmap pages currently outstanding */
47058  sqlite3_int64 szMmap; /* Desired maximum mmap size */
47059  PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
47060  /*
47061  ** End of the routinely-changing class members
47062  ***************************************************************************/
47063 
47064  u16 nExtra; /* Add this many bytes to each in-memory page */
47065  i16 nReserve; /* Number of unused bytes at end of each page */
47066  u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
47067  u32 sectorSize; /* Assumed sector size during rollback */
47068  int pageSize; /* Number of bytes in a page */
47069  Pgno mxPgno; /* Maximum allowed size of the database */
47070  i64 journalSizeLimit; /* Size limit for persistent journal files */
47071  char *zFilename; /* Name of the database file */
47072  char *zJournal; /* Name of the journal file */
47073  int (*xBusyHandler)(void*); /* Function to call when busy */
47074  void *pBusyHandlerArg; /* Context argument for xBusyHandler */
47075  int aStat[3]; /* Total cache hits, misses and writes */
47076 #ifdef SQLITE_TEST
47077  int nRead; /* Database pages read */
47078 #endif
47079  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
47080 #ifdef SQLITE_HAS_CODEC
47081  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
47082  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
47083  void (*xCodecFree)(void*); /* Destructor for the codec */
47084  void *pCodec; /* First argument to xCodec... methods */
47085 #endif
47086  char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
47087  PCache *pPCache; /* Pointer to page cache object */
47088 #ifndef SQLITE_OMIT_WAL
47089  Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
47090  char *zWal; /* File name for write-ahead log */
47091 #endif
47092 };
47093 
47094 /*
47095 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
47096 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
47097 ** or CACHE_WRITE to sqlite3_db_status().
47098 */
47099 #define PAGER_STAT_HIT 0
47100 #define PAGER_STAT_MISS 1
47101 #define PAGER_STAT_WRITE 2
47102 
47103 /*
47104 ** The following global variables hold counters used for
47105 ** testing purposes only. These variables do not exist in
47106 ** a non-testing build. These variables are not thread-safe.
47107 */
47108 #ifdef SQLITE_TEST
47109 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
47110 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
47111 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
47112 # define PAGER_INCR(v) v++
47113 #else
47114 # define PAGER_INCR(v)
47115 #endif
47116 
47117 
47118 
47119 /*
47120 ** Journal files begin with the following magic string. The data
47121 ** was obtained from /dev/random. It is used only as a sanity check.
47122 **
47123 ** Since version 2.8.0, the journal format contains additional sanity
47124 ** checking information. If the power fails while the journal is being
47125 ** written, semi-random garbage data might appear in the journal
47126 ** file after power is restored. If an attempt is then made
47127 ** to roll the journal back, the database could be corrupted. The additional
47128 ** sanity checking data is an attempt to discover the garbage in the
47129 ** journal and ignore it.
47130 **
47131 ** The sanity checking information for the new journal format consists
47132 ** of a 32-bit checksum on each page of data. The checksum covers both
47133 ** the page number and the pPager->pageSize bytes of data for the page.
47134 ** This cksum is initialized to a 32-bit random value that appears in the
47135 ** journal file right after the header. The random initializer is important,
47136 ** because garbage data that appears at the end of a journal is likely
47137 ** data that was once in other files that have now been deleted. If the
47138 ** garbage data came from an obsolete journal file, the checksums might
47139 ** be correct. But by initializing the checksum to random value which
47140 ** is different for every journal, we minimize that risk.
47141 */
47142 static const unsigned char aJournalMagic[] = {
47143  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
47144 };
47145 
47146 /*
47147 ** The size of the of each page record in the journal is given by
47148 ** the following macro.
47149 */
47150 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
47151 
47152 /*
47153 ** The journal header size for this pager. This is usually the same
47154 ** size as a single disk sector. See also setSectorSize().
47155 */
47156 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
47157 
47158 /*
47159 ** The macro MEMDB is true if we are dealing with an in-memory database.
47160 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
47161 ** the value of MEMDB will be a constant and the compiler will optimize
47162 ** out code that would never execute.
47163 */
47164 #ifdef SQLITE_OMIT_MEMORYDB
47165 # define MEMDB 0
47166 #else
47167 # define MEMDB pPager->memDb
47168 #endif
47169 
47170 /*
47171 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
47172 ** interfaces to access the database using memory-mapped I/O.
47173 */
47174 #if SQLITE_MAX_MMAP_SIZE>0
47175 # define USEFETCH(x) ((x)->bUseFetch)
47176 #else
47177 # define USEFETCH(x) 0
47178 #endif
47179 
47180 /*
47181 ** The maximum legal page number is (2^31 - 1).
47182 */
47183 #define PAGER_MAX_PGNO 2147483647
47184 
47185 /*
47186 ** The argument to this macro is a file descriptor (type sqlite3_file*).
47187 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
47188 **
47189 ** This is so that expressions can be written as:
47190 **
47191 ** if( isOpen(pPager->jfd) ){ ...
47192 **
47193 ** instead of
47194 **
47195 ** if( pPager->jfd->pMethods ){ ...
47196 */
47197 #define isOpen(pFd) ((pFd)->pMethods!=0)
47198 
47199 /*
47200 ** Return true if this pager uses a write-ahead log instead of the usual
47201 ** rollback journal. Otherwise false.
47202 */
47203 #ifndef SQLITE_OMIT_WAL
47204 SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager){
47205  return (pPager->pWal!=0);
47206 }
47207 # define pagerUseWal(x) sqlite3PagerUseWal(x)
47208 #else
47209 # define pagerUseWal(x) 0
47210 # define pagerRollbackWal(x) 0
47211 # define pagerWalFrames(v,w,x,y) 0
47212 # define pagerOpenWalIfPresent(z) SQLITE_OK
47213 # define pagerBeginReadTransaction(z) SQLITE_OK
47214 #endif
47215 
47216 #ifndef NDEBUG
47217 /*
47218 ** Usage:
47219 **
47220 ** assert( assert_pager_state(pPager) );
47221 **
47222 ** This function runs many asserts to try to find inconsistencies in
47223 ** the internal state of the Pager object.
47224 */
47225 static int assert_pager_state(Pager *p){
47226  Pager *pPager = p;
47227 
47228  /* State must be valid. */
47229  assert( p->eState==PAGER_OPEN
47230  || p->eState==PAGER_READER
47231  || p->eState==PAGER_WRITER_LOCKED
47232  || p->eState==PAGER_WRITER_CACHEMOD
47233  || p->eState==PAGER_WRITER_DBMOD
47234  || p->eState==PAGER_WRITER_FINISHED
47235  || p->eState==PAGER_ERROR
47236  );
47237 
47238  /* Regardless of the current state, a temp-file connection always behaves
47239  ** as if it has an exclusive lock on the database file. It never updates
47240  ** the change-counter field, so the changeCountDone flag is always set.
47241  */
47242  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
47243  assert( p->tempFile==0 || pPager->changeCountDone );
47244 
47245  /* If the useJournal flag is clear, the journal-mode must be "OFF".
47246  ** And if the journal-mode is "OFF", the journal file must not be open.
47247  */
47248  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
47249  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
47250 
47251  /* Check that MEMDB implies noSync. And an in-memory journal. Since
47252  ** this means an in-memory pager performs no IO at all, it cannot encounter
47253  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
47254  ** a journal file. (although the in-memory journal implementation may
47255  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
47256  ** is therefore not possible for an in-memory pager to enter the ERROR
47257  ** state.
47258  */
47259  if( MEMDB ){
47260  assert( !isOpen(p->fd) );
47261  assert( p->noSync );
47262  assert( p->journalMode==PAGER_JOURNALMODE_OFF
47263  || p->journalMode==PAGER_JOURNALMODE_MEMORY
47264  );
47265  assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
47266  assert( pagerUseWal(p)==0 );
47267  }
47268 
47269  /* If changeCountDone is set, a RESERVED lock or greater must be held
47270  ** on the file.
47271  */
47272  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
47273  assert( p->eLock!=PENDING_LOCK );
47274 
47275  switch( p->eState ){
47276  case PAGER_OPEN:
47277  assert( !MEMDB );
47278  assert( pPager->errCode==SQLITE_OK );
47279  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
47280  break;
47281 
47282  case PAGER_READER:
47283  assert( pPager->errCode==SQLITE_OK );
47284  assert( p->eLock!=UNKNOWN_LOCK );
47285  assert( p->eLock>=SHARED_LOCK );
47286  break;
47287 
47288  case PAGER_WRITER_LOCKED:
47289  assert( p->eLock!=UNKNOWN_LOCK );
47290  assert( pPager->errCode==SQLITE_OK );
47291  if( !pagerUseWal(pPager) ){
47292  assert( p->eLock>=RESERVED_LOCK );
47293  }
47294  assert( pPager->dbSize==pPager->dbOrigSize );
47295  assert( pPager->dbOrigSize==pPager->dbFileSize );
47296  assert( pPager->dbOrigSize==pPager->dbHintSize );
47297  assert( pPager->setMaster==0 );
47298  break;
47299 
47300  case PAGER_WRITER_CACHEMOD:
47301  assert( p->eLock!=UNKNOWN_LOCK );
47302  assert( pPager->errCode==SQLITE_OK );
47303  if( !pagerUseWal(pPager) ){
47304  /* It is possible that if journal_mode=wal here that neither the
47305  ** journal file nor the WAL file are open. This happens during
47306  ** a rollback transaction that switches from journal_mode=off
47307  ** to journal_mode=wal.
47308  */
47309  assert( p->eLock>=RESERVED_LOCK );
47310  assert( isOpen(p->jfd)
47311  || p->journalMode==PAGER_JOURNALMODE_OFF
47312  || p->journalMode==PAGER_JOURNALMODE_WAL
47313  );
47314  }
47315  assert( pPager->dbOrigSize==pPager->dbFileSize );
47316  assert( pPager->dbOrigSize==pPager->dbHintSize );
47317  break;
47318 
47319  case PAGER_WRITER_DBMOD:
47320  assert( p->eLock==EXCLUSIVE_LOCK );
47321  assert( pPager->errCode==SQLITE_OK );
47322  assert( !pagerUseWal(pPager) );
47323  assert( p->eLock>=EXCLUSIVE_LOCK );
47324  assert( isOpen(p->jfd)
47325  || p->journalMode==PAGER_JOURNALMODE_OFF
47326  || p->journalMode==PAGER_JOURNALMODE_WAL
47327  );
47328  assert( pPager->dbOrigSize<=pPager->dbHintSize );
47329  break;
47330 
47331  case PAGER_WRITER_FINISHED:
47332  assert( p->eLock==EXCLUSIVE_LOCK );
47333  assert( pPager->errCode==SQLITE_OK );
47334  assert( !pagerUseWal(pPager) );
47335  assert( isOpen(p->jfd)
47336  || p->journalMode==PAGER_JOURNALMODE_OFF
47337  || p->journalMode==PAGER_JOURNALMODE_WAL
47338  );
47339  break;
47340 
47341  case PAGER_ERROR:
47342  /* There must be at least one outstanding reference to the pager if
47343  ** in ERROR state. Otherwise the pager should have already dropped
47344  ** back to OPEN state.
47345  */
47346  assert( pPager->errCode!=SQLITE_OK );
47347  assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
47348  break;
47349  }
47350 
47351  return 1;
47352 }
47353 #endif /* ifndef NDEBUG */
47354 
47355 #ifdef SQLITE_DEBUG
47356 /*
47357 ** Return a pointer to a human readable string in a static buffer
47358 ** containing the state of the Pager object passed as an argument. This
47359 ** is intended to be used within debuggers. For example, as an alternative
47360 ** to "print *pPager" in gdb:
47361 **
47362 ** (gdb) printf "%s", print_pager_state(pPager)
47363 */
47364 static char *print_pager_state(Pager *p){
47365  static char zRet[1024];
47366 
47367  sqlite3_snprintf(1024, zRet,
47368  "Filename: %s\n"
47369  "State: %s errCode=%d\n"
47370  "Lock: %s\n"
47371  "Locking mode: locking_mode=%s\n"
47372  "Journal mode: journal_mode=%s\n"
47373  "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
47374  "Journal: journalOff=%lld journalHdr=%lld\n"
47375  "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
47376  , p->zFilename
47377  , p->eState==PAGER_OPEN ? "OPEN" :
47378  p->eState==PAGER_READER ? "READER" :
47379  p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
47380  p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
47381  p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
47382  p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
47383  p->eState==PAGER_ERROR ? "ERROR" : "?error?"
47384  , (int)p->errCode
47385  , p->eLock==NO_LOCK ? "NO_LOCK" :
47386  p->eLock==RESERVED_LOCK ? "RESERVED" :
47387  p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
47388  p->eLock==SHARED_LOCK ? "SHARED" :
47389  p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
47390  , p->exclusiveMode ? "exclusive" : "normal"
47391  , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
47392  p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
47393  p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
47394  p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
47395  p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
47396  p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
47397  , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
47398  , p->journalOff, p->journalHdr
47399  , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
47400  );
47401 
47402  return zRet;
47403 }
47404 #endif
47405 
47406 /*
47407 ** Return true if it is necessary to write page *pPg into the sub-journal.
47408 ** A page needs to be written into the sub-journal if there exists one
47409 ** or more open savepoints for which:
47410 **
47411 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
47412 ** * The bit corresponding to the page-number is not set in
47413 ** PagerSavepoint.pInSavepoint.
47414 */
47415 static int subjRequiresPage(PgHdr *pPg){
47416  Pager *pPager = pPg->pPager;
47417  PagerSavepoint *p;
47418  Pgno pgno = pPg->pgno;
47419  int i;
47420  for(i=0; i<pPager->nSavepoint; i++){
47421  p = &pPager->aSavepoint[i];
47422  if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
47423  return 1;
47424  }
47425  }
47426  return 0;
47427 }
47428 
47429 #ifdef SQLITE_DEBUG
47430 /*
47431 ** Return true if the page is already in the journal file.
47432 */
47433 static int pageInJournal(Pager *pPager, PgHdr *pPg){
47434  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
47435 }
47436 #endif
47437 
47438 /*
47439 ** Read a 32-bit integer from the given file descriptor. Store the integer
47440 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
47441 ** error code is something goes wrong.
47442 **
47443 ** All values are stored on disk as big-endian.
47444 */
47445 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
47446  unsigned char ac[4];
47447  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
47448  if( rc==SQLITE_OK ){
47449  *pRes = sqlite3Get4byte(ac);
47450  }
47451  return rc;
47452 }
47453 
47454 /*
47455 ** Write a 32-bit integer into a string buffer in big-endian byte order.
47456 */
47457 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
47458 
47459 
47460 /*
47461 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
47462 ** on success or an error code is something goes wrong.
47463 */
47464 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
47465  char ac[4];
47466  put32bits(ac, val);
47467  return sqlite3OsWrite(fd, ac, 4, offset);
47468 }
47469 
47470 /*
47471 ** Unlock the database file to level eLock, which must be either NO_LOCK
47472 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
47473 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
47474 **
47475 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47476 ** called, do not modify it. See the comment above the #define of
47477 ** UNKNOWN_LOCK for an explanation of this.
47478 */
47479 static int pagerUnlockDb(Pager *pPager, int eLock){
47480  int rc = SQLITE_OK;
47481 
47482  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
47483  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
47484  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
47485  if( isOpen(pPager->fd) ){
47486  assert( pPager->eLock>=eLock );
47487  rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
47488  if( pPager->eLock!=UNKNOWN_LOCK ){
47489  pPager->eLock = (u8)eLock;
47490  }
47491  IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
47492  }
47493  return rc;
47494 }
47495 
47496 /*
47497 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
47498 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
47499 ** Pager.eLock variable to the new locking state.
47500 **
47501 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47502 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
47503 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
47504 ** of this.
47505 */
47506 static int pagerLockDb(Pager *pPager, int eLock){
47507  int rc = SQLITE_OK;
47508 
47509  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
47510  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
47511  rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
47512  if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
47513  pPager->eLock = (u8)eLock;
47514  IOTRACE(("LOCK %p %d\n", pPager, eLock))
47515  }
47516  }
47517  return rc;
47518 }
47519 
47520 /*
47521 ** This function determines whether or not the atomic-write optimization
47522 ** can be used with this pager. The optimization can be used if:
47523 **
47524 ** (a) the value returned by OsDeviceCharacteristics() indicates that
47525 ** a database page may be written atomically, and
47526 ** (b) the value returned by OsSectorSize() is less than or equal
47527 ** to the page size.
47528 **
47529 ** The optimization is also always enabled for temporary files. It is
47530 ** an error to call this function if pPager is opened on an in-memory
47531 ** database.
47532 **
47533 ** If the optimization cannot be used, 0 is returned. If it can be used,
47534 ** then the value returned is the size of the journal file when it
47535 ** contains rollback data for exactly one page.
47536 */
47537 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47538 static int jrnlBufferSize(Pager *pPager){
47539  assert( !MEMDB );
47540  if( !pPager->tempFile ){
47541  int dc; /* Device characteristics */
47542  int nSector; /* Sector size */
47543  int szPage; /* Page size */
47544 
47545  assert( isOpen(pPager->fd) );
47546  dc = sqlite3OsDeviceCharacteristics(pPager->fd);
47547  nSector = pPager->sectorSize;
47548  szPage = pPager->pageSize;
47549 
47550  assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
47551  assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
47552  if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
47553  return 0;
47554  }
47555  }
47556 
47557  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
47558 }
47559 #else
47560 # define jrnlBufferSize(x) 0
47561 #endif
47562 
47563 /*
47564 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
47565 ** on the cache using a hash function. This is used for testing
47566 ** and debugging only.
47567 */
47568 #ifdef SQLITE_CHECK_PAGES
47569 /*
47570 ** Return a 32-bit hash of the page data for pPage.
47571 */
47572 static u32 pager_datahash(int nByte, unsigned char *pData){
47573  u32 hash = 0;
47574  int i;
47575  for(i=0; i<nByte; i++){
47576  hash = (hash*1039) + pData[i];
47577  }
47578  return hash;
47579 }
47580 static u32 pager_pagehash(PgHdr *pPage){
47581  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
47582 }
47583 static void pager_set_pagehash(PgHdr *pPage){
47584  pPage->pageHash = pager_pagehash(pPage);
47585 }
47586 
47587 /*
47588 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
47589 ** is defined, and NDEBUG is not defined, an assert() statement checks
47590 ** that the page is either dirty or still matches the calculated page-hash.
47591 */
47592 #define CHECK_PAGE(x) checkPage(x)
47593 static void checkPage(PgHdr *pPg){
47594  Pager *pPager = pPg->pPager;
47595  assert( pPager->eState!=PAGER_ERROR );
47596  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
47597 }
47598 
47599 #else
47600 #define pager_datahash(X,Y) 0
47601 #define pager_pagehash(X) 0
47602 #define pager_set_pagehash(X)
47603 #define CHECK_PAGE(x)
47604 #endif /* SQLITE_CHECK_PAGES */
47605 
47606 /*
47607 ** When this is called the journal file for pager pPager must be open.
47608 ** This function attempts to read a master journal file name from the
47609 ** end of the file and, if successful, copies it into memory supplied
47610 ** by the caller. See comments above writeMasterJournal() for the format
47611 ** used to store a master journal file name at the end of a journal file.
47612 **
47613 ** zMaster must point to a buffer of at least nMaster bytes allocated by
47614 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
47615 ** enough space to write the master journal name). If the master journal
47616 ** name in the journal is longer than nMaster bytes (including a
47617 ** nul-terminator), then this is handled as if no master journal name
47618 ** were present in the journal.
47619 **
47620 ** If a master journal file name is present at the end of the journal
47621 ** file, then it is copied into the buffer pointed to by zMaster. A
47622 ** nul-terminator byte is appended to the buffer following the master
47623 ** journal file name.
47624 **
47625 ** If it is determined that no master journal file name is present
47626 ** zMaster[0] is set to 0 and SQLITE_OK returned.
47627 **
47628 ** If an error occurs while reading from the journal file, an SQLite
47629 ** error code is returned.
47630 */
47631 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
47632  int rc; /* Return code */
47633  u32 len; /* Length in bytes of master journal name */
47634  i64 szJ; /* Total size in bytes of journal file pJrnl */
47635  u32 cksum; /* MJ checksum value read from journal */
47636  u32 u; /* Unsigned loop counter */
47637  unsigned char aMagic[8]; /* A buffer to hold the magic header */
47638  zMaster[0] = '\0';
47639 
47640  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
47641  || szJ<16
47642  || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
47643  || len>=nMaster
47644  || len==0
47645  || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
47646  || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
47647  || memcmp(aMagic, aJournalMagic, 8)
47648  || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
47649  ){
47650  return rc;
47651  }
47652 
47653  /* See if the checksum matches the master journal name */
47654  for(u=0; u<len; u++){
47655  cksum -= zMaster[u];
47656  }
47657  if( cksum ){
47658  /* If the checksum doesn't add up, then one or more of the disk sectors
47659  ** containing the master journal filename is corrupted. This means
47660  ** definitely roll back, so just return SQLITE_OK and report a (nul)
47661  ** master-journal filename.
47662  */
47663  len = 0;
47664  }
47665  zMaster[len] = '\0';
47666 
47667  return SQLITE_OK;
47668 }
47669 
47670 /*
47671 ** Return the offset of the sector boundary at or immediately
47672 ** following the value in pPager->journalOff, assuming a sector
47673 ** size of pPager->sectorSize bytes.
47674 **
47675 ** i.e for a sector size of 512:
47676 **
47677 ** Pager.journalOff Return value
47678 ** ---------------------------------------
47679 ** 0 0
47680 ** 512 512
47681 ** 100 512
47682 ** 2000 2048
47683 **
47684 */
47685 static i64 journalHdrOffset(Pager *pPager){
47686  i64 offset = 0;
47687  i64 c = pPager->journalOff;
47688  if( c ){
47689  offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
47690  }
47691  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
47692  assert( offset>=c );
47693  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
47694  return offset;
47695 }
47696 
47697 /*
47698 ** The journal file must be open when this function is called.
47699 **
47700 ** This function is a no-op if the journal file has not been written to
47701 ** within the current transaction (i.e. if Pager.journalOff==0).
47702 **
47703 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
47704 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
47705 ** zero the 28-byte header at the start of the journal file. In either case,
47706 ** if the pager is not in no-sync mode, sync the journal file immediately
47707 ** after writing or truncating it.
47708 **
47709 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
47710 ** following the truncation or zeroing described above the size of the
47711 ** journal file in bytes is larger than this value, then truncate the
47712 ** journal file to Pager.journalSizeLimit bytes. The journal file does
47713 ** not need to be synced following this operation.
47714 **
47715 ** If an IO error occurs, abandon processing and return the IO error code.
47716 ** Otherwise, return SQLITE_OK.
47717 */
47718 static int zeroJournalHdr(Pager *pPager, int doTruncate){
47719  int rc = SQLITE_OK; /* Return code */
47720  assert( isOpen(pPager->jfd) );
47721  assert( !sqlite3JournalIsInMemory(pPager->jfd) );
47722  if( pPager->journalOff ){
47723  const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
47724 
47725  IOTRACE(("JZEROHDR %p\n", pPager))
47726  if( doTruncate || iLimit==0 ){
47727  rc = sqlite3OsTruncate(pPager->jfd, 0);
47728  }else{
47729  static const char zeroHdr[28] = {0};
47730  rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
47731  }
47732  if( rc==SQLITE_OK && !pPager->noSync ){
47733  rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
47734  }
47735 
47736  /* At this point the transaction is committed but the write lock
47737  ** is still held on the file. If there is a size limit configured for
47738  ** the persistent journal and the journal file currently consumes more
47739  ** space than that limit allows for, truncate it now. There is no need
47740  ** to sync the file following this operation.
47741  */
47742  if( rc==SQLITE_OK && iLimit>0 ){
47743  i64 sz;
47744  rc = sqlite3OsFileSize(pPager->jfd, &sz);
47745  if( rc==SQLITE_OK && sz>iLimit ){
47746  rc = sqlite3OsTruncate(pPager->jfd, iLimit);
47747  }
47748  }
47749  }
47750  return rc;
47751 }
47752 
47753 /*
47754 ** The journal file must be open when this routine is called. A journal
47755 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
47756 ** current location.
47757 **
47758 ** The format for the journal header is as follows:
47759 ** - 8 bytes: Magic identifying journal format.
47760 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
47761 ** - 4 bytes: Random number used for page hash.
47762 ** - 4 bytes: Initial database page count.
47763 ** - 4 bytes: Sector size used by the process that wrote this journal.
47764 ** - 4 bytes: Database page size.
47765 **
47766 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
47767 */
47768 static int writeJournalHdr(Pager *pPager){
47769  int rc = SQLITE_OK; /* Return code */
47770  char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
47771  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
47772  u32 nWrite; /* Bytes of header sector written */
47773  int ii; /* Loop counter */
47774 
47775  assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
47776 
47777  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
47778  nHeader = JOURNAL_HDR_SZ(pPager);
47779  }
47780 
47781  /* If there are active savepoints and any of them were created
47782  ** since the most recent journal header was written, update the
47783  ** PagerSavepoint.iHdrOffset fields now.
47784  */
47785  for(ii=0; ii<pPager->nSavepoint; ii++){
47786  if( pPager->aSavepoint[ii].iHdrOffset==0 ){
47787  pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
47788  }
47789  }
47790 
47791  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
47792 
47793  /*
47794  ** Write the nRec Field - the number of page records that follow this
47795  ** journal header. Normally, zero is written to this value at this time.
47796  ** After the records are added to the journal (and the journal synced,
47797  ** if in full-sync mode), the zero is overwritten with the true number
47798  ** of records (see syncJournal()).
47799  **
47800  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
47801  ** reading the journal this value tells SQLite to assume that the
47802  ** rest of the journal file contains valid page records. This assumption
47803  ** is dangerous, as if a failure occurred whilst writing to the journal
47804  ** file it may contain some garbage data. There are two scenarios
47805  ** where this risk can be ignored:
47806  **
47807  ** * When the pager is in no-sync mode. Corruption can follow a
47808  ** power failure in this case anyway.
47809  **
47810  ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
47811  ** that garbage data is never appended to the journal file.
47812  */
47813  assert( isOpen(pPager->fd) || pPager->noSync );
47814  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
47815  || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
47816  ){
47817  memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
47818  put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
47819  }else{
47820  memset(zHeader, 0, sizeof(aJournalMagic)+4);
47821  }
47822 
47823  /* The random check-hash initializer */
47824  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
47825  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
47826  /* The initial database size */
47827  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
47828  /* The assumed sector size for this process */
47829  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
47830 
47831  /* The page size */
47832  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
47833 
47834  /* Initializing the tail of the buffer is not necessary. Everything
47835  ** works find if the following memset() is omitted. But initializing
47836  ** the memory prevents valgrind from complaining, so we are willing to
47837  ** take the performance hit.
47838  */
47839  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
47840  nHeader-(sizeof(aJournalMagic)+20));
47841 
47842  /* In theory, it is only necessary to write the 28 bytes that the
47843  ** journal header consumes to the journal file here. Then increment the
47844  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
47845  ** record is written to the following sector (leaving a gap in the file
47846  ** that will be implicitly filled in by the OS).
47847  **
47848  ** However it has been discovered that on some systems this pattern can
47849  ** be significantly slower than contiguously writing data to the file,
47850  ** even if that means explicitly writing data to the block of
47851  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
47852  ** is done.
47853  **
47854  ** The loop is required here in case the sector-size is larger than the
47855  ** database page size. Since the zHeader buffer is only Pager.pageSize
47856  ** bytes in size, more than one call to sqlite3OsWrite() may be required
47857  ** to populate the entire journal header sector.
47858  */
47859  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
47860  IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
47861  rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
47862  assert( pPager->journalHdr <= pPager->journalOff );
47863  pPager->journalOff += nHeader;
47864  }
47865 
47866  return rc;
47867 }
47868 
47869 /*
47870 ** The journal file must be open when this is called. A journal header file
47871 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
47872 ** file. The current location in the journal file is given by
47873 ** pPager->journalOff. See comments above function writeJournalHdr() for
47874 ** a description of the journal header format.
47875 **
47876 ** If the header is read successfully, *pNRec is set to the number of
47877 ** page records following this header and *pDbSize is set to the size of the
47878 ** database before the transaction began, in pages. Also, pPager->cksumInit
47879 ** is set to the value read from the journal header. SQLITE_OK is returned
47880 ** in this case.
47881 **
47882 ** If the journal header file appears to be corrupted, SQLITE_DONE is
47883 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
47884 ** cannot be read from the journal file an error code is returned.
47885 */
47886 static int readJournalHdr(
47887  Pager *pPager, /* Pager object */
47888  int isHot,
47889  i64 journalSize, /* Size of the open journal file in bytes */
47890  u32 *pNRec, /* OUT: Value read from the nRec field */
47891  u32 *pDbSize /* OUT: Value of original database size field */
47892 ){
47893  int rc; /* Return code */
47894  unsigned char aMagic[8]; /* A buffer to hold the magic header */
47895  i64 iHdrOff; /* Offset of journal header being read */
47896 
47897  assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
47898 
47899  /* Advance Pager.journalOff to the start of the next sector. If the
47900  ** journal file is too small for there to be a header stored at this
47901  ** point, return SQLITE_DONE.
47902  */
47903  pPager->journalOff = journalHdrOffset(pPager);
47904  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
47905  return SQLITE_DONE;
47906  }
47907  iHdrOff = pPager->journalOff;
47908 
47909  /* Read in the first 8 bytes of the journal header. If they do not match
47910  ** the magic string found at the start of each journal header, return
47911  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
47912  ** proceed.
47913  */
47914  if( isHot || iHdrOff!=pPager->journalHdr ){
47915  rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
47916  if( rc ){
47917  return rc;
47918  }
47919  if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
47920  return SQLITE_DONE;
47921  }
47922  }
47923 
47924  /* Read the first three 32-bit fields of the journal header: The nRec
47925  ** field, the checksum-initializer and the database size at the start
47926  ** of the transaction. Return an error code if anything goes wrong.
47927  */
47928  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
47929  || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
47930  || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
47931  ){
47932  return rc;
47933  }
47934 
47935  if( pPager->journalOff==0 ){
47936  u32 iPageSize; /* Page-size field of journal header */
47937  u32 iSectorSize; /* Sector-size field of journal header */
47938 
47939  /* Read the page-size and sector-size journal header fields. */
47940  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
47941  || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
47942  ){
47943  return rc;
47944  }
47945 
47946  /* Versions of SQLite prior to 3.5.8 set the page-size field of the
47947  ** journal header to zero. In this case, assume that the Pager.pageSize
47948  ** variable is already set to the correct page size.
47949  */
47950  if( iPageSize==0 ){
47951  iPageSize = pPager->pageSize;
47952  }
47953 
47954  /* Check that the values read from the page-size and sector-size fields
47955  ** are within range. To be 'in range', both values need to be a power
47956  ** of two greater than or equal to 512 or 32, and not greater than their
47957  ** respective compile time maximum limits.
47958  */
47959  if( iPageSize<512 || iSectorSize<32
47960  || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
47961  || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
47962  ){
47963  /* If the either the page-size or sector-size in the journal-header is
47964  ** invalid, then the process that wrote the journal-header must have
47965  ** crashed before the header was synced. In this case stop reading
47966  ** the journal file here.
47967  */
47968  return SQLITE_DONE;
47969  }
47970 
47971  /* Update the page-size to match the value read from the journal.
47972  ** Use a testcase() macro to make sure that malloc failure within
47973  ** PagerSetPagesize() is tested.
47974  */
47975  rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
47976  testcase( rc!=SQLITE_OK );
47977 
47978  /* Update the assumed sector-size to match the value used by
47979  ** the process that created this journal. If this journal was
47980  ** created by a process other than this one, then this routine
47981  ** is being called from within pager_playback(). The local value
47982  ** of Pager.sectorSize is restored at the end of that routine.
47983  */
47984  pPager->sectorSize = iSectorSize;
47985  }
47986 
47987  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
47988  return rc;
47989 }
47990 
47991 
47992 /*
47993 ** Write the supplied master journal name into the journal file for pager
47994 ** pPager at the current location. The master journal name must be the last
47995 ** thing written to a journal file. If the pager is in full-sync mode, the
47996 ** journal file descriptor is advanced to the next sector boundary before
47997 ** anything is written. The format is:
47998 **
47999 ** + 4 bytes: PAGER_MJ_PGNO.
48000 ** + N bytes: Master journal filename in utf-8.
48001 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
48002 ** + 4 bytes: Master journal name checksum.
48003 ** + 8 bytes: aJournalMagic[].
48004 **
48005 ** The master journal page checksum is the sum of the bytes in the master
48006 ** journal name, where each byte is interpreted as a signed 8-bit integer.
48007 **
48008 ** If zMaster is a NULL pointer (occurs for a single database transaction),
48009 ** this call is a no-op.
48010 */
48011 static int writeMasterJournal(Pager *pPager, const char *zMaster){
48012  int rc; /* Return code */
48013  int nMaster; /* Length of string zMaster */
48014  i64 iHdrOff; /* Offset of header in journal file */
48015  i64 jrnlSize; /* Size of journal file on disk */
48016  u32 cksum = 0; /* Checksum of string zMaster */
48017 
48018  assert( pPager->setMaster==0 );
48019  assert( !pagerUseWal(pPager) );
48020 
48021  if( !zMaster
48022  || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
48023  || !isOpen(pPager->jfd)
48024  ){
48025  return SQLITE_OK;
48026  }
48027  pPager->setMaster = 1;
48028  assert( pPager->journalHdr <= pPager->journalOff );
48029 
48030  /* Calculate the length in bytes and the checksum of zMaster */
48031  for(nMaster=0; zMaster[nMaster]; nMaster++){
48032  cksum += zMaster[nMaster];
48033  }
48034 
48035  /* If in full-sync mode, advance to the next disk sector before writing
48036  ** the master journal name. This is in case the previous page written to
48037  ** the journal has already been synced.
48038  */
48039  if( pPager->fullSync ){
48040  pPager->journalOff = journalHdrOffset(pPager);
48041  }
48042  iHdrOff = pPager->journalOff;
48043 
48044  /* Write the master journal data to the end of the journal file. If
48045  ** an error occurs, return the error code to the caller.
48046  */
48047  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
48048  || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
48049  || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
48050  || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
48051  || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
48052  iHdrOff+4+nMaster+8)))
48053  ){
48054  return rc;
48055  }
48056  pPager->journalOff += (nMaster+20);
48057 
48058  /* If the pager is in peristent-journal mode, then the physical
48059  ** journal-file may extend past the end of the master-journal name
48060  ** and 8 bytes of magic data just written to the file. This is
48061  ** dangerous because the code to rollback a hot-journal file
48062  ** will not be able to find the master-journal name to determine
48063  ** whether or not the journal is hot.
48064  **
48065  ** Easiest thing to do in this scenario is to truncate the journal
48066  ** file to the required size.
48067  */
48068  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
48069  && jrnlSize>pPager->journalOff
48070  ){
48071  rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
48072  }
48073  return rc;
48074 }
48075 
48076 /*
48077 ** Discard the entire contents of the in-memory page-cache.
48078 */
48079 static void pager_reset(Pager *pPager){
48080  pPager->iDataVersion++;
48081  sqlite3BackupRestart(pPager->pBackup);
48082  sqlite3PcacheClear(pPager->pPCache);
48083 }
48084 
48085 /*
48086 ** Return the pPager->iDataVersion value
48087 */
48088 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
48089  assert( pPager->eState>PAGER_OPEN );
48090  return pPager->iDataVersion;
48091 }
48092 
48093 /*
48094 ** Free all structures in the Pager.aSavepoint[] array and set both
48095 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
48096 ** if it is open and the pager is not in exclusive mode.
48097 */
48098 static void releaseAllSavepoints(Pager *pPager){
48099  int ii; /* Iterator for looping through Pager.aSavepoint */
48100  for(ii=0; ii<pPager->nSavepoint; ii++){
48101  sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
48102  }
48103  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
48104  sqlite3OsClose(pPager->sjfd);
48105  }
48106  sqlite3_free(pPager->aSavepoint);
48107  pPager->aSavepoint = 0;
48108  pPager->nSavepoint = 0;
48109  pPager->nSubRec = 0;
48110 }
48111 
48112 /*
48113 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
48114 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
48115 ** or SQLITE_NOMEM if a malloc failure occurs.
48116 */
48117 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
48118  int ii; /* Loop counter */
48119  int rc = SQLITE_OK; /* Result code */
48120 
48121  for(ii=0; ii<pPager->nSavepoint; ii++){
48122  PagerSavepoint *p = &pPager->aSavepoint[ii];
48123  if( pgno<=p->nOrig ){
48124  rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
48125  testcase( rc==SQLITE_NOMEM );
48126  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
48127  }
48128  }
48129  return rc;
48130 }
48131 
48132 /*
48133 ** This function is a no-op if the pager is in exclusive mode and not
48134 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
48135 ** state.
48136 **
48137 ** If the pager is not in exclusive-access mode, the database file is
48138 ** completely unlocked. If the file is unlocked and the file-system does
48139 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
48140 ** closed (if it is open).
48141 **
48142 ** If the pager is in ERROR state when this function is called, the
48143 ** contents of the pager cache are discarded before switching back to
48144 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
48145 ** or not, any journal file left in the file-system will be treated
48146 ** as a hot-journal and rolled back the next time a read-transaction
48147 ** is opened (by this or by any other connection).
48148 */
48149 static void pager_unlock(Pager *pPager){
48150 
48151  assert( pPager->eState==PAGER_READER
48152  || pPager->eState==PAGER_OPEN
48153  || pPager->eState==PAGER_ERROR
48154  );
48155 
48156  sqlite3BitvecDestroy(pPager->pInJournal);
48157  pPager->pInJournal = 0;
48158  releaseAllSavepoints(pPager);
48159 
48160  if( pagerUseWal(pPager) ){
48161  assert( !isOpen(pPager->jfd) );
48162  sqlite3WalEndReadTransaction(pPager->pWal);
48163  pPager->eState = PAGER_OPEN;
48164  }else if( !pPager->exclusiveMode ){
48165  int rc; /* Error code returned by pagerUnlockDb() */
48166  int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
48167 
48168  /* If the operating system support deletion of open files, then
48169  ** close the journal file when dropping the database lock. Otherwise
48170  ** another connection with journal_mode=delete might delete the file
48171  ** out from under us.
48172  */
48173  assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
48174  assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
48175  assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
48176  assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
48177  assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
48178  assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
48179  if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
48180  || 1!=(pPager->journalMode & 5)
48181  ){
48182  sqlite3OsClose(pPager->jfd);
48183  }
48184 
48185  /* If the pager is in the ERROR state and the call to unlock the database
48186  ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
48187  ** above the #define for UNKNOWN_LOCK for an explanation of why this
48188  ** is necessary.
48189  */
48190  rc = pagerUnlockDb(pPager, NO_LOCK);
48191  if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
48192  pPager->eLock = UNKNOWN_LOCK;
48193  }
48194 
48195  /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
48196  ** without clearing the error code. This is intentional - the error
48197  ** code is cleared and the cache reset in the block below.
48198  */
48199  assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
48200  pPager->changeCountDone = 0;
48201  pPager->eState = PAGER_OPEN;
48202  }
48203 
48204  /* If Pager.errCode is set, the contents of the pager cache cannot be
48205  ** trusted. Now that there are no outstanding references to the pager,
48206  ** it can safely move back to PAGER_OPEN state. This happens in both
48207  ** normal and exclusive-locking mode.
48208  */
48209  assert( pPager->errCode==SQLITE_OK || !MEMDB );
48210  if( pPager->errCode ){
48211  if( pPager->tempFile==0 ){
48212  pager_reset(pPager);
48213  pPager->changeCountDone = 0;
48214  pPager->eState = PAGER_OPEN;
48215  }else{
48216  pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
48217  }
48218  if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
48219  pPager->errCode = SQLITE_OK;
48220  }
48221 
48222  pPager->journalOff = 0;
48223  pPager->journalHdr = 0;
48224  pPager->setMaster = 0;
48225 }
48226 
48227 /*
48228 ** This function is called whenever an IOERR or FULL error that requires
48229 ** the pager to transition into the ERROR state may ahve occurred.
48230 ** The first argument is a pointer to the pager structure, the second
48231 ** the error-code about to be returned by a pager API function. The
48232 ** value returned is a copy of the second argument to this function.
48233 **
48234 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
48235 ** IOERR sub-codes, the pager enters the ERROR state and the error code
48236 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
48237 ** all major API calls on the Pager will immediately return Pager.errCode.
48238 **
48239 ** The ERROR state indicates that the contents of the pager-cache
48240 ** cannot be trusted. This state can be cleared by completely discarding
48241 ** the contents of the pager-cache. If a transaction was active when
48242 ** the persistent error occurred, then the rollback journal may need
48243 ** to be replayed to restore the contents of the database file (as if
48244 ** it were a hot-journal).
48245 */
48246 static int pager_error(Pager *pPager, int rc){
48247  int rc2 = rc & 0xff;
48248  assert( rc==SQLITE_OK || !MEMDB );
48249  assert(
48250  pPager->errCode==SQLITE_FULL ||
48251  pPager->errCode==SQLITE_OK ||
48252  (pPager->errCode & 0xff)==SQLITE_IOERR
48253  );
48254  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
48255  pPager->errCode = rc;
48256  pPager->eState = PAGER_ERROR;
48257  }
48258  return rc;
48259 }
48260 
48261 static int pager_truncate(Pager *pPager, Pgno nPage);
48262 
48263 /*
48264 ** The write transaction open on pPager is being committed (bCommit==1)
48265 ** or rolled back (bCommit==0).
48266 **
48267 ** Return TRUE if and only if all dirty pages should be flushed to disk.
48268 **
48269 ** Rules:
48270 **
48271 ** * For non-TEMP databases, always sync to disk. This is necessary
48272 ** for transactions to be durable.
48273 **
48274 ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
48275 ** file has been created already (via a spill on pagerStress()) and
48276 ** when the number of dirty pages in memory exceeds 25% of the total
48277 ** cache size.
48278 */
48279 static int pagerFlushOnCommit(Pager *pPager, int bCommit){
48280  if( pPager->tempFile==0 ) return 1;
48281  if( !bCommit ) return 0;
48282  if( !isOpen(pPager->fd) ) return 0;
48283  return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
48284 }
48285 
48286 /*
48287 ** This routine ends a transaction. A transaction is usually ended by
48288 ** either a COMMIT or a ROLLBACK operation. This routine may be called
48289 ** after rollback of a hot-journal, or if an error occurs while opening
48290 ** the journal file or writing the very first journal-header of a
48291 ** database transaction.
48292 **
48293 ** This routine is never called in PAGER_ERROR state. If it is called
48294 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
48295 ** exclusive than a RESERVED lock, it is a no-op.
48296 **
48297 ** Otherwise, any active savepoints are released.
48298 **
48299 ** If the journal file is open, then it is "finalized". Once a journal
48300 ** file has been finalized it is not possible to use it to roll back a
48301 ** transaction. Nor will it be considered to be a hot-journal by this
48302 ** or any other database connection. Exactly how a journal is finalized
48303 ** depends on whether or not the pager is running in exclusive mode and
48304 ** the current journal-mode (Pager.journalMode value), as follows:
48305 **
48306 ** journalMode==MEMORY
48307 ** Journal file descriptor is simply closed. This destroys an
48308 ** in-memory journal.
48309 **
48310 ** journalMode==TRUNCATE
48311 ** Journal file is truncated to zero bytes in size.
48312 **
48313 ** journalMode==PERSIST
48314 ** The first 28 bytes of the journal file are zeroed. This invalidates
48315 ** the first journal header in the file, and hence the entire journal
48316 ** file. An invalid journal file cannot be rolled back.
48317 **
48318 ** journalMode==DELETE
48319 ** The journal file is closed and deleted using sqlite3OsDelete().
48320 **
48321 ** If the pager is running in exclusive mode, this method of finalizing
48322 ** the journal file is never used. Instead, if the journalMode is
48323 ** DELETE and the pager is in exclusive mode, the method described under
48324 ** journalMode==PERSIST is used instead.
48325 **
48326 ** After the journal is finalized, the pager moves to PAGER_READER state.
48327 ** If running in non-exclusive rollback mode, the lock on the file is
48328 ** downgraded to a SHARED_LOCK.
48329 **
48330 ** SQLITE_OK is returned if no error occurs. If an error occurs during
48331 ** any of the IO operations to finalize the journal file or unlock the
48332 ** database then the IO error code is returned to the user. If the
48333 ** operation to finalize the journal file fails, then the code still
48334 ** tries to unlock the database file if not in exclusive mode. If the
48335 ** unlock operation fails as well, then the first error code related
48336 ** to the first error encountered (the journal finalization one) is
48337 ** returned.
48338 */
48339 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
48340  int rc = SQLITE_OK; /* Error code from journal finalization operation */
48341  int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
48342 
48343  /* Do nothing if the pager does not have an open write transaction
48344  ** or at least a RESERVED lock. This function may be called when there
48345  ** is no write-transaction active but a RESERVED or greater lock is
48346  ** held under two circumstances:
48347  **
48348  ** 1. After a successful hot-journal rollback, it is called with
48349  ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
48350  **
48351  ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
48352  ** lock switches back to locking_mode=normal and then executes a
48353  ** read-transaction, this function is called with eState==PAGER_READER
48354  ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
48355  */
48356  assert( assert_pager_state(pPager) );
48357  assert( pPager->eState!=PAGER_ERROR );
48358  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
48359  return SQLITE_OK;
48360  }
48361 
48362  releaseAllSavepoints(pPager);
48363  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
48364  if( isOpen(pPager->jfd) ){
48365  assert( !pagerUseWal(pPager) );
48366 
48367  /* Finalize the journal file. */
48368  if( sqlite3JournalIsInMemory(pPager->jfd) ){
48369  /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
48370  sqlite3OsClose(pPager->jfd);
48371  }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
48372  if( pPager->journalOff==0 ){
48373  rc = SQLITE_OK;
48374  }else{
48375  rc = sqlite3OsTruncate(pPager->jfd, 0);
48376  if( rc==SQLITE_OK && pPager->fullSync ){
48377  /* Make sure the new file size is written into the inode right away.
48378  ** Otherwise the journal might resurrect following a power loss and
48379  ** cause the last transaction to roll back. See
48380  ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
48381  */
48382  rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
48383  }
48384  }
48385  pPager->journalOff = 0;
48386  }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
48387  || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
48388  ){
48389  rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
48390  pPager->journalOff = 0;
48391  }else{
48392  /* This branch may be executed with Pager.journalMode==MEMORY if
48393  ** a hot-journal was just rolled back. In this case the journal
48394  ** file should be closed and deleted. If this connection writes to
48395  ** the database file, it will do so using an in-memory journal.
48396  */
48397  int bDelete = !pPager->tempFile;
48398  assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
48399  assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
48400  || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
48401  || pPager->journalMode==PAGER_JOURNALMODE_WAL
48402  );
48403  sqlite3OsClose(pPager->jfd);
48404  if( bDelete ){
48405  rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
48406  }
48407  }
48408  }
48409 
48410 #ifdef SQLITE_CHECK_PAGES
48411  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
48412  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
48413  PgHdr *p = sqlite3PagerLookup(pPager, 1);
48414  if( p ){
48415  p->pageHash = 0;
48416  sqlite3PagerUnrefNotNull(p);
48417  }
48418  }
48419 #endif
48420 
48421  sqlite3BitvecDestroy(pPager->pInJournal);
48422  pPager->pInJournal = 0;
48423  pPager->nRec = 0;
48424  if( rc==SQLITE_OK ){
48425  if( pagerFlushOnCommit(pPager, bCommit) ){
48426  sqlite3PcacheCleanAll(pPager->pPCache);
48427  }else{
48428  sqlite3PcacheClearWritable(pPager->pPCache);
48429  }
48430  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
48431  }
48432 
48433  if( pagerUseWal(pPager) ){
48434  /* Drop the WAL write-lock, if any. Also, if the connection was in
48435  ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
48436  ** lock held on the database file.
48437  */
48438  rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
48439  assert( rc2==SQLITE_OK );
48440  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
48441  /* This branch is taken when committing a transaction in rollback-journal
48442  ** mode if the database file on disk is larger than the database image.
48443  ** At this point the journal has been finalized and the transaction
48444  ** successfully committed, but the EXCLUSIVE lock is still held on the
48445  ** file. So it is safe to truncate the database file to its minimum
48446  ** required size. */
48447  assert( pPager->eLock==EXCLUSIVE_LOCK );
48448  rc = pager_truncate(pPager, pPager->dbSize);
48449  }
48450 
48451  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
48452  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
48453  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
48454  }
48455 
48456  if( !pPager->exclusiveMode
48457  && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
48458  ){
48459  rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
48460  pPager->changeCountDone = 0;
48461  }
48462  pPager->eState = PAGER_READER;
48463  pPager->setMaster = 0;
48464 
48465  return (rc==SQLITE_OK?rc2:rc);
48466 }
48467 
48468 /*
48469 ** Execute a rollback if a transaction is active and unlock the
48470 ** database file.
48471 **
48472 ** If the pager has already entered the ERROR state, do not attempt
48473 ** the rollback at this time. Instead, pager_unlock() is called. The
48474 ** call to pager_unlock() will discard all in-memory pages, unlock
48475 ** the database file and move the pager back to OPEN state. If this
48476 ** means that there is a hot-journal left in the file-system, the next
48477 ** connection to obtain a shared lock on the pager (which may be this one)
48478 ** will roll it back.
48479 **
48480 ** If the pager has not already entered the ERROR state, but an IO or
48481 ** malloc error occurs during a rollback, then this will itself cause
48482 ** the pager to enter the ERROR state. Which will be cleared by the
48483 ** call to pager_unlock(), as described above.
48484 */
48485 static void pagerUnlockAndRollback(Pager *pPager){
48486  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
48487  assert( assert_pager_state(pPager) );
48488  if( pPager->eState>=PAGER_WRITER_LOCKED ){
48489  sqlite3BeginBenignMalloc();
48490  sqlite3PagerRollback(pPager);
48491  sqlite3EndBenignMalloc();
48492  }else if( !pPager->exclusiveMode ){
48493  assert( pPager->eState==PAGER_READER );
48494  pager_end_transaction(pPager, 0, 0);
48495  }
48496  }
48497  pager_unlock(pPager);
48498 }
48499 
48500 /*
48501 ** Parameter aData must point to a buffer of pPager->pageSize bytes
48502 ** of data. Compute and return a checksum based ont the contents of the
48503 ** page of data and the current value of pPager->cksumInit.
48504 **
48505 ** This is not a real checksum. It is really just the sum of the
48506 ** random initial value (pPager->cksumInit) and every 200th byte
48507 ** of the page data, starting with byte offset (pPager->pageSize%200).
48508 ** Each byte is interpreted as an 8-bit unsigned integer.
48509 **
48510 ** Changing the formula used to compute this checksum results in an
48511 ** incompatible journal file format.
48512 **
48513 ** If journal corruption occurs due to a power failure, the most likely
48514 ** scenario is that one end or the other of the record will be changed.
48515 ** It is much less likely that the two ends of the journal record will be
48516 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
48517 ** though fast and simple, catches the mostly likely kind of corruption.
48518 */
48519 static u32 pager_cksum(Pager *pPager, const u8 *aData){
48520  u32 cksum = pPager->cksumInit; /* Checksum value to return */
48521  int i = pPager->pageSize-200; /* Loop counter */
48522  while( i>0 ){
48523  cksum += aData[i];
48524  i -= 200;
48525  }
48526  return cksum;
48527 }
48528 
48529 /*
48530 ** Report the current page size and number of reserved bytes back
48531 ** to the codec.
48532 */
48533 #ifdef SQLITE_HAS_CODEC
48534 static void pagerReportSize(Pager *pPager){
48535  if( pPager->xCodecSizeChng ){
48536  pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
48537  (int)pPager->nReserve);
48538  }
48539 }
48540 #else
48541 # define pagerReportSize(X) /* No-op if we do not support a codec */
48542 #endif
48543 
48544 #ifdef SQLITE_HAS_CODEC
48545 /*
48546 ** Make sure the number of reserved bits is the same in the destination
48547 ** pager as it is in the source. This comes up when a VACUUM changes the
48548 ** number of reserved bits to the "optimal" amount.
48549 */
48550 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
48551  if( pDest->nReserve!=pSrc->nReserve ){
48552  pDest->nReserve = pSrc->nReserve;
48553  pagerReportSize(pDest);
48554  }
48555 }
48556 #endif
48557 
48558 /*
48559 ** Read a single page from either the journal file (if isMainJrnl==1) or
48560 ** from the sub-journal (if isMainJrnl==0) and playback that page.
48561 ** The page begins at offset *pOffset into the file. The *pOffset
48562 ** value is increased to the start of the next page in the journal.
48563 **
48564 ** The main rollback journal uses checksums - the statement journal does
48565 ** not.
48566 **
48567 ** If the page number of the page record read from the (sub-)journal file
48568 ** is greater than the current value of Pager.dbSize, then playback is
48569 ** skipped and SQLITE_OK is returned.
48570 **
48571 ** If pDone is not NULL, then it is a record of pages that have already
48572 ** been played back. If the page at *pOffset has already been played back
48573 ** (if the corresponding pDone bit is set) then skip the playback.
48574 ** Make sure the pDone bit corresponding to the *pOffset page is set
48575 ** prior to returning.
48576 **
48577 ** If the page record is successfully read from the (sub-)journal file
48578 ** and played back, then SQLITE_OK is returned. If an IO error occurs
48579 ** while reading the record from the (sub-)journal file or while writing
48580 ** to the database file, then the IO error code is returned. If data
48581 ** is successfully read from the (sub-)journal file but appears to be
48582 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
48583 ** two circumstances:
48584 **
48585 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
48586 ** * If the record is being rolled back from the main journal file
48587 ** and the checksum field does not match the record content.
48588 **
48589 ** Neither of these two scenarios are possible during a savepoint rollback.
48590 **
48591 ** If this is a savepoint rollback, then memory may have to be dynamically
48592 ** allocated by this function. If this is the case and an allocation fails,
48593 ** SQLITE_NOMEM is returned.
48594 */
48595 static int pager_playback_one_page(
48596  Pager *pPager, /* The pager being played back */
48597  i64 *pOffset, /* Offset of record to playback */
48598  Bitvec *pDone, /* Bitvec of pages already played back */
48599  int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
48600  int isSavepnt /* True for a savepoint rollback */
48601 ){
48602  int rc;
48603  PgHdr *pPg; /* An existing page in the cache */
48604  Pgno pgno; /* The page number of a page in journal */
48605  u32 cksum; /* Checksum used for sanity checking */
48606  char *aData; /* Temporary storage for the page */
48607  sqlite3_file *jfd; /* The file descriptor for the journal file */
48608  int isSynced; /* True if journal page is synced */
48609 
48610  assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
48611  assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
48612  assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
48613  assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
48614 
48615  aData = pPager->pTmpSpace;
48616  assert( aData ); /* Temp storage must have already been allocated */
48617  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
48618 
48619  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
48620  ** or savepoint rollback done at the request of the caller) or this is
48621  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
48622  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
48623  ** only reads from the main journal, not the sub-journal.
48624  */
48625  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
48626  || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
48627  );
48628  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
48629 
48630  /* Read the page number and page data from the journal or sub-journal
48631  ** file. Return an error code to the caller if an IO error occurs.
48632  */
48633  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
48634  rc = read32bits(jfd, *pOffset, &pgno);
48635  if( rc!=SQLITE_OK ) return rc;
48636  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
48637  if( rc!=SQLITE_OK ) return rc;
48638  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
48639 
48640  /* Sanity checking on the page. This is more important that I originally
48641  ** thought. If a power failure occurs while the journal is being written,
48642  ** it could cause invalid data to be written into the journal. We need to
48643  ** detect this invalid data (with high probability) and ignore it.
48644  */
48645  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
48646  assert( !isSavepnt );
48647  return SQLITE_DONE;
48648  }
48649  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
48650  return SQLITE_OK;
48651  }
48652  if( isMainJrnl ){
48653  rc = read32bits(jfd, (*pOffset)-4, &cksum);
48654  if( rc ) return rc;
48655  if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
48656  return SQLITE_DONE;
48657  }
48658  }
48659 
48660  /* If this page has already been played back before during the current
48661  ** rollback, then don't bother to play it back again.
48662  */
48663  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
48664  return rc;
48665  }
48666 
48667  /* When playing back page 1, restore the nReserve setting
48668  */
48669  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
48670  pPager->nReserve = ((u8*)aData)[20];
48671  pagerReportSize(pPager);
48672  }
48673 
48674  /* If the pager is in CACHEMOD state, then there must be a copy of this
48675  ** page in the pager cache. In this case just update the pager cache,
48676  ** not the database file. The page is left marked dirty in this case.
48677  **
48678  ** An exception to the above rule: If the database is in no-sync mode
48679  ** and a page is moved during an incremental vacuum then the page may
48680  ** not be in the pager cache. Later: if a malloc() or IO error occurs
48681  ** during a Movepage() call, then the page may not be in the cache
48682  ** either. So the condition described in the above paragraph is not
48683  ** assert()able.
48684  **
48685  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
48686  ** pager cache if it exists and the main file. The page is then marked
48687  ** not dirty. Since this code is only executed in PAGER_OPEN state for
48688  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
48689  ** if the pager is in OPEN state.
48690  **
48691  ** Ticket #1171: The statement journal might contain page content that is
48692  ** different from the page content at the start of the transaction.
48693  ** This occurs when a page is changed prior to the start of a statement
48694  ** then changed again within the statement. When rolling back such a
48695  ** statement we must not write to the original database unless we know
48696  ** for certain that original page contents are synced into the main rollback
48697  ** journal. Otherwise, a power loss might leave modified data in the
48698  ** database file without an entry in the rollback journal that can
48699  ** restore the database to its original form. Two conditions must be
48700  ** met before writing to the database files. (1) the database must be
48701  ** locked. (2) we know that the original page content is fully synced
48702  ** in the main journal either because the page is not in cache or else
48703  ** the page is marked as needSync==0.
48704  **
48705  ** 2008-04-14: When attempting to vacuum a corrupt database file, it
48706  ** is possible to fail a statement on a database that does not yet exist.
48707  ** Do not attempt to write if database file has never been opened.
48708  */
48709  if( pagerUseWal(pPager) ){
48710  pPg = 0;
48711  }else{
48712  pPg = sqlite3PagerLookup(pPager, pgno);
48713  }
48714  assert( pPg || !MEMDB );
48715  assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
48716  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
48717  PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
48718  (isMainJrnl?"main-journal":"sub-journal")
48719  ));
48720  if( isMainJrnl ){
48721  isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
48722  }else{
48723  isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
48724  }
48725  if( isOpen(pPager->fd)
48726  && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48727  && isSynced
48728  ){
48729  i64 ofst = (pgno-1)*(i64)pPager->pageSize;
48730  testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
48731  assert( !pagerUseWal(pPager) );
48732  rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
48733  if( pgno>pPager->dbFileSize ){
48734  pPager->dbFileSize = pgno;
48735  }
48736  if( pPager->pBackup ){
48737  CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
48738  sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
48739  CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
48740  }
48741  }else if( !isMainJrnl && pPg==0 ){
48742  /* If this is a rollback of a savepoint and data was not written to
48743  ** the database and the page is not in-memory, there is a potential
48744  ** problem. When the page is next fetched by the b-tree layer, it
48745  ** will be read from the database file, which may or may not be
48746  ** current.
48747  **
48748  ** There are a couple of different ways this can happen. All are quite
48749  ** obscure. When running in synchronous mode, this can only happen
48750  ** if the page is on the free-list at the start of the transaction, then
48751  ** populated, then moved using sqlite3PagerMovepage().
48752  **
48753  ** The solution is to add an in-memory page to the cache containing
48754  ** the data just read from the sub-journal. Mark the page as dirty
48755  ** and if the pager requires a journal-sync, then mark the page as
48756  ** requiring a journal-sync before it is written.
48757  */
48758  assert( isSavepnt );
48759  assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
48760  pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
48761  rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
48762  assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
48763  pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
48764  if( rc!=SQLITE_OK ) return rc;
48765  sqlite3PcacheMakeDirty(pPg);
48766  }
48767  if( pPg ){
48768  /* No page should ever be explicitly rolled back that is in use, except
48769  ** for page 1 which is held in use in order to keep the lock on the
48770  ** database active. However such a page may be rolled back as a result
48771  ** of an internal error resulting in an automatic call to
48772  ** sqlite3PagerRollback().
48773  */
48774  void *pData;
48775  pData = pPg->pData;
48776  memcpy(pData, (u8*)aData, pPager->pageSize);
48777  pPager->xReiniter(pPg);
48778  /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
48779  ** that call was dangerous and had no detectable benefit since the cache
48780  ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
48781  ** has been removed. */
48782  pager_set_pagehash(pPg);
48783 
48784  /* If this was page 1, then restore the value of Pager.dbFileVers.
48785  ** Do this before any decoding. */
48786  if( pgno==1 ){
48787  memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
48788  }
48789 
48790  /* Decode the page just read from disk */
48791  CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT);
48792  sqlite3PcacheRelease(pPg);
48793  }
48794  return rc;
48795 }
48796 
48797 /*
48798 ** Parameter zMaster is the name of a master journal file. A single journal
48799 ** file that referred to the master journal file has just been rolled back.
48800 ** This routine checks if it is possible to delete the master journal file,
48801 ** and does so if it is.
48802 **
48803 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
48804 ** available for use within this function.
48805 **
48806 ** When a master journal file is created, it is populated with the names
48807 ** of all of its child journals, one after another, formatted as utf-8
48808 ** encoded text. The end of each child journal file is marked with a
48809 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
48810 ** file for a transaction involving two databases might be:
48811 **
48812 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
48813 **
48814 ** A master journal file may only be deleted once all of its child
48815 ** journals have been rolled back.
48816 **
48817 ** This function reads the contents of the master-journal file into
48818 ** memory and loops through each of the child journal names. For
48819 ** each child journal, it checks if:
48820 **
48821 ** * if the child journal exists, and if so
48822 ** * if the child journal contains a reference to master journal
48823 ** file zMaster
48824 **
48825 ** If a child journal can be found that matches both of the criteria
48826 ** above, this function returns without doing anything. Otherwise, if
48827 ** no such child journal can be found, file zMaster is deleted from
48828 ** the file-system using sqlite3OsDelete().
48829 **
48830 ** If an IO error within this function, an error code is returned. This
48831 ** function allocates memory by calling sqlite3Malloc(). If an allocation
48832 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
48833 ** occur, SQLITE_OK is returned.
48834 **
48835 ** TODO: This function allocates a single block of memory to load
48836 ** the entire contents of the master journal file. This could be
48837 ** a couple of kilobytes or so - potentially larger than the page
48838 ** size.
48839 */
48840 static int pager_delmaster(Pager *pPager, const char *zMaster){
48841  sqlite3_vfs *pVfs = pPager->pVfs;
48842  int rc; /* Return code */
48843  sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
48844  sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
48845  char *zMasterJournal = 0; /* Contents of master journal file */
48846  i64 nMasterJournal; /* Size of master journal file */
48847  char *zJournal; /* Pointer to one journal within MJ file */
48848  char *zMasterPtr; /* Space to hold MJ filename from a journal file */
48849  int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
48850 
48851  /* Allocate space for both the pJournal and pMaster file descriptors.
48852  ** If successful, open the master journal file for reading.
48853  */
48854  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
48855  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
48856  if( !pMaster ){
48857  rc = SQLITE_NOMEM_BKPT;
48858  }else{
48859  const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
48860  rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
48861  }
48862  if( rc!=SQLITE_OK ) goto delmaster_out;
48863 
48864  /* Load the entire master journal file into space obtained from
48865  ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
48866  ** sufficient space (in zMasterPtr) to hold the names of master
48867  ** journal files extracted from regular rollback-journals.
48868  */
48869  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
48870  if( rc!=SQLITE_OK ) goto delmaster_out;
48871  nMasterPtr = pVfs->mxPathname+1;
48872  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
48873  if( !zMasterJournal ){
48874  rc = SQLITE_NOMEM_BKPT;
48875  goto delmaster_out;
48876  }
48877  zMasterPtr = &zMasterJournal[nMasterJournal+1];
48878  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
48879  if( rc!=SQLITE_OK ) goto delmaster_out;
48880  zMasterJournal[nMasterJournal] = 0;
48881 
48882  zJournal = zMasterJournal;
48883  while( (zJournal-zMasterJournal)<nMasterJournal ){
48884  int exists;
48885  rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
48886  if( rc!=SQLITE_OK ){
48887  goto delmaster_out;
48888  }
48889  if( exists ){
48890  /* One of the journals pointed to by the master journal exists.
48891  ** Open it and check if it points at the master journal. If
48892  ** so, return without deleting the master journal file.
48893  */
48894  int c;
48895  int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
48896  rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
48897  if( rc!=SQLITE_OK ){
48898  goto delmaster_out;
48899  }
48900 
48901  rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
48902  sqlite3OsClose(pJournal);
48903  if( rc!=SQLITE_OK ){
48904  goto delmaster_out;
48905  }
48906 
48907  c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
48908  if( c ){
48909  /* We have a match. Do not delete the master journal file. */
48910  goto delmaster_out;
48911  }
48912  }
48913  zJournal += (sqlite3Strlen30(zJournal)+1);
48914  }
48915 
48916  sqlite3OsClose(pMaster);
48917  rc = sqlite3OsDelete(pVfs, zMaster, 0);
48918 
48919 delmaster_out:
48920  sqlite3_free(zMasterJournal);
48921  if( pMaster ){
48922  sqlite3OsClose(pMaster);
48923  assert( !isOpen(pJournal) );
48924  sqlite3_free(pMaster);
48925  }
48926  return rc;
48927 }
48928 
48929 
48930 /*
48931 ** This function is used to change the actual size of the database
48932 ** file in the file-system. This only happens when committing a transaction,
48933 ** or rolling back a transaction (including rolling back a hot-journal).
48934 **
48935 ** If the main database file is not open, or the pager is not in either
48936 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
48937 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
48938 ** If the file on disk is currently larger than nPage pages, then use the VFS
48939 ** xTruncate() method to truncate it.
48940 **
48941 ** Or, it might be the case that the file on disk is smaller than
48942 ** nPage pages. Some operating system implementations can get confused if
48943 ** you try to truncate a file to some size that is larger than it
48944 ** currently is, so detect this case and write a single zero byte to
48945 ** the end of the new file instead.
48946 **
48947 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
48948 ** the database file, return the error code to the caller.
48949 */
48950 static int pager_truncate(Pager *pPager, Pgno nPage){
48951  int rc = SQLITE_OK;
48952  assert( pPager->eState!=PAGER_ERROR );
48953  assert( pPager->eState!=PAGER_READER );
48954 
48955  if( isOpen(pPager->fd)
48956  && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48957  ){
48958  i64 currentSize, newSize;
48959  int szPage = pPager->pageSize;
48960  assert( pPager->eLock==EXCLUSIVE_LOCK );
48961  /* TODO: Is it safe to use Pager.dbFileSize here? */
48962  rc = sqlite3OsFileSize(pPager->fd, &currentSize);
48963  newSize = szPage*(i64)nPage;
48964  if( rc==SQLITE_OK && currentSize!=newSize ){
48965  if( currentSize>newSize ){
48966  rc = sqlite3OsTruncate(pPager->fd, newSize);
48967  }else if( (currentSize+szPage)<=newSize ){
48968  char *pTmp = pPager->pTmpSpace;
48969  memset(pTmp, 0, szPage);
48970  testcase( (newSize-szPage) == currentSize );
48971  testcase( (newSize-szPage) > currentSize );
48972  rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
48973  }
48974  if( rc==SQLITE_OK ){
48975  pPager->dbFileSize = nPage;
48976  }
48977  }
48978  }
48979  return rc;
48980 }
48981 
48982 /*
48983 ** Return a sanitized version of the sector-size of OS file pFile. The
48984 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
48985 */
48986 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
48987  int iRet = sqlite3OsSectorSize(pFile);
48988  if( iRet<32 ){
48989  iRet = 512;
48990  }else if( iRet>MAX_SECTOR_SIZE ){
48991  assert( MAX_SECTOR_SIZE>=512 );
48992  iRet = MAX_SECTOR_SIZE;
48993  }
48994  return iRet;
48995 }
48996 
48997 /*
48998 ** Set the value of the Pager.sectorSize variable for the given
48999 ** pager based on the value returned by the xSectorSize method
49000 ** of the open database file. The sector size will be used
49001 ** to determine the size and alignment of journal header and
49002 ** master journal pointers within created journal files.
49003 **
49004 ** For temporary files the effective sector size is always 512 bytes.
49005 **
49006 ** Otherwise, for non-temporary files, the effective sector size is
49007 ** the value returned by the xSectorSize() method rounded up to 32 if
49008 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
49009 ** is greater than MAX_SECTOR_SIZE.
49010 **
49011 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
49012 ** the effective sector size to its minimum value (512). The purpose of
49013 ** pPager->sectorSize is to define the "blast radius" of bytes that
49014 ** might change if a crash occurs while writing to a single byte in
49015 ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
49016 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
49017 ** size. For backwards compatibility of the rollback journal file format,
49018 ** we cannot reduce the effective sector size below 512.
49019 */
49020 static void setSectorSize(Pager *pPager){
49021  assert( isOpen(pPager->fd) || pPager->tempFile );
49022 
49023  if( pPager->tempFile
49024  || (sqlite3OsDeviceCharacteristics(pPager->fd) &
49025  SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
49026  ){
49027  /* Sector size doesn't matter for temporary files. Also, the file
49028  ** may not have been opened yet, in which case the OsSectorSize()
49029  ** call will segfault. */
49030  pPager->sectorSize = 512;
49031  }else{
49032  pPager->sectorSize = sqlite3SectorSize(pPager->fd);
49033  }
49034 }
49035 
49036 /*
49037 ** Playback the journal and thus restore the database file to
49038 ** the state it was in before we started making changes.
49039 **
49040 ** The journal file format is as follows:
49041 **
49042 ** (1) 8 byte prefix. A copy of aJournalMagic[].
49043 ** (2) 4 byte big-endian integer which is the number of valid page records
49044 ** in the journal. If this value is 0xffffffff, then compute the
49045 ** number of page records from the journal size.
49046 ** (3) 4 byte big-endian integer which is the initial value for the
49047 ** sanity checksum.
49048 ** (4) 4 byte integer which is the number of pages to truncate the
49049 ** database to during a rollback.
49050 ** (5) 4 byte big-endian integer which is the sector size. The header
49051 ** is this many bytes in size.
49052 ** (6) 4 byte big-endian integer which is the page size.
49053 ** (7) zero padding out to the next sector size.
49054 ** (8) Zero or more pages instances, each as follows:
49055 ** + 4 byte page number.
49056 ** + pPager->pageSize bytes of data.
49057 ** + 4 byte checksum
49058 **
49059 ** When we speak of the journal header, we mean the first 7 items above.
49060 ** Each entry in the journal is an instance of the 8th item.
49061 **
49062 ** Call the value from the second bullet "nRec". nRec is the number of
49063 ** valid page entries in the journal. In most cases, you can compute the
49064 ** value of nRec from the size of the journal file. But if a power
49065 ** failure occurred while the journal was being written, it could be the
49066 ** case that the size of the journal file had already been increased but
49067 ** the extra entries had not yet made it safely to disk. In such a case,
49068 ** the value of nRec computed from the file size would be too large. For
49069 ** that reason, we always use the nRec value in the header.
49070 **
49071 ** If the nRec value is 0xffffffff it means that nRec should be computed
49072 ** from the file size. This value is used when the user selects the
49073 ** no-sync option for the journal. A power failure could lead to corruption
49074 ** in this case. But for things like temporary table (which will be
49075 ** deleted when the power is restored) we don't care.
49076 **
49077 ** If the file opened as the journal file is not a well-formed
49078 ** journal file then all pages up to the first corrupted page are rolled
49079 ** back (or no pages if the journal header is corrupted). The journal file
49080 ** is then deleted and SQLITE_OK returned, just as if no corruption had
49081 ** been encountered.
49082 **
49083 ** If an I/O or malloc() error occurs, the journal-file is not deleted
49084 ** and an error code is returned.
49085 **
49086 ** The isHot parameter indicates that we are trying to rollback a journal
49087 ** that might be a hot journal. Or, it could be that the journal is
49088 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
49089 ** If the journal really is hot, reset the pager cache prior rolling
49090 ** back any content. If the journal is merely persistent, no reset is
49091 ** needed.
49092 */
49093 static int pager_playback(Pager *pPager, int isHot){
49094  sqlite3_vfs *pVfs = pPager->pVfs;
49095  i64 szJ; /* Size of the journal file in bytes */
49096  u32 nRec; /* Number of Records in the journal */
49097  u32 u; /* Unsigned loop counter */
49098  Pgno mxPg = 0; /* Size of the original file in pages */
49099  int rc; /* Result code of a subroutine */
49100  int res = 1; /* Value returned by sqlite3OsAccess() */
49101  char *zMaster = 0; /* Name of master journal file if any */
49102  int needPagerReset; /* True to reset page prior to first page rollback */
49103  int nPlayback = 0; /* Total number of pages restored from journal */
49104 
49105  /* Figure out how many records are in the journal. Abort early if
49106  ** the journal is empty.
49107  */
49108  assert( isOpen(pPager->jfd) );
49109  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
49110  if( rc!=SQLITE_OK ){
49111  goto end_playback;
49112  }
49113 
49114  /* Read the master journal name from the journal, if it is present.
49115  ** If a master journal file name is specified, but the file is not
49116  ** present on disk, then the journal is not hot and does not need to be
49117  ** played back.
49118  **
49119  ** TODO: Technically the following is an error because it assumes that
49120  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
49121  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
49122  ** mxPathname is 512, which is the same as the minimum allowable value
49123  ** for pageSize.
49124  */
49125  zMaster = pPager->pTmpSpace;
49126  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49127  if( rc==SQLITE_OK && zMaster[0] ){
49128  rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
49129  }
49130  zMaster = 0;
49131  if( rc!=SQLITE_OK || !res ){
49132  goto end_playback;
49133  }
49134  pPager->journalOff = 0;
49135  needPagerReset = isHot;
49136 
49137  /* This loop terminates either when a readJournalHdr() or
49138  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
49139  ** occurs.
49140  */
49141  while( 1 ){
49142  /* Read the next journal header from the journal file. If there are
49143  ** not enough bytes left in the journal file for a complete header, or
49144  ** it is corrupted, then a process must have failed while writing it.
49145  ** This indicates nothing more needs to be rolled back.
49146  */
49147  rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
49148  if( rc!=SQLITE_OK ){
49149  if( rc==SQLITE_DONE ){
49150  rc = SQLITE_OK;
49151  }
49152  goto end_playback;
49153  }
49154 
49155  /* If nRec is 0xffffffff, then this journal was created by a process
49156  ** working in no-sync mode. This means that the rest of the journal
49157  ** file consists of pages, there are no more journal headers. Compute
49158  ** the value of nRec based on this assumption.
49159  */
49160  if( nRec==0xffffffff ){
49161  assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
49162  nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
49163  }
49164 
49165  /* If nRec is 0 and this rollback is of a transaction created by this
49166  ** process and if this is the final header in the journal, then it means
49167  ** that this part of the journal was being filled but has not yet been
49168  ** synced to disk. Compute the number of pages based on the remaining
49169  ** size of the file.
49170  **
49171  ** The third term of the test was added to fix ticket #2565.
49172  ** When rolling back a hot journal, nRec==0 always means that the next
49173  ** chunk of the journal contains zero pages to be rolled back. But
49174  ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
49175  ** the journal, it means that the journal might contain additional
49176  ** pages that need to be rolled back and that the number of pages
49177  ** should be computed based on the journal file size.
49178  */
49179  if( nRec==0 && !isHot &&
49180  pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
49181  nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
49182  }
49183 
49184  /* If this is the first header read from the journal, truncate the
49185  ** database file back to its original size.
49186  */
49187  if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
49188  rc = pager_truncate(pPager, mxPg);
49189  if( rc!=SQLITE_OK ){
49190  goto end_playback;
49191  }
49192  pPager->dbSize = mxPg;
49193  }
49194 
49195  /* Copy original pages out of the journal and back into the
49196  ** database file and/or page cache.
49197  */
49198  for(u=0; u<nRec; u++){
49199  if( needPagerReset ){
49200  pager_reset(pPager);
49201  needPagerReset = 0;
49202  }
49203  rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
49204  if( rc==SQLITE_OK ){
49205  nPlayback++;
49206  }else{
49207  if( rc==SQLITE_DONE ){
49208  pPager->journalOff = szJ;
49209  break;
49210  }else if( rc==SQLITE_IOERR_SHORT_READ ){
49211  /* If the journal has been truncated, simply stop reading and
49212  ** processing the journal. This might happen if the journal was
49213  ** not completely written and synced prior to a crash. In that
49214  ** case, the database should have never been written in the
49215  ** first place so it is OK to simply abandon the rollback. */
49216  rc = SQLITE_OK;
49217  goto end_playback;
49218  }else{
49219  /* If we are unable to rollback, quit and return the error
49220  ** code. This will cause the pager to enter the error state
49221  ** so that no further harm will be done. Perhaps the next
49222  ** process to come along will be able to rollback the database.
49223  */
49224  goto end_playback;
49225  }
49226  }
49227  }
49228  }
49229  /*NOTREACHED*/
49230  assert( 0 );
49231 
49232 end_playback:
49233  /* Following a rollback, the database file should be back in its original
49234  ** state prior to the start of the transaction, so invoke the
49235  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
49236  ** assertion that the transaction counter was modified.
49237  */
49238 #ifdef SQLITE_DEBUG
49239  if( pPager->fd->pMethods ){
49240  sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
49241  }
49242 #endif
49243 
49244  /* If this playback is happening automatically as a result of an IO or
49245  ** malloc error that occurred after the change-counter was updated but
49246  ** before the transaction was committed, then the change-counter
49247  ** modification may just have been reverted. If this happens in exclusive
49248  ** mode, then subsequent transactions performed by the connection will not
49249  ** update the change-counter at all. This may lead to cache inconsistency
49250  ** problems for other processes at some point in the future. So, just
49251  ** in case this has happened, clear the changeCountDone flag now.
49252  */
49253  pPager->changeCountDone = pPager->tempFile;
49254 
49255  if( rc==SQLITE_OK ){
49256  zMaster = pPager->pTmpSpace;
49257  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49258  testcase( rc!=SQLITE_OK );
49259  }
49260  if( rc==SQLITE_OK
49261  && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49262  ){
49263  rc = sqlite3PagerSync(pPager, 0);
49264  }
49265  if( rc==SQLITE_OK ){
49266  rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
49267  testcase( rc!=SQLITE_OK );
49268  }
49269  if( rc==SQLITE_OK && zMaster[0] && res ){
49270  /* If there was a master journal and this routine will return success,
49271  ** see if it is possible to delete the master journal.
49272  */
49273  rc = pager_delmaster(pPager, zMaster);
49274  testcase( rc!=SQLITE_OK );
49275  }
49276  if( isHot && nPlayback ){
49277  sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
49278  nPlayback, pPager->zJournal);
49279  }
49280 
49281  /* The Pager.sectorSize variable may have been updated while rolling
49282  ** back a journal created by a process with a different sector size
49283  ** value. Reset it to the correct value for this process.
49284  */
49285  setSectorSize(pPager);
49286  return rc;
49287 }
49288 
49289 
49290 /*
49291 ** Read the content for page pPg out of the database file and into
49292 ** pPg->pData. A shared lock or greater must be held on the database
49293 ** file before this function is called.
49294 **
49295 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
49296 ** the value read from the database file.
49297 **
49298 ** If an IO error occurs, then the IO error is returned to the caller.
49299 ** Otherwise, SQLITE_OK is returned.
49300 */
49301 static int readDbPage(PgHdr *pPg, u32 iFrame){
49302  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
49303  Pgno pgno = pPg->pgno; /* Page number to read */
49304  int rc = SQLITE_OK; /* Return code */
49305  int pgsz = pPager->pageSize; /* Number of bytes to read */
49306 
49307  assert( pPager->eState>=PAGER_READER && !MEMDB );
49308  assert( isOpen(pPager->fd) );
49309 
49310 #ifndef SQLITE_OMIT_WAL
49311  if( iFrame ){
49312  /* Try to pull the page from the write-ahead log. */
49313  rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
49314  }else
49315 #endif
49316  {
49317  i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
49318  rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
49319  if( rc==SQLITE_IOERR_SHORT_READ ){
49320  rc = SQLITE_OK;
49321  }
49322  }
49323 
49324  if( pgno==1 ){
49325  if( rc ){
49326  /* If the read is unsuccessful, set the dbFileVers[] to something
49327  ** that will never be a valid file version. dbFileVers[] is a copy
49328  ** of bytes 24..39 of the database. Bytes 28..31 should always be
49329  ** zero or the size of the database in page. Bytes 32..35 and 35..39
49330  ** should be page numbers which are never 0xffffffff. So filling
49331  ** pPager->dbFileVers[] with all 0xff bytes should suffice.
49332  **
49333  ** For an encrypted database, the situation is more complex: bytes
49334  ** 24..39 of the database are white noise. But the probability of
49335  ** white noise equaling 16 bytes of 0xff is vanishingly small so
49336  ** we should still be ok.
49337  */
49338  memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
49339  }else{
49340  u8 *dbFileVers = &((u8*)pPg->pData)[24];
49341  memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
49342  }
49343  }
49344  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
49345 
49346  PAGER_INCR(sqlite3_pager_readdb_count);
49347  PAGER_INCR(pPager->nRead);
49348  IOTRACE(("PGIN %p %d\n", pPager, pgno));
49349  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
49350  PAGERID(pPager), pgno, pager_pagehash(pPg)));
49351 
49352  return rc;
49353 }
49354 
49355 /*
49356 ** Update the value of the change-counter at offsets 24 and 92 in
49357 ** the header and the sqlite version number at offset 96.
49358 **
49359 ** This is an unconditional update. See also the pager_incr_changecounter()
49360 ** routine which only updates the change-counter if the update is actually
49361 ** needed, as determined by the pPager->changeCountDone state variable.
49362 */
49363 static void pager_write_changecounter(PgHdr *pPg){
49364  u32 change_counter;
49365 
49366  /* Increment the value just read and write it back to byte 24. */
49367  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
49368  put32bits(((char*)pPg->pData)+24, change_counter);
49369 
49370  /* Also store the SQLite version number in bytes 96..99 and in
49371  ** bytes 92..95 store the change counter for which the version number
49372  ** is valid. */
49373  put32bits(((char*)pPg->pData)+92, change_counter);
49374  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
49375 }
49376 
49377 #ifndef SQLITE_OMIT_WAL
49378 /*
49379 ** This function is invoked once for each page that has already been
49380 ** written into the log file when a WAL transaction is rolled back.
49381 ** Parameter iPg is the page number of said page. The pCtx argument
49382 ** is actually a pointer to the Pager structure.
49383 **
49384 ** If page iPg is present in the cache, and has no outstanding references,
49385 ** it is discarded. Otherwise, if there are one or more outstanding
49386 ** references, the page content is reloaded from the database. If the
49387 ** attempt to reload content from the database is required and fails,
49388 ** return an SQLite error code. Otherwise, SQLITE_OK.
49389 */
49390 static int pagerUndoCallback(void *pCtx, Pgno iPg){
49391  int rc = SQLITE_OK;
49392  Pager *pPager = (Pager *)pCtx;
49393  PgHdr *pPg;
49394 
49395  assert( pagerUseWal(pPager) );
49396  pPg = sqlite3PagerLookup(pPager, iPg);
49397  if( pPg ){
49398  if( sqlite3PcachePageRefcount(pPg)==1 ){
49399  sqlite3PcacheDrop(pPg);
49400  }else{
49401  u32 iFrame = 0;
49402  rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
49403  if( rc==SQLITE_OK ){
49404  rc = readDbPage(pPg, iFrame);
49405  }
49406  if( rc==SQLITE_OK ){
49407  pPager->xReiniter(pPg);
49408  }
49409  sqlite3PagerUnrefNotNull(pPg);
49410  }
49411  }
49412 
49413  /* Normally, if a transaction is rolled back, any backup processes are
49414  ** updated as data is copied out of the rollback journal and into the
49415  ** database. This is not generally possible with a WAL database, as
49416  ** rollback involves simply truncating the log file. Therefore, if one
49417  ** or more frames have already been written to the log (and therefore
49418  ** also copied into the backup databases) as part of this transaction,
49419  ** the backups must be restarted.
49420  */
49421  sqlite3BackupRestart(pPager->pBackup);
49422 
49423  return rc;
49424 }
49425 
49426 /*
49427 ** This function is called to rollback a transaction on a WAL database.
49428 */
49429 static int pagerRollbackWal(Pager *pPager){
49430  int rc; /* Return Code */
49431  PgHdr *pList; /* List of dirty pages to revert */
49432 
49433  /* For all pages in the cache that are currently dirty or have already
49434  ** been written (but not committed) to the log file, do one of the
49435  ** following:
49436  **
49437  ** + Discard the cached page (if refcount==0), or
49438  ** + Reload page content from the database (if refcount>0).
49439  */
49440  pPager->dbSize = pPager->dbOrigSize;
49441  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
49442  pList = sqlite3PcacheDirtyList(pPager->pPCache);
49443  while( pList && rc==SQLITE_OK ){
49444  PgHdr *pNext = pList->pDirty;
49445  rc = pagerUndoCallback((void *)pPager, pList->pgno);
49446  pList = pNext;
49447  }
49448 
49449  return rc;
49450 }
49451 
49452 /*
49453 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
49454 ** the contents of the list of pages headed by pList (connected by pDirty),
49455 ** this function notifies any active backup processes that the pages have
49456 ** changed.
49457 **
49458 ** The list of pages passed into this routine is always sorted by page number.
49459 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
49460 */
49461 static int pagerWalFrames(
49462  Pager *pPager, /* Pager object */
49463  PgHdr *pList, /* List of frames to log */
49464  Pgno nTruncate, /* Database size after this commit */
49465  int isCommit /* True if this is a commit */
49466 ){
49467  int rc; /* Return code */
49468  int nList; /* Number of pages in pList */
49469  PgHdr *p; /* For looping over pages */
49470 
49471  assert( pPager->pWal );
49472  assert( pList );
49473 #ifdef SQLITE_DEBUG
49474  /* Verify that the page list is in accending order */
49475  for(p=pList; p && p->pDirty; p=p->pDirty){
49476  assert( p->pgno < p->pDirty->pgno );
49477  }
49478 #endif
49479 
49480  assert( pList->pDirty==0 || isCommit );
49481  if( isCommit ){
49482  /* If a WAL transaction is being committed, there is no point in writing
49483  ** any pages with page numbers greater than nTruncate into the WAL file.
49484  ** They will never be read by any client. So remove them from the pDirty
49485  ** list here. */
49486  PgHdr **ppNext = &pList;
49487  nList = 0;
49488  for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
49489  if( p->pgno<=nTruncate ){
49490  ppNext = &p->pDirty;
49491  nList++;
49492  }
49493  }
49494  assert( pList );
49495  }else{
49496  nList = 1;
49497  }
49498  pPager->aStat[PAGER_STAT_WRITE] += nList;
49499 
49500  if( pList->pgno==1 ) pager_write_changecounter(pList);
49501  rc = sqlite3WalFrames(pPager->pWal,
49502  pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
49503  );
49504  if( rc==SQLITE_OK && pPager->pBackup ){
49505  for(p=pList; p; p=p->pDirty){
49506  sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
49507  }
49508  }
49509 
49510 #ifdef SQLITE_CHECK_PAGES
49511  pList = sqlite3PcacheDirtyList(pPager->pPCache);
49512  for(p=pList; p; p=p->pDirty){
49513  pager_set_pagehash(p);
49514  }
49515 #endif
49516 
49517  return rc;
49518 }
49519 
49520 /*
49521 ** Begin a read transaction on the WAL.
49522 **
49523 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
49524 ** makes a snapshot of the database at the current point in time and preserves
49525 ** that snapshot for use by the reader in spite of concurrently changes by
49526 ** other writers or checkpointers.
49527 */
49528 static int pagerBeginReadTransaction(Pager *pPager){
49529  int rc; /* Return code */
49530  int changed = 0; /* True if cache must be reset */
49531 
49532  assert( pagerUseWal(pPager) );
49533  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
49534 
49535  /* sqlite3WalEndReadTransaction() was not called for the previous
49536  ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
49537  ** are in locking_mode=NORMAL and EndRead() was previously called,
49538  ** the duplicate call is harmless.
49539  */
49540  sqlite3WalEndReadTransaction(pPager->pWal);
49541 
49542  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
49543  if( rc!=SQLITE_OK || changed ){
49544  pager_reset(pPager);
49545  if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
49546  }
49547 
49548  return rc;
49549 }
49550 #endif
49551 
49552 /*
49553 ** This function is called as part of the transition from PAGER_OPEN
49554 ** to PAGER_READER state to determine the size of the database file
49555 ** in pages (assuming the page size currently stored in Pager.pageSize).
49556 **
49557 ** If no error occurs, SQLITE_OK is returned and the size of the database
49558 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
49559 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
49560 */
49561 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
49562  Pgno nPage; /* Value to return via *pnPage */
49563 
49564  /* Query the WAL sub-system for the database size. The WalDbsize()
49565  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
49566  ** if the database size is not available. The database size is not
49567  ** available from the WAL sub-system if the log file is empty or
49568  ** contains no valid committed transactions.
49569  */
49570  assert( pPager->eState==PAGER_OPEN );
49571  assert( pPager->eLock>=SHARED_LOCK );
49572  assert( isOpen(pPager->fd) );
49573  assert( pPager->tempFile==0 );
49574  nPage = sqlite3WalDbsize(pPager->pWal);
49575 
49576  /* If the number of pages in the database is not available from the
49577  ** WAL sub-system, determine the page counte based on the size of
49578  ** the database file. If the size of the database file is not an
49579  ** integer multiple of the page-size, round up the result.
49580  */
49581  if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
49582  i64 n = 0; /* Size of db file in bytes */
49583  int rc = sqlite3OsFileSize(pPager->fd, &n);
49584  if( rc!=SQLITE_OK ){
49585  return rc;
49586  }
49587  nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
49588  }
49589 
49590  /* If the current number of pages in the file is greater than the
49591  ** configured maximum pager number, increase the allowed limit so
49592  ** that the file can be read.
49593  */
49594  if( nPage>pPager->mxPgno ){
49595  pPager->mxPgno = (Pgno)nPage;
49596  }
49597 
49598  *pnPage = nPage;
49599  return SQLITE_OK;
49600 }
49601 
49602 #ifndef SQLITE_OMIT_WAL
49603 /*
49604 ** Check if the *-wal file that corresponds to the database opened by pPager
49605 ** exists if the database is not empy, or verify that the *-wal file does
49606 ** not exist (by deleting it) if the database file is empty.
49607 **
49608 ** If the database is not empty and the *-wal file exists, open the pager
49609 ** in WAL mode. If the database is empty or if no *-wal file exists and
49610 ** if no error occurs, make sure Pager.journalMode is not set to
49611 ** PAGER_JOURNALMODE_WAL.
49612 **
49613 ** Return SQLITE_OK or an error code.
49614 **
49615 ** The caller must hold a SHARED lock on the database file to call this
49616 ** function. Because an EXCLUSIVE lock on the db file is required to delete
49617 ** a WAL on a none-empty database, this ensures there is no race condition
49618 ** between the xAccess() below and an xDelete() being executed by some
49619 ** other connection.
49620 */
49621 static int pagerOpenWalIfPresent(Pager *pPager){
49622  int rc = SQLITE_OK;
49623  assert( pPager->eState==PAGER_OPEN );
49624  assert( pPager->eLock>=SHARED_LOCK );
49625 
49626  if( !pPager->tempFile ){
49627  int isWal; /* True if WAL file exists */
49628  Pgno nPage; /* Size of the database file */
49629 
49630  rc = pagerPagecount(pPager, &nPage);
49631  if( rc ) return rc;
49632  if( nPage==0 ){
49633  rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
49634  if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
49635  isWal = 0;
49636  }else{
49637  rc = sqlite3OsAccess(
49638  pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
49639  );
49640  }
49641  if( rc==SQLITE_OK ){
49642  if( isWal ){
49643  testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
49644  rc = sqlite3PagerOpenWal(pPager, 0);
49645  }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
49646  pPager->journalMode = PAGER_JOURNALMODE_DELETE;
49647  }
49648  }
49649  }
49650  return rc;
49651 }
49652 #endif
49653 
49654 /*
49655 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
49656 ** the entire master journal file. The case pSavepoint==NULL occurs when
49657 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
49658 ** savepoint.
49659 **
49660 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
49661 ** being rolled back), then the rollback consists of up to three stages,
49662 ** performed in the order specified:
49663 **
49664 ** * Pages are played back from the main journal starting at byte
49665 ** offset PagerSavepoint.iOffset and continuing to
49666 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
49667 ** file if PagerSavepoint.iHdrOffset is zero.
49668 **
49669 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
49670 ** back starting from the journal header immediately following
49671 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
49672 **
49673 ** * Pages are then played back from the sub-journal file, starting
49674 ** with the PagerSavepoint.iSubRec and continuing to the end of
49675 ** the journal file.
49676 **
49677 ** Throughout the rollback process, each time a page is rolled back, the
49678 ** corresponding bit is set in a bitvec structure (variable pDone in the
49679 ** implementation below). This is used to ensure that a page is only
49680 ** rolled back the first time it is encountered in either journal.
49681 **
49682 ** If pSavepoint is NULL, then pages are only played back from the main
49683 ** journal file. There is no need for a bitvec in this case.
49684 **
49685 ** In either case, before playback commences the Pager.dbSize variable
49686 ** is reset to the value that it held at the start of the savepoint
49687 ** (or transaction). No page with a page-number greater than this value
49688 ** is played back. If one is encountered it is simply skipped.
49689 */
49690 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
49691  i64 szJ; /* Effective size of the main journal */
49692  i64 iHdrOff; /* End of first segment of main-journal records */
49693  int rc = SQLITE_OK; /* Return code */
49694  Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
49695 
49696  assert( pPager->eState!=PAGER_ERROR );
49697  assert( pPager->eState>=PAGER_WRITER_LOCKED );
49698 
49699  /* Allocate a bitvec to use to store the set of pages rolled back */
49700  if( pSavepoint ){
49701  pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
49702  if( !pDone ){
49703  return SQLITE_NOMEM_BKPT;
49704  }
49705  }
49706 
49707  /* Set the database size back to the value it was before the savepoint
49708  ** being reverted was opened.
49709  */
49710  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
49711  pPager->changeCountDone = pPager->tempFile;
49712 
49713  if( !pSavepoint && pagerUseWal(pPager) ){
49714  return pagerRollbackWal(pPager);
49715  }
49716 
49717  /* Use pPager->journalOff as the effective size of the main rollback
49718  ** journal. The actual file might be larger than this in
49719  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
49720  ** past pPager->journalOff is off-limits to us.
49721  */
49722  szJ = pPager->journalOff;
49723  assert( pagerUseWal(pPager)==0 || szJ==0 );
49724 
49725  /* Begin by rolling back records from the main journal starting at
49726  ** PagerSavepoint.iOffset and continuing to the next journal header.
49727  ** There might be records in the main journal that have a page number
49728  ** greater than the current database size (pPager->dbSize) but those
49729  ** will be skipped automatically. Pages are added to pDone as they
49730  ** are played back.
49731  */
49732  if( pSavepoint && !pagerUseWal(pPager) ){
49733  iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
49734  pPager->journalOff = pSavepoint->iOffset;
49735  while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
49736  rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49737  }
49738  assert( rc!=SQLITE_DONE );
49739  }else{
49740  pPager->journalOff = 0;
49741  }
49742 
49743  /* Continue rolling back records out of the main journal starting at
49744  ** the first journal header seen and continuing until the effective end
49745  ** of the main journal file. Continue to skip out-of-range pages and
49746  ** continue adding pages rolled back to pDone.
49747  */
49748  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
49749  u32 ii; /* Loop counter */
49750  u32 nJRec = 0; /* Number of Journal Records */
49751  u32 dummy;
49752  rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
49753  assert( rc!=SQLITE_DONE );
49754 
49755  /*
49756  ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
49757  ** test is related to ticket #2565. See the discussion in the
49758  ** pager_playback() function for additional information.
49759  */
49760  if( nJRec==0
49761  && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
49762  ){
49763  nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
49764  }
49765  for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
49766  rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49767  }
49768  assert( rc!=SQLITE_DONE );
49769  }
49770  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
49771 
49772  /* Finally, rollback pages from the sub-journal. Page that were
49773  ** previously rolled back out of the main journal (and are hence in pDone)
49774  ** will be skipped. Out-of-range pages are also skipped.
49775  */
49776  if( pSavepoint ){
49777  u32 ii; /* Loop counter */
49778  i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
49779 
49780  if( pagerUseWal(pPager) ){
49781  rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
49782  }
49783  for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
49784  assert( offset==(i64)ii*(4+pPager->pageSize) );
49785  rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
49786  }
49787  assert( rc!=SQLITE_DONE );
49788  }
49789 
49790  sqlite3BitvecDestroy(pDone);
49791  if( rc==SQLITE_OK ){
49792  pPager->journalOff = szJ;
49793  }
49794 
49795  return rc;
49796 }
49797 
49798 /*
49799 ** Change the maximum number of in-memory pages that are allowed
49800 ** before attempting to recycle clean and unused pages.
49801 */
49802 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
49803  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
49804 }
49805 
49806 /*
49807 ** Change the maximum number of in-memory pages that are allowed
49808 ** before attempting to spill pages to journal.
49809 */
49810 SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
49811  return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
49812 }
49813 
49814 /*
49815 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
49816 */
49817 static void pagerFixMaplimit(Pager *pPager){
49818 #if SQLITE_MAX_MMAP_SIZE>0
49819  sqlite3_file *fd = pPager->fd;
49820  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
49821  sqlite3_int64 sz;
49822  sz = pPager->szMmap;
49823  pPager->bUseFetch = (sz>0);
49824  sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
49825  }
49826 #endif
49827 }
49828 
49829 /*
49830 ** Change the maximum size of any memory mapping made of the database file.
49831 */
49832 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
49833  pPager->szMmap = szMmap;
49834  pagerFixMaplimit(pPager);
49835 }
49836 
49837 /*
49838 ** Free as much memory as possible from the pager.
49839 */
49840 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
49841  sqlite3PcacheShrink(pPager->pPCache);
49842 }
49843 
49844 /*
49845 ** Adjust settings of the pager to those specified in the pgFlags parameter.
49846 **
49847 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
49848 ** of the database to damage due to OS crashes or power failures by
49849 ** changing the number of syncs()s when writing the journals.
49850 ** There are four levels:
49851 **
49852 ** OFF sqlite3OsSync() is never called. This is the default
49853 ** for temporary and transient files.
49854 **
49855 ** NORMAL The journal is synced once before writes begin on the
49856 ** database. This is normally adequate protection, but
49857 ** it is theoretically possible, though very unlikely,
49858 ** that an inopertune power failure could leave the journal
49859 ** in a state which would cause damage to the database
49860 ** when it is rolled back.
49861 **
49862 ** FULL The journal is synced twice before writes begin on the
49863 ** database (with some additional information - the nRec field
49864 ** of the journal header - being written in between the two
49865 ** syncs). If we assume that writing a
49866 ** single disk sector is atomic, then this mode provides
49867 ** assurance that the journal will not be corrupted to the
49868 ** point of causing damage to the database during rollback.
49869 **
49870 ** EXTRA This is like FULL except that is also syncs the directory
49871 ** that contains the rollback journal after the rollback
49872 ** journal is unlinked.
49873 **
49874 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
49875 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
49876 ** prior to the start of checkpoint and that the database file is synced
49877 ** at the conclusion of the checkpoint if the entire content of the WAL
49878 ** was written back into the database. But no sync operations occur for
49879 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
49880 ** file is synced following each commit operation, in addition to the
49881 ** syncs associated with NORMAL. There is no difference between FULL
49882 ** and EXTRA for WAL mode.
49883 **
49884 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
49885 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
49886 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
49887 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
49888 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
49889 ** synchronous=FULL versus synchronous=NORMAL setting determines when
49890 ** the xSync primitive is called and is relevant to all platforms.
49891 **
49892 ** Numeric values associated with these states are OFF==1, NORMAL=2,
49893 ** and FULL=3.
49894 */
49895 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
49896 SQLITE_PRIVATE void sqlite3PagerSetFlags(
49897  Pager *pPager, /* The pager to set safety level for */
49898  unsigned pgFlags /* Various flags */
49899 ){
49900  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
49901  if( pPager->tempFile ){
49902  pPager->noSync = 1;
49903  pPager->fullSync = 0;
49904  pPager->extraSync = 0;
49905  }else{
49906  pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
49907  pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
49908  pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
49909  }
49910  if( pPager->noSync ){
49911  pPager->syncFlags = 0;
49912  pPager->ckptSyncFlags = 0;
49913  }else if( pgFlags & PAGER_FULLFSYNC ){
49914  pPager->syncFlags = SQLITE_SYNC_FULL;
49915  pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49916  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
49917  pPager->syncFlags = SQLITE_SYNC_NORMAL;
49918  pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49919  }else{
49920  pPager->syncFlags = SQLITE_SYNC_NORMAL;
49921  pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
49922  }
49923  pPager->walSyncFlags = pPager->syncFlags;
49924  if( pPager->fullSync ){
49925  pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
49926  }
49927  if( pgFlags & PAGER_CACHESPILL ){
49928  pPager->doNotSpill &= ~SPILLFLAG_OFF;
49929  }else{
49930  pPager->doNotSpill |= SPILLFLAG_OFF;
49931  }
49932 }
49933 #endif
49934 
49935 /*
49936 ** The following global variable is incremented whenever the library
49937 ** attempts to open a temporary file. This information is used for
49938 ** testing and analysis only.
49939 */
49940 #ifdef SQLITE_TEST
49941 SQLITE_API int sqlite3_opentemp_count = 0;
49942 #endif
49943 
49944 /*
49945 ** Open a temporary file.
49946 **
49947 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
49948 ** or some other error code if we fail. The OS will automatically
49949 ** delete the temporary file when it is closed.
49950 **
49951 ** The flags passed to the VFS layer xOpen() call are those specified
49952 ** by parameter vfsFlags ORed with the following:
49953 **
49954 ** SQLITE_OPEN_READWRITE
49955 ** SQLITE_OPEN_CREATE
49956 ** SQLITE_OPEN_EXCLUSIVE
49957 ** SQLITE_OPEN_DELETEONCLOSE
49958 */
49959 static int pagerOpentemp(
49960  Pager *pPager, /* The pager object */
49961  sqlite3_file *pFile, /* Write the file descriptor here */
49962  int vfsFlags /* Flags passed through to the VFS */
49963 ){
49964  int rc; /* Return code */
49965 
49966 #ifdef SQLITE_TEST
49967  sqlite3_opentemp_count++; /* Used for testing and analysis only */
49968 #endif
49969 
49970  vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
49971  SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
49972  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
49973  assert( rc!=SQLITE_OK || isOpen(pFile) );
49974  return rc;
49975 }
49976 
49977 /*
49978 ** Set the busy handler function.
49979 **
49980 ** The pager invokes the busy-handler if sqlite3OsLock() returns
49981 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
49982 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
49983 ** lock. It does *not* invoke the busy handler when upgrading from
49984 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
49985 ** (which occurs during hot-journal rollback). Summary:
49986 **
49987 ** Transition | Invokes xBusyHandler
49988 ** --------------------------------------------------------
49989 ** NO_LOCK -> SHARED_LOCK | Yes
49990 ** SHARED_LOCK -> RESERVED_LOCK | No
49991 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
49992 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
49993 **
49994 ** If the busy-handler callback returns non-zero, the lock is
49995 ** retried. If it returns zero, then the SQLITE_BUSY error is
49996 ** returned to the caller of the pager API function.
49997 */
49998 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
49999  Pager *pPager, /* Pager object */
50000  int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
50001  void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
50002 ){
50003  pPager->xBusyHandler = xBusyHandler;
50004  pPager->pBusyHandlerArg = pBusyHandlerArg;
50005 
50006  if( isOpen(pPager->fd) ){
50007  void **ap = (void **)&pPager->xBusyHandler;
50008  assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
50009  assert( ap[1]==pBusyHandlerArg );
50010  sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
50011  }
50012 }
50013 
50014 /*
50015 ** Change the page size used by the Pager object. The new page size
50016 ** is passed in *pPageSize.
50017 **
50018 ** If the pager is in the error state when this function is called, it
50019 ** is a no-op. The value returned is the error state error code (i.e.
50020 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
50021 **
50022 ** Otherwise, if all of the following are true:
50023 **
50024 ** * the new page size (value of *pPageSize) is valid (a power
50025 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
50026 **
50027 ** * there are no outstanding page references, and
50028 **
50029 ** * the database is either not an in-memory database or it is
50030 ** an in-memory database that currently consists of zero pages.
50031 **
50032 ** then the pager object page size is set to *pPageSize.
50033 **
50034 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
50035 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
50036 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
50037 ** In all other cases, SQLITE_OK is returned.
50038 **
50039 ** If the page size is not changed, either because one of the enumerated
50040 ** conditions above is not true, the pager was in error state when this
50041 ** function was called, or because the memory allocation attempt failed,
50042 ** then *pPageSize is set to the old, retained page size before returning.
50043 */
50044 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
50045  int rc = SQLITE_OK;
50046 
50047  /* It is not possible to do a full assert_pager_state() here, as this
50048  ** function may be called from within PagerOpen(), before the state
50049  ** of the Pager object is internally consistent.
50050  **
50051  ** At one point this function returned an error if the pager was in
50052  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
50053  ** there is at least one outstanding page reference, this function
50054  ** is a no-op for that case anyhow.
50055  */
50056 
50057  u32 pageSize = *pPageSize;
50058  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
50059  if( (pPager->memDb==0 || pPager->dbSize==0)
50060  && sqlite3PcacheRefCount(pPager->pPCache)==0
50061  && pageSize && pageSize!=(u32)pPager->pageSize
50062  ){
50063  char *pNew = NULL; /* New temp space */
50064  i64 nByte = 0;
50065 
50066  if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
50067  rc = sqlite3OsFileSize(pPager->fd, &nByte);
50068  }
50069  if( rc==SQLITE_OK ){
50070  pNew = (char *)sqlite3PageMalloc(pageSize);
50071  if( !pNew ) rc = SQLITE_NOMEM_BKPT;
50072  }
50073 
50074  if( rc==SQLITE_OK ){
50075  pager_reset(pPager);
50076  rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
50077  }
50078  if( rc==SQLITE_OK ){
50079  sqlite3PageFree(pPager->pTmpSpace);
50080  pPager->pTmpSpace = pNew;
50081  pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
50082  pPager->pageSize = pageSize;
50083  }else{
50084  sqlite3PageFree(pNew);
50085  }
50086  }
50087 
50088  *pPageSize = pPager->pageSize;
50089  if( rc==SQLITE_OK ){
50090  if( nReserve<0 ) nReserve = pPager->nReserve;
50091  assert( nReserve>=0 && nReserve<1000 );
50092  pPager->nReserve = (i16)nReserve;
50093  pagerReportSize(pPager);
50094  pagerFixMaplimit(pPager);
50095  }
50096  return rc;
50097 }
50098 
50099 /*
50100 ** Return a pointer to the "temporary page" buffer held internally
50101 ** by the pager. This is a buffer that is big enough to hold the
50102 ** entire content of a database page. This buffer is used internally
50103 ** during rollback and will be overwritten whenever a rollback
50104 ** occurs. But other modules are free to use it too, as long as
50105 ** no rollbacks are happening.
50106 */
50107 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
50108  return pPager->pTmpSpace;
50109 }
50110 
50111 /*
50112 ** Attempt to set the maximum database page count if mxPage is positive.
50113 ** Make no changes if mxPage is zero or negative. And never reduce the
50114 ** maximum page count below the current size of the database.
50115 **
50116 ** Regardless of mxPage, return the current maximum page count.
50117 */
50118 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
50119  if( mxPage>0 ){
50120  pPager->mxPgno = mxPage;
50121  }
50122  assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
50123  assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
50124  return pPager->mxPgno;
50125 }
50126 
50127 /*
50128 ** The following set of routines are used to disable the simulated
50129 ** I/O error mechanism. These routines are used to avoid simulated
50130 ** errors in places where we do not care about errors.
50131 **
50132 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
50133 ** and generate no code.
50134 */
50135 #ifdef SQLITE_TEST
50136 SQLITE_API extern int sqlite3_io_error_pending;
50137 SQLITE_API extern int sqlite3_io_error_hit;
50138 static int saved_cnt;
50139 void disable_simulated_io_errors(void){
50140  saved_cnt = sqlite3_io_error_pending;
50141  sqlite3_io_error_pending = -1;
50142 }
50143 void enable_simulated_io_errors(void){
50144  sqlite3_io_error_pending = saved_cnt;
50145 }
50146 #else
50147 # define disable_simulated_io_errors()
50148 # define enable_simulated_io_errors()
50149 #endif
50150 
50151 /*
50152 ** Read the first N bytes from the beginning of the file into memory
50153 ** that pDest points to.
50154 **
50155 ** If the pager was opened on a transient file (zFilename==""), or
50156 ** opened on a file less than N bytes in size, the output buffer is
50157 ** zeroed and SQLITE_OK returned. The rationale for this is that this
50158 ** function is used to read database headers, and a new transient or
50159 ** zero sized database has a header than consists entirely of zeroes.
50160 **
50161 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
50162 ** the error code is returned to the caller and the contents of the
50163 ** output buffer undefined.
50164 */
50165 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
50166  int rc = SQLITE_OK;
50167  memset(pDest, 0, N);
50168  assert( isOpen(pPager->fd) || pPager->tempFile );
50169 
50170  /* This routine is only called by btree immediately after creating
50171  ** the Pager object. There has not been an opportunity to transition
50172  ** to WAL mode yet.
50173  */
50174  assert( !pagerUseWal(pPager) );
50175 
50176  if( isOpen(pPager->fd) ){
50177  IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
50178  rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
50179  if( rc==SQLITE_IOERR_SHORT_READ ){
50180  rc = SQLITE_OK;
50181  }
50182  }
50183  return rc;
50184 }
50185 
50186 /*
50187 ** This function may only be called when a read-transaction is open on
50188 ** the pager. It returns the total number of pages in the database.
50189 **
50190 ** However, if the file is between 1 and <page-size> bytes in size, then
50191 ** this is considered a 1 page file.
50192 */
50193 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
50194  assert( pPager->eState>=PAGER_READER );
50195  assert( pPager->eState!=PAGER_WRITER_FINISHED );
50196  *pnPage = (int)pPager->dbSize;
50197 }
50198 
50199 
50200 /*
50201 ** Try to obtain a lock of type locktype on the database file. If
50202 ** a similar or greater lock is already held, this function is a no-op
50203 ** (returning SQLITE_OK immediately).
50204 **
50205 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
50206 ** the busy callback if the lock is currently not available. Repeat
50207 ** until the busy callback returns false or until the attempt to
50208 ** obtain the lock succeeds.
50209 **
50210 ** Return SQLITE_OK on success and an error code if we cannot obtain
50211 ** the lock. If the lock is obtained successfully, set the Pager.state
50212 ** variable to locktype before returning.
50213 */
50214 static int pager_wait_on_lock(Pager *pPager, int locktype){
50215  int rc; /* Return code */
50216 
50217  /* Check that this is either a no-op (because the requested lock is
50218  ** already held), or one of the transitions that the busy-handler
50219  ** may be invoked during, according to the comment above
50220  ** sqlite3PagerSetBusyhandler().
50221  */
50222  assert( (pPager->eLock>=locktype)
50223  || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
50224  || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
50225  );
50226 
50227  do {
50228  rc = pagerLockDb(pPager, locktype);
50229  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
50230  return rc;
50231 }
50232 
50233 /*
50234 ** Function assertTruncateConstraint(pPager) checks that one of the
50235 ** following is true for all dirty pages currently in the page-cache:
50236 **
50237 ** a) The page number is less than or equal to the size of the
50238 ** current database image, in pages, OR
50239 **
50240 ** b) if the page content were written at this time, it would not
50241 ** be necessary to write the current content out to the sub-journal
50242 ** (as determined by function subjRequiresPage()).
50243 **
50244 ** If the condition asserted by this function were not true, and the
50245 ** dirty page were to be discarded from the cache via the pagerStress()
50246 ** routine, pagerStress() would not write the current page content to
50247 ** the database file. If a savepoint transaction were rolled back after
50248 ** this happened, the correct behavior would be to restore the current
50249 ** content of the page. However, since this content is not present in either
50250 ** the database file or the portion of the rollback journal and
50251 ** sub-journal rolled back the content could not be restored and the
50252 ** database image would become corrupt. It is therefore fortunate that
50253 ** this circumstance cannot arise.
50254 */
50255 #if defined(SQLITE_DEBUG)
50256 static void assertTruncateConstraintCb(PgHdr *pPg){
50257  assert( pPg->flags&PGHDR_DIRTY );
50258  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
50259 }
50260 static void assertTruncateConstraint(Pager *pPager){
50261  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
50262 }
50263 #else
50264 # define assertTruncateConstraint(pPager)
50265 #endif
50266 
50267 /*
50268 ** Truncate the in-memory database file image to nPage pages. This
50269 ** function does not actually modify the database file on disk. It
50270 ** just sets the internal state of the pager object so that the
50271 ** truncation will be done when the current transaction is committed.
50272 **
50273 ** This function is only called right before committing a transaction.
50274 ** Once this function has been called, the transaction must either be
50275 ** rolled back or committed. It is not safe to call this function and
50276 ** then continue writing to the database.
50277 */
50278 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
50279  assert( pPager->dbSize>=nPage );
50280  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
50281  pPager->dbSize = nPage;
50282 
50283  /* At one point the code here called assertTruncateConstraint() to
50284  ** ensure that all pages being truncated away by this operation are,
50285  ** if one or more savepoints are open, present in the savepoint
50286  ** journal so that they can be restored if the savepoint is rolled
50287  ** back. This is no longer necessary as this function is now only
50288  ** called right before committing a transaction. So although the
50289  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
50290  ** they cannot be rolled back. So the assertTruncateConstraint() call
50291  ** is no longer correct. */
50292 }
50293 
50294 
50295 /*
50296 ** This function is called before attempting a hot-journal rollback. It
50297 ** syncs the journal file to disk, then sets pPager->journalHdr to the
50298 ** size of the journal file so that the pager_playback() routine knows
50299 ** that the entire journal file has been synced.
50300 **
50301 ** Syncing a hot-journal to disk before attempting to roll it back ensures
50302 ** that if a power-failure occurs during the rollback, the process that
50303 ** attempts rollback following system recovery sees the same journal
50304 ** content as this process.
50305 **
50306 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
50307 ** an SQLite error code.
50308 */
50309 static int pagerSyncHotJournal(Pager *pPager){
50310  int rc = SQLITE_OK;
50311  if( !pPager->noSync ){
50312  rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
50313  }
50314  if( rc==SQLITE_OK ){
50315  rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
50316  }
50317  return rc;
50318 }
50319 
50320 /*
50321 ** Obtain a reference to a memory mapped page object for page number pgno.
50322 ** The new object will use the pointer pData, obtained from xFetch().
50323 ** If successful, set *ppPage to point to the new page reference
50324 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
50325 ** *ppPage to zero.
50326 **
50327 ** Page references obtained by calling this function should be released
50328 ** by calling pagerReleaseMapPage().
50329 */
50330 static int pagerAcquireMapPage(
50331  Pager *pPager, /* Pager object */
50332  Pgno pgno, /* Page number */
50333  void *pData, /* xFetch()'d data for this page */
50334  PgHdr **ppPage /* OUT: Acquired page object */
50335 ){
50336  PgHdr *p; /* Memory mapped page to return */
50337 
50338  if( pPager->pMmapFreelist ){
50339  *ppPage = p = pPager->pMmapFreelist;
50340  pPager->pMmapFreelist = p->pDirty;
50341  p->pDirty = 0;
50342  memset(p->pExtra, 0, pPager->nExtra);
50343  }else{
50344  *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
50345  if( p==0 ){
50346  sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
50347  return SQLITE_NOMEM_BKPT;
50348  }
50349  p->pExtra = (void *)&p[1];
50350  p->flags = PGHDR_MMAP;
50351  p->nRef = 1;
50352  p->pPager = pPager;
50353  }
50354 
50355  assert( p->pExtra==(void *)&p[1] );
50356  assert( p->pPage==0 );
50357  assert( p->flags==PGHDR_MMAP );
50358  assert( p->pPager==pPager );
50359  assert( p->nRef==1 );
50360 
50361  p->pgno = pgno;
50362  p->pData = pData;
50363  pPager->nMmapOut++;
50364 
50365  return SQLITE_OK;
50366 }
50367 
50368 /*
50369 ** Release a reference to page pPg. pPg must have been returned by an
50370 ** earlier call to pagerAcquireMapPage().
50371 */
50372 static void pagerReleaseMapPage(PgHdr *pPg){
50373  Pager *pPager = pPg->pPager;
50374  pPager->nMmapOut--;
50375  pPg->pDirty = pPager->pMmapFreelist;
50376  pPager->pMmapFreelist = pPg;
50377 
50378  assert( pPager->fd->pMethods->iVersion>=3 );
50379  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
50380 }
50381 
50382 /*
50383 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
50384 */
50385 static void pagerFreeMapHdrs(Pager *pPager){
50386  PgHdr *p;
50387  PgHdr *pNext;
50388  for(p=pPager->pMmapFreelist; p; p=pNext){
50389  pNext = p->pDirty;
50390  sqlite3_free(p);
50391  }
50392 }
50393 
50394 
50395 /*
50396 ** Shutdown the page cache. Free all memory and close all files.
50397 **
50398 ** If a transaction was in progress when this routine is called, that
50399 ** transaction is rolled back. All outstanding pages are invalidated
50400 ** and their memory is freed. Any attempt to use a page associated
50401 ** with this page cache after this function returns will likely
50402 ** result in a coredump.
50403 **
50404 ** This function always succeeds. If a transaction is active an attempt
50405 ** is made to roll it back. If an error occurs during the rollback
50406 ** a hot journal may be left in the filesystem but no error is returned
50407 ** to the caller.
50408 */
50409 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
50410  u8 *pTmp = (u8 *)pPager->pTmpSpace;
50411 
50412  assert( assert_pager_state(pPager) );
50413  disable_simulated_io_errors();
50414  sqlite3BeginBenignMalloc();
50415  pagerFreeMapHdrs(pPager);
50416  /* pPager->errCode = 0; */
50417  pPager->exclusiveMode = 0;
50418 #ifndef SQLITE_OMIT_WAL
50419  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
50420  pPager->pWal = 0;
50421 #endif
50422  pager_reset(pPager);
50423  if( MEMDB ){
50424  pager_unlock(pPager);
50425  }else{
50426  /* If it is open, sync the journal file before calling UnlockAndRollback.
50427  ** If this is not done, then an unsynced portion of the open journal
50428  ** file may be played back into the database. If a power failure occurs
50429  ** while this is happening, the database could become corrupt.
50430  **
50431  ** If an error occurs while trying to sync the journal, shift the pager
50432  ** into the ERROR state. This causes UnlockAndRollback to unlock the
50433  ** database and close the journal file without attempting to roll it
50434  ** back or finalize it. The next database user will have to do hot-journal
50435  ** rollback before accessing the database file.
50436  */
50437  if( isOpen(pPager->jfd) ){
50438  pager_error(pPager, pagerSyncHotJournal(pPager));
50439  }
50440  pagerUnlockAndRollback(pPager);
50441  }
50442  sqlite3EndBenignMalloc();
50443  enable_simulated_io_errors();
50444  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
50445  IOTRACE(("CLOSE %p\n", pPager))
50446  sqlite3OsClose(pPager->jfd);
50447  sqlite3OsClose(pPager->fd);
50448  sqlite3PageFree(pTmp);
50449  sqlite3PcacheClose(pPager->pPCache);
50450 
50451 #ifdef SQLITE_HAS_CODEC
50452  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
50453 #endif
50454 
50455  assert( !pPager->aSavepoint && !pPager->pInJournal );
50456  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
50457 
50458  sqlite3_free(pPager);
50459  return SQLITE_OK;
50460 }
50461 
50462 #if !defined(NDEBUG) || defined(SQLITE_TEST)
50463 /*
50464 ** Return the page number for page pPg.
50465 */
50466 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
50467  return pPg->pgno;
50468 }
50469 #endif
50470 
50471 /*
50472 ** Increment the reference count for page pPg.
50473 */
50474 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
50475  sqlite3PcacheRef(pPg);
50476 }
50477 
50478 /*
50479 ** Sync the journal. In other words, make sure all the pages that have
50480 ** been written to the journal have actually reached the surface of the
50481 ** disk and can be restored in the event of a hot-journal rollback.
50482 **
50483 ** If the Pager.noSync flag is set, then this function is a no-op.
50484 ** Otherwise, the actions required depend on the journal-mode and the
50485 ** device characteristics of the file-system, as follows:
50486 **
50487 ** * If the journal file is an in-memory journal file, no action need
50488 ** be taken.
50489 **
50490 ** * Otherwise, if the device does not support the SAFE_APPEND property,
50491 ** then the nRec field of the most recently written journal header
50492 ** is updated to contain the number of journal records that have
50493 ** been written following it. If the pager is operating in full-sync
50494 ** mode, then the journal file is synced before this field is updated.
50495 **
50496 ** * If the device does not support the SEQUENTIAL property, then
50497 ** journal file is synced.
50498 **
50499 ** Or, in pseudo-code:
50500 **
50501 ** if( NOT <in-memory journal> ){
50502 ** if( NOT SAFE_APPEND ){
50503 ** if( <full-sync mode> ) xSync(<journal file>);
50504 ** <update nRec field>
50505 ** }
50506 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
50507 ** }
50508 **
50509 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
50510 ** page currently held in memory before returning SQLITE_OK. If an IO
50511 ** error is encountered, then the IO error code is returned to the caller.
50512 */
50513 static int syncJournal(Pager *pPager, int newHdr){
50514  int rc; /* Return code */
50515 
50516  assert( pPager->eState==PAGER_WRITER_CACHEMOD
50517  || pPager->eState==PAGER_WRITER_DBMOD
50518  );
50519  assert( assert_pager_state(pPager) );
50520  assert( !pagerUseWal(pPager) );
50521 
50522  rc = sqlite3PagerExclusiveLock(pPager);
50523  if( rc!=SQLITE_OK ) return rc;
50524 
50525  if( !pPager->noSync ){
50526  assert( !pPager->tempFile );
50527  if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
50528  const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
50529  assert( isOpen(pPager->jfd) );
50530 
50531  if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50532  /* This block deals with an obscure problem. If the last connection
50533  ** that wrote to this database was operating in persistent-journal
50534  ** mode, then the journal file may at this point actually be larger
50535  ** than Pager.journalOff bytes. If the next thing in the journal
50536  ** file happens to be a journal-header (written as part of the
50537  ** previous connection's transaction), and a crash or power-failure
50538  ** occurs after nRec is updated but before this connection writes
50539  ** anything else to the journal file (or commits/rolls back its
50540  ** transaction), then SQLite may become confused when doing the
50541  ** hot-journal rollback following recovery. It may roll back all
50542  ** of this connections data, then proceed to rolling back the old,
50543  ** out-of-date data that follows it. Database corruption.
50544  **
50545  ** To work around this, if the journal file does appear to contain
50546  ** a valid header following Pager.journalOff, then write a 0x00
50547  ** byte to the start of it to prevent it from being recognized.
50548  **
50549  ** Variable iNextHdrOffset is set to the offset at which this
50550  ** problematic header will occur, if it exists. aMagic is used
50551  ** as a temporary buffer to inspect the first couple of bytes of
50552  ** the potential journal header.
50553  */
50554  i64 iNextHdrOffset;
50555  u8 aMagic[8];
50556  u8 zHeader[sizeof(aJournalMagic)+4];
50557 
50558  memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
50559  put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
50560 
50561  iNextHdrOffset = journalHdrOffset(pPager);
50562  rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
50563  if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
50564  static const u8 zerobyte = 0;
50565  rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
50566  }
50567  if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
50568  return rc;
50569  }
50570 
50571  /* Write the nRec value into the journal file header. If in
50572  ** full-synchronous mode, sync the journal first. This ensures that
50573  ** all data has really hit the disk before nRec is updated to mark
50574  ** it as a candidate for rollback.
50575  **
50576  ** This is not required if the persistent media supports the
50577  ** SAFE_APPEND property. Because in this case it is not possible
50578  ** for garbage data to be appended to the file, the nRec field
50579  ** is populated with 0xFFFFFFFF when the journal header is written
50580  ** and never needs to be updated.
50581  */
50582  if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50583  PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50584  IOTRACE(("JSYNC %p\n", pPager))
50585  rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
50586  if( rc!=SQLITE_OK ) return rc;
50587  }
50588  IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
50589  rc = sqlite3OsWrite(
50590  pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
50591  );
50592  if( rc!=SQLITE_OK ) return rc;
50593  }
50594  if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50595  PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50596  IOTRACE(("JSYNC %p\n", pPager))
50597  rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
50598  (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
50599  );
50600  if( rc!=SQLITE_OK ) return rc;
50601  }
50602 
50603  pPager->journalHdr = pPager->journalOff;
50604  if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50605  pPager->nRec = 0;
50606  rc = writeJournalHdr(pPager);
50607  if( rc!=SQLITE_OK ) return rc;
50608  }
50609  }else{
50610  pPager->journalHdr = pPager->journalOff;
50611  }
50612  }
50613 
50614  /* Unless the pager is in noSync mode, the journal file was just
50615  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
50616  ** all pages.
50617  */
50618  sqlite3PcacheClearSyncFlags(pPager->pPCache);
50619  pPager->eState = PAGER_WRITER_DBMOD;
50620  assert( assert_pager_state(pPager) );
50621  return SQLITE_OK;
50622 }
50623 
50624 /*
50625 ** The argument is the first in a linked list of dirty pages connected
50626 ** by the PgHdr.pDirty pointer. This function writes each one of the
50627 ** in-memory pages in the list to the database file. The argument may
50628 ** be NULL, representing an empty list. In this case this function is
50629 ** a no-op.
50630 **
50631 ** The pager must hold at least a RESERVED lock when this function
50632 ** is called. Before writing anything to the database file, this lock
50633 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
50634 ** SQLITE_BUSY is returned and no data is written to the database file.
50635 **
50636 ** If the pager is a temp-file pager and the actual file-system file
50637 ** is not yet open, it is created and opened before any data is
50638 ** written out.
50639 **
50640 ** Once the lock has been upgraded and, if necessary, the file opened,
50641 ** the pages are written out to the database file in list order. Writing
50642 ** a page is skipped if it meets either of the following criteria:
50643 **
50644 ** * The page number is greater than Pager.dbSize, or
50645 ** * The PGHDR_DONT_WRITE flag is set on the page.
50646 **
50647 ** If writing out a page causes the database file to grow, Pager.dbFileSize
50648 ** is updated accordingly. If page 1 is written out, then the value cached
50649 ** in Pager.dbFileVers[] is updated to match the new value stored in
50650 ** the database file.
50651 **
50652 ** If everything is successful, SQLITE_OK is returned. If an IO error
50653 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
50654 ** be obtained, SQLITE_BUSY is returned.
50655 */
50656 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
50657  int rc = SQLITE_OK; /* Return code */
50658 
50659  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
50660  assert( !pagerUseWal(pPager) );
50661  assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
50662  assert( pPager->eLock==EXCLUSIVE_LOCK );
50663  assert( isOpen(pPager->fd) || pList->pDirty==0 );
50664 
50665  /* If the file is a temp-file has not yet been opened, open it now. It
50666  ** is not possible for rc to be other than SQLITE_OK if this branch
50667  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
50668  */
50669  if( !isOpen(pPager->fd) ){
50670  assert( pPager->tempFile && rc==SQLITE_OK );
50671  rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
50672  }
50673 
50674  /* Before the first write, give the VFS a hint of what the final
50675  ** file size will be.
50676  */
50677  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
50678  if( rc==SQLITE_OK
50679  && pPager->dbHintSize<pPager->dbSize
50680  && (pList->pDirty || pList->pgno>pPager->dbHintSize)
50681  ){
50682  sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
50683  sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
50684  pPager->dbHintSize = pPager->dbSize;
50685  }
50686 
50687  while( rc==SQLITE_OK && pList ){
50688  Pgno pgno = pList->pgno;
50689 
50690  /* If there are dirty pages in the page cache with page numbers greater
50691  ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
50692  ** make the file smaller (presumably by auto-vacuum code). Do not write
50693  ** any such pages to the file.
50694  **
50695  ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
50696  ** set (set by sqlite3PagerDontWrite()).
50697  */
50698  if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
50699  i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
50700  char *pData; /* Data to write */
50701 
50702  assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
50703  if( pList->pgno==1 ) pager_write_changecounter(pList);
50704 
50705  /* Encode the database */
50706  CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
50707 
50708  /* Write out the page data. */
50709  rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
50710 
50711  /* If page 1 was just written, update Pager.dbFileVers to match
50712  ** the value now stored in the database file. If writing this
50713  ** page caused the database file to grow, update dbFileSize.
50714  */
50715  if( pgno==1 ){
50716  memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
50717  }
50718  if( pgno>pPager->dbFileSize ){
50719  pPager->dbFileSize = pgno;
50720  }
50721  pPager->aStat[PAGER_STAT_WRITE]++;
50722 
50723  /* Update any backup objects copying the contents of this pager. */
50724  sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
50725 
50726  PAGERTRACE(("STORE %d page %d hash(%08x)\n",
50727  PAGERID(pPager), pgno, pager_pagehash(pList)));
50728  IOTRACE(("PGOUT %p %d\n", pPager, pgno));
50729  PAGER_INCR(sqlite3_pager_writedb_count);
50730  }else{
50731  PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
50732  }
50733  pager_set_pagehash(pList);
50734  pList = pList->pDirty;
50735  }
50736 
50737  return rc;
50738 }
50739 
50740 /*
50741 ** Ensure that the sub-journal file is open. If it is already open, this
50742 ** function is a no-op.
50743 **
50744 ** SQLITE_OK is returned if everything goes according to plan. An
50745 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
50746 ** fails.
50747 */
50748 static int openSubJournal(Pager *pPager){
50749  int rc = SQLITE_OK;
50750  if( !isOpen(pPager->sjfd) ){
50751  const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
50752  | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
50753  | SQLITE_OPEN_DELETEONCLOSE;
50754  int nStmtSpill = sqlite3Config.nStmtSpill;
50755  if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
50756  nStmtSpill = -1;
50757  }
50758  rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
50759  }
50760  return rc;
50761 }
50762 
50763 /*
50764 ** Append a record of the current state of page pPg to the sub-journal.
50765 **
50766 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
50767 ** for all open savepoints before returning.
50768 **
50769 ** This function returns SQLITE_OK if everything is successful, an IO
50770 ** error code if the attempt to write to the sub-journal fails, or
50771 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
50772 ** bitvec.
50773 */
50774 static int subjournalPage(PgHdr *pPg){
50775  int rc = SQLITE_OK;
50776  Pager *pPager = pPg->pPager;
50777  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
50778 
50779  /* Open the sub-journal, if it has not already been opened */
50780  assert( pPager->useJournal );
50781  assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
50782  assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
50783  assert( pagerUseWal(pPager)
50784  || pageInJournal(pPager, pPg)
50785  || pPg->pgno>pPager->dbOrigSize
50786  );
50787  rc = openSubJournal(pPager);
50788 
50789  /* If the sub-journal was opened successfully (or was already open),
50790  ** write the journal record into the file. */
50791  if( rc==SQLITE_OK ){
50792  void *pData = pPg->pData;
50793  i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
50794  char *pData2;
50795 
50796  CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
50797  PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
50798  rc = write32bits(pPager->sjfd, offset, pPg->pgno);
50799  if( rc==SQLITE_OK ){
50800  rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
50801  }
50802  }
50803  }
50804  if( rc==SQLITE_OK ){
50805  pPager->nSubRec++;
50806  assert( pPager->nSavepoint>0 );
50807  rc = addToSavepointBitvecs(pPager, pPg->pgno);
50808  }
50809  return rc;
50810 }
50811 static int subjournalPageIfRequired(PgHdr *pPg){
50812  if( subjRequiresPage(pPg) ){
50813  return subjournalPage(pPg);
50814  }else{
50815  return SQLITE_OK;
50816  }
50817 }
50818 
50819 /*
50820 ** This function is called by the pcache layer when it has reached some
50821 ** soft memory limit. The first argument is a pointer to a Pager object
50822 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
50823 ** database). The second argument is a reference to a page that is
50824 ** currently dirty but has no outstanding references. The page
50825 ** is always associated with the Pager object passed as the first
50826 ** argument.
50827 **
50828 ** The job of this function is to make pPg clean by writing its contents
50829 ** out to the database file, if possible. This may involve syncing the
50830 ** journal file.
50831 **
50832 ** If successful, sqlite3PcacheMakeClean() is called on the page and
50833 ** SQLITE_OK returned. If an IO error occurs while trying to make the
50834 ** page clean, the IO error code is returned. If the page cannot be
50835 ** made clean for some other reason, but no error occurs, then SQLITE_OK
50836 ** is returned by sqlite3PcacheMakeClean() is not called.
50837 */
50838 static int pagerStress(void *p, PgHdr *pPg){
50839  Pager *pPager = (Pager *)p;
50840  int rc = SQLITE_OK;
50841 
50842  assert( pPg->pPager==pPager );
50843  assert( pPg->flags&PGHDR_DIRTY );
50844 
50845  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
50846  ** journal (and adding a new header) is not allowed. This occurs
50847  ** during calls to sqlite3PagerWrite() while trying to journal multiple
50848  ** pages belonging to the same sector.
50849  **
50850  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
50851  ** regardless of whether or not a sync is required. This is set during
50852  ** a rollback or by user request, respectively.
50853  **
50854  ** Spilling is also prohibited when in an error state since that could
50855  ** lead to database corruption. In the current implementation it
50856  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
50857  ** while in the error state, hence it is impossible for this routine to
50858  ** be called in the error state. Nevertheless, we include a NEVER()
50859  ** test for the error state as a safeguard against future changes.
50860  */
50861  if( NEVER(pPager->errCode) ) return SQLITE_OK;
50862  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
50863  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
50864  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
50865  if( pPager->doNotSpill
50866  && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
50867  || (pPg->flags & PGHDR_NEED_SYNC)!=0)
50868  ){
50869  return SQLITE_OK;
50870  }
50871 
50872  pPg->pDirty = 0;
50873  if( pagerUseWal(pPager) ){
50874  /* Write a single frame for this page to the log. */
50875  rc = subjournalPageIfRequired(pPg);
50876  if( rc==SQLITE_OK ){
50877  rc = pagerWalFrames(pPager, pPg, 0, 0);
50878  }
50879  }else{
50880 
50881  /* Sync the journal file if required. */
50882  if( pPg->flags&PGHDR_NEED_SYNC
50883  || pPager->eState==PAGER_WRITER_CACHEMOD
50884  ){
50885  rc = syncJournal(pPager, 1);
50886  }
50887 
50888  /* Write the contents of the page out to the database file. */
50889  if( rc==SQLITE_OK ){
50890  assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
50891  rc = pager_write_pagelist(pPager, pPg);
50892  }
50893  }
50894 
50895  /* Mark the page as clean. */
50896  if( rc==SQLITE_OK ){
50897  PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
50898  sqlite3PcacheMakeClean(pPg);
50899  }
50900 
50901  return pager_error(pPager, rc);
50902 }
50903 
50904 /*
50905 ** Flush all unreferenced dirty pages to disk.
50906 */
50907 SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
50908  int rc = pPager->errCode;
50909  if( !MEMDB ){
50910  PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
50911  assert( assert_pager_state(pPager) );
50912  while( rc==SQLITE_OK && pList ){
50913  PgHdr *pNext = pList->pDirty;
50914  if( pList->nRef==0 ){
50915  rc = pagerStress((void*)pPager, pList);
50916  }
50917  pList = pNext;
50918  }
50919  }
50920 
50921  return rc;
50922 }
50923 
50924 /*
50925 ** Allocate and initialize a new Pager object and put a pointer to it
50926 ** in *ppPager. The pager should eventually be freed by passing it
50927 ** to sqlite3PagerClose().
50928 **
50929 ** The zFilename argument is the path to the database file to open.
50930 ** If zFilename is NULL then a randomly-named temporary file is created
50931 ** and used as the file to be cached. Temporary files are be deleted
50932 ** automatically when they are closed. If zFilename is ":memory:" then
50933 ** all information is held in cache. It is never written to disk.
50934 ** This can be used to implement an in-memory database.
50935 **
50936 ** The nExtra parameter specifies the number of bytes of space allocated
50937 ** along with each page reference. This space is available to the user
50938 ** via the sqlite3PagerGetExtra() API.
50939 **
50940 ** The flags argument is used to specify properties that affect the
50941 ** operation of the pager. It should be passed some bitwise combination
50942 ** of the PAGER_* flags.
50943 **
50944 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
50945 ** of the xOpen() method of the supplied VFS when opening files.
50946 **
50947 ** If the pager object is allocated and the specified file opened
50948 ** successfully, SQLITE_OK is returned and *ppPager set to point to
50949 ** the new pager object. If an error occurs, *ppPager is set to NULL
50950 ** and error code returned. This function may return SQLITE_NOMEM
50951 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
50952 ** various SQLITE_IO_XXX errors.
50953 */
50954 SQLITE_PRIVATE int sqlite3PagerOpen(
50955  sqlite3_vfs *pVfs, /* The virtual file system to use */
50956  Pager **ppPager, /* OUT: Return the Pager structure here */
50957  const char *zFilename, /* Name of the database file to open */
50958  int nExtra, /* Extra bytes append to each in-memory page */
50959  int flags, /* flags controlling this file */
50960  int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
50961  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
50962 ){
50963  u8 *pPtr;
50964  Pager *pPager = 0; /* Pager object to allocate and return */
50965  int rc = SQLITE_OK; /* Return code */
50966  int tempFile = 0; /* True for temp files (incl. in-memory files) */
50967  int memDb = 0; /* True if this is an in-memory file */
50968  int readOnly = 0; /* True if this is a read-only file */
50969  int journalFileSize; /* Bytes to allocate for each journal fd */
50970  char *zPathname = 0; /* Full path to database file */
50971  int nPathname = 0; /* Number of bytes in zPathname */
50972  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
50973  int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
50974  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
50975  const char *zUri = 0; /* URI args to copy */
50976  int nUri = 0; /* Number of bytes of URI args at *zUri */
50977 
50978  /* Figure out how much space is required for each journal file-handle
50979  ** (there are two of them, the main journal and the sub-journal). */
50980  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
50981 
50982  /* Set the output variable to NULL in case an error occurs. */
50983  *ppPager = 0;
50984 
50985 #ifndef SQLITE_OMIT_MEMORYDB
50986  if( flags & PAGER_MEMORY ){
50987  memDb = 1;
50988  if( zFilename && zFilename[0] ){
50989  zPathname = sqlite3DbStrDup(0, zFilename);
50990  if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
50991  nPathname = sqlite3Strlen30(zPathname);
50992  zFilename = 0;
50993  }
50994  }
50995 #endif
50996 
50997  /* Compute and store the full pathname in an allocated buffer pointed
50998  ** to by zPathname, length nPathname. Or, if this is a temporary file,
50999  ** leave both nPathname and zPathname set to 0.
51000  */
51001  if( zFilename && zFilename[0] ){
51002  const char *z;
51003  nPathname = pVfs->mxPathname+1;
51004  zPathname = sqlite3DbMallocRaw(0, nPathname*2);
51005  if( zPathname==0 ){
51006  return SQLITE_NOMEM_BKPT;
51007  }
51008  zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
51009  rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
51010  nPathname = sqlite3Strlen30(zPathname);
51011  z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
51012  while( *z ){
51013  z += sqlite3Strlen30(z)+1;
51014  z += sqlite3Strlen30(z)+1;
51015  }
51016  nUri = (int)(&z[1] - zUri);
51017  assert( nUri>=0 );
51018  if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
51019  /* This branch is taken when the journal path required by
51020  ** the database being opened will be more than pVfs->mxPathname
51021  ** bytes in length. This means the database cannot be opened,
51022  ** as it will not be possible to open the journal file or even
51023  ** check for a hot-journal before reading.
51024  */
51025  rc = SQLITE_CANTOPEN_BKPT;
51026  }
51027  if( rc!=SQLITE_OK ){
51028  sqlite3DbFree(0, zPathname);
51029  return rc;
51030  }
51031  }
51032 
51033  /* Allocate memory for the Pager structure, PCache object, the
51034  ** three file descriptors, the database file name and the journal
51035  ** file name. The layout in memory is as follows:
51036  **
51037  ** Pager object (sizeof(Pager) bytes)
51038  ** PCache object (sqlite3PcacheSize() bytes)
51039  ** Database file handle (pVfs->szOsFile bytes)
51040  ** Sub-journal file handle (journalFileSize bytes)
51041  ** Main journal file handle (journalFileSize bytes)
51042  ** Database file name (nPathname+1 bytes)
51043  ** Journal file name (nPathname+8+1 bytes)
51044  */
51045  pPtr = (u8 *)sqlite3MallocZero(
51046  ROUND8(sizeof(*pPager)) + /* Pager structure */
51047  ROUND8(pcacheSize) + /* PCache object */
51048  ROUND8(pVfs->szOsFile) + /* The main db file */
51049  journalFileSize * 2 + /* The two journal files */
51050  nPathname + 1 + nUri + /* zFilename */
51051  nPathname + 8 + 2 /* zJournal */
51052 #ifndef SQLITE_OMIT_WAL
51053  + nPathname + 4 + 2 /* zWal */
51054 #endif
51055  );
51056  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
51057  if( !pPtr ){
51058  sqlite3DbFree(0, zPathname);
51059  return SQLITE_NOMEM_BKPT;
51060  }
51061  pPager = (Pager*)(pPtr);
51062  pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
51063  pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
51064  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
51065  pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
51066  pPager->zFilename = (char*)(pPtr += journalFileSize);
51067  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
51068 
51069  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
51070  if( zPathname ){
51071  assert( nPathname>0 );
51072  pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
51073  memcpy(pPager->zFilename, zPathname, nPathname);
51074  if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
51075  memcpy(pPager->zJournal, zPathname, nPathname);
51076  memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
51077  sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
51078 #ifndef SQLITE_OMIT_WAL
51079  pPager->zWal = &pPager->zJournal[nPathname+8+1];
51080  memcpy(pPager->zWal, zPathname, nPathname);
51081  memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
51082  sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
51083 #endif
51084  sqlite3DbFree(0, zPathname);
51085  }
51086  pPager->pVfs = pVfs;
51087  pPager->vfsFlags = vfsFlags;
51088 
51089  /* Open the pager file.
51090  */
51091  if( zFilename && zFilename[0] ){
51092  int fout = 0; /* VFS flags returned by xOpen() */
51093  rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
51094  assert( !memDb );
51095  readOnly = (fout&SQLITE_OPEN_READONLY);
51096 
51097  /* If the file was successfully opened for read/write access,
51098  ** choose a default page size in case we have to create the
51099  ** database file. The default page size is the maximum of:
51100  **
51101  ** + SQLITE_DEFAULT_PAGE_SIZE,
51102  ** + The value returned by sqlite3OsSectorSize()
51103  ** + The largest page size that can be written atomically.
51104  */
51105  if( rc==SQLITE_OK ){
51106  int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
51107  if( !readOnly ){
51108  setSectorSize(pPager);
51109  assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
51110  if( szPageDflt<pPager->sectorSize ){
51111  if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
51112  szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
51113  }else{
51114  szPageDflt = (u32)pPager->sectorSize;
51115  }
51116  }
51117 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
51118  {
51119  int ii;
51120  assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
51121  assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
51122  assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
51123  for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
51124  if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
51125  szPageDflt = ii;
51126  }
51127  }
51128  }
51129 #endif
51130  }
51131  pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
51132  if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
51133  || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
51134  vfsFlags |= SQLITE_OPEN_READONLY;
51135  goto act_like_temp_file;
51136  }
51137  }
51138  }else{
51139  /* If a temporary file is requested, it is not opened immediately.
51140  ** In this case we accept the default page size and delay actually
51141  ** opening the file until the first call to OsWrite().
51142  **
51143  ** This branch is also run for an in-memory database. An in-memory
51144  ** database is the same as a temp-file that is never written out to
51145  ** disk and uses an in-memory rollback journal.
51146  **
51147  ** This branch also runs for files marked as immutable.
51148  */
51149 act_like_temp_file:
51150  tempFile = 1;
51151  pPager->eState = PAGER_READER; /* Pretend we already have a lock */
51152  pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
51153  pPager->noLock = 1; /* Do no locking */
51154  readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
51155  }
51156 
51157  /* The following call to PagerSetPagesize() serves to set the value of
51158  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
51159  */
51160  if( rc==SQLITE_OK ){
51161  assert( pPager->memDb==0 );
51162  rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
51163  testcase( rc!=SQLITE_OK );
51164  }
51165 
51166  /* Initialize the PCache object. */
51167  if( rc==SQLITE_OK ){
51168  assert( nExtra<1000 );
51169  nExtra = ROUND8(nExtra);
51170  rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
51171  !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
51172  }
51173 
51174  /* If an error occurred above, free the Pager structure and close the file.
51175  */
51176  if( rc!=SQLITE_OK ){
51177  sqlite3OsClose(pPager->fd);
51178  sqlite3PageFree(pPager->pTmpSpace);
51179  sqlite3_free(pPager);
51180  return rc;
51181  }
51182 
51183  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
51184  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
51185 
51186  pPager->useJournal = (u8)useJournal;
51187  /* pPager->stmtOpen = 0; */
51188  /* pPager->stmtInUse = 0; */
51189  /* pPager->nRef = 0; */
51190  /* pPager->stmtSize = 0; */
51191  /* pPager->stmtJSize = 0; */
51192  /* pPager->nPage = 0; */
51193  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
51194  /* pPager->state = PAGER_UNLOCK; */
51195  /* pPager->errMask = 0; */
51196  pPager->tempFile = (u8)tempFile;
51197  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
51198  || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
51199  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
51200  pPager->exclusiveMode = (u8)tempFile;
51201  pPager->changeCountDone = pPager->tempFile;
51202  pPager->memDb = (u8)memDb;
51203  pPager->readOnly = (u8)readOnly;
51204  assert( useJournal || pPager->tempFile );
51205  pPager->noSync = pPager->tempFile;
51206  if( pPager->noSync ){
51207  assert( pPager->fullSync==0 );
51208  assert( pPager->extraSync==0 );
51209  assert( pPager->syncFlags==0 );
51210  assert( pPager->walSyncFlags==0 );
51211  assert( pPager->ckptSyncFlags==0 );
51212  }else{
51213  pPager->fullSync = 1;
51214  pPager->extraSync = 0;
51215  pPager->syncFlags = SQLITE_SYNC_NORMAL;
51216  pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
51217  pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
51218  }
51219  /* pPager->pFirst = 0; */
51220  /* pPager->pFirstSynced = 0; */
51221  /* pPager->pLast = 0; */
51222  pPager->nExtra = (u16)nExtra;
51223  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
51224  assert( isOpen(pPager->fd) || tempFile );
51225  setSectorSize(pPager);
51226  if( !useJournal ){
51227  pPager->journalMode = PAGER_JOURNALMODE_OFF;
51228  }else if( memDb ){
51229  pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
51230  }
51231  /* pPager->xBusyHandler = 0; */
51232  /* pPager->pBusyHandlerArg = 0; */
51233  pPager->xReiniter = xReinit;
51234  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
51235  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
51236 
51237  *ppPager = pPager;
51238  return SQLITE_OK;
51239 }
51240 
51241 
51242 /* Verify that the database file has not be deleted or renamed out from
51243 ** under the pager. Return SQLITE_OK if the database is still were it ought
51244 ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
51245 ** code from sqlite3OsAccess()) if the database has gone missing.
51246 */
51247 static int databaseIsUnmoved(Pager *pPager){
51248  int bHasMoved = 0;
51249  int rc;
51250 
51251  if( pPager->tempFile ) return SQLITE_OK;
51252  if( pPager->dbSize==0 ) return SQLITE_OK;
51253  assert( pPager->zFilename && pPager->zFilename[0] );
51254  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
51255  if( rc==SQLITE_NOTFOUND ){
51256  /* If the HAS_MOVED file-control is unimplemented, assume that the file
51257  ** has not been moved. That is the historical behavior of SQLite: prior to
51258  ** version 3.8.3, it never checked */
51259  rc = SQLITE_OK;
51260  }else if( rc==SQLITE_OK && bHasMoved ){
51261  rc = SQLITE_READONLY_DBMOVED;
51262  }
51263  return rc;
51264 }
51265 
51266 
51267 /*
51268 ** This function is called after transitioning from PAGER_UNLOCK to
51269 ** PAGER_SHARED state. It tests if there is a hot journal present in
51270 ** the file-system for the given pager. A hot journal is one that
51271 ** needs to be played back. According to this function, a hot-journal
51272 ** file exists if the following criteria are met:
51273 **
51274 ** * The journal file exists in the file system, and
51275 ** * No process holds a RESERVED or greater lock on the database file, and
51276 ** * The database file itself is greater than 0 bytes in size, and
51277 ** * The first byte of the journal file exists and is not 0x00.
51278 **
51279 ** If the current size of the database file is 0 but a journal file
51280 ** exists, that is probably an old journal left over from a prior
51281 ** database with the same name. In this case the journal file is
51282 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
51283 ** is returned.
51284 **
51285 ** This routine does not check if there is a master journal filename
51286 ** at the end of the file. If there is, and that master journal file
51287 ** does not exist, then the journal file is not really hot. In this
51288 ** case this routine will return a false-positive. The pager_playback()
51289 ** routine will discover that the journal file is not really hot and
51290 ** will not roll it back.
51291 **
51292 ** If a hot-journal file is found to exist, *pExists is set to 1 and
51293 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
51294 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
51295 ** to determine whether or not a hot-journal file exists, the IO error
51296 ** code is returned and the value of *pExists is undefined.
51297 */
51298 static int hasHotJournal(Pager *pPager, int *pExists){
51299  sqlite3_vfs * const pVfs = pPager->pVfs;
51300  int rc = SQLITE_OK; /* Return code */
51301  int exists = 1; /* True if a journal file is present */
51302  int jrnlOpen = !!isOpen(pPager->jfd);
51303 
51304  assert( pPager->useJournal );
51305  assert( isOpen(pPager->fd) );
51306  assert( pPager->eState==PAGER_OPEN );
51307 
51308  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
51309  SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
51310  ));
51311 
51312  *pExists = 0;
51313  if( !jrnlOpen ){
51314  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
51315  }
51316  if( rc==SQLITE_OK && exists ){
51317  int locked = 0; /* True if some process holds a RESERVED lock */
51318 
51319  /* Race condition here: Another process might have been holding the
51320  ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
51321  ** call above, but then delete the journal and drop the lock before
51322  ** we get to the following sqlite3OsCheckReservedLock() call. If that
51323  ** is the case, this routine might think there is a hot journal when
51324  ** in fact there is none. This results in a false-positive which will
51325  ** be dealt with by the playback routine. Ticket #3883.
51326  */
51327  rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
51328  if( rc==SQLITE_OK && !locked ){
51329  Pgno nPage; /* Number of pages in database file */
51330 
51331  assert( pPager->tempFile==0 );
51332  rc = pagerPagecount(pPager, &nPage);
51333  if( rc==SQLITE_OK ){
51334  /* If the database is zero pages in size, that means that either (1) the
51335  ** journal is a remnant from a prior database with the same name where
51336  ** the database file but not the journal was deleted, or (2) the initial
51337  ** transaction that populates a new database is being rolled back.
51338  ** In either case, the journal file can be deleted. However, take care
51339  ** not to delete the journal file if it is already open due to
51340  ** journal_mode=PERSIST.
51341  */
51342  if( nPage==0 && !jrnlOpen ){
51343  sqlite3BeginBenignMalloc();
51344  if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
51345  sqlite3OsDelete(pVfs, pPager->zJournal, 0);
51346  if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
51347  }
51348  sqlite3EndBenignMalloc();
51349  }else{
51350  /* The journal file exists and no other connection has a reserved
51351  ** or greater lock on the database file. Now check that there is
51352  ** at least one non-zero bytes at the start of the journal file.
51353  ** If there is, then we consider this journal to be hot. If not,
51354  ** it can be ignored.
51355  */
51356  if( !jrnlOpen ){
51357  int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
51358  rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
51359  }
51360  if( rc==SQLITE_OK ){
51361  u8 first = 0;
51362  rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
51363  if( rc==SQLITE_IOERR_SHORT_READ ){
51364  rc = SQLITE_OK;
51365  }
51366  if( !jrnlOpen ){
51367  sqlite3OsClose(pPager->jfd);
51368  }
51369  *pExists = (first!=0);
51370  }else if( rc==SQLITE_CANTOPEN ){
51371  /* If we cannot open the rollback journal file in order to see if
51372  ** it has a zero header, that might be due to an I/O error, or
51373  ** it might be due to the race condition described above and in
51374  ** ticket #3883. Either way, assume that the journal is hot.
51375  ** This might be a false positive. But if it is, then the
51376  ** automatic journal playback and recovery mechanism will deal
51377  ** with it under an EXCLUSIVE lock where we do not need to
51378  ** worry so much with race conditions.
51379  */
51380  *pExists = 1;
51381  rc = SQLITE_OK;
51382  }
51383  }
51384  }
51385  }
51386  }
51387 
51388  return rc;
51389 }
51390 
51391 /*
51392 ** This function is called to obtain a shared lock on the database file.
51393 ** It is illegal to call sqlite3PagerGet() until after this function
51394 ** has been successfully called. If a shared-lock is already held when
51395 ** this function is called, it is a no-op.
51396 **
51397 ** The following operations are also performed by this function.
51398 **
51399 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
51400 ** on the database file), then an attempt is made to obtain a
51401 ** SHARED lock on the database file. Immediately after obtaining
51402 ** the SHARED lock, the file-system is checked for a hot-journal,
51403 ** which is played back if present. Following any hot-journal
51404 ** rollback, the contents of the cache are validated by checking
51405 ** the 'change-counter' field of the database file header and
51406 ** discarded if they are found to be invalid.
51407 **
51408 ** 2) If the pager is running in exclusive-mode, and there are currently
51409 ** no outstanding references to any pages, and is in the error state,
51410 ** then an attempt is made to clear the error state by discarding
51411 ** the contents of the page cache and rolling back any open journal
51412 ** file.
51413 **
51414 ** If everything is successful, SQLITE_OK is returned. If an IO error
51415 ** occurs while locking the database, checking for a hot-journal file or
51416 ** rolling back a journal file, the IO error code is returned.
51417 */
51418 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
51419  int rc = SQLITE_OK; /* Return code */
51420 
51421  /* This routine is only called from b-tree and only when there are no
51422  ** outstanding pages. This implies that the pager state should either
51423  ** be OPEN or READER. READER is only possible if the pager is or was in
51424  ** exclusive access mode. */
51425  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
51426  assert( assert_pager_state(pPager) );
51427  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
51428  assert( pPager->errCode==SQLITE_OK );
51429 
51430  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
51431  int bHotJournal = 1; /* True if there exists a hot journal-file */
51432 
51433  assert( !MEMDB );
51434  assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
51435 
51436  rc = pager_wait_on_lock(pPager, SHARED_LOCK);
51437  if( rc!=SQLITE_OK ){
51438  assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
51439  goto failed;
51440  }
51441 
51442  /* If a journal file exists, and there is no RESERVED lock on the
51443  ** database file, then it either needs to be played back or deleted.
51444  */
51445  if( pPager->eLock<=SHARED_LOCK ){
51446  rc = hasHotJournal(pPager, &bHotJournal);
51447  }
51448  if( rc!=SQLITE_OK ){
51449  goto failed;
51450  }
51451  if( bHotJournal ){
51452  if( pPager->readOnly ){
51453  rc = SQLITE_READONLY_ROLLBACK;
51454  goto failed;
51455  }
51456 
51457  /* Get an EXCLUSIVE lock on the database file. At this point it is
51458  ** important that a RESERVED lock is not obtained on the way to the
51459  ** EXCLUSIVE lock. If it were, another process might open the
51460  ** database file, detect the RESERVED lock, and conclude that the
51461  ** database is safe to read while this process is still rolling the
51462  ** hot-journal back.
51463  **
51464  ** Because the intermediate RESERVED lock is not requested, any
51465  ** other process attempting to access the database file will get to
51466  ** this point in the code and fail to obtain its own EXCLUSIVE lock
51467  ** on the database file.
51468  **
51469  ** Unless the pager is in locking_mode=exclusive mode, the lock is
51470  ** downgraded to SHARED_LOCK before this function returns.
51471  */
51472  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
51473  if( rc!=SQLITE_OK ){
51474  goto failed;
51475  }
51476 
51477  /* If it is not already open and the file exists on disk, open the
51478  ** journal for read/write access. Write access is required because
51479  ** in exclusive-access mode the file descriptor will be kept open
51480  ** and possibly used for a transaction later on. Also, write-access
51481  ** is usually required to finalize the journal in journal_mode=persist
51482  ** mode (and also for journal_mode=truncate on some systems).
51483  **
51484  ** If the journal does not exist, it usually means that some
51485  ** other connection managed to get in and roll it back before
51486  ** this connection obtained the exclusive lock above. Or, it
51487  ** may mean that the pager was in the error-state when this
51488  ** function was called and the journal file does not exist.
51489  */
51490  if( !isOpen(pPager->jfd) ){
51491  sqlite3_vfs * const pVfs = pPager->pVfs;
51492  int bExists; /* True if journal file exists */
51493  rc = sqlite3OsAccess(
51494  pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
51495  if( rc==SQLITE_OK && bExists ){
51496  int fout = 0;
51497  int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
51498  assert( !pPager->tempFile );
51499  rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
51500  assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51501  if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
51502  rc = SQLITE_CANTOPEN_BKPT;
51503  sqlite3OsClose(pPager->jfd);
51504  }
51505  }
51506  }
51507 
51508  /* Playback and delete the journal. Drop the database write
51509  ** lock and reacquire the read lock. Purge the cache before
51510  ** playing back the hot-journal so that we don't end up with
51511  ** an inconsistent cache. Sync the hot journal before playing
51512  ** it back since the process that crashed and left the hot journal
51513  ** probably did not sync it and we are required to always sync
51514  ** the journal before playing it back.
51515  */
51516  if( isOpen(pPager->jfd) ){
51517  assert( rc==SQLITE_OK );
51518  rc = pagerSyncHotJournal(pPager);
51519  if( rc==SQLITE_OK ){
51520  rc = pager_playback(pPager, !pPager->tempFile);
51521  pPager->eState = PAGER_OPEN;
51522  }
51523  }else if( !pPager->exclusiveMode ){
51524  pagerUnlockDb(pPager, SHARED_LOCK);
51525  }
51526 
51527  if( rc!=SQLITE_OK ){
51528  /* This branch is taken if an error occurs while trying to open
51529  ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
51530  ** pager_unlock() routine will be called before returning to unlock
51531  ** the file. If the unlock attempt fails, then Pager.eLock must be
51532  ** set to UNKNOWN_LOCK (see the comment above the #define for
51533  ** UNKNOWN_LOCK above for an explanation).
51534  **
51535  ** In order to get pager_unlock() to do this, set Pager.eState to
51536  ** PAGER_ERROR now. This is not actually counted as a transition
51537  ** to ERROR state in the state diagram at the top of this file,
51538  ** since we know that the same call to pager_unlock() will very
51539  ** shortly transition the pager object to the OPEN state. Calling
51540  ** assert_pager_state() would fail now, as it should not be possible
51541  ** to be in ERROR state when there are zero outstanding page
51542  ** references.
51543  */
51544  pager_error(pPager, rc);
51545  goto failed;
51546  }
51547 
51548  assert( pPager->eState==PAGER_OPEN );
51549  assert( (pPager->eLock==SHARED_LOCK)
51550  || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
51551  );
51552  }
51553 
51554  if( !pPager->tempFile && pPager->hasHeldSharedLock ){
51555  /* The shared-lock has just been acquired then check to
51556  ** see if the database has been modified. If the database has changed,
51557  ** flush the cache. The hasHeldSharedLock flag prevents this from
51558  ** occurring on the very first access to a file, in order to save a
51559  ** single unnecessary sqlite3OsRead() call at the start-up.
51560  **
51561  ** Database changes are detected by looking at 15 bytes beginning
51562  ** at offset 24 into the file. The first 4 of these 16 bytes are
51563  ** a 32-bit counter that is incremented with each change. The
51564  ** other bytes change randomly with each file change when
51565  ** a codec is in use.
51566  **
51567  ** There is a vanishingly small chance that a change will not be
51568  ** detected. The chance of an undetected change is so small that
51569  ** it can be neglected.
51570  */
51571  Pgno nPage = 0;
51572  char dbFileVers[sizeof(pPager->dbFileVers)];
51573 
51574  rc = pagerPagecount(pPager, &nPage);
51575  if( rc ) goto failed;
51576 
51577  if( nPage>0 ){
51578  IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
51579  rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
51580  if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
51581  goto failed;
51582  }
51583  }else{
51584  memset(dbFileVers, 0, sizeof(dbFileVers));
51585  }
51586 
51587  if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
51588  pager_reset(pPager);
51589 
51590  /* Unmap the database file. It is possible that external processes
51591  ** may have truncated the database file and then extended it back
51592  ** to its original size while this process was not holding a lock.
51593  ** In this case there may exist a Pager.pMap mapping that appears
51594  ** to be the right size but is not actually valid. Avoid this
51595  ** possibility by unmapping the db here. */
51596  if( USEFETCH(pPager) ){
51597  sqlite3OsUnfetch(pPager->fd, 0, 0);
51598  }
51599  }
51600  }
51601 
51602  /* If there is a WAL file in the file-system, open this database in WAL
51603  ** mode. Otherwise, the following function call is a no-op.
51604  */
51605  rc = pagerOpenWalIfPresent(pPager);
51606 #ifndef SQLITE_OMIT_WAL
51607  assert( pPager->pWal==0 || rc==SQLITE_OK );
51608 #endif
51609  }
51610 
51611  if( pagerUseWal(pPager) ){
51612  assert( rc==SQLITE_OK );
51613  rc = pagerBeginReadTransaction(pPager);
51614  }
51615 
51616  if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
51617  rc = pagerPagecount(pPager, &pPager->dbSize);
51618  }
51619 
51620  failed:
51621  if( rc!=SQLITE_OK ){
51622  assert( !MEMDB );
51623  pager_unlock(pPager);
51624  assert( pPager->eState==PAGER_OPEN );
51625  }else{
51626  pPager->eState = PAGER_READER;
51627  pPager->hasHeldSharedLock = 1;
51628  }
51629  return rc;
51630 }
51631 
51632 /*
51633 ** If the reference count has reached zero, rollback any active
51634 ** transaction and unlock the pager.
51635 **
51636 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
51637 ** the rollback journal, the unlock is not performed and there is
51638 ** nothing to rollback, so this routine is a no-op.
51639 */
51640 static void pagerUnlockIfUnused(Pager *pPager){
51641  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
51642  pagerUnlockAndRollback(pPager);
51643  }
51644 }
51645 
51646 /*
51647 ** Acquire a reference to page number pgno in pager pPager (a page
51648 ** reference has type DbPage*). If the requested reference is
51649 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
51650 **
51651 ** If the requested page is already in the cache, it is returned.
51652 ** Otherwise, a new page object is allocated and populated with data
51653 ** read from the database file. In some cases, the pcache module may
51654 ** choose not to allocate a new page object and may reuse an existing
51655 ** object with no outstanding references.
51656 **
51657 ** The extra data appended to a page is always initialized to zeros the
51658 ** first time a page is loaded into memory. If the page requested is
51659 ** already in the cache when this function is called, then the extra
51660 ** data is left as it was when the page object was last used.
51661 **
51662 ** If the database image is smaller than the requested page or if a
51663 ** non-zero value is passed as the noContent parameter and the
51664 ** requested page is not already stored in the cache, then no
51665 ** actual disk read occurs. In this case the memory image of the
51666 ** page is initialized to all zeros.
51667 **
51668 ** If noContent is true, it means that we do not care about the contents
51669 ** of the page. This occurs in two scenarios:
51670 **
51671 ** a) When reading a free-list leaf page from the database, and
51672 **
51673 ** b) When a savepoint is being rolled back and we need to load
51674 ** a new page into the cache to be filled with the data read
51675 ** from the savepoint journal.
51676 **
51677 ** If noContent is true, then the data returned is zeroed instead of
51678 ** being read from the database. Additionally, the bits corresponding
51679 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
51680 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
51681 ** savepoints are set. This means if the page is made writable at any
51682 ** point in the future, using a call to sqlite3PagerWrite(), its contents
51683 ** will not be journaled. This saves IO.
51684 **
51685 ** The acquisition might fail for several reasons. In all cases,
51686 ** an appropriate error code is returned and *ppPage is set to NULL.
51687 **
51688 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
51689 ** to find a page in the in-memory cache first. If the page is not already
51690 ** in memory, this routine goes to disk to read it in whereas Lookup()
51691 ** just returns 0. This routine acquires a read-lock the first time it
51692 ** has to go to disk, and could also playback an old journal if necessary.
51693 ** Since Lookup() never goes to disk, it never has to deal with locks
51694 ** or journal files.
51695 */
51696 SQLITE_PRIVATE int sqlite3PagerGet(
51697  Pager *pPager, /* The pager open on the database file */
51698  Pgno pgno, /* Page number to fetch */
51699  DbPage **ppPage, /* Write a pointer to the page here */
51700  int flags /* PAGER_GET_XXX flags */
51701 ){
51702  int rc = SQLITE_OK;
51703  PgHdr *pPg = 0;
51704  u32 iFrame = 0; /* Frame to read from WAL file */
51705  const int noContent = (flags & PAGER_GET_NOCONTENT);
51706 
51707  /* It is acceptable to use a read-only (mmap) page for any page except
51708  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
51709  ** flag was specified by the caller. And so long as the db is not a
51710  ** temporary or in-memory database. */
51711  const int bMmapOk = (pgno>1 && USEFETCH(pPager)
51712  && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
51713 #ifdef SQLITE_HAS_CODEC
51714  && pPager->xCodec==0
51715 #endif
51716  );
51717 
51718  /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
51719  ** allows the compiler optimizer to reuse the results of the "pgno>1"
51720  ** test in the previous statement, and avoid testing pgno==0 in the
51721  ** common case where pgno is large. */
51722  if( pgno<=1 && pgno==0 ){
51723  return SQLITE_CORRUPT_BKPT;
51724  }
51725  assert( pPager->eState>=PAGER_READER );
51726  assert( assert_pager_state(pPager) );
51727  assert( noContent==0 || bMmapOk==0 );
51728 
51729  assert( pPager->hasHeldSharedLock==1 );
51730 
51731  /* If the pager is in the error state, return an error immediately.
51732  ** Otherwise, request the page from the PCache layer. */
51733  if( pPager->errCode!=SQLITE_OK ){
51734  rc = pPager->errCode;
51735  }else{
51736  if( bMmapOk && pagerUseWal(pPager) ){
51737  rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51738  if( rc!=SQLITE_OK ) goto pager_acquire_err;
51739  }
51740 
51741  if( bMmapOk && iFrame==0 ){
51742  void *pData = 0;
51743 
51744  rc = sqlite3OsFetch(pPager->fd,
51745  (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
51746  );
51747 
51748  if( rc==SQLITE_OK && pData ){
51749  if( pPager->eState>PAGER_READER || pPager->tempFile ){
51750  pPg = sqlite3PagerLookup(pPager, pgno);
51751  }
51752  if( pPg==0 ){
51753  rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
51754  }else{
51755  sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
51756  }
51757  if( pPg ){
51758  assert( rc==SQLITE_OK );
51759  *ppPage = pPg;
51760  return SQLITE_OK;
51761  }
51762  }
51763  if( rc!=SQLITE_OK ){
51764  goto pager_acquire_err;
51765  }
51766  }
51767 
51768  {
51769  sqlite3_pcache_page *pBase;
51770  pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
51771  if( pBase==0 ){
51772  rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
51773  if( rc!=SQLITE_OK ) goto pager_acquire_err;
51774  if( pBase==0 ){
51775  pPg = *ppPage = 0;
51776  rc = SQLITE_NOMEM_BKPT;
51777  goto pager_acquire_err;
51778  }
51779  }
51780  pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
51781  assert( pPg!=0 );
51782  }
51783  }
51784 
51785  if( rc!=SQLITE_OK ){
51786  /* Either the call to sqlite3PcacheFetch() returned an error or the
51787  ** pager was already in the error-state when this function was called.
51788  ** Set pPg to 0 and jump to the exception handler. */
51789  pPg = 0;
51790  goto pager_acquire_err;
51791  }
51792  assert( pPg==(*ppPage) );
51793  assert( pPg->pgno==pgno );
51794  assert( pPg->pPager==pPager || pPg->pPager==0 );
51795 
51796  if( pPg->pPager && !noContent ){
51797  /* In this case the pcache already contains an initialized copy of
51798  ** the page. Return without further ado. */
51799  assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
51800  pPager->aStat[PAGER_STAT_HIT]++;
51801  return SQLITE_OK;
51802 
51803  }else{
51804  /* The pager cache has created a new page. Its content needs to
51805  ** be initialized. */
51806 
51807  pPg->pPager = pPager;
51808 
51809  /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
51810  ** number greater than this, or the unused locking-page, is requested. */
51811  if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
51812  rc = SQLITE_CORRUPT_BKPT;
51813  goto pager_acquire_err;
51814  }
51815 
51816  assert( !isOpen(pPager->fd) || !MEMDB );
51817  if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
51818  if( pgno>pPager->mxPgno ){
51819  rc = SQLITE_FULL;
51820  goto pager_acquire_err;
51821  }
51822  if( noContent ){
51823  /* Failure to set the bits in the InJournal bit-vectors is benign.
51824  ** It merely means that we might do some extra work to journal a
51825  ** page that does not need to be journaled. Nevertheless, be sure
51826  ** to test the case where a malloc error occurs while trying to set
51827  ** a bit in a bit vector.
51828  */
51829  sqlite3BeginBenignMalloc();
51830  if( pgno<=pPager->dbOrigSize ){
51831  TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
51832  testcase( rc==SQLITE_NOMEM );
51833  }
51834  TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
51835  testcase( rc==SQLITE_NOMEM );
51836  sqlite3EndBenignMalloc();
51837  }
51838  memset(pPg->pData, 0, pPager->pageSize);
51839  IOTRACE(("ZERO %p %d\n", pPager, pgno));
51840  }else{
51841  if( pagerUseWal(pPager) && bMmapOk==0 ){
51842  rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51843  if( rc!=SQLITE_OK ) goto pager_acquire_err;
51844  }
51845  assert( pPg->pPager==pPager );
51846  pPager->aStat[PAGER_STAT_MISS]++;
51847  rc = readDbPage(pPg, iFrame);
51848  if( rc!=SQLITE_OK ){
51849  goto pager_acquire_err;
51850  }
51851  }
51852  pager_set_pagehash(pPg);
51853  }
51854 
51855  return SQLITE_OK;
51856 
51857 pager_acquire_err:
51858  assert( rc!=SQLITE_OK );
51859  if( pPg ){
51860  sqlite3PcacheDrop(pPg);
51861  }
51862  pagerUnlockIfUnused(pPager);
51863 
51864  *ppPage = 0;
51865  return rc;
51866 }
51867 
51868 /*
51869 ** Acquire a page if it is already in the in-memory cache. Do
51870 ** not read the page from disk. Return a pointer to the page,
51871 ** or 0 if the page is not in cache.
51872 **
51873 ** See also sqlite3PagerGet(). The difference between this routine
51874 ** and sqlite3PagerGet() is that _get() will go to the disk and read
51875 ** in the page if the page is not already in cache. This routine
51876 ** returns NULL if the page is not in cache or if a disk I/O error
51877 ** has ever happened.
51878 */
51879 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
51880  sqlite3_pcache_page *pPage;
51881  assert( pPager!=0 );
51882  assert( pgno!=0 );
51883  assert( pPager->pPCache!=0 );
51884  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
51885  assert( pPage==0 || pPager->hasHeldSharedLock );
51886  if( pPage==0 ) return 0;
51887  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
51888 }
51889 
51890 /*
51891 ** Release a page reference.
51892 **
51893 ** If the number of references to the page drop to zero, then the
51894 ** page is added to the LRU list. When all references to all pages
51895 ** are released, a rollback occurs and the lock on the database is
51896 ** removed.
51897 */
51898 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
51899  Pager *pPager;
51900  assert( pPg!=0 );
51901  pPager = pPg->pPager;
51902  if( pPg->flags & PGHDR_MMAP ){
51903  pagerReleaseMapPage(pPg);
51904  }else{
51905  sqlite3PcacheRelease(pPg);
51906  }
51907  pagerUnlockIfUnused(pPager);
51908 }
51909 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
51910  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
51911 }
51912 
51913 /*
51914 ** This function is called at the start of every write transaction.
51915 ** There must already be a RESERVED or EXCLUSIVE lock on the database
51916 ** file when this routine is called.
51917 **
51918 ** Open the journal file for pager pPager and write a journal header
51919 ** to the start of it. If there are active savepoints, open the sub-journal
51920 ** as well. This function is only used when the journal file is being
51921 ** opened to write a rollback log for a transaction. It is not used
51922 ** when opening a hot journal file to roll it back.
51923 **
51924 ** If the journal file is already open (as it may be in exclusive mode),
51925 ** then this function just writes a journal header to the start of the
51926 ** already open file.
51927 **
51928 ** Whether or not the journal file is opened by this function, the
51929 ** Pager.pInJournal bitvec structure is allocated.
51930 **
51931 ** Return SQLITE_OK if everything is successful. Otherwise, return
51932 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
51933 ** an IO error code if opening or writing the journal file fails.
51934 */
51935 static int pager_open_journal(Pager *pPager){
51936  int rc = SQLITE_OK; /* Return code */
51937  sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
51938 
51939  assert( pPager->eState==PAGER_WRITER_LOCKED );
51940  assert( assert_pager_state(pPager) );
51941  assert( pPager->pInJournal==0 );
51942 
51943  /* If already in the error state, this function is a no-op. But on
51944  ** the other hand, this routine is never called if we are already in
51945  ** an error state. */
51946  if( NEVER(pPager->errCode) ) return pPager->errCode;
51947 
51948  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
51949  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
51950  if( pPager->pInJournal==0 ){
51951  return SQLITE_NOMEM_BKPT;
51952  }
51953 
51954  /* Open the journal file if it is not already open. */
51955  if( !isOpen(pPager->jfd) ){
51956  if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
51957  sqlite3MemJournalOpen(pPager->jfd);
51958  }else{
51959  int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
51960  int nSpill;
51961 
51962  if( pPager->tempFile ){
51963  flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
51964  nSpill = sqlite3Config.nStmtSpill;
51965  }else{
51966  flags |= SQLITE_OPEN_MAIN_JOURNAL;
51967  nSpill = jrnlBufferSize(pPager);
51968  }
51969 
51970  /* Verify that the database still has the same name as it did when
51971  ** it was originally opened. */
51972  rc = databaseIsUnmoved(pPager);
51973  if( rc==SQLITE_OK ){
51974  rc = sqlite3JournalOpen (
51975  pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
51976  );
51977  }
51978  }
51979  assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51980  }
51981 
51982 
51983  /* Write the first journal header to the journal file and open
51984  ** the sub-journal if necessary.
51985  */
51986  if( rc==SQLITE_OK ){
51987  /* TODO: Check if all of these are really required. */
51988  pPager->nRec = 0;
51989  pPager->journalOff = 0;
51990  pPager->setMaster = 0;
51991  pPager->journalHdr = 0;
51992  rc = writeJournalHdr(pPager);
51993  }
51994  }
51995 
51996  if( rc!=SQLITE_OK ){
51997  sqlite3BitvecDestroy(pPager->pInJournal);
51998  pPager->pInJournal = 0;
51999  }else{
52000  assert( pPager->eState==PAGER_WRITER_LOCKED );
52001  pPager->eState = PAGER_WRITER_CACHEMOD;
52002  }
52003 
52004  return rc;
52005 }
52006 
52007 /*
52008 ** Begin a write-transaction on the specified pager object. If a
52009 ** write-transaction has already been opened, this function is a no-op.
52010 **
52011 ** If the exFlag argument is false, then acquire at least a RESERVED
52012 ** lock on the database file. If exFlag is true, then acquire at least
52013 ** an EXCLUSIVE lock. If such a lock is already held, no locking
52014 ** functions need be called.
52015 **
52016 ** If the subjInMemory argument is non-zero, then any sub-journal opened
52017 ** within this transaction will be opened as an in-memory file. This
52018 ** has no effect if the sub-journal is already opened (as it may be when
52019 ** running in exclusive mode) or if the transaction does not require a
52020 ** sub-journal. If the subjInMemory argument is zero, then any required
52021 ** sub-journal is implemented in-memory if pPager is an in-memory database,
52022 ** or using a temporary file otherwise.
52023 */
52024 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
52025  int rc = SQLITE_OK;
52026 
52027  if( pPager->errCode ) return pPager->errCode;
52028  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
52029  pPager->subjInMemory = (u8)subjInMemory;
52030 
52031  if( ALWAYS(pPager->eState==PAGER_READER) ){
52032  assert( pPager->pInJournal==0 );
52033 
52034  if( pagerUseWal(pPager) ){
52035  /* If the pager is configured to use locking_mode=exclusive, and an
52036  ** exclusive lock on the database is not already held, obtain it now.
52037  */
52038  if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
52039  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
52040  if( rc!=SQLITE_OK ){
52041  return rc;
52042  }
52043  (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
52044  }
52045 
52046  /* Grab the write lock on the log file. If successful, upgrade to
52047  ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
52048  ** The busy-handler is not invoked if another connection already
52049  ** holds the write-lock. If possible, the upper layer will call it.
52050  */
52051  rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
52052  }else{
52053  /* Obtain a RESERVED lock on the database file. If the exFlag parameter
52054  ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
52055  ** busy-handler callback can be used when upgrading to the EXCLUSIVE
52056  ** lock, but not when obtaining the RESERVED lock.
52057  */
52058  rc = pagerLockDb(pPager, RESERVED_LOCK);
52059  if( rc==SQLITE_OK && exFlag ){
52060  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
52061  }
52062  }
52063 
52064  if( rc==SQLITE_OK ){
52065  /* Change to WRITER_LOCKED state.
52066  **
52067  ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
52068  ** when it has an open transaction, but never to DBMOD or FINISHED.
52069  ** This is because in those states the code to roll back savepoint
52070  ** transactions may copy data from the sub-journal into the database
52071  ** file as well as into the page cache. Which would be incorrect in
52072  ** WAL mode.
52073  */
52074  pPager->eState = PAGER_WRITER_LOCKED;
52075  pPager->dbHintSize = pPager->dbSize;
52076  pPager->dbFileSize = pPager->dbSize;
52077  pPager->dbOrigSize = pPager->dbSize;
52078  pPager->journalOff = 0;
52079  }
52080 
52081  assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
52082  assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
52083  assert( assert_pager_state(pPager) );
52084  }
52085 
52086  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
52087  return rc;
52088 }
52089 
52090 /*
52091 ** Write page pPg onto the end of the rollback journal.
52092 */
52093 static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
52094  Pager *pPager = pPg->pPager;
52095  int rc;
52096  u32 cksum;
52097  char *pData2;
52098  i64 iOff = pPager->journalOff;
52099 
52100  /* We should never write to the journal file the page that
52101  ** contains the database locks. The following assert verifies
52102  ** that we do not. */
52103  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
52104 
52105  assert( pPager->journalHdr<=pPager->journalOff );
52106  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
52107  cksum = pager_cksum(pPager, (u8*)pData2);
52108 
52109  /* Even if an IO or diskfull error occurs while journalling the
52110  ** page in the block above, set the need-sync flag for the page.
52111  ** Otherwise, when the transaction is rolled back, the logic in
52112  ** playback_one_page() will think that the page needs to be restored
52113  ** in the database file. And if an IO error occurs while doing so,
52114  ** then corruption may follow.
52115  */
52116  pPg->flags |= PGHDR_NEED_SYNC;
52117 
52118  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
52119  if( rc!=SQLITE_OK ) return rc;
52120  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
52121  if( rc!=SQLITE_OK ) return rc;
52122  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
52123  if( rc!=SQLITE_OK ) return rc;
52124 
52125  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
52126  pPager->journalOff, pPager->pageSize));
52127  PAGER_INCR(sqlite3_pager_writej_count);
52128  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
52129  PAGERID(pPager), pPg->pgno,
52130  ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
52131 
52132  pPager->journalOff += 8 + pPager->pageSize;
52133  pPager->nRec++;
52134  assert( pPager->pInJournal!=0 );
52135  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
52136  testcase( rc==SQLITE_NOMEM );
52137  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52138  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
52139  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52140  return rc;
52141 }
52142 
52143 /*
52144 ** Mark a single data page as writeable. The page is written into the
52145 ** main journal or sub-journal as required. If the page is written into
52146 ** one of the journals, the corresponding bit is set in the
52147 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
52148 ** of any open savepoints as appropriate.
52149 */
52150 static int pager_write(PgHdr *pPg){
52151  Pager *pPager = pPg->pPager;
52152  int rc = SQLITE_OK;
52153 
52154  /* This routine is not called unless a write-transaction has already
52155  ** been started. The journal file may or may not be open at this point.
52156  ** It is never called in the ERROR state.
52157  */
52158  assert( pPager->eState==PAGER_WRITER_LOCKED
52159  || pPager->eState==PAGER_WRITER_CACHEMOD
52160  || pPager->eState==PAGER_WRITER_DBMOD
52161  );
52162  assert( assert_pager_state(pPager) );
52163  assert( pPager->errCode==0 );
52164  assert( pPager->readOnly==0 );
52165  CHECK_PAGE(pPg);
52166 
52167  /* The journal file needs to be opened. Higher level routines have already
52168  ** obtained the necessary locks to begin the write-transaction, but the
52169  ** rollback journal might not yet be open. Open it now if this is the case.
52170  **
52171  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
52172  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
52173  ** an error might occur and the pager would end up in WRITER_LOCKED state
52174  ** with pages marked as dirty in the cache.
52175  */
52176  if( pPager->eState==PAGER_WRITER_LOCKED ){
52177  rc = pager_open_journal(pPager);
52178  if( rc!=SQLITE_OK ) return rc;
52179  }
52180  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
52181  assert( assert_pager_state(pPager) );
52182 
52183  /* Mark the page that is about to be modified as dirty. */
52184  sqlite3PcacheMakeDirty(pPg);
52185 
52186  /* If a rollback journal is in use, them make sure the page that is about
52187  ** to change is in the rollback journal, or if the page is a new page off
52188  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
52189  */
52190  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
52191  if( pPager->pInJournal!=0
52192  && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
52193  ){
52194  assert( pagerUseWal(pPager)==0 );
52195  if( pPg->pgno<=pPager->dbOrigSize ){
52196  rc = pagerAddPageToRollbackJournal(pPg);
52197  if( rc!=SQLITE_OK ){
52198  return rc;
52199  }
52200  }else{
52201  if( pPager->eState!=PAGER_WRITER_DBMOD ){
52202  pPg->flags |= PGHDR_NEED_SYNC;
52203  }
52204  PAGERTRACE(("APPEND %d page %d needSync=%d\n",
52205  PAGERID(pPager), pPg->pgno,
52206  ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
52207  }
52208  }
52209 
52210  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
52211  ** and before writing the page into the rollback journal. Wait until now,
52212  ** after the page has been successfully journalled, before setting the
52213  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
52214  */
52215  pPg->flags |= PGHDR_WRITEABLE;
52216 
52217  /* If the statement journal is open and the page is not in it,
52218  ** then write the page into the statement journal.
52219  */
52220  if( pPager->nSavepoint>0 ){
52221  rc = subjournalPageIfRequired(pPg);
52222  }
52223 
52224  /* Update the database size and return. */
52225  if( pPager->dbSize<pPg->pgno ){
52226  pPager->dbSize = pPg->pgno;
52227  }
52228  return rc;
52229 }
52230 
52231 /*
52232 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
52233 ** is larger than the page size. SQLite makes the (reasonable) assumption that
52234 ** all bytes of a sector are written together by hardware. Hence, all bytes of
52235 ** a sector need to be journalled in case of a power loss in the middle of
52236 ** a write.
52237 **
52238 ** Usually, the sector size is less than or equal to the page size, in which
52239 ** case pages can be individually written. This routine only runs in the
52240 ** exceptional case where the page size is smaller than the sector size.
52241 */
52242 static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
52243  int rc = SQLITE_OK; /* Return code */
52244  Pgno nPageCount; /* Total number of pages in database file */
52245  Pgno pg1; /* First page of the sector pPg is located on. */
52246  int nPage = 0; /* Number of pages starting at pg1 to journal */
52247  int ii; /* Loop counter */
52248  int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
52249  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
52250  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
52251 
52252  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
52253  ** a journal header to be written between the pages journaled by
52254  ** this function.
52255  */
52256  assert( !MEMDB );
52257  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
52258  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
52259 
52260  /* This trick assumes that both the page-size and sector-size are
52261  ** an integer power of 2. It sets variable pg1 to the identifier
52262  ** of the first page of the sector pPg is located on.
52263  */
52264  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
52265 
52266  nPageCount = pPager->dbSize;
52267  if( pPg->pgno>nPageCount ){
52268  nPage = (pPg->pgno - pg1)+1;
52269  }else if( (pg1+nPagePerSector-1)>nPageCount ){
52270  nPage = nPageCount+1-pg1;
52271  }else{
52272  nPage = nPagePerSector;
52273  }
52274  assert(nPage>0);
52275  assert(pg1<=pPg->pgno);
52276  assert((pg1+nPage)>pPg->pgno);
52277 
52278  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
52279  Pgno pg = pg1+ii;
52280  PgHdr *pPage;
52281  if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
52282  if( pg!=PAGER_MJ_PGNO(pPager) ){
52283  rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
52284  if( rc==SQLITE_OK ){
52285  rc = pager_write(pPage);
52286  if( pPage->flags&PGHDR_NEED_SYNC ){
52287  needSync = 1;
52288  }
52289  sqlite3PagerUnrefNotNull(pPage);
52290  }
52291  }
52292  }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
52293  if( pPage->flags&PGHDR_NEED_SYNC ){
52294  needSync = 1;
52295  }
52296  sqlite3PagerUnrefNotNull(pPage);
52297  }
52298  }
52299 
52300  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
52301  ** starting at pg1, then it needs to be set for all of them. Because
52302  ** writing to any of these nPage pages may damage the others, the
52303  ** journal file must contain sync()ed copies of all of them
52304  ** before any of them can be written out to the database file.
52305  */
52306  if( rc==SQLITE_OK && needSync ){
52307  assert( !MEMDB );
52308  for(ii=0; ii<nPage; ii++){
52309  PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
52310  if( pPage ){
52311  pPage->flags |= PGHDR_NEED_SYNC;
52312  sqlite3PagerUnrefNotNull(pPage);
52313  }
52314  }
52315  }
52316 
52317  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
52318  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
52319  return rc;
52320 }
52321 
52322 /*
52323 ** Mark a data page as writeable. This routine must be called before
52324 ** making changes to a page. The caller must check the return value
52325 ** of this function and be careful not to change any page data unless
52326 ** this routine returns SQLITE_OK.
52327 **
52328 ** The difference between this function and pager_write() is that this
52329 ** function also deals with the special case where 2 or more pages
52330 ** fit on a single disk sector. In this case all co-resident pages
52331 ** must have been written to the journal file before returning.
52332 **
52333 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
52334 ** as appropriate. Otherwise, SQLITE_OK.
52335 */
52336 SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
52337  Pager *pPager = pPg->pPager;
52338  assert( (pPg->flags & PGHDR_MMAP)==0 );
52339  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52340  assert( assert_pager_state(pPager) );
52341  if( pPager->errCode ){
52342  return pPager->errCode;
52343  }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
52344  if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
52345  return SQLITE_OK;
52346  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
52347  assert( pPager->tempFile==0 );
52348  return pagerWriteLargeSector(pPg);
52349  }else{
52350  return pager_write(pPg);
52351  }
52352 }
52353 
52354 /*
52355 ** Return TRUE if the page given in the argument was previously passed
52356 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
52357 ** to change the content of the page.
52358 */
52359 #ifndef NDEBUG
52360 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
52361  return pPg->flags & PGHDR_WRITEABLE;
52362 }
52363 #endif
52364 
52365 /*
52366 ** A call to this routine tells the pager that it is not necessary to
52367 ** write the information on page pPg back to the disk, even though
52368 ** that page might be marked as dirty. This happens, for example, when
52369 ** the page has been added as a leaf of the freelist and so its
52370 ** content no longer matters.
52371 **
52372 ** The overlying software layer calls this routine when all of the data
52373 ** on the given page is unused. The pager marks the page as clean so
52374 ** that it does not get written to disk.
52375 **
52376 ** Tests show that this optimization can quadruple the speed of large
52377 ** DELETE operations.
52378 **
52379 ** This optimization cannot be used with a temp-file, as the page may
52380 ** have been dirty at the start of the transaction. In that case, if
52381 ** memory pressure forces page pPg out of the cache, the data does need
52382 ** to be written out to disk so that it may be read back in if the
52383 ** current transaction is rolled back.
52384 */
52385 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
52386  Pager *pPager = pPg->pPager;
52387  if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
52388  PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
52389  IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
52390  pPg->flags |= PGHDR_DONT_WRITE;
52391  pPg->flags &= ~PGHDR_WRITEABLE;
52392  testcase( pPg->flags & PGHDR_NEED_SYNC );
52393  pager_set_pagehash(pPg);
52394  }
52395 }
52396 
52397 /*
52398 ** This routine is called to increment the value of the database file
52399 ** change-counter, stored as a 4-byte big-endian integer starting at
52400 ** byte offset 24 of the pager file. The secondary change counter at
52401 ** 92 is also updated, as is the SQLite version number at offset 96.
52402 **
52403 ** But this only happens if the pPager->changeCountDone flag is false.
52404 ** To avoid excess churning of page 1, the update only happens once.
52405 ** See also the pager_write_changecounter() routine that does an
52406 ** unconditional update of the change counters.
52407 **
52408 ** If the isDirectMode flag is zero, then this is done by calling
52409 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
52410 ** page data. In this case the file will be updated when the current
52411 ** transaction is committed.
52412 **
52413 ** The isDirectMode flag may only be non-zero if the library was compiled
52414 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
52415 ** if isDirect is non-zero, then the database file is updated directly
52416 ** by writing an updated version of page 1 using a call to the
52417 ** sqlite3OsWrite() function.
52418 */
52419 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
52420  int rc = SQLITE_OK;
52421 
52422  assert( pPager->eState==PAGER_WRITER_CACHEMOD
52423  || pPager->eState==PAGER_WRITER_DBMOD
52424  );
52425  assert( assert_pager_state(pPager) );
52426 
52427  /* Declare and initialize constant integer 'isDirect'. If the
52428  ** atomic-write optimization is enabled in this build, then isDirect
52429  ** is initialized to the value passed as the isDirectMode parameter
52430  ** to this function. Otherwise, it is always set to zero.
52431  **
52432  ** The idea is that if the atomic-write optimization is not
52433  ** enabled at compile time, the compiler can omit the tests of
52434  ** 'isDirect' below, as well as the block enclosed in the
52435  ** "if( isDirect )" condition.
52436  */
52437 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
52438 # define DIRECT_MODE 0
52439  assert( isDirectMode==0 );
52440  UNUSED_PARAMETER(isDirectMode);
52441 #else
52442 # define DIRECT_MODE isDirectMode
52443 #endif
52444 
52445  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
52446  PgHdr *pPgHdr; /* Reference to page 1 */
52447 
52448  assert( !pPager->tempFile && isOpen(pPager->fd) );
52449 
52450  /* Open page 1 of the file for writing. */
52451  rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
52452  assert( pPgHdr==0 || rc==SQLITE_OK );
52453 
52454  /* If page one was fetched successfully, and this function is not
52455  ** operating in direct-mode, make page 1 writable. When not in
52456  ** direct mode, page 1 is always held in cache and hence the PagerGet()
52457  ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
52458  */
52459  if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
52460  rc = sqlite3PagerWrite(pPgHdr);
52461  }
52462 
52463  if( rc==SQLITE_OK ){
52464  /* Actually do the update of the change counter */
52465  pager_write_changecounter(pPgHdr);
52466 
52467  /* If running in direct mode, write the contents of page 1 to the file. */
52468  if( DIRECT_MODE ){
52469  const void *zBuf;
52470  assert( pPager->dbFileSize>0 );
52471  CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
52472  if( rc==SQLITE_OK ){
52473  rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
52474  pPager->aStat[PAGER_STAT_WRITE]++;
52475  }
52476  if( rc==SQLITE_OK ){
52477  /* Update the pager's copy of the change-counter. Otherwise, the
52478  ** next time a read transaction is opened the cache will be
52479  ** flushed (as the change-counter values will not match). */
52480  const void *pCopy = (const void *)&((const char *)zBuf)[24];
52481  memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
52482  pPager->changeCountDone = 1;
52483  }
52484  }else{
52485  pPager->changeCountDone = 1;
52486  }
52487  }
52488 
52489  /* Release the page reference. */
52490  sqlite3PagerUnref(pPgHdr);
52491  }
52492  return rc;
52493 }
52494 
52495 /*
52496 ** Sync the database file to disk. This is a no-op for in-memory databases
52497 ** or pages with the Pager.noSync flag set.
52498 **
52499 ** If successful, or if called on a pager for which it is a no-op, this
52500 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
52501 */
52502 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
52503  int rc = SQLITE_OK;
52504 
52505  if( isOpen(pPager->fd) ){
52506  void *pArg = (void*)zMaster;
52507  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
52508  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
52509  }
52510  if( rc==SQLITE_OK && !pPager->noSync ){
52511  assert( !MEMDB );
52512  rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
52513  }
52514  return rc;
52515 }
52516 
52517 /*
52518 ** This function may only be called while a write-transaction is active in
52519 ** rollback. If the connection is in WAL mode, this call is a no-op.
52520 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
52521 ** the database file, an attempt is made to obtain one.
52522 **
52523 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
52524 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
52525 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
52526 ** returned.
52527 */
52528 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
52529  int rc = pPager->errCode;
52530  assert( assert_pager_state(pPager) );
52531  if( rc==SQLITE_OK ){
52532  assert( pPager->eState==PAGER_WRITER_CACHEMOD
52533  || pPager->eState==PAGER_WRITER_DBMOD
52534  || pPager->eState==PAGER_WRITER_LOCKED
52535  );
52536  assert( assert_pager_state(pPager) );
52537  if( 0==pagerUseWal(pPager) ){
52538  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
52539  }
52540  }
52541  return rc;
52542 }
52543 
52544 /*
52545 ** Sync the database file for the pager pPager. zMaster points to the name
52546 ** of a master journal file that should be written into the individual
52547 ** journal file. zMaster may be NULL, which is interpreted as no master
52548 ** journal (a single database transaction).
52549 **
52550 ** This routine ensures that:
52551 **
52552 ** * The database file change-counter is updated,
52553 ** * the journal is synced (unless the atomic-write optimization is used),
52554 ** * all dirty pages are written to the database file,
52555 ** * the database file is truncated (if required), and
52556 ** * the database file synced.
52557 **
52558 ** The only thing that remains to commit the transaction is to finalize
52559 ** (delete, truncate or zero the first part of) the journal file (or
52560 ** delete the master journal file if specified).
52561 **
52562 ** Note that if zMaster==NULL, this does not overwrite a previous value
52563 ** passed to an sqlite3PagerCommitPhaseOne() call.
52564 **
52565 ** If the final parameter - noSync - is true, then the database file itself
52566 ** is not synced. The caller must call sqlite3PagerSync() directly to
52567 ** sync the database file before calling CommitPhaseTwo() to delete the
52568 ** journal file in this case.
52569 */
52570 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
52571  Pager *pPager, /* Pager object */
52572  const char *zMaster, /* If not NULL, the master journal name */
52573  int noSync /* True to omit the xSync on the db file */
52574 ){
52575  int rc = SQLITE_OK; /* Return code */
52576 
52577  assert( pPager->eState==PAGER_WRITER_LOCKED
52578  || pPager->eState==PAGER_WRITER_CACHEMOD
52579  || pPager->eState==PAGER_WRITER_DBMOD
52580  || pPager->eState==PAGER_ERROR
52581  );
52582  assert( assert_pager_state(pPager) );
52583 
52584  /* If a prior error occurred, report that error again. */
52585  if( NEVER(pPager->errCode) ) return pPager->errCode;
52586 
52587  /* Provide the ability to easily simulate an I/O error during testing */
52588  if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
52589 
52590  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
52591  pPager->zFilename, zMaster, pPager->dbSize));
52592 
52593  /* If no database changes have been made, return early. */
52594  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
52595 
52596  assert( MEMDB==0 || pPager->tempFile );
52597  assert( isOpen(pPager->fd) || pPager->tempFile );
52598  if( 0==pagerFlushOnCommit(pPager, 1) ){
52599  /* If this is an in-memory db, or no pages have been written to, or this
52600  ** function has already been called, it is mostly a no-op. However, any
52601  ** backup in progress needs to be restarted. */
52602  sqlite3BackupRestart(pPager->pBackup);
52603  }else{
52604  if( pagerUseWal(pPager) ){
52605  PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
52606  PgHdr *pPageOne = 0;
52607  if( pList==0 ){
52608  /* Must have at least one page for the WAL commit flag.
52609  ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
52610  rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
52611  pList = pPageOne;
52612  pList->pDirty = 0;
52613  }
52614  assert( rc==SQLITE_OK );
52615  if( ALWAYS(pList) ){
52616  rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
52617  }
52618  sqlite3PagerUnref(pPageOne);
52619  if( rc==SQLITE_OK ){
52620  sqlite3PcacheCleanAll(pPager->pPCache);
52621  }
52622  }else{
52623  /* The following block updates the change-counter. Exactly how it
52624  ** does this depends on whether or not the atomic-update optimization
52625  ** was enabled at compile time, and if this transaction meets the
52626  ** runtime criteria to use the operation:
52627  **
52628  ** * The file-system supports the atomic-write property for
52629  ** blocks of size page-size, and
52630  ** * This commit is not part of a multi-file transaction, and
52631  ** * Exactly one page has been modified and store in the journal file.
52632  **
52633  ** If the optimization was not enabled at compile time, then the
52634  ** pager_incr_changecounter() function is called to update the change
52635  ** counter in 'indirect-mode'. If the optimization is compiled in but
52636  ** is not applicable to this transaction, call sqlite3JournalCreate()
52637  ** to make sure the journal file has actually been created, then call
52638  ** pager_incr_changecounter() to update the change-counter in indirect
52639  ** mode.
52640  **
52641  ** Otherwise, if the optimization is both enabled and applicable,
52642  ** then call pager_incr_changecounter() to update the change-counter
52643  ** in 'direct' mode. In this case the journal file will never be
52644  ** created for this transaction.
52645  */
52646  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
52647  PgHdr *pPg;
52648  assert( isOpen(pPager->jfd)
52649  || pPager->journalMode==PAGER_JOURNALMODE_OFF
52650  || pPager->journalMode==PAGER_JOURNALMODE_WAL
52651  );
52652  if( !zMaster && isOpen(pPager->jfd)
52653  && pPager->journalOff==jrnlBufferSize(pPager)
52654  && pPager->dbSize>=pPager->dbOrigSize
52655  && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
52656  ){
52657  /* Update the db file change counter via the direct-write method. The
52658  ** following call will modify the in-memory representation of page 1
52659  ** to include the updated change counter and then write page 1
52660  ** directly to the database file. Because of the atomic-write
52661  ** property of the host file-system, this is safe.
52662  */
52663  rc = pager_incr_changecounter(pPager, 1);
52664  }else{
52665  rc = sqlite3JournalCreate(pPager->jfd);
52666  if( rc==SQLITE_OK ){
52667  rc = pager_incr_changecounter(pPager, 0);
52668  }
52669  }
52670  #else
52671  rc = pager_incr_changecounter(pPager, 0);
52672  #endif
52673  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52674 
52675  /* Write the master journal name into the journal file. If a master
52676  ** journal file name has already been written to the journal file,
52677  ** or if zMaster is NULL (no master journal), then this call is a no-op.
52678  */
52679  rc = writeMasterJournal(pPager, zMaster);
52680  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52681 
52682  /* Sync the journal file and write all dirty pages to the database.
52683  ** If the atomic-update optimization is being used, this sync will not
52684  ** create the journal file or perform any real IO.
52685  **
52686  ** Because the change-counter page was just modified, unless the
52687  ** atomic-update optimization is used it is almost certain that the
52688  ** journal requires a sync here. However, in locking_mode=exclusive
52689  ** on a system under memory pressure it is just possible that this is
52690  ** not the case. In this case it is likely enough that the redundant
52691  ** xSync() call will be changed to a no-op by the OS anyhow.
52692  */
52693  rc = syncJournal(pPager, 0);
52694  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52695 
52696  rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
52697  if( rc!=SQLITE_OK ){
52698  assert( rc!=SQLITE_IOERR_BLOCKED );
52699  goto commit_phase_one_exit;
52700  }
52701  sqlite3PcacheCleanAll(pPager->pPCache);
52702 
52703  /* If the file on disk is smaller than the database image, use
52704  ** pager_truncate to grow the file here. This can happen if the database
52705  ** image was extended as part of the current transaction and then the
52706  ** last page in the db image moved to the free-list. In this case the
52707  ** last page is never written out to disk, leaving the database file
52708  ** undersized. Fix this now if it is the case. */
52709  if( pPager->dbSize>pPager->dbFileSize ){
52710  Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
52711  assert( pPager->eState==PAGER_WRITER_DBMOD );
52712  rc = pager_truncate(pPager, nNew);
52713  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52714  }
52715 
52716  /* Finally, sync the database file. */
52717  if( !noSync ){
52718  rc = sqlite3PagerSync(pPager, zMaster);
52719  }
52720  IOTRACE(("DBSYNC %p\n", pPager))
52721  }
52722  }
52723 
52724 commit_phase_one_exit:
52725  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
52726  pPager->eState = PAGER_WRITER_FINISHED;
52727  }
52728  return rc;
52729 }
52730 
52731 
52732 /*
52733 ** When this function is called, the database file has been completely
52734 ** updated to reflect the changes made by the current transaction and
52735 ** synced to disk. The journal file still exists in the file-system
52736 ** though, and if a failure occurs at this point it will eventually
52737 ** be used as a hot-journal and the current transaction rolled back.
52738 **
52739 ** This function finalizes the journal file, either by deleting,
52740 ** truncating or partially zeroing it, so that it cannot be used
52741 ** for hot-journal rollback. Once this is done the transaction is
52742 ** irrevocably committed.
52743 **
52744 ** If an error occurs, an IO error code is returned and the pager
52745 ** moves into the error state. Otherwise, SQLITE_OK is returned.
52746 */
52747 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
52748  int rc = SQLITE_OK; /* Return code */
52749 
52750  /* This routine should not be called if a prior error has occurred.
52751  ** But if (due to a coding error elsewhere in the system) it does get
52752  ** called, just return the same error code without doing anything. */
52753  if( NEVER(pPager->errCode) ) return pPager->errCode;
52754 
52755  assert( pPager->eState==PAGER_WRITER_LOCKED
52756  || pPager->eState==PAGER_WRITER_FINISHED
52757  || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
52758  );
52759  assert( assert_pager_state(pPager) );
52760 
52761  /* An optimization. If the database was not actually modified during
52762  ** this transaction, the pager is running in exclusive-mode and is
52763  ** using persistent journals, then this function is a no-op.
52764  **
52765  ** The start of the journal file currently contains a single journal
52766  ** header with the nRec field set to 0. If such a journal is used as
52767  ** a hot-journal during hot-journal rollback, 0 changes will be made
52768  ** to the database file. So there is no need to zero the journal
52769  ** header. Since the pager is in exclusive mode, there is no need
52770  ** to drop any locks either.
52771  */
52772  if( pPager->eState==PAGER_WRITER_LOCKED
52773  && pPager->exclusiveMode
52774  && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
52775  ){
52776  assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
52777  pPager->eState = PAGER_READER;
52778  return SQLITE_OK;
52779  }
52780 
52781  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
52782  pPager->iDataVersion++;
52783  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
52784  return pager_error(pPager, rc);
52785 }
52786 
52787 /*
52788 ** If a write transaction is open, then all changes made within the
52789 ** transaction are reverted and the current write-transaction is closed.
52790 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
52791 ** state if an error occurs.
52792 **
52793 ** If the pager is already in PAGER_ERROR state when this function is called,
52794 ** it returns Pager.errCode immediately. No work is performed in this case.
52795 **
52796 ** Otherwise, in rollback mode, this function performs two functions:
52797 **
52798 ** 1) It rolls back the journal file, restoring all database file and
52799 ** in-memory cache pages to the state they were in when the transaction
52800 ** was opened, and
52801 **
52802 ** 2) It finalizes the journal file, so that it is not used for hot
52803 ** rollback at any point in the future.
52804 **
52805 ** Finalization of the journal file (task 2) is only performed if the
52806 ** rollback is successful.
52807 **
52808 ** In WAL mode, all cache-entries containing data modified within the
52809 ** current transaction are either expelled from the cache or reverted to
52810 ** their pre-transaction state by re-reading data from the database or
52811 ** WAL files. The WAL transaction is then closed.
52812 */
52813 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
52814  int rc = SQLITE_OK; /* Return code */
52815  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
52816 
52817  /* PagerRollback() is a no-op if called in READER or OPEN state. If
52818  ** the pager is already in the ERROR state, the rollback is not
52819  ** attempted here. Instead, the error code is returned to the caller.
52820  */
52821  assert( assert_pager_state(pPager) );
52822  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
52823  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
52824 
52825  if( pagerUseWal(pPager) ){
52826  int rc2;
52827  rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
52828  rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
52829  if( rc==SQLITE_OK ) rc = rc2;
52830  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
52831  int eState = pPager->eState;
52832  rc = pager_end_transaction(pPager, 0, 0);
52833  if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
52834  /* This can happen using journal_mode=off. Move the pager to the error
52835  ** state to indicate that the contents of the cache may not be trusted.
52836  ** Any active readers will get SQLITE_ABORT.
52837  */
52838  pPager->errCode = SQLITE_ABORT;
52839  pPager->eState = PAGER_ERROR;
52840  return rc;
52841  }
52842  }else{
52843  rc = pager_playback(pPager, 0);
52844  }
52845 
52846  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
52847  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
52848  || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
52849  || rc==SQLITE_CANTOPEN
52850  );
52851 
52852  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
52853  ** cache. So call pager_error() on the way out to make any error persistent.
52854  */
52855  return pager_error(pPager, rc);
52856 }
52857 
52858 /*
52859 ** Return TRUE if the database file is opened read-only. Return FALSE
52860 ** if the database is (in theory) writable.
52861 */
52862 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
52863  return pPager->readOnly;
52864 }
52865 
52866 #ifdef SQLITE_DEBUG
52867 /*
52868 ** Return the sum of the reference counts for all pages held by pPager.
52869 */
52870 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
52871  return sqlite3PcacheRefCount(pPager->pPCache);
52872 }
52873 #endif
52874 
52875 /*
52876 ** Return the approximate number of bytes of memory currently
52877 ** used by the pager and its associated cache.
52878 */
52879 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
52880  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
52881  + 5*sizeof(void*);
52882  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
52883  + sqlite3MallocSize(pPager)
52884  + pPager->pageSize;
52885 }
52886 
52887 /*
52888 ** Return the number of references to the specified page.
52889 */
52890 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
52891  return sqlite3PcachePageRefcount(pPage);
52892 }
52893 
52894 #ifdef SQLITE_TEST
52895 /*
52896 ** This routine is used for testing and analysis only.
52897 */
52898 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
52899  static int a[11];
52900  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
52901  a[1] = sqlite3PcachePagecount(pPager->pPCache);
52902  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
52903  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
52904  a[4] = pPager->eState;
52905  a[5] = pPager->errCode;
52906  a[6] = pPager->aStat[PAGER_STAT_HIT];
52907  a[7] = pPager->aStat[PAGER_STAT_MISS];
52908  a[8] = 0; /* Used to be pPager->nOvfl */
52909  a[9] = pPager->nRead;
52910  a[10] = pPager->aStat[PAGER_STAT_WRITE];
52911  return a;
52912 }
52913 #endif
52914 
52915 /*
52916 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
52917 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
52918 ** current cache hit or miss count, according to the value of eStat. If the
52919 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
52920 ** returning.
52921 */
52922 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
52923 
52924  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
52925  || eStat==SQLITE_DBSTATUS_CACHE_MISS
52926  || eStat==SQLITE_DBSTATUS_CACHE_WRITE
52927  );
52928 
52929  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
52930  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
52931  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
52932 
52933  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
52934  if( reset ){
52935  pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
52936  }
52937 }
52938 
52939 /*
52940 ** Return true if this is an in-memory or temp-file backed pager.
52941 */
52942 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
52943  return pPager->tempFile;
52944 }
52945 
52946 /*
52947 ** Check that there are at least nSavepoint savepoints open. If there are
52948 ** currently less than nSavepoints open, then open one or more savepoints
52949 ** to make up the difference. If the number of savepoints is already
52950 ** equal to nSavepoint, then this function is a no-op.
52951 **
52952 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
52953 ** occurs while opening the sub-journal file, then an IO error code is
52954 ** returned. Otherwise, SQLITE_OK.
52955 */
52956 static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
52957  int rc = SQLITE_OK; /* Return code */
52958  int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
52959  int ii; /* Iterator variable */
52960  PagerSavepoint *aNew; /* New Pager.aSavepoint array */
52961 
52962  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52963  assert( assert_pager_state(pPager) );
52964  assert( nSavepoint>nCurrent && pPager->useJournal );
52965 
52966  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
52967  ** if the allocation fails. Otherwise, zero the new portion in case a
52968  ** malloc failure occurs while populating it in the for(...) loop below.
52969  */
52970  aNew = (PagerSavepoint *)sqlite3Realloc(
52971  pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
52972  );
52973  if( !aNew ){
52974  return SQLITE_NOMEM_BKPT;
52975  }
52976  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
52977  pPager->aSavepoint = aNew;
52978 
52979  /* Populate the PagerSavepoint structures just allocated. */
52980  for(ii=nCurrent; ii<nSavepoint; ii++){
52981  aNew[ii].nOrig = pPager->dbSize;
52982  if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
52983  aNew[ii].iOffset = pPager->journalOff;
52984  }else{
52985  aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
52986  }
52987  aNew[ii].iSubRec = pPager->nSubRec;
52988  aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
52989  if( !aNew[ii].pInSavepoint ){
52990  return SQLITE_NOMEM_BKPT;
52991  }
52992  if( pagerUseWal(pPager) ){
52993  sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
52994  }
52995  pPager->nSavepoint = ii+1;
52996  }
52997  assert( pPager->nSavepoint==nSavepoint );
52998  assertTruncateConstraint(pPager);
52999  return rc;
53000 }
53001 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
53002  assert( pPager->eState>=PAGER_WRITER_LOCKED );
53003  assert( assert_pager_state(pPager) );
53004 
53005  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
53006  return pagerOpenSavepoint(pPager, nSavepoint);
53007  }else{
53008  return SQLITE_OK;
53009  }
53010 }
53011 
53012 
53013 /*
53014 ** This function is called to rollback or release (commit) a savepoint.
53015 ** The savepoint to release or rollback need not be the most recently
53016 ** created savepoint.
53017 **
53018 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
53019 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
53020 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
53021 ** that have occurred since the specified savepoint was created.
53022 **
53023 ** The savepoint to rollback or release is identified by parameter
53024 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
53025 ** (the first created). A value of (Pager.nSavepoint-1) means operate
53026 ** on the most recently created savepoint. If iSavepoint is greater than
53027 ** (Pager.nSavepoint-1), then this function is a no-op.
53028 **
53029 ** If a negative value is passed to this function, then the current
53030 ** transaction is rolled back. This is different to calling
53031 ** sqlite3PagerRollback() because this function does not terminate
53032 ** the transaction or unlock the database, it just restores the
53033 ** contents of the database to its original state.
53034 **
53035 ** In any case, all savepoints with an index greater than iSavepoint
53036 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
53037 ** then savepoint iSavepoint is also destroyed.
53038 **
53039 ** This function may return SQLITE_NOMEM if a memory allocation fails,
53040 ** or an IO error code if an IO error occurs while rolling back a
53041 ** savepoint. If no errors occur, SQLITE_OK is returned.
53042 */
53043 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
53044  int rc = pPager->errCode;
53045 
53046 #ifdef SQLITE_ENABLE_ZIPVFS
53047  if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
53048 #endif
53049 
53050  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
53051  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
53052 
53053  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
53054  int ii; /* Iterator variable */
53055  int nNew; /* Number of remaining savepoints after this op. */
53056 
53057  /* Figure out how many savepoints will still be active after this
53058  ** operation. Store this value in nNew. Then free resources associated
53059  ** with any savepoints that are destroyed by this operation.
53060  */
53061  nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
53062  for(ii=nNew; ii<pPager->nSavepoint; ii++){
53063  sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
53064  }
53065  pPager->nSavepoint = nNew;
53066 
53067  /* If this is a release of the outermost savepoint, truncate
53068  ** the sub-journal to zero bytes in size. */
53069  if( op==SAVEPOINT_RELEASE ){
53070  if( nNew==0 && isOpen(pPager->sjfd) ){
53071  /* Only truncate if it is an in-memory sub-journal. */
53072  if( sqlite3JournalIsInMemory(pPager->sjfd) ){
53073  rc = sqlite3OsTruncate(pPager->sjfd, 0);
53074  assert( rc==SQLITE_OK );
53075  }
53076  pPager->nSubRec = 0;
53077  }
53078  }
53079  /* Else this is a rollback operation, playback the specified savepoint.
53080  ** If this is a temp-file, it is possible that the journal file has
53081  ** not yet been opened. In this case there have been no changes to
53082  ** the database file, so the playback operation can be skipped.
53083  */
53084  else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
53085  PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
53086  rc = pagerPlaybackSavepoint(pPager, pSavepoint);
53087  assert(rc!=SQLITE_DONE);
53088  }
53089 
53090 #ifdef SQLITE_ENABLE_ZIPVFS
53091  /* If the cache has been modified but the savepoint cannot be rolled
53092  ** back journal_mode=off, put the pager in the error state. This way,
53093  ** if the VFS used by this pager includes ZipVFS, the entire transaction
53094  ** can be rolled back at the ZipVFS level. */
53095  else if(
53096  pPager->journalMode==PAGER_JOURNALMODE_OFF
53097  && pPager->eState>=PAGER_WRITER_CACHEMOD
53098  ){
53099  pPager->errCode = SQLITE_ABORT;
53100  pPager->eState = PAGER_ERROR;
53101  }
53102 #endif
53103  }
53104 
53105  return rc;
53106 }
53107 
53108 /*
53109 ** Return the full pathname of the database file.
53110 **
53111 ** Except, if the pager is in-memory only, then return an empty string if
53112 ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
53113 ** used to report the filename to the user, for compatibility with legacy
53114 ** behavior. But when the Btree needs to know the filename for matching to
53115 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
53116 ** participate in shared-cache.
53117 */
53118 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
53119  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
53120 }
53121 
53122 /*
53123 ** Return the VFS structure for the pager.
53124 */
53125 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
53126  return pPager->pVfs;
53127 }
53128 
53129 /*
53130 ** Return the file handle for the database file associated
53131 ** with the pager. This might return NULL if the file has
53132 ** not yet been opened.
53133 */
53134 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
53135  return pPager->fd;
53136 }
53137 
53138 /*
53139 ** Return the file handle for the journal file (if it exists).
53140 ** This will be either the rollback journal or the WAL file.
53141 */
53142 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
53143 #if SQLITE_OMIT_WAL
53144  return pPager->jfd;
53145 #else
53146  return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
53147 #endif
53148 }
53149 
53150 /*
53151 ** Return the full pathname of the journal file.
53152 */
53153 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
53154  return pPager->zJournal;
53155 }
53156 
53157 #ifdef SQLITE_HAS_CODEC
53158 /*
53159 ** Set or retrieve the codec for this pager
53160 */
53161 SQLITE_PRIVATE void sqlite3PagerSetCodec(
53162  Pager *pPager,
53163  void *(*xCodec)(void*,void*,Pgno,int),
53164  void (*xCodecSizeChng)(void*,int,int),
53165  void (*xCodecFree)(void*),
53166  void *pCodec
53167 ){
53168  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
53169  pPager->xCodec = pPager->memDb ? 0 : xCodec;
53170  pPager->xCodecSizeChng = xCodecSizeChng;
53171  pPager->xCodecFree = xCodecFree;
53172  pPager->pCodec = pCodec;
53173  pagerReportSize(pPager);
53174 }
53175 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
53176  return pPager->pCodec;
53177 }
53178 
53179 /*
53180 ** This function is called by the wal module when writing page content
53181 ** into the log file.
53182 **
53183 ** This function returns a pointer to a buffer containing the encrypted
53184 ** page content. If a malloc fails, this function may return NULL.
53185 */
53186 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
53187  void *aData = 0;
53188  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
53189  return aData;
53190 }
53191 
53192 /*
53193 ** Return the current pager state
53194 */
53195 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
53196  return pPager->eState;
53197 }
53198 #endif /* SQLITE_HAS_CODEC */
53199 
53200 #ifndef SQLITE_OMIT_AUTOVACUUM
53201 /*
53202 ** Move the page pPg to location pgno in the file.
53203 **
53204 ** There must be no references to the page previously located at
53205 ** pgno (which we call pPgOld) though that page is allowed to be
53206 ** in cache. If the page previously located at pgno is not already
53207 ** in the rollback journal, it is not put there by by this routine.
53208 **
53209 ** References to the page pPg remain valid. Updating any
53210 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
53211 ** allocated along with the page) is the responsibility of the caller.
53212 **
53213 ** A transaction must be active when this routine is called. It used to be
53214 ** required that a statement transaction was not active, but this restriction
53215 ** has been removed (CREATE INDEX needs to move a page when a statement
53216 ** transaction is active).
53217 **
53218 ** If the fourth argument, isCommit, is non-zero, then this page is being
53219 ** moved as part of a database reorganization just before the transaction
53220 ** is being committed. In this case, it is guaranteed that the database page
53221 ** pPg refers to will not be written to again within this transaction.
53222 **
53223 ** This function may return SQLITE_NOMEM or an IO error code if an error
53224 ** occurs. Otherwise, it returns SQLITE_OK.
53225 */
53226 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
53227  PgHdr *pPgOld; /* The page being overwritten. */
53228  Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
53229  int rc; /* Return code */
53230  Pgno origPgno; /* The original page number */
53231 
53232  assert( pPg->nRef>0 );
53233  assert( pPager->eState==PAGER_WRITER_CACHEMOD
53234  || pPager->eState==PAGER_WRITER_DBMOD
53235  );
53236  assert( assert_pager_state(pPager) );
53237 
53238  /* In order to be able to rollback, an in-memory database must journal
53239  ** the page we are moving from.
53240  */
53241  assert( pPager->tempFile || !MEMDB );
53242  if( pPager->tempFile ){
53243  rc = sqlite3PagerWrite(pPg);
53244  if( rc ) return rc;
53245  }
53246 
53247  /* If the page being moved is dirty and has not been saved by the latest
53248  ** savepoint, then save the current contents of the page into the
53249  ** sub-journal now. This is required to handle the following scenario:
53250  **
53251  ** BEGIN;
53252  ** <journal page X, then modify it in memory>
53253  ** SAVEPOINT one;
53254  ** <Move page X to location Y>
53255  ** ROLLBACK TO one;
53256  **
53257  ** If page X were not written to the sub-journal here, it would not
53258  ** be possible to restore its contents when the "ROLLBACK TO one"
53259  ** statement were is processed.
53260  **
53261  ** subjournalPage() may need to allocate space to store pPg->pgno into
53262  ** one or more savepoint bitvecs. This is the reason this function
53263  ** may return SQLITE_NOMEM.
53264  */
53265  if( (pPg->flags & PGHDR_DIRTY)!=0
53266  && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
53267  ){
53268  return rc;
53269  }
53270 
53271  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
53272  PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
53273  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
53274 
53275  /* If the journal needs to be sync()ed before page pPg->pgno can
53276  ** be written to, store pPg->pgno in local variable needSyncPgno.
53277  **
53278  ** If the isCommit flag is set, there is no need to remember that
53279  ** the journal needs to be sync()ed before database page pPg->pgno
53280  ** can be written to. The caller has already promised not to write to it.
53281  */
53282  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
53283  needSyncPgno = pPg->pgno;
53284  assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
53285  pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
53286  assert( pPg->flags&PGHDR_DIRTY );
53287  }
53288 
53289  /* If the cache contains a page with page-number pgno, remove it
53290  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
53291  ** page pgno before the 'move' operation, it needs to be retained
53292  ** for the page moved there.
53293  */
53294  pPg->flags &= ~PGHDR_NEED_SYNC;
53295  pPgOld = sqlite3PagerLookup(pPager, pgno);
53296  assert( !pPgOld || pPgOld->nRef==1 );
53297  if( pPgOld ){
53298  pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
53299  if( pPager->tempFile ){
53300  /* Do not discard pages from an in-memory database since we might
53301  ** need to rollback later. Just move the page out of the way. */
53302  sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
53303  }else{
53304  sqlite3PcacheDrop(pPgOld);
53305  }
53306  }
53307 
53308  origPgno = pPg->pgno;
53309  sqlite3PcacheMove(pPg, pgno);
53310  sqlite3PcacheMakeDirty(pPg);
53311 
53312  /* For an in-memory database, make sure the original page continues
53313  ** to exist, in case the transaction needs to roll back. Use pPgOld
53314  ** as the original page since it has already been allocated.
53315  */
53316  if( pPager->tempFile && pPgOld ){
53317  sqlite3PcacheMove(pPgOld, origPgno);
53318  sqlite3PagerUnrefNotNull(pPgOld);
53319  }
53320 
53321  if( needSyncPgno ){
53322  /* If needSyncPgno is non-zero, then the journal file needs to be
53323  ** sync()ed before any data is written to database file page needSyncPgno.
53324  ** Currently, no such page exists in the page-cache and the
53325  ** "is journaled" bitvec flag has been set. This needs to be remedied by
53326  ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
53327  ** flag.
53328  **
53329  ** If the attempt to load the page into the page-cache fails, (due
53330  ** to a malloc() or IO failure), clear the bit in the pInJournal[]
53331  ** array. Otherwise, if the page is loaded and written again in
53332  ** this transaction, it may be written to the database file before
53333  ** it is synced into the journal file. This way, it may end up in
53334  ** the journal file twice, but that is not a problem.
53335  */
53336  PgHdr *pPgHdr;
53337  rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
53338  if( rc!=SQLITE_OK ){
53339  if( needSyncPgno<=pPager->dbOrigSize ){
53340  assert( pPager->pTmpSpace!=0 );
53341  sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
53342  }
53343  return rc;
53344  }
53345  pPgHdr->flags |= PGHDR_NEED_SYNC;
53346  sqlite3PcacheMakeDirty(pPgHdr);
53347  sqlite3PagerUnrefNotNull(pPgHdr);
53348  }
53349 
53350  return SQLITE_OK;
53351 }
53352 #endif
53353 
53354 /*
53355 ** The page handle passed as the first argument refers to a dirty page
53356 ** with a page number other than iNew. This function changes the page's
53357 ** page number to iNew and sets the value of the PgHdr.flags field to
53358 ** the value passed as the third parameter.
53359 */
53360 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
53361  assert( pPg->pgno!=iNew );
53362  pPg->flags = flags;
53363  sqlite3PcacheMove(pPg, iNew);
53364 }
53365 
53366 /*
53367 ** Return a pointer to the data for the specified page.
53368 */
53369 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
53370  assert( pPg->nRef>0 || pPg->pPager->memDb );
53371  return pPg->pData;
53372 }
53373 
53374 /*
53375 ** Return a pointer to the Pager.nExtra bytes of "extra" space
53376 ** allocated along with the specified page.
53377 */
53378 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
53379  return pPg->pExtra;
53380 }
53381 
53382 /*
53383 ** Get/set the locking-mode for this pager. Parameter eMode must be one
53384 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
53385 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
53386 ** the locking-mode is set to the value specified.
53387 **
53388 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
53389 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
53390 ** locking-mode.
53391 */
53392 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
53393  assert( eMode==PAGER_LOCKINGMODE_QUERY
53394  || eMode==PAGER_LOCKINGMODE_NORMAL
53395  || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
53396  assert( PAGER_LOCKINGMODE_QUERY<0 );
53397  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
53398  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
53399  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
53400  pPager->exclusiveMode = (u8)eMode;
53401  }
53402  return (int)pPager->exclusiveMode;
53403 }
53404 
53405 /*
53406 ** Set the journal-mode for this pager. Parameter eMode must be one of:
53407 **
53408 ** PAGER_JOURNALMODE_DELETE
53409 ** PAGER_JOURNALMODE_TRUNCATE
53410 ** PAGER_JOURNALMODE_PERSIST
53411 ** PAGER_JOURNALMODE_OFF
53412 ** PAGER_JOURNALMODE_MEMORY
53413 ** PAGER_JOURNALMODE_WAL
53414 **
53415 ** The journalmode is set to the value specified if the change is allowed.
53416 ** The change may be disallowed for the following reasons:
53417 **
53418 ** * An in-memory database can only have its journal_mode set to _OFF
53419 ** or _MEMORY.
53420 **
53421 ** * Temporary databases cannot have _WAL journalmode.
53422 **
53423 ** The returned indicate the current (possibly updated) journal-mode.
53424 */
53425 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
53426  u8 eOld = pPager->journalMode; /* Prior journalmode */
53427 
53428 #ifdef SQLITE_DEBUG
53429  /* The print_pager_state() routine is intended to be used by the debugger
53430  ** only. We invoke it once here to suppress a compiler warning. */
53431  print_pager_state(pPager);
53432 #endif
53433 
53434 
53435  /* The eMode parameter is always valid */
53436  assert( eMode==PAGER_JOURNALMODE_DELETE
53437  || eMode==PAGER_JOURNALMODE_TRUNCATE
53438  || eMode==PAGER_JOURNALMODE_PERSIST
53439  || eMode==PAGER_JOURNALMODE_OFF
53440  || eMode==PAGER_JOURNALMODE_WAL
53441  || eMode==PAGER_JOURNALMODE_MEMORY );
53442 
53443  /* This routine is only called from the OP_JournalMode opcode, and
53444  ** the logic there will never allow a temporary file to be changed
53445  ** to WAL mode.
53446  */
53447  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
53448 
53449  /* Do allow the journalmode of an in-memory database to be set to
53450  ** anything other than MEMORY or OFF
53451  */
53452  if( MEMDB ){
53453  assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
53454  if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
53455  eMode = eOld;
53456  }
53457  }
53458 
53459  if( eMode!=eOld ){
53460 
53461  /* Change the journal mode. */
53462  assert( pPager->eState!=PAGER_ERROR );
53463  pPager->journalMode = (u8)eMode;
53464 
53465  /* When transistioning from TRUNCATE or PERSIST to any other journal
53466  ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
53467  ** delete the journal file.
53468  */
53469  assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
53470  assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
53471  assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
53472  assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
53473  assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
53474  assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
53475 
53476  assert( isOpen(pPager->fd) || pPager->exclusiveMode );
53477  if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
53478 
53479  /* In this case we would like to delete the journal file. If it is
53480  ** not possible, then that is not a problem. Deleting the journal file
53481  ** here is an optimization only.
53482  **
53483  ** Before deleting the journal file, obtain a RESERVED lock on the
53484  ** database file. This ensures that the journal file is not deleted
53485  ** while it is in use by some other client.
53486  */
53487  sqlite3OsClose(pPager->jfd);
53488  if( pPager->eLock>=RESERVED_LOCK ){
53489  sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53490  }else{
53491  int rc = SQLITE_OK;
53492  int state = pPager->eState;
53493  assert( state==PAGER_OPEN || state==PAGER_READER );
53494  if( state==PAGER_OPEN ){
53495  rc = sqlite3PagerSharedLock(pPager);
53496  }
53497  if( pPager->eState==PAGER_READER ){
53498  assert( rc==SQLITE_OK );
53499  rc = pagerLockDb(pPager, RESERVED_LOCK);
53500  }
53501  if( rc==SQLITE_OK ){
53502  sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53503  }
53504  if( rc==SQLITE_OK && state==PAGER_READER ){
53505  pagerUnlockDb(pPager, SHARED_LOCK);
53506  }else if( state==PAGER_OPEN ){
53507  pager_unlock(pPager);
53508  }
53509  assert( state==pPager->eState );
53510  }
53511  }else if( eMode==PAGER_JOURNALMODE_OFF ){
53512  sqlite3OsClose(pPager->jfd);
53513  }
53514  }
53515 
53516  /* Return the new journal mode */
53517  return (int)pPager->journalMode;
53518 }
53519 
53520 /*
53521 ** Return the current journal mode.
53522 */
53523 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
53524  return (int)pPager->journalMode;
53525 }
53526 
53527 /*
53528 ** Return TRUE if the pager is in a state where it is OK to change the
53529 ** journalmode. Journalmode changes can only happen when the database
53530 ** is unmodified.
53531 */
53532 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
53533  assert( assert_pager_state(pPager) );
53534  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
53535  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
53536  return 1;
53537 }
53538 
53539 /*
53540 ** Get/set the size-limit used for persistent journal files.
53541 **
53542 ** Setting the size limit to -1 means no limit is enforced.
53543 ** An attempt to set a limit smaller than -1 is a no-op.
53544 */
53545 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
53546  if( iLimit>=-1 ){
53547  pPager->journalSizeLimit = iLimit;
53548  sqlite3WalLimit(pPager->pWal, iLimit);
53549  }
53550  return pPager->journalSizeLimit;
53551 }
53552 
53553 /*
53554 ** Return a pointer to the pPager->pBackup variable. The backup module
53555 ** in backup.c maintains the content of this variable. This module
53556 ** uses it opaquely as an argument to sqlite3BackupRestart() and
53557 ** sqlite3BackupUpdate() only.
53558 */
53559 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
53560  return &pPager->pBackup;
53561 }
53562 
53563 #ifndef SQLITE_OMIT_VACUUM
53564 /*
53565 ** Unless this is an in-memory or temporary database, clear the pager cache.
53566 */
53567 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
53568  assert( MEMDB==0 || pPager->tempFile );
53569  if( pPager->tempFile==0 ) pager_reset(pPager);
53570 }
53571 #endif
53572 
53573 
53574 #ifndef SQLITE_OMIT_WAL
53575 /*
53576 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
53577 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
53578 ** or wal_blocking_checkpoint() API functions.
53579 **
53580 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
53581 */
53582 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
53583  int rc = SQLITE_OK;
53584  if( pPager->pWal ){
53585  rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
53586  (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
53587  pPager->pBusyHandlerArg,
53588  pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
53589  pnLog, pnCkpt
53590  );
53591  }
53592  return rc;
53593 }
53594 
53595 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
53596  return sqlite3WalCallback(pPager->pWal);
53597 }
53598 
53599 /*
53600 ** Return true if the underlying VFS for the given pager supports the
53601 ** primitives necessary for write-ahead logging.
53602 */
53603 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
53604  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
53605  if( pPager->noLock ) return 0;
53606  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
53607 }
53608 
53609 /*
53610 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
53611 ** is obtained instead, immediately release it.
53612 */
53613 static int pagerExclusiveLock(Pager *pPager){
53614  int rc; /* Return code */
53615 
53616  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53617  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
53618  if( rc!=SQLITE_OK ){
53619  /* If the attempt to grab the exclusive lock failed, release the
53620  ** pending lock that may have been obtained instead. */
53621  pagerUnlockDb(pPager, SHARED_LOCK);
53622  }
53623 
53624  return rc;
53625 }
53626 
53627 /*
53628 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
53629 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
53630 ** lock on the database file and use heap-memory to store the wal-index
53631 ** in. Otherwise, use the normal shared-memory.
53632 */
53633 static int pagerOpenWal(Pager *pPager){
53634  int rc = SQLITE_OK;
53635 
53636  assert( pPager->pWal==0 && pPager->tempFile==0 );
53637  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53638 
53639  /* If the pager is already in exclusive-mode, the WAL module will use
53640  ** heap-memory for the wal-index instead of the VFS shared-memory
53641  ** implementation. Take the exclusive lock now, before opening the WAL
53642  ** file, to make sure this is safe.
53643  */
53644  if( pPager->exclusiveMode ){
53645  rc = pagerExclusiveLock(pPager);
53646  }
53647 
53648  /* Open the connection to the log file. If this operation fails,
53649  ** (e.g. due to malloc() failure), return an error code.
53650  */
53651  if( rc==SQLITE_OK ){
53652  rc = sqlite3WalOpen(pPager->pVfs,
53653  pPager->fd, pPager->zWal, pPager->exclusiveMode,
53654  pPager->journalSizeLimit, &pPager->pWal
53655  );
53656  }
53657  pagerFixMaplimit(pPager);
53658 
53659  return rc;
53660 }
53661 
53662 
53663 /*
53664 ** The caller must be holding a SHARED lock on the database file to call
53665 ** this function.
53666 **
53667 ** If the pager passed as the first argument is open on a real database
53668 ** file (not a temp file or an in-memory database), and the WAL file
53669 ** is not already open, make an attempt to open it now. If successful,
53670 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
53671 ** not support the xShmXXX() methods, return an error code. *pbOpen is
53672 ** not modified in either case.
53673 **
53674 ** If the pager is open on a temp-file (or in-memory database), or if
53675 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
53676 ** without doing anything.
53677 */
53678 SQLITE_PRIVATE int sqlite3PagerOpenWal(
53679  Pager *pPager, /* Pager object */
53680  int *pbOpen /* OUT: Set to true if call is a no-op */
53681 ){
53682  int rc = SQLITE_OK; /* Return code */
53683 
53684  assert( assert_pager_state(pPager) );
53685  assert( pPager->eState==PAGER_OPEN || pbOpen );
53686  assert( pPager->eState==PAGER_READER || !pbOpen );
53687  assert( pbOpen==0 || *pbOpen==0 );
53688  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
53689 
53690  if( !pPager->tempFile && !pPager->pWal ){
53691  if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
53692 
53693  /* Close any rollback journal previously open */
53694  sqlite3OsClose(pPager->jfd);
53695 
53696  rc = pagerOpenWal(pPager);
53697  if( rc==SQLITE_OK ){
53698  pPager->journalMode = PAGER_JOURNALMODE_WAL;
53699  pPager->eState = PAGER_OPEN;
53700  }
53701  }else{
53702  *pbOpen = 1;
53703  }
53704 
53705  return rc;
53706 }
53707 
53708 /*
53709 ** This function is called to close the connection to the log file prior
53710 ** to switching from WAL to rollback mode.
53711 **
53712 ** Before closing the log file, this function attempts to take an
53713 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
53714 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
53715 ** If successful, the EXCLUSIVE lock is not released before returning.
53716 */
53717 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
53718  int rc = SQLITE_OK;
53719 
53720  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
53721 
53722  /* If the log file is not already open, but does exist in the file-system,
53723  ** it may need to be checkpointed before the connection can switch to
53724  ** rollback mode. Open it now so this can happen.
53725  */
53726  if( !pPager->pWal ){
53727  int logexists = 0;
53728  rc = pagerLockDb(pPager, SHARED_LOCK);
53729  if( rc==SQLITE_OK ){
53730  rc = sqlite3OsAccess(
53731  pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
53732  );
53733  }
53734  if( rc==SQLITE_OK && logexists ){
53735  rc = pagerOpenWal(pPager);
53736  }
53737  }
53738 
53739  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
53740  ** the database file, the log and log-summary files will be deleted.
53741  */
53742  if( rc==SQLITE_OK && pPager->pWal ){
53743  rc = pagerExclusiveLock(pPager);
53744  if( rc==SQLITE_OK ){
53745  rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
53746  pPager->pageSize, (u8*)pPager->pTmpSpace);
53747  pPager->pWal = 0;
53748  pagerFixMaplimit(pPager);
53749  if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
53750  }
53751  }
53752  return rc;
53753 }
53754 
53755 #ifdef SQLITE_ENABLE_SNAPSHOT
53756 /*
53757 ** If this is a WAL database, obtain a snapshot handle for the snapshot
53758 ** currently open. Otherwise, return an error.
53759 */
53760 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
53761  int rc = SQLITE_ERROR;
53762  if( pPager->pWal ){
53763  rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
53764  }
53765  return rc;
53766 }
53767 
53768 /*
53769 ** If this is a WAL database, store a pointer to pSnapshot. Next time a
53770 ** read transaction is opened, attempt to read from the snapshot it
53771 ** identifies. If this is not a WAL database, return an error.
53772 */
53773 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
53774  int rc = SQLITE_OK;
53775  if( pPager->pWal ){
53776  sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
53777  }else{
53778  rc = SQLITE_ERROR;
53779  }
53780  return rc;
53781 }
53782 #endif /* SQLITE_ENABLE_SNAPSHOT */
53783 #endif /* !SQLITE_OMIT_WAL */
53784 
53785 #ifdef SQLITE_ENABLE_ZIPVFS
53786 /*
53787 ** A read-lock must be held on the pager when this function is called. If
53788 ** the pager is in WAL mode and the WAL file currently contains one or more
53789 ** frames, return the size in bytes of the page images stored within the
53790 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
53791 ** is empty, return 0.
53792 */
53793 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
53794  assert( pPager->eState>=PAGER_READER );
53795  return sqlite3WalFramesize(pPager->pWal);
53796 }
53797 #endif
53798 
53799 #endif /* SQLITE_OMIT_DISKIO */
53800 
53801 /************** End of pager.c ***********************************************/
53802 /************** Begin file wal.c *********************************************/
53803 /*
53804 ** 2010 February 1
53805 **
53806 ** The author disclaims copyright to this source code. In place of
53807 ** a legal notice, here is a blessing:
53808 **
53809 ** May you do good and not evil.
53810 ** May you find forgiveness for yourself and forgive others.
53811 ** May you share freely, never taking more than you give.
53812 **
53813 *************************************************************************
53814 **
53815 ** This file contains the implementation of a write-ahead log (WAL) used in
53816 ** "journal_mode=WAL" mode.
53817 **
53818 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
53819 **
53820 ** A WAL file consists of a header followed by zero or more "frames".
53821 ** Each frame records the revised content of a single page from the
53822 ** database file. All changes to the database are recorded by writing
53823 ** frames into the WAL. Transactions commit when a frame is written that
53824 ** contains a commit marker. A single WAL can and usually does record
53825 ** multiple transactions. Periodically, the content of the WAL is
53826 ** transferred back into the database file in an operation called a
53827 ** "checkpoint".
53828 **
53829 ** A single WAL file can be used multiple times. In other words, the
53830 ** WAL can fill up with frames and then be checkpointed and then new
53831 ** frames can overwrite the old ones. A WAL always grows from beginning
53832 ** toward the end. Checksums and counters attached to each frame are
53833 ** used to determine which frames within the WAL are valid and which
53834 ** are leftovers from prior checkpoints.
53835 **
53836 ** The WAL header is 32 bytes in size and consists of the following eight
53837 ** big-endian 32-bit unsigned integer values:
53838 **
53839 ** 0: Magic number. 0x377f0682 or 0x377f0683
53840 ** 4: File format version. Currently 3007000
53841 ** 8: Database page size. Example: 1024
53842 ** 12: Checkpoint sequence number
53843 ** 16: Salt-1, random integer incremented with each checkpoint
53844 ** 20: Salt-2, a different random integer changing with each ckpt
53845 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
53846 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
53847 **
53848 ** Immediately following the wal-header are zero or more frames. Each
53849 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
53850 ** of page data. The frame-header is six big-endian 32-bit unsigned
53851 ** integer values, as follows:
53852 **
53853 ** 0: Page number.
53854 ** 4: For commit records, the size of the database image in pages
53855 ** after the commit. For all other records, zero.
53856 ** 8: Salt-1 (copied from the header)
53857 ** 12: Salt-2 (copied from the header)
53858 ** 16: Checksum-1.
53859 ** 20: Checksum-2.
53860 **
53861 ** A frame is considered valid if and only if the following conditions are
53862 ** true:
53863 **
53864 ** (1) The salt-1 and salt-2 values in the frame-header match
53865 ** salt values in the wal-header
53866 **
53867 ** (2) The checksum values in the final 8 bytes of the frame-header
53868 ** exactly match the checksum computed consecutively on the
53869 ** WAL header and the first 8 bytes and the content of all frames
53870 ** up to and including the current frame.
53871 **
53872 ** The checksum is computed using 32-bit big-endian integers if the
53873 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
53874 ** is computed using little-endian if the magic number is 0x377f0682.
53875 ** The checksum values are always stored in the frame header in a
53876 ** big-endian format regardless of which byte order is used to compute
53877 ** the checksum. The checksum is computed by interpreting the input as
53878 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
53879 ** algorithm used for the checksum is as follows:
53880 **
53881 ** for i from 0 to n-1 step 2:
53882 ** s0 += x[i] + s1;
53883 ** s1 += x[i+1] + s0;
53884 ** endfor
53885 **
53886 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
53887 ** in reverse order (the largest fibonacci weight occurs on the first element
53888 ** of the sequence being summed.) The s1 value spans all 32-bit
53889 ** terms of the sequence whereas s0 omits the final term.
53890 **
53891 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
53892 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
53893 ** The VFS.xSync operations serve as write barriers - all writes launched
53894 ** before the xSync must complete before any write that launches after the
53895 ** xSync begins.
53896 **
53897 ** After each checkpoint, the salt-1 value is incremented and the salt-2
53898 ** value is randomized. This prevents old and new frames in the WAL from
53899 ** being considered valid at the same time and being checkpointing together
53900 ** following a crash.
53901 **
53902 ** READER ALGORITHM
53903 **
53904 ** To read a page from the database (call it page number P), a reader
53905 ** first checks the WAL to see if it contains page P. If so, then the
53906 ** last valid instance of page P that is a followed by a commit frame
53907 ** or is a commit frame itself becomes the value read. If the WAL
53908 ** contains no copies of page P that are valid and which are a commit
53909 ** frame or are followed by a commit frame, then page P is read from
53910 ** the database file.
53911 **
53912 ** To start a read transaction, the reader records the index of the last
53913 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
53914 ** for all subsequent read operations. New transactions can be appended
53915 ** to the WAL, but as long as the reader uses its original mxFrame value
53916 ** and ignores the newly appended content, it will see a consistent snapshot
53917 ** of the database from a single point in time. This technique allows
53918 ** multiple concurrent readers to view different versions of the database
53919 ** content simultaneously.
53920 **
53921 ** The reader algorithm in the previous paragraphs works correctly, but
53922 ** because frames for page P can appear anywhere within the WAL, the
53923 ** reader has to scan the entire WAL looking for page P frames. If the
53924 ** WAL is large (multiple megabytes is typical) that scan can be slow,
53925 ** and read performance suffers. To overcome this problem, a separate
53926 ** data structure called the wal-index is maintained to expedite the
53927 ** search for frames of a particular page.
53928 **
53929 ** WAL-INDEX FORMAT
53930 **
53931 ** Conceptually, the wal-index is shared memory, though VFS implementations
53932 ** might choose to implement the wal-index using a mmapped file. Because
53933 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
53934 ** on a network filesystem. All users of the database must be able to
53935 ** share memory.
53936 **
53937 ** The wal-index is transient. After a crash, the wal-index can (and should
53938 ** be) reconstructed from the original WAL file. In fact, the VFS is required
53939 ** to either truncate or zero the header of the wal-index when the last
53940 ** connection to it closes. Because the wal-index is transient, it can
53941 ** use an architecture-specific format; it does not have to be cross-platform.
53942 ** Hence, unlike the database and WAL file formats which store all values
53943 ** as big endian, the wal-index can store multi-byte values in the native
53944 ** byte order of the host computer.
53945 **
53946 ** The purpose of the wal-index is to answer this question quickly: Given
53947 ** a page number P and a maximum frame index M, return the index of the
53948 ** last frame in the wal before frame M for page P in the WAL, or return
53949 ** NULL if there are no frames for page P in the WAL prior to M.
53950 **
53951 ** The wal-index consists of a header region, followed by an one or
53952 ** more index blocks.
53953 **
53954 ** The wal-index header contains the total number of frames within the WAL
53955 ** in the mxFrame field.
53956 **
53957 ** Each index block except for the first contains information on
53958 ** HASHTABLE_NPAGE frames. The first index block contains information on
53959 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
53960 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
53961 ** first index block are the same size as all other index blocks in the
53962 ** wal-index.
53963 **
53964 ** Each index block contains two sections, a page-mapping that contains the
53965 ** database page number associated with each wal frame, and a hash-table
53966 ** that allows readers to query an index block for a specific page number.
53967 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
53968 ** for the first index block) 32-bit page numbers. The first entry in the
53969 ** first index-block contains the database page number corresponding to the
53970 ** first frame in the WAL file. The first entry in the second index block
53971 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
53972 ** the log, and so on.
53973 **
53974 ** The last index block in a wal-index usually contains less than the full
53975 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
53976 ** depending on the contents of the WAL file. This does not change the
53977 ** allocated size of the page-mapping array - the page-mapping array merely
53978 ** contains unused entries.
53979 **
53980 ** Even without using the hash table, the last frame for page P
53981 ** can be found by scanning the page-mapping sections of each index block
53982 ** starting with the last index block and moving toward the first, and
53983 ** within each index block, starting at the end and moving toward the
53984 ** beginning. The first entry that equals P corresponds to the frame
53985 ** holding the content for that page.
53986 **
53987 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
53988 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
53989 ** hash table for each page number in the mapping section, so the hash
53990 ** table is never more than half full. The expected number of collisions
53991 ** prior to finding a match is 1. Each entry of the hash table is an
53992 ** 1-based index of an entry in the mapping section of the same
53993 ** index block. Let K be the 1-based index of the largest entry in
53994 ** the mapping section. (For index blocks other than the last, K will
53995 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
53996 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
53997 ** contain a value of 0.
53998 **
53999 ** To look for page P in the hash table, first compute a hash iKey on
54000 ** P as follows:
54001 **
54002 ** iKey = (P * 383) % HASHTABLE_NSLOT
54003 **
54004 ** Then start scanning entries of the hash table, starting with iKey
54005 ** (wrapping around to the beginning when the end of the hash table is
54006 ** reached) until an unused hash slot is found. Let the first unused slot
54007 ** be at index iUnused. (iUnused might be less than iKey if there was
54008 ** wrap-around.) Because the hash table is never more than half full,
54009 ** the search is guaranteed to eventually hit an unused entry. Let
54010 ** iMax be the value between iKey and iUnused, closest to iUnused,
54011 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
54012 ** no hash slot such that aHash[i]==p) then page P is not in the
54013 ** current index block. Otherwise the iMax-th mapping entry of the
54014 ** current index block corresponds to the last entry that references
54015 ** page P.
54016 **
54017 ** A hash search begins with the last index block and moves toward the
54018 ** first index block, looking for entries corresponding to page P. On
54019 ** average, only two or three slots in each index block need to be
54020 ** examined in order to either find the last entry for page P, or to
54021 ** establish that no such entry exists in the block. Each index block
54022 ** holds over 4000 entries. So two or three index blocks are sufficient
54023 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
54024 ** comparisons (on average) suffice to either locate a frame in the
54025 ** WAL or to establish that the frame does not exist in the WAL. This
54026 ** is much faster than scanning the entire 10MB WAL.
54027 **
54028 ** Note that entries are added in order of increasing K. Hence, one
54029 ** reader might be using some value K0 and a second reader that started
54030 ** at a later time (after additional transactions were added to the WAL
54031 ** and to the wal-index) might be using a different value K1, where K1>K0.
54032 ** Both readers can use the same hash table and mapping section to get
54033 ** the correct result. There may be entries in the hash table with
54034 ** K>K0 but to the first reader, those entries will appear to be unused
54035 ** slots in the hash table and so the first reader will get an answer as
54036 ** if no values greater than K0 had ever been inserted into the hash table
54037 ** in the first place - which is what reader one wants. Meanwhile, the
54038 ** second reader using K1 will see additional values that were inserted
54039 ** later, which is exactly what reader two wants.
54040 **
54041 ** When a rollback occurs, the value of K is decreased. Hash table entries
54042 ** that correspond to frames greater than the new K value are removed
54043 ** from the hash table at this point.
54044 */
54045 #ifndef SQLITE_OMIT_WAL
54046 
54047 /* #include "wal.h" */
54048 
54049 /*
54050 ** Trace output macros
54051 */
54052 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
54053 SQLITE_PRIVATE int sqlite3WalTrace = 0;
54054 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
54055 #else
54056 # define WALTRACE(X)
54057 #endif
54058 
54059 /*
54060 ** The maximum (and only) versions of the wal and wal-index formats
54061 ** that may be interpreted by this version of SQLite.
54062 **
54063 ** If a client begins recovering a WAL file and finds that (a) the checksum
54064 ** values in the wal-header are correct and (b) the version field is not
54065 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
54066 **
54067 ** Similarly, if a client successfully reads a wal-index header (i.e. the
54068 ** checksum test is successful) and finds that the version field is not
54069 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
54070 ** returns SQLITE_CANTOPEN.
54071 */
54072 #define WAL_MAX_VERSION 3007000
54073 #define WALINDEX_MAX_VERSION 3007000
54074 
54075 /*
54076 ** Indices of various locking bytes. WAL_NREADER is the number
54077 ** of available reader locks and should be at least 3. The default
54078 ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
54079 */
54080 #define WAL_WRITE_LOCK 0
54081 #define WAL_ALL_BUT_WRITE 1
54082 #define WAL_CKPT_LOCK 1
54083 #define WAL_RECOVER_LOCK 2
54084 #define WAL_READ_LOCK(I) (3+(I))
54085 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
54086 
54087 
54088 /* Object declarations */
54089 typedef struct WalIndexHdr WalIndexHdr;
54090 typedef struct WalIterator WalIterator;
54091 typedef struct WalCkptInfo WalCkptInfo;
54092 
54093 
54094 /*
54095 ** The following object holds a copy of the wal-index header content.
54096 **
54097 ** The actual header in the wal-index consists of two copies of this
54098 ** object followed by one instance of the WalCkptInfo object.
54099 ** For all versions of SQLite through 3.10.0 and probably beyond,
54100 ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
54101 ** the total header size is 136 bytes.
54102 **
54103 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
54104 ** Or it can be 1 to represent a 65536-byte page. The latter case was
54105 ** added in 3.7.1 when support for 64K pages was added.
54106 */
54107 struct WalIndexHdr {
54108  u32 iVersion; /* Wal-index version */
54109  u32 unused; /* Unused (padding) field */
54110  u32 iChange; /* Counter incremented each transaction */
54111  u8 isInit; /* 1 when initialized */
54112  u8 bigEndCksum; /* True if checksums in WAL are big-endian */
54113  u16 szPage; /* Database page size in bytes. 1==64K */
54114  u32 mxFrame; /* Index of last valid frame in the WAL */
54115  u32 nPage; /* Size of database in pages */
54116  u32 aFrameCksum[2]; /* Checksum of last frame in log */
54117  u32 aSalt[2]; /* Two salt values copied from WAL header */
54118  u32 aCksum[2]; /* Checksum over all prior fields */
54119 };
54120 
54121 /*
54122 ** A copy of the following object occurs in the wal-index immediately
54123 ** following the second copy of the WalIndexHdr. This object stores
54124 ** information used by checkpoint.
54125 **
54126 ** nBackfill is the number of frames in the WAL that have been written
54127 ** back into the database. (We call the act of moving content from WAL to
54128 ** database "backfilling".) The nBackfill number is never greater than
54129 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
54130 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
54131 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
54132 ** mxFrame back to zero when the WAL is reset.
54133 **
54134 ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
54135 ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
54136 ** the nBackfillAttempted is set before any backfilling is done and the
54137 ** nBackfill is only set after all backfilling completes. So if a checkpoint
54138 ** crashes, nBackfillAttempted might be larger than nBackfill. The
54139 ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
54140 **
54141 ** The aLock[] field is a set of bytes used for locking. These bytes should
54142 ** never be read or written.
54143 **
54144 ** There is one entry in aReadMark[] for each reader lock. If a reader
54145 ** holds read-lock K, then the value in aReadMark[K] is no greater than
54146 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
54147 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
54148 ** a special case; its value is never used and it exists as a place-holder
54149 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
54150 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
54151 ** directly from the database.
54152 **
54153 ** The value of aReadMark[K] may only be changed by a thread that
54154 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
54155 ** aReadMark[K] cannot changed while there is a reader is using that mark
54156 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
54157 **
54158 ** The checkpointer may only transfer frames from WAL to database where
54159 ** the frame numbers are less than or equal to every aReadMark[] that is
54160 ** in use (that is, every aReadMark[j] for which there is a corresponding
54161 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
54162 ** largest value and will increase an unused aReadMark[] to mxFrame if there
54163 ** is not already an aReadMark[] equal to mxFrame. The exception to the
54164 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
54165 ** in the WAL has been backfilled into the database) then new readers
54166 ** will choose aReadMark[0] which has value 0 and hence such reader will
54167 ** get all their all content directly from the database file and ignore
54168 ** the WAL.
54169 **
54170 ** Writers normally append new frames to the end of the WAL. However,
54171 ** if nBackfill equals mxFrame (meaning that all WAL content has been
54172 ** written back into the database) and if no readers are using the WAL
54173 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
54174 ** the writer will first "reset" the WAL back to the beginning and start
54175 ** writing new content beginning at frame 1.
54176 **
54177 ** We assume that 32-bit loads are atomic and so no locks are needed in
54178 ** order to read from any aReadMark[] entries.
54179 */
54180 struct WalCkptInfo {
54181  u32 nBackfill; /* Number of WAL frames backfilled into DB */
54182  u32 aReadMark[WAL_NREADER]; /* Reader marks */
54183  u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
54184  u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
54185  u32 notUsed0; /* Available for future enhancements */
54186 };
54187 #define READMARK_NOT_USED 0xffffffff
54188 
54189 
54190 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
54191 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
54192 ** only support mandatory file-locks, we do not read or write data
54193 ** from the region of the file on which locks are applied.
54194 */
54195 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
54196 #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
54197 
54198 /* Size of header before each frame in wal */
54199 #define WAL_FRAME_HDRSIZE 24
54200 
54201 /* Size of write ahead log header, including checksum. */
54202 /* #define WAL_HDRSIZE 24 */
54203 #define WAL_HDRSIZE 32
54204 
54205 /* WAL magic value. Either this value, or the same value with the least
54206 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
54207 ** big-endian format in the first 4 bytes of a WAL file.
54208 **
54209 ** If the LSB is set, then the checksums for each frame within the WAL
54210 ** file are calculated by treating all data as an array of 32-bit
54211 ** big-endian words. Otherwise, they are calculated by interpreting
54212 ** all data as 32-bit little-endian words.
54213 */
54214 #define WAL_MAGIC 0x377f0682
54215 
54216 /*
54217 ** Return the offset of frame iFrame in the write-ahead log file,
54218 ** assuming a database page size of szPage bytes. The offset returned
54219 ** is to the start of the write-ahead log frame-header.
54220 */
54221 #define walFrameOffset(iFrame, szPage) ( \
54222  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
54223 )
54224 
54225 /*
54226 ** An open write-ahead log file is represented by an instance of the
54227 ** following object.
54228 */
54229 struct Wal {
54230  sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
54231  sqlite3_file *pDbFd; /* File handle for the database file */
54232  sqlite3_file *pWalFd; /* File handle for WAL file */
54233  u32 iCallback; /* Value to pass to log callback (or 0) */
54234  i64 mxWalSize; /* Truncate WAL to this size upon reset */
54235  int nWiData; /* Size of array apWiData */
54236  int szFirstBlock; /* Size of first block written to WAL file */
54237  volatile u32 **apWiData; /* Pointer to wal-index content in memory */
54238  u32 szPage; /* Database page size */
54239  i16 readLock; /* Which read lock is being held. -1 for none */
54240  u8 syncFlags; /* Flags to use to sync header writes */
54241  u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
54242  u8 writeLock; /* True if in a write transaction */
54243  u8 ckptLock; /* True if holding a checkpoint lock */
54244  u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
54245  u8 truncateOnCommit; /* True to truncate WAL file on commit */
54246  u8 syncHeader; /* Fsync the WAL header if true */
54247  u8 padToSectorBoundary; /* Pad transactions out to the next sector */
54248  WalIndexHdr hdr; /* Wal-index header for current transaction */
54249  u32 minFrame; /* Ignore wal frames before this one */
54250  u32 iReCksum; /* On commit, recalculate checksums from here */
54251  const char *zWalName; /* Name of WAL file */
54252  u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
54253 #ifdef SQLITE_DEBUG
54254  u8 lockError; /* True if a locking error has occurred */
54255 #endif
54256 #ifdef SQLITE_ENABLE_SNAPSHOT
54257  WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
54258 #endif
54259 };
54260 
54261 /*
54262 ** Candidate values for Wal.exclusiveMode.
54263 */
54264 #define WAL_NORMAL_MODE 0
54265 #define WAL_EXCLUSIVE_MODE 1
54266 #define WAL_HEAPMEMORY_MODE 2
54267 
54268 /*
54269 ** Possible values for WAL.readOnly
54270 */
54271 #define WAL_RDWR 0 /* Normal read/write connection */
54272 #define WAL_RDONLY 1 /* The WAL file is readonly */
54273 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
54274 
54275 /*
54276 ** Each page of the wal-index mapping contains a hash-table made up of
54277 ** an array of HASHTABLE_NSLOT elements of the following type.
54278 */
54279 typedef u16 ht_slot;
54280 
54281 /*
54282 ** This structure is used to implement an iterator that loops through
54283 ** all frames in the WAL in database page order. Where two or more frames
54284 ** correspond to the same database page, the iterator visits only the
54285 ** frame most recently written to the WAL (in other words, the frame with
54286 ** the largest index).
54287 **
54288 ** The internals of this structure are only accessed by:
54289 **
54290 ** walIteratorInit() - Create a new iterator,
54291 ** walIteratorNext() - Step an iterator,
54292 ** walIteratorFree() - Free an iterator.
54293 **
54294 ** This functionality is used by the checkpoint code (see walCheckpoint()).
54295 */
54296 struct WalIterator {
54297  int iPrior; /* Last result returned from the iterator */
54298  int nSegment; /* Number of entries in aSegment[] */
54299  struct WalSegment {
54300  int iNext; /* Next slot in aIndex[] not yet returned */
54301  ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
54302  u32 *aPgno; /* Array of page numbers. */
54303  int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
54304  int iZero; /* Frame number associated with aPgno[0] */
54305  } aSegment[1]; /* One for every 32KB page in the wal-index */
54306 };
54307 
54308 /*
54309 ** Define the parameters of the hash tables in the wal-index file. There
54310 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
54311 ** wal-index.
54312 **
54313 ** Changing any of these constants will alter the wal-index format and
54314 ** create incompatibilities.
54315 */
54316 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
54317 #define HASHTABLE_HASH_1 383 /* Should be prime */
54318 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
54319 
54320 /*
54321 ** The block of page numbers associated with the first hash-table in a
54322 ** wal-index is smaller than usual. This is so that there is a complete
54323 ** hash-table on each aligned 32KB page of the wal-index.
54324 */
54325 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
54326 
54327 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
54328 #define WALINDEX_PGSZ ( \
54329  sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
54330 )
54331 
54332 /*
54333 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
54334 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
54335 ** numbered from zero.
54336 **
54337 ** If this call is successful, *ppPage is set to point to the wal-index
54338 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
54339 ** then an SQLite error code is returned and *ppPage is set to 0.
54340 */
54341 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
54342  int rc = SQLITE_OK;
54343 
54344  /* Enlarge the pWal->apWiData[] array if required */
54345  if( pWal->nWiData<=iPage ){
54346  int nByte = sizeof(u32*)*(iPage+1);
54347  volatile u32 **apNew;
54348  apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
54349  if( !apNew ){
54350  *ppPage = 0;
54351  return SQLITE_NOMEM_BKPT;
54352  }
54353  memset((void*)&apNew[pWal->nWiData], 0,
54354  sizeof(u32*)*(iPage+1-pWal->nWiData));
54355  pWal->apWiData = apNew;
54356  pWal->nWiData = iPage+1;
54357  }
54358 
54359  /* Request a pointer to the required page from the VFS */
54360  if( pWal->apWiData[iPage]==0 ){
54361  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54362  pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
54363  if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
54364  }else{
54365  rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
54366  pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
54367  );
54368  if( rc==SQLITE_READONLY ){
54369  pWal->readOnly |= WAL_SHM_RDONLY;
54370  rc = SQLITE_OK;
54371  }
54372  }
54373  }
54374 
54375  *ppPage = pWal->apWiData[iPage];
54376  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
54377  return rc;
54378 }
54379 
54380 /*
54381 ** Return a pointer to the WalCkptInfo structure in the wal-index.
54382 */
54383 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
54384  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54385  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
54386 }
54387 
54388 /*
54389 ** Return a pointer to the WalIndexHdr structure in the wal-index.
54390 */
54391 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
54392  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54393  return (volatile WalIndexHdr*)pWal->apWiData[0];
54394 }
54395 
54396 /*
54397 ** The argument to this macro must be of type u32. On a little-endian
54398 ** architecture, it returns the u32 value that results from interpreting
54399 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
54400 ** returns the value that would be produced by interpreting the 4 bytes
54401 ** of the input value as a little-endian integer.
54402 */
54403 #define BYTESWAP32(x) ( \
54404  (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
54405  + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
54406 )
54407 
54408 /*
54409 ** Generate or extend an 8 byte checksum based on the data in
54410 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
54411 ** initial values of 0 and 0 if aIn==NULL).
54412 **
54413 ** The checksum is written back into aOut[] before returning.
54414 **
54415 ** nByte must be a positive multiple of 8.
54416 */
54417 static void walChecksumBytes(
54418  int nativeCksum, /* True for native byte-order, false for non-native */
54419  u8 *a, /* Content to be checksummed */
54420  int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
54421  const u32 *aIn, /* Initial checksum value input */
54422  u32 *aOut /* OUT: Final checksum value output */
54423 ){
54424  u32 s1, s2;
54425  u32 *aData = (u32 *)a;
54426  u32 *aEnd = (u32 *)&a[nByte];
54427 
54428  if( aIn ){
54429  s1 = aIn[0];
54430  s2 = aIn[1];
54431  }else{
54432  s1 = s2 = 0;
54433  }
54434 
54435  assert( nByte>=8 );
54436  assert( (nByte&0x00000007)==0 );
54437 
54438  if( nativeCksum ){
54439  do {
54440  s1 += *aData++ + s2;
54441  s2 += *aData++ + s1;
54442  }while( aData<aEnd );
54443  }else{
54444  do {
54445  s1 += BYTESWAP32(aData[0]) + s2;
54446  s2 += BYTESWAP32(aData[1]) + s1;
54447  aData += 2;
54448  }while( aData<aEnd );
54449  }
54450 
54451  aOut[0] = s1;
54452  aOut[1] = s2;
54453 }
54454 
54455 static void walShmBarrier(Wal *pWal){
54456  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
54457  sqlite3OsShmBarrier(pWal->pDbFd);
54458  }
54459 }
54460 
54461 /*
54462 ** Write the header information in pWal->hdr into the wal-index.
54463 **
54464 ** The checksum on pWal->hdr is updated before it is written.
54465 */
54466 static void walIndexWriteHdr(Wal *pWal){
54467  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
54468  const int nCksum = offsetof(WalIndexHdr, aCksum);
54469 
54470  assert( pWal->writeLock );
54471  pWal->hdr.isInit = 1;
54472  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
54473  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
54474  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54475  walShmBarrier(pWal);
54476  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54477 }
54478 
54479 /*
54480 ** This function encodes a single frame header and writes it to a buffer
54481 ** supplied by the caller. A frame-header is made up of a series of
54482 ** 4-byte big-endian integers, as follows:
54483 **
54484 ** 0: Page number.
54485 ** 4: For commit records, the size of the database image in pages
54486 ** after the commit. For all other records, zero.
54487 ** 8: Salt-1 (copied from the wal-header)
54488 ** 12: Salt-2 (copied from the wal-header)
54489 ** 16: Checksum-1.
54490 ** 20: Checksum-2.
54491 */
54492 static void walEncodeFrame(
54493  Wal *pWal, /* The write-ahead log */
54494  u32 iPage, /* Database page number for frame */
54495  u32 nTruncate, /* New db size (or 0 for non-commit frames) */
54496  u8 *aData, /* Pointer to page data */
54497  u8 *aFrame /* OUT: Write encoded frame here */
54498 ){
54499  int nativeCksum; /* True for native byte-order checksums */
54500  u32 *aCksum = pWal->hdr.aFrameCksum;
54501  assert( WAL_FRAME_HDRSIZE==24 );
54502  sqlite3Put4byte(&aFrame[0], iPage);
54503  sqlite3Put4byte(&aFrame[4], nTruncate);
54504  if( pWal->iReCksum==0 ){
54505  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
54506 
54507  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54508  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54509  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54510 
54511  sqlite3Put4byte(&aFrame[16], aCksum[0]);
54512  sqlite3Put4byte(&aFrame[20], aCksum[1]);
54513  }else{
54514  memset(&aFrame[8], 0, 16);
54515  }
54516 }
54517 
54518 /*
54519 ** Check to see if the frame with header in aFrame[] and content
54520 ** in aData[] is valid. If it is a valid frame, fill *piPage and
54521 ** *pnTruncate and return true. Return if the frame is not valid.
54522 */
54523 static int walDecodeFrame(
54524  Wal *pWal, /* The write-ahead log */
54525  u32 *piPage, /* OUT: Database page number for frame */
54526  u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
54527  u8 *aData, /* Pointer to page data (for checksum) */
54528  u8 *aFrame /* Frame data */
54529 ){
54530  int nativeCksum; /* True for native byte-order checksums */
54531  u32 *aCksum = pWal->hdr.aFrameCksum;
54532  u32 pgno; /* Page number of the frame */
54533  assert( WAL_FRAME_HDRSIZE==24 );
54534 
54535  /* A frame is only valid if the salt values in the frame-header
54536  ** match the salt values in the wal-header.
54537  */
54538  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
54539  return 0;
54540  }
54541 
54542  /* A frame is only valid if the page number is creater than zero.
54543  */
54544  pgno = sqlite3Get4byte(&aFrame[0]);
54545  if( pgno==0 ){
54546  return 0;
54547  }
54548 
54549  /* A frame is only valid if a checksum of the WAL header,
54550  ** all prior frams, the first 16 bytes of this frame-header,
54551  ** and the frame-data matches the checksum in the last 8
54552  ** bytes of this frame-header.
54553  */
54554  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54555  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54556  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54557  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
54558  || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
54559  ){
54560  /* Checksum failed. */
54561  return 0;
54562  }
54563 
54564  /* If we reach this point, the frame is valid. Return the page number
54565  ** and the new database size.
54566  */
54567  *piPage = pgno;
54568  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
54569  return 1;
54570 }
54571 
54572 
54573 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
54574 /*
54575 ** Names of locks. This routine is used to provide debugging output and is not
54576 ** a part of an ordinary build.
54577 */
54578 static const char *walLockName(int lockIdx){
54579  if( lockIdx==WAL_WRITE_LOCK ){
54580  return "WRITE-LOCK";
54581  }else if( lockIdx==WAL_CKPT_LOCK ){
54582  return "CKPT-LOCK";
54583  }else if( lockIdx==WAL_RECOVER_LOCK ){
54584  return "RECOVER-LOCK";
54585  }else{
54586  static char zName[15];
54587  sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
54588  lockIdx-WAL_READ_LOCK(0));
54589  return zName;
54590  }
54591 }
54592 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
54593 
54594 
54595 /*
54596 ** Set or release locks on the WAL. Locks are either shared or exclusive.
54597 ** A lock cannot be moved directly between shared and exclusive - it must go
54598 ** through the unlocked state first.
54599 **
54600 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
54601 */
54602 static int walLockShared(Wal *pWal, int lockIdx){
54603  int rc;
54604  if( pWal->exclusiveMode ) return SQLITE_OK;
54605  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54606  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
54607  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
54608  walLockName(lockIdx), rc ? "failed" : "ok"));
54609  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54610  return rc;
54611 }
54612 static void walUnlockShared(Wal *pWal, int lockIdx){
54613  if( pWal->exclusiveMode ) return;
54614  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54615  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
54616  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
54617 }
54618 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
54619  int rc;
54620  if( pWal->exclusiveMode ) return SQLITE_OK;
54621  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54622  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
54623  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
54624  walLockName(lockIdx), n, rc ? "failed" : "ok"));
54625  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54626  return rc;
54627 }
54628 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
54629  if( pWal->exclusiveMode ) return;
54630  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54631  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
54632  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
54633  walLockName(lockIdx), n));
54634 }
54635 
54636 /*
54637 ** Compute a hash on a page number. The resulting hash value must land
54638 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
54639 ** the hash to the next value in the event of a collision.
54640 */
54641 static int walHash(u32 iPage){
54642  assert( iPage>0 );
54643  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
54644  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
54645 }
54646 static int walNextHash(int iPriorHash){
54647  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
54648 }
54649 
54650 /*
54651 ** Return pointers to the hash table and page number array stored on
54652 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
54653 ** numbered starting from 0.
54654 **
54655 ** Set output variable *paHash to point to the start of the hash table
54656 ** in the wal-index file. Set *piZero to one less than the frame
54657 ** number of the first frame indexed by this hash table. If a
54658 ** slot in the hash table is set to N, it refers to frame number
54659 ** (*piZero+N) in the log.
54660 **
54661 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
54662 ** first frame indexed by the hash table, frame (*piZero+1).
54663 */
54664 static int walHashGet(
54665  Wal *pWal, /* WAL handle */
54666  int iHash, /* Find the iHash'th table */
54667  volatile ht_slot **paHash, /* OUT: Pointer to hash index */
54668  volatile u32 **paPgno, /* OUT: Pointer to page number array */
54669  u32 *piZero /* OUT: Frame associated with *paPgno[0] */
54670 ){
54671  int rc; /* Return code */
54672  volatile u32 *aPgno;
54673 
54674  rc = walIndexPage(pWal, iHash, &aPgno);
54675  assert( rc==SQLITE_OK || iHash>0 );
54676 
54677  if( rc==SQLITE_OK ){
54678  u32 iZero;
54679  volatile ht_slot *aHash;
54680 
54681  aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
54682  if( iHash==0 ){
54683  aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
54684  iZero = 0;
54685  }else{
54686  iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
54687  }
54688 
54689  *paPgno = &aPgno[-1];
54690  *paHash = aHash;
54691  *piZero = iZero;
54692  }
54693  return rc;
54694 }
54695 
54696 /*
54697 ** Return the number of the wal-index page that contains the hash-table
54698 ** and page-number array that contain entries corresponding to WAL frame
54699 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
54700 ** are numbered starting from 0.
54701 */
54702 static int walFramePage(u32 iFrame){
54703  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
54704  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
54705  && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
54706  && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
54707  && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
54708  && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
54709  );
54710  return iHash;
54711 }
54712 
54713 /*
54714 ** Return the page number associated with frame iFrame in this WAL.
54715 */
54716 static u32 walFramePgno(Wal *pWal, u32 iFrame){
54717  int iHash = walFramePage(iFrame);
54718  if( iHash==0 ){
54719  return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
54720  }
54721  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
54722 }
54723 
54724 /*
54725 ** Remove entries from the hash table that point to WAL slots greater
54726 ** than pWal->hdr.mxFrame.
54727 **
54728 ** This function is called whenever pWal->hdr.mxFrame is decreased due
54729 ** to a rollback or savepoint.
54730 **
54731 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
54732 ** updated. Any later hash tables will be automatically cleared when
54733 ** pWal->hdr.mxFrame advances to the point where those hash tables are
54734 ** actually needed.
54735 */
54736 static void walCleanupHash(Wal *pWal){
54737  volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
54738  volatile u32 *aPgno = 0; /* Page number array for hash table */
54739  u32 iZero = 0; /* frame == (aHash[x]+iZero) */
54740  int iLimit = 0; /* Zero values greater than this */
54741  int nByte; /* Number of bytes to zero in aPgno[] */
54742  int i; /* Used to iterate through aHash[] */
54743 
54744  assert( pWal->writeLock );
54745  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
54746  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
54747  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
54748 
54749  if( pWal->hdr.mxFrame==0 ) return;
54750 
54751  /* Obtain pointers to the hash-table and page-number array containing
54752  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
54753  ** that the page said hash-table and array reside on is already mapped.
54754  */
54755  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
54756  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
54757  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
54758 
54759  /* Zero all hash-table entries that correspond to frame numbers greater
54760  ** than pWal->hdr.mxFrame.
54761  */
54762  iLimit = pWal->hdr.mxFrame - iZero;
54763  assert( iLimit>0 );
54764  for(i=0; i<HASHTABLE_NSLOT; i++){
54765  if( aHash[i]>iLimit ){
54766  aHash[i] = 0;
54767  }
54768  }
54769 
54770  /* Zero the entries in the aPgno array that correspond to frames with
54771  ** frame numbers greater than pWal->hdr.mxFrame.
54772  */
54773  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
54774  memset((void *)&aPgno[iLimit+1], 0, nByte);
54775 
54776 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54777  /* Verify that the every entry in the mapping region is still reachable
54778  ** via the hash table even after the cleanup.
54779  */
54780  if( iLimit ){
54781  int j; /* Loop counter */
54782  int iKey; /* Hash key */
54783  for(j=1; j<=iLimit; j++){
54784  for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
54785  if( aHash[iKey]==j ) break;
54786  }
54787  assert( aHash[iKey]==j );
54788  }
54789  }
54790 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54791 }
54792 
54793 
54794 /*
54795 ** Set an entry in the wal-index that will map database page number
54796 ** pPage into WAL frame iFrame.
54797 */
54798 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
54799  int rc; /* Return code */
54800  u32 iZero = 0; /* One less than frame number of aPgno[1] */
54801  volatile u32 *aPgno = 0; /* Page number array */
54802  volatile ht_slot *aHash = 0; /* Hash table */
54803 
54804  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
54805 
54806  /* Assuming the wal-index file was successfully mapped, populate the
54807  ** page number array and hash table entry.
54808  */
54809  if( rc==SQLITE_OK ){
54810  int iKey; /* Hash table key */
54811  int idx; /* Value to write to hash-table slot */
54812  int nCollide; /* Number of hash collisions */
54813 
54814  idx = iFrame - iZero;
54815  assert( idx <= HASHTABLE_NSLOT/2 + 1 );
54816 
54817  /* If this is the first entry to be added to this hash-table, zero the
54818  ** entire hash table and aPgno[] array before proceeding.
54819  */
54820  if( idx==1 ){
54821  int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
54822  memset((void*)&aPgno[1], 0, nByte);
54823  }
54824 
54825  /* If the entry in aPgno[] is already set, then the previous writer
54826  ** must have exited unexpectedly in the middle of a transaction (after
54827  ** writing one or more dirty pages to the WAL to free up memory).
54828  ** Remove the remnants of that writers uncommitted transaction from
54829  ** the hash-table before writing any new entries.
54830  */
54831  if( aPgno[idx] ){
54832  walCleanupHash(pWal);
54833  assert( !aPgno[idx] );
54834  }
54835 
54836  /* Write the aPgno[] array entry and the hash-table slot. */
54837  nCollide = idx;
54838  for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
54839  if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
54840  }
54841  aPgno[idx] = iPage;
54842  aHash[iKey] = (ht_slot)idx;
54843 
54844 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54845  /* Verify that the number of entries in the hash table exactly equals
54846  ** the number of entries in the mapping region.
54847  */
54848  {
54849  int i; /* Loop counter */
54850  int nEntry = 0; /* Number of entries in the hash table */
54851  for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
54852  assert( nEntry==idx );
54853  }
54854 
54855  /* Verify that the every entry in the mapping region is reachable
54856  ** via the hash table. This turns out to be a really, really expensive
54857  ** thing to check, so only do this occasionally - not on every
54858  ** iteration.
54859  */
54860  if( (idx&0x3ff)==0 ){
54861  int i; /* Loop counter */
54862  for(i=1; i<=idx; i++){
54863  for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
54864  if( aHash[iKey]==i ) break;
54865  }
54866  assert( aHash[iKey]==i );
54867  }
54868  }
54869 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54870  }
54871 
54872 
54873  return rc;
54874 }
54875 
54876 
54877 /*
54878 ** Recover the wal-index by reading the write-ahead log file.
54879 **
54880 ** This routine first tries to establish an exclusive lock on the
54881 ** wal-index to prevent other threads/processes from doing anything
54882 ** with the WAL or wal-index while recovery is running. The
54883 ** WAL_RECOVER_LOCK is also held so that other threads will know
54884 ** that this thread is running recovery. If unable to establish
54885 ** the necessary locks, this routine returns SQLITE_BUSY.
54886 */
54887 static int walIndexRecover(Wal *pWal){
54888  int rc; /* Return Code */
54889  i64 nSize; /* Size of log file */
54890  u32 aFrameCksum[2] = {0, 0};
54891  int iLock; /* Lock offset to lock for checkpoint */
54892  int nLock; /* Number of locks to hold */
54893 
54894  /* Obtain an exclusive lock on all byte in the locking range not already
54895  ** locked by the caller. The caller is guaranteed to have locked the
54896  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
54897  ** If successful, the same bytes that are locked here are unlocked before
54898  ** this function returns.
54899  */
54900  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
54901  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
54902  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
54903  assert( pWal->writeLock );
54904  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
54905  nLock = SQLITE_SHM_NLOCK - iLock;
54906  rc = walLockExclusive(pWal, iLock, nLock);
54907  if( rc ){
54908  return rc;
54909  }
54910  WALTRACE(("WAL%p: recovery begin...\n", pWal));
54911 
54912  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
54913 
54914  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
54915  if( rc!=SQLITE_OK ){
54916  goto recovery_error;
54917  }
54918 
54919  if( nSize>WAL_HDRSIZE ){
54920  u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
54921  u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
54922  int szFrame; /* Number of bytes in buffer aFrame[] */
54923  u8 *aData; /* Pointer to data part of aFrame buffer */
54924  int iFrame; /* Index of last frame read */
54925  i64 iOffset; /* Next offset to read from log file */
54926  int szPage; /* Page size according to the log */
54927  u32 magic; /* Magic value read from WAL header */
54928  u32 version; /* Magic value read from WAL header */
54929  int isValid; /* True if this frame is valid */
54930 
54931  /* Read in the WAL header. */
54932  rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
54933  if( rc!=SQLITE_OK ){
54934  goto recovery_error;
54935  }
54936 
54937  /* If the database page size is not a power of two, or is greater than
54938  ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
54939  ** data. Similarly, if the 'magic' value is invalid, ignore the whole
54940  ** WAL file.
54941  */
54942  magic = sqlite3Get4byte(&aBuf[0]);
54943  szPage = sqlite3Get4byte(&aBuf[8]);
54944  if( (magic&0xFFFFFFFE)!=WAL_MAGIC
54945  || szPage&(szPage-1)
54946  || szPage>SQLITE_MAX_PAGE_SIZE
54947  || szPage<512
54948  ){
54949  goto finished;
54950  }
54951  pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
54952  pWal->szPage = szPage;
54953  pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
54954  memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
54955 
54956  /* Verify that the WAL header checksum is correct */
54957  walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
54958  aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
54959  );
54960  if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
54961  || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
54962  ){
54963  goto finished;
54964  }
54965 
54966  /* Verify that the version number on the WAL format is one that
54967  ** are able to understand */
54968  version = sqlite3Get4byte(&aBuf[4]);
54969  if( version!=WAL_MAX_VERSION ){
54970  rc = SQLITE_CANTOPEN_BKPT;
54971  goto finished;
54972  }
54973 
54974  /* Malloc a buffer to read frames into. */
54975  szFrame = szPage + WAL_FRAME_HDRSIZE;
54976  aFrame = (u8 *)sqlite3_malloc64(szFrame);
54977  if( !aFrame ){
54978  rc = SQLITE_NOMEM_BKPT;
54979  goto recovery_error;
54980  }
54981  aData = &aFrame[WAL_FRAME_HDRSIZE];
54982 
54983  /* Read all frames from the log file. */
54984  iFrame = 0;
54985  for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
54986  u32 pgno; /* Database page number for frame */
54987  u32 nTruncate; /* dbsize field from frame header */
54988 
54989  /* Read and decode the next log frame. */
54990  iFrame++;
54991  rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
54992  if( rc!=SQLITE_OK ) break;
54993  isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
54994  if( !isValid ) break;
54995  rc = walIndexAppend(pWal, iFrame, pgno);
54996  if( rc!=SQLITE_OK ) break;
54997 
54998  /* If nTruncate is non-zero, this is a commit record. */
54999  if( nTruncate ){
55000  pWal->hdr.mxFrame = iFrame;
55001  pWal->hdr.nPage = nTruncate;
55002  pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
55003  testcase( szPage<=32768 );
55004  testcase( szPage>=65536 );
55005  aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
55006  aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
55007  }
55008  }
55009 
55010  sqlite3_free(aFrame);
55011  }
55012 
55013 finished:
55014  if( rc==SQLITE_OK ){
55015  volatile WalCkptInfo *pInfo;
55016  int i;
55017  pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
55018  pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
55019  walIndexWriteHdr(pWal);
55020 
55021  /* Reset the checkpoint-header. This is safe because this thread is
55022  ** currently holding locks that exclude all other readers, writers and
55023  ** checkpointers.
55024  */
55025  pInfo = walCkptInfo(pWal);
55026  pInfo->nBackfill = 0;
55027  pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
55028  pInfo->aReadMark[0] = 0;
55029  for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
55030  if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
55031 
55032  /* If more than one frame was recovered from the log file, report an
55033  ** event via sqlite3_log(). This is to help with identifying performance
55034  ** problems caused by applications routinely shutting down without
55035  ** checkpointing the log file.
55036  */
55037  if( pWal->hdr.nPage ){
55038  sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
55039  "recovered %d frames from WAL file %s",
55040  pWal->hdr.mxFrame, pWal->zWalName
55041  );
55042  }
55043  }
55044 
55045 recovery_error:
55046  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
55047  walUnlockExclusive(pWal, iLock, nLock);
55048  return rc;
55049 }
55050 
55051 /*
55052 ** Close an open wal-index.
55053 */
55054 static void walIndexClose(Wal *pWal, int isDelete){
55055  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
55056  int i;
55057  for(i=0; i<pWal->nWiData; i++){
55058  sqlite3_free((void *)pWal->apWiData[i]);
55059  pWal->apWiData[i] = 0;
55060  }
55061  }else{
55062  sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
55063  }
55064 }
55065 
55066 /*
55067 ** Open a connection to the WAL file zWalName. The database file must
55068 ** already be opened on connection pDbFd. The buffer that zWalName points
55069 ** to must remain valid for the lifetime of the returned Wal* handle.
55070 **
55071 ** A SHARED lock should be held on the database file when this function
55072 ** is called. The purpose of this SHARED lock is to prevent any other
55073 ** client from unlinking the WAL or wal-index file. If another process
55074 ** were to do this just after this client opened one of these files, the
55075 ** system would be badly broken.
55076 **
55077 ** If the log file is successfully opened, SQLITE_OK is returned and
55078 ** *ppWal is set to point to a new WAL handle. If an error occurs,
55079 ** an SQLite error code is returned and *ppWal is left unmodified.
55080 */
55081 SQLITE_PRIVATE int sqlite3WalOpen(
55082  sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
55083  sqlite3_file *pDbFd, /* The open database file */
55084  const char *zWalName, /* Name of the WAL file */
55085  int bNoShm, /* True to run in heap-memory mode */
55086  i64 mxWalSize, /* Truncate WAL to this size on reset */
55087  Wal **ppWal /* OUT: Allocated Wal handle */
55088 ){
55089  int rc; /* Return Code */
55090  Wal *pRet; /* Object to allocate and return */
55091  int flags; /* Flags passed to OsOpen() */
55092 
55093  assert( zWalName && zWalName[0] );
55094  assert( pDbFd );
55095 
55096  /* In the amalgamation, the os_unix.c and os_win.c source files come before
55097  ** this source file. Verify that the #defines of the locking byte offsets
55098  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
55099  ** For that matter, if the lock offset ever changes from its initial design
55100  ** value of 120, we need to know that so there is an assert() to check it.
55101  */
55102  assert( 120==WALINDEX_LOCK_OFFSET );
55103  assert( 136==WALINDEX_HDR_SIZE );
55104 #ifdef WIN_SHM_BASE
55105  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
55106 #endif
55107 #ifdef UNIX_SHM_BASE
55108  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
55109 #endif
55110 
55111 
55112  /* Allocate an instance of struct Wal to return. */
55113  *ppWal = 0;
55114  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
55115  if( !pRet ){
55116  return SQLITE_NOMEM_BKPT;
55117  }
55118 
55119  pRet->pVfs = pVfs;
55120  pRet->pWalFd = (sqlite3_file *)&pRet[1];
55121  pRet->pDbFd = pDbFd;
55122  pRet->readLock = -1;
55123  pRet->mxWalSize = mxWalSize;
55124  pRet->zWalName = zWalName;
55125  pRet->syncHeader = 1;
55126  pRet->padToSectorBoundary = 1;
55127  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
55128 
55129  /* Open file handle on the write-ahead log file. */
55130  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
55131  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
55132  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
55133  pRet->readOnly = WAL_RDONLY;
55134  }
55135 
55136  if( rc!=SQLITE_OK ){
55137  walIndexClose(pRet, 0);
55138  sqlite3OsClose(pRet->pWalFd);
55139  sqlite3_free(pRet);
55140  }else{
55141  int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
55142  if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
55143  if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
55144  pRet->padToSectorBoundary = 0;
55145  }
55146  *ppWal = pRet;
55147  WALTRACE(("WAL%d: opened\n", pRet));
55148  }
55149  return rc;
55150 }
55151 
55152 /*
55153 ** Change the size to which the WAL file is trucated on each reset.
55154 */
55155 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
55156  if( pWal ) pWal->mxWalSize = iLimit;
55157 }
55158 
55159 /*
55160 ** Find the smallest page number out of all pages held in the WAL that
55161 ** has not been returned by any prior invocation of this method on the
55162 ** same WalIterator object. Write into *piFrame the frame index where
55163 ** that page was last written into the WAL. Write into *piPage the page
55164 ** number.
55165 **
55166 ** Return 0 on success. If there are no pages in the WAL with a page
55167 ** number larger than *piPage, then return 1.
55168 */
55169 static int walIteratorNext(
55170  WalIterator *p, /* Iterator */
55171  u32 *piPage, /* OUT: The page number of the next page */
55172  u32 *piFrame /* OUT: Wal frame index of next page */
55173 ){
55174  u32 iMin; /* Result pgno must be greater than iMin */
55175  u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
55176  int i; /* For looping through segments */
55177 
55178  iMin = p->iPrior;
55179  assert( iMin<0xffffffff );
55180  for(i=p->nSegment-1; i>=0; i--){
55181  struct WalSegment *pSegment = &p->aSegment[i];
55182  while( pSegment->iNext<pSegment->nEntry ){
55183  u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
55184  if( iPg>iMin ){
55185  if( iPg<iRet ){
55186  iRet = iPg;
55187  *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
55188  }
55189  break;
55190  }
55191  pSegment->iNext++;
55192  }
55193  }
55194 
55195  *piPage = p->iPrior = iRet;
55196  return (iRet==0xFFFFFFFF);
55197 }
55198 
55199 /*
55200 ** This function merges two sorted lists into a single sorted list.
55201 **
55202 ** aLeft[] and aRight[] are arrays of indices. The sort key is
55203 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
55204 ** is guaranteed for all J<K:
55205 **
55206 ** aContent[aLeft[J]] < aContent[aLeft[K]]
55207 ** aContent[aRight[J]] < aContent[aRight[K]]
55208 **
55209 ** This routine overwrites aRight[] with a new (probably longer) sequence
55210 ** of indices such that the aRight[] contains every index that appears in
55211 ** either aLeft[] or the old aRight[] and such that the second condition
55212 ** above is still met.
55213 **
55214 ** The aContent[aLeft[X]] values will be unique for all X. And the
55215 ** aContent[aRight[X]] values will be unique too. But there might be
55216 ** one or more combinations of X and Y such that
55217 **
55218 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
55219 **
55220 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
55221 */
55222 static void walMerge(
55223  const u32 *aContent, /* Pages in wal - keys for the sort */
55224  ht_slot *aLeft, /* IN: Left hand input list */
55225  int nLeft, /* IN: Elements in array *paLeft */
55226  ht_slot **paRight, /* IN/OUT: Right hand input list */
55227  int *pnRight, /* IN/OUT: Elements in *paRight */
55228  ht_slot *aTmp /* Temporary buffer */
55229 ){
55230  int iLeft = 0; /* Current index in aLeft */
55231  int iRight = 0; /* Current index in aRight */
55232  int iOut = 0; /* Current index in output buffer */
55233  int nRight = *pnRight;
55234  ht_slot *aRight = *paRight;
55235 
55236  assert( nLeft>0 && nRight>0 );
55237  while( iRight<nRight || iLeft<nLeft ){
55238  ht_slot logpage;
55239  Pgno dbpage;
55240 
55241  if( (iLeft<nLeft)
55242  && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
55243  ){
55244  logpage = aLeft[iLeft++];
55245  }else{
55246  logpage = aRight[iRight++];
55247  }
55248  dbpage = aContent[logpage];
55249 
55250  aTmp[iOut++] = logpage;
55251  if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
55252 
55253  assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
55254  assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
55255  }
55256 
55257  *paRight = aLeft;
55258  *pnRight = iOut;
55259  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
55260 }
55261 
55262 /*
55263 ** Sort the elements in list aList using aContent[] as the sort key.
55264 ** Remove elements with duplicate keys, preferring to keep the
55265 ** larger aList[] values.
55266 **
55267 ** The aList[] entries are indices into aContent[]. The values in
55268 ** aList[] are to be sorted so that for all J<K:
55269 **
55270 ** aContent[aList[J]] < aContent[aList[K]]
55271 **
55272 ** For any X and Y such that
55273 **
55274 ** aContent[aList[X]] == aContent[aList[Y]]
55275 **
55276 ** Keep the larger of the two values aList[X] and aList[Y] and discard
55277 ** the smaller.
55278 */
55279 static void walMergesort(
55280  const u32 *aContent, /* Pages in wal */
55281  ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
55282  ht_slot *aList, /* IN/OUT: List to sort */
55283  int *pnList /* IN/OUT: Number of elements in aList[] */
55284 ){
55285  struct Sublist {
55286  int nList; /* Number of elements in aList */
55287  ht_slot *aList; /* Pointer to sub-list content */
55288  };
55289 
55290  const int nList = *pnList; /* Size of input list */
55291  int nMerge = 0; /* Number of elements in list aMerge */
55292  ht_slot *aMerge = 0; /* List to be merged */
55293  int iList; /* Index into input list */
55294  u32 iSub = 0; /* Index into aSub array */
55295  struct Sublist aSub[13]; /* Array of sub-lists */
55296 
55297  memset(aSub, 0, sizeof(aSub));
55298  assert( nList<=HASHTABLE_NPAGE && nList>0 );
55299  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
55300 
55301  for(iList=0; iList<nList; iList++){
55302  nMerge = 1;
55303  aMerge = &aList[iList];
55304  for(iSub=0; iList & (1<<iSub); iSub++){
55305  struct Sublist *p;
55306  assert( iSub<ArraySize(aSub) );
55307  p = &aSub[iSub];
55308  assert( p->aList && p->nList<=(1<<iSub) );
55309  assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
55310  walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55311  }
55312  aSub[iSub].aList = aMerge;
55313  aSub[iSub].nList = nMerge;
55314  }
55315 
55316  for(iSub++; iSub<ArraySize(aSub); iSub++){
55317  if( nList & (1<<iSub) ){
55318  struct Sublist *p;
55319  assert( iSub<ArraySize(aSub) );
55320  p = &aSub[iSub];
55321  assert( p->nList<=(1<<iSub) );
55322  assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
55323  walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55324  }
55325  }
55326  assert( aMerge==aList );
55327  *pnList = nMerge;
55328 
55329 #ifdef SQLITE_DEBUG
55330  {
55331  int i;
55332  for(i=1; i<*pnList; i++){
55333  assert( aContent[aList[i]] > aContent[aList[i-1]] );
55334  }
55335  }
55336 #endif
55337 }
55338 
55339 /*
55340 ** Free an iterator allocated by walIteratorInit().
55341 */
55342 static void walIteratorFree(WalIterator *p){
55343  sqlite3_free(p);
55344 }
55345 
55346 /*
55347 ** Construct a WalInterator object that can be used to loop over all
55348 ** pages in the WAL in ascending order. The caller must hold the checkpoint
55349 ** lock.
55350 **
55351 ** On success, make *pp point to the newly allocated WalInterator object
55352 ** return SQLITE_OK. Otherwise, return an error code. If this routine
55353 ** returns an error, the value of *pp is undefined.
55354 **
55355 ** The calling routine should invoke walIteratorFree() to destroy the
55356 ** WalIterator object when it has finished with it.
55357 */
55358 static int walIteratorInit(Wal *pWal, WalIterator **pp){
55359  WalIterator *p; /* Return value */
55360  int nSegment; /* Number of segments to merge */
55361  u32 iLast; /* Last frame in log */
55362  int nByte; /* Number of bytes to allocate */
55363  int i; /* Iterator variable */
55364  ht_slot *aTmp; /* Temp space used by merge-sort */
55365  int rc = SQLITE_OK; /* Return Code */
55366 
55367  /* This routine only runs while holding the checkpoint lock. And
55368  ** it only runs if there is actually content in the log (mxFrame>0).
55369  */
55370  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
55371  iLast = pWal->hdr.mxFrame;
55372 
55373  /* Allocate space for the WalIterator object. */
55374  nSegment = walFramePage(iLast) + 1;
55375  nByte = sizeof(WalIterator)
55376  + (nSegment-1)*sizeof(struct WalSegment)
55377  + iLast*sizeof(ht_slot);
55378  p = (WalIterator *)sqlite3_malloc64(nByte);
55379  if( !p ){
55380  return SQLITE_NOMEM_BKPT;
55381  }
55382  memset(p, 0, nByte);
55383  p->nSegment = nSegment;
55384 
55385  /* Allocate temporary space used by the merge-sort routine. This block
55386  ** of memory will be freed before this function returns.
55387  */
55388  aTmp = (ht_slot *)sqlite3_malloc64(
55389  sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
55390  );
55391  if( !aTmp ){
55392  rc = SQLITE_NOMEM_BKPT;
55393  }
55394 
55395  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
55396  volatile ht_slot *aHash;
55397  u32 iZero;
55398  volatile u32 *aPgno;
55399 
55400  rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
55401  if( rc==SQLITE_OK ){
55402  int j; /* Counter variable */
55403  int nEntry; /* Number of entries in this segment */
55404  ht_slot *aIndex; /* Sorted index for this segment */
55405 
55406  aPgno++;
55407  if( (i+1)==nSegment ){
55408  nEntry = (int)(iLast - iZero);
55409  }else{
55410  nEntry = (int)((u32*)aHash - (u32*)aPgno);
55411  }
55412  aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
55413  iZero++;
55414 
55415  for(j=0; j<nEntry; j++){
55416  aIndex[j] = (ht_slot)j;
55417  }
55418  walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
55419  p->aSegment[i].iZero = iZero;
55420  p->aSegment[i].nEntry = nEntry;
55421  p->aSegment[i].aIndex = aIndex;
55422  p->aSegment[i].aPgno = (u32 *)aPgno;
55423  }
55424  }
55425  sqlite3_free(aTmp);
55426 
55427  if( rc!=SQLITE_OK ){
55428  walIteratorFree(p);
55429  }
55430  *pp = p;
55431  return rc;
55432 }
55433 
55434 /*
55435 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
55436 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
55437 ** busy-handler function. Invoke it and retry the lock until either the
55438 ** lock is successfully obtained or the busy-handler returns 0.
55439 */
55440 static int walBusyLock(
55441  Wal *pWal, /* WAL connection */
55442  int (*xBusy)(void*), /* Function to call when busy */
55443  void *pBusyArg, /* Context argument for xBusyHandler */
55444  int lockIdx, /* Offset of first byte to lock */
55445  int n /* Number of bytes to lock */
55446 ){
55447  int rc;
55448  do {
55449  rc = walLockExclusive(pWal, lockIdx, n);
55450  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
55451  return rc;
55452 }
55453 
55454 /*
55455 ** The cache of the wal-index header must be valid to call this function.
55456 ** Return the page-size in bytes used by the database.
55457 */
55458 static int walPagesize(Wal *pWal){
55459  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55460 }
55461 
55462 /*
55463 ** The following is guaranteed when this function is called:
55464 **
55465 ** a) the WRITER lock is held,
55466 ** b) the entire log file has been checkpointed, and
55467 ** c) any existing readers are reading exclusively from the database
55468 ** file - there are no readers that may attempt to read a frame from
55469 ** the log file.
55470 **
55471 ** This function updates the shared-memory structures so that the next
55472 ** client to write to the database (which may be this one) does so by
55473 ** writing frames into the start of the log file.
55474 **
55475 ** The value of parameter salt1 is used as the aSalt[1] value in the
55476 ** new wal-index header. It should be passed a pseudo-random value (i.e.
55477 ** one obtained from sqlite3_randomness()).
55478 */
55479 static void walRestartHdr(Wal *pWal, u32 salt1){
55480  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
55481  int i; /* Loop counter */
55482  u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
55483  pWal->nCkpt++;
55484  pWal->hdr.mxFrame = 0;
55485  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
55486  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
55487  walIndexWriteHdr(pWal);
55488  pInfo->nBackfill = 0;
55489  pInfo->nBackfillAttempted = 0;
55490  pInfo->aReadMark[1] = 0;
55491  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
55492  assert( pInfo->aReadMark[0]==0 );
55493 }
55494 
55495 /*
55496 ** Copy as much content as we can from the WAL back into the database file
55497 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
55498 **
55499 ** The amount of information copies from WAL to database might be limited
55500 ** by active readers. This routine will never overwrite a database page
55501 ** that a concurrent reader might be using.
55502 **
55503 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
55504 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
55505 ** checkpoints are always run by a background thread or background
55506 ** process, foreground threads will never block on a lengthy fsync call.
55507 **
55508 ** Fsync is called on the WAL before writing content out of the WAL and
55509 ** into the database. This ensures that if the new content is persistent
55510 ** in the WAL and can be recovered following a power-loss or hard reset.
55511 **
55512 ** Fsync is also called on the database file if (and only if) the entire
55513 ** WAL content is copied into the database file. This second fsync makes
55514 ** it safe to delete the WAL since the new content will persist in the
55515 ** database file.
55516 **
55517 ** This routine uses and updates the nBackfill field of the wal-index header.
55518 ** This is the only routine that will increase the value of nBackfill.
55519 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
55520 ** its value.)
55521 **
55522 ** The caller must be holding sufficient locks to ensure that no other
55523 ** checkpoint is running (in any other thread or process) at the same
55524 ** time.
55525 */
55526 static int walCheckpoint(
55527  Wal *pWal, /* Wal connection */
55528  int eMode, /* One of PASSIVE, FULL or RESTART */
55529  int (*xBusy)(void*), /* Function to call when busy */
55530  void *pBusyArg, /* Context argument for xBusyHandler */
55531  int sync_flags, /* Flags for OsSync() (or 0) */
55532  u8 *zBuf /* Temporary buffer to use */
55533 ){
55534  int rc = SQLITE_OK; /* Return code */
55535  int szPage; /* Database page-size */
55536  WalIterator *pIter = 0; /* Wal iterator context */
55537  u32 iDbpage = 0; /* Next database page to write */
55538  u32 iFrame = 0; /* Wal frame containing data for iDbpage */
55539  u32 mxSafeFrame; /* Max frame that can be backfilled */
55540  u32 mxPage; /* Max database page to write */
55541  int i; /* Loop counter */
55542  volatile WalCkptInfo *pInfo; /* The checkpoint status information */
55543 
55544  szPage = walPagesize(pWal);
55545  testcase( szPage<=32768 );
55546  testcase( szPage>=65536 );
55547  pInfo = walCkptInfo(pWal);
55548  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55549 
55550  /* Allocate the iterator */
55551  rc = walIteratorInit(pWal, &pIter);
55552  if( rc!=SQLITE_OK ){
55553  return rc;
55554  }
55555  assert( pIter );
55556 
55557  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
55558  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
55559  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
55560 
55561  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
55562  ** safe to write into the database. Frames beyond mxSafeFrame might
55563  ** overwrite database pages that are in use by active readers and thus
55564  ** cannot be backfilled from the WAL.
55565  */
55566  mxSafeFrame = pWal->hdr.mxFrame;
55567  mxPage = pWal->hdr.nPage;
55568  for(i=1; i<WAL_NREADER; i++){
55569  /* Thread-sanitizer reports that the following is an unsafe read,
55570  ** as some other thread may be in the process of updating the value
55571  ** of the aReadMark[] slot. The assumption here is that if that is
55572  ** happening, the other client may only be increasing the value,
55573  ** not decreasing it. So assuming either that either the "old" or
55574  ** "new" version of the value is read, and not some arbitrary value
55575  ** that would never be written by a real client, things are still
55576  ** safe. */
55577  u32 y = pInfo->aReadMark[i];
55578  if( mxSafeFrame>y ){
55579  assert( y<=pWal->hdr.mxFrame );
55580  rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
55581  if( rc==SQLITE_OK ){
55582  pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
55583  walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
55584  }else if( rc==SQLITE_BUSY ){
55585  mxSafeFrame = y;
55586  xBusy = 0;
55587  }else{
55588  goto walcheckpoint_out;
55589  }
55590  }
55591  }
55592 
55593  if( pInfo->nBackfill<mxSafeFrame
55594  && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
55595  ){
55596  i64 nSize; /* Current size of database file */
55597  u32 nBackfill = pInfo->nBackfill;
55598 
55599  pInfo->nBackfillAttempted = mxSafeFrame;
55600 
55601  /* Sync the WAL to disk */
55602  if( sync_flags ){
55603  rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
55604  }
55605 
55606  /* If the database may grow as a result of this checkpoint, hint
55607  ** about the eventual size of the db file to the VFS layer.
55608  */
55609  if( rc==SQLITE_OK ){
55610  i64 nReq = ((i64)mxPage * szPage);
55611  rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
55612  if( rc==SQLITE_OK && nSize<nReq ){
55613  sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
55614  }
55615  }
55616 
55617 
55618  /* Iterate through the contents of the WAL, copying data to the db file */
55619  while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
55620  i64 iOffset;
55621  assert( walFramePgno(pWal, iFrame)==iDbpage );
55622  if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
55623  continue;
55624  }
55625  iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
55626  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
55627  rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
55628  if( rc!=SQLITE_OK ) break;
55629  iOffset = (iDbpage-1)*(i64)szPage;
55630  testcase( IS_BIG_INT(iOffset) );
55631  rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
55632  if( rc!=SQLITE_OK ) break;
55633  }
55634 
55635  /* If work was actually accomplished... */
55636  if( rc==SQLITE_OK ){
55637  if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
55638  i64 szDb = pWal->hdr.nPage*(i64)szPage;
55639  testcase( IS_BIG_INT(szDb) );
55640  rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
55641  if( rc==SQLITE_OK && sync_flags ){
55642  rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
55643  }
55644  }
55645  if( rc==SQLITE_OK ){
55646  pInfo->nBackfill = mxSafeFrame;
55647  }
55648  }
55649 
55650  /* Release the reader lock held while backfilling */
55651  walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
55652  }
55653 
55654  if( rc==SQLITE_BUSY ){
55655  /* Reset the return code so as not to report a checkpoint failure
55656  ** just because there are active readers. */
55657  rc = SQLITE_OK;
55658  }
55659  }
55660 
55661  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
55662  ** entire wal file has been copied into the database file, then block
55663  ** until all readers have finished using the wal file. This ensures that
55664  ** the next process to write to the database restarts the wal file.
55665  */
55666  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
55667  assert( pWal->writeLock );
55668  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55669  rc = SQLITE_BUSY;
55670  }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
55671  u32 salt1;
55672  sqlite3_randomness(4, &salt1);
55673  assert( pInfo->nBackfill==pWal->hdr.mxFrame );
55674  rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
55675  if( rc==SQLITE_OK ){
55676  if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
55677  /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
55678  ** SQLITE_CHECKPOINT_RESTART with the addition that it also
55679  ** truncates the log file to zero bytes just prior to a
55680  ** successful return.
55681  **
55682  ** In theory, it might be safe to do this without updating the
55683  ** wal-index header in shared memory, as all subsequent reader or
55684  ** writer clients should see that the entire log file has been
55685  ** checkpointed and behave accordingly. This seems unsafe though,
55686  ** as it would leave the system in a state where the contents of
55687  ** the wal-index header do not match the contents of the
55688  ** file-system. To avoid this, update the wal-index header to
55689  ** indicate that the log file contains zero valid frames. */
55690  walRestartHdr(pWal, salt1);
55691  rc = sqlite3OsTruncate(pWal->pWalFd, 0);
55692  }
55693  walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
55694  }
55695  }
55696  }
55697 
55698  walcheckpoint_out:
55699  walIteratorFree(pIter);
55700  return rc;
55701 }
55702 
55703 /*
55704 ** If the WAL file is currently larger than nMax bytes in size, truncate
55705 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
55706 */
55707 static void walLimitSize(Wal *pWal, i64 nMax){
55708  i64 sz;
55709  int rx;
55710  sqlite3BeginBenignMalloc();
55711  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
55712  if( rx==SQLITE_OK && (sz > nMax ) ){
55713  rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
55714  }
55715  sqlite3EndBenignMalloc();
55716  if( rx ){
55717  sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
55718  }
55719 }
55720 
55721 /*
55722 ** Close a connection to a log file.
55723 */
55724 SQLITE_PRIVATE int sqlite3WalClose(
55725  Wal *pWal, /* Wal to close */
55726  int sync_flags, /* Flags to pass to OsSync() (or 0) */
55727  int nBuf,
55728  u8 *zBuf /* Buffer of at least nBuf bytes */
55729 ){
55730  int rc = SQLITE_OK;
55731  if( pWal ){
55732  int isDelete = 0; /* True to unlink wal and wal-index files */
55733 
55734  /* If an EXCLUSIVE lock can be obtained on the database file (using the
55735  ** ordinary, rollback-mode locking methods, this guarantees that the
55736  ** connection associated with this log file is the only connection to
55737  ** the database. In this case checkpoint the database and unlink both
55738  ** the wal and wal-index files.
55739  **
55740  ** The EXCLUSIVE lock is not released before returning.
55741  */
55742  rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
55743  if( rc==SQLITE_OK ){
55744  if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
55745  pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
55746  }
55747  rc = sqlite3WalCheckpoint(
55748  pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
55749  );
55750  if( rc==SQLITE_OK ){
55751  int bPersist = -1;
55752  sqlite3OsFileControlHint(
55753  pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
55754  );
55755  if( bPersist!=1 ){
55756  /* Try to delete the WAL file if the checkpoint completed and
55757  ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
55758  ** mode (!bPersist) */
55759  isDelete = 1;
55760  }else if( pWal->mxWalSize>=0 ){
55761  /* Try to truncate the WAL file to zero bytes if the checkpoint
55762  ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
55763  ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
55764  ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
55765  ** to zero bytes as truncating to the journal_size_limit might
55766  ** leave a corrupt WAL file on disk. */
55767  walLimitSize(pWal, 0);
55768  }
55769  }
55770  }
55771 
55772  walIndexClose(pWal, isDelete);
55773  sqlite3OsClose(pWal->pWalFd);
55774  if( isDelete ){
55775  sqlite3BeginBenignMalloc();
55776  sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
55777  sqlite3EndBenignMalloc();
55778  }
55779  WALTRACE(("WAL%p: closed\n", pWal));
55780  sqlite3_free((void *)pWal->apWiData);
55781  sqlite3_free(pWal);
55782  }
55783  return rc;
55784 }
55785 
55786 /*
55787 ** Try to read the wal-index header. Return 0 on success and 1 if
55788 ** there is a problem.
55789 **
55790 ** The wal-index is in shared memory. Another thread or process might
55791 ** be writing the header at the same time this procedure is trying to
55792 ** read it, which might result in inconsistency. A dirty read is detected
55793 ** by verifying that both copies of the header are the same and also by
55794 ** a checksum on the header.
55795 **
55796 ** If and only if the read is consistent and the header is different from
55797 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
55798 ** and *pChanged is set to 1.
55799 **
55800 ** If the checksum cannot be verified return non-zero. If the header
55801 ** is read successfully and the checksum verified, return zero.
55802 */
55803 static int walIndexTryHdr(Wal *pWal, int *pChanged){
55804  u32 aCksum[2]; /* Checksum on the header content */
55805  WalIndexHdr h1, h2; /* Two copies of the header content */
55806  WalIndexHdr volatile *aHdr; /* Header in shared memory */
55807 
55808  /* The first page of the wal-index must be mapped at this point. */
55809  assert( pWal->nWiData>0 && pWal->apWiData[0] );
55810 
55811  /* Read the header. This might happen concurrently with a write to the
55812  ** same area of shared memory on a different CPU in a SMP,
55813  ** meaning it is possible that an inconsistent snapshot is read
55814  ** from the file. If this happens, return non-zero.
55815  **
55816  ** There are two copies of the header at the beginning of the wal-index.
55817  ** When reading, read [0] first then [1]. Writes are in the reverse order.
55818  ** Memory barriers are used to prevent the compiler or the hardware from
55819  ** reordering the reads and writes.
55820  */
55821  aHdr = walIndexHdr(pWal);
55822  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
55823  walShmBarrier(pWal);
55824  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
55825 
55826  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
55827  return 1; /* Dirty read */
55828  }
55829  if( h1.isInit==0 ){
55830  return 1; /* Malformed header - probably all zeros */
55831  }
55832  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
55833  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
55834  return 1; /* Checksum does not match */
55835  }
55836 
55837  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
55838  *pChanged = 1;
55839  memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
55840  pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55841  testcase( pWal->szPage<=32768 );
55842  testcase( pWal->szPage>=65536 );
55843  }
55844 
55845  /* The header was successfully read. Return zero. */
55846  return 0;
55847 }
55848 
55849 /*
55850 ** Read the wal-index header from the wal-index and into pWal->hdr.
55851 ** If the wal-header appears to be corrupt, try to reconstruct the
55852 ** wal-index from the WAL before returning.
55853 **
55854 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
55855 ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
55856 ** to 0.
55857 **
55858 ** If the wal-index header is successfully read, return SQLITE_OK.
55859 ** Otherwise an SQLite error code.
55860 */
55861 static int walIndexReadHdr(Wal *pWal, int *pChanged){
55862  int rc; /* Return code */
55863  int badHdr; /* True if a header read failed */
55864  volatile u32 *page0; /* Chunk of wal-index containing header */
55865 
55866  /* Ensure that page 0 of the wal-index (the page that contains the
55867  ** wal-index header) is mapped. Return early if an error occurs here.
55868  */
55869  assert( pChanged );
55870  rc = walIndexPage(pWal, 0, &page0);
55871  if( rc!=SQLITE_OK ){
55872  return rc;
55873  };
55874  assert( page0 || pWal->writeLock==0 );
55875 
55876  /* If the first page of the wal-index has been mapped, try to read the
55877  ** wal-index header immediately, without holding any lock. This usually
55878  ** works, but may fail if the wal-index header is corrupt or currently
55879  ** being modified by another thread or process.
55880  */
55881  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
55882 
55883  /* If the first attempt failed, it might have been due to a race
55884  ** with a writer. So get a WRITE lock and try again.
55885  */
55886  assert( badHdr==0 || pWal->writeLock==0 );
55887  if( badHdr ){
55888  if( pWal->readOnly & WAL_SHM_RDONLY ){
55889  if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
55890  walUnlockShared(pWal, WAL_WRITE_LOCK);
55891  rc = SQLITE_READONLY_RECOVERY;
55892  }
55893  }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
55894  pWal->writeLock = 1;
55895  if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
55896  badHdr = walIndexTryHdr(pWal, pChanged);
55897  if( badHdr ){
55898  /* If the wal-index header is still malformed even while holding
55899  ** a WRITE lock, it can only mean that the header is corrupted and
55900  ** needs to be reconstructed. So run recovery to do exactly that.
55901  */
55902  rc = walIndexRecover(pWal);
55903  *pChanged = 1;
55904  }
55905  }
55906  pWal->writeLock = 0;
55907  walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
55908  }
55909  }
55910 
55911  /* If the header is read successfully, check the version number to make
55912  ** sure the wal-index was not constructed with some future format that
55913  ** this version of SQLite cannot understand.
55914  */
55915  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
55916  rc = SQLITE_CANTOPEN_BKPT;
55917  }
55918 
55919  return rc;
55920 }
55921 
55922 /*
55923 ** This is the value that walTryBeginRead returns when it needs to
55924 ** be retried.
55925 */
55926 #define WAL_RETRY (-1)
55927 
55928 /*
55929 ** Attempt to start a read transaction. This might fail due to a race or
55930 ** other transient condition. When that happens, it returns WAL_RETRY to
55931 ** indicate to the caller that it is safe to retry immediately.
55932 **
55933 ** On success return SQLITE_OK. On a permanent failure (such an
55934 ** I/O error or an SQLITE_BUSY because another process is running
55935 ** recovery) return a positive error code.
55936 **
55937 ** The useWal parameter is true to force the use of the WAL and disable
55938 ** the case where the WAL is bypassed because it has been completely
55939 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
55940 ** to make a copy of the wal-index header into pWal->hdr. If the
55941 ** wal-index header has changed, *pChanged is set to 1 (as an indication
55942 ** to the caller that the local paget cache is obsolete and needs to be
55943 ** flushed.) When useWal==1, the wal-index header is assumed to already
55944 ** be loaded and the pChanged parameter is unused.
55945 **
55946 ** The caller must set the cnt parameter to the number of prior calls to
55947 ** this routine during the current read attempt that returned WAL_RETRY.
55948 ** This routine will start taking more aggressive measures to clear the
55949 ** race conditions after multiple WAL_RETRY returns, and after an excessive
55950 ** number of errors will ultimately return SQLITE_PROTOCOL. The
55951 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
55952 ** and is not honoring the locking protocol. There is a vanishingly small
55953 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
55954 ** bad luck when there is lots of contention for the wal-index, but that
55955 ** possibility is so small that it can be safely neglected, we believe.
55956 **
55957 ** On success, this routine obtains a read lock on
55958 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
55959 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
55960 ** that means the Wal does not hold any read lock. The reader must not
55961 ** access any database page that is modified by a WAL frame up to and
55962 ** including frame number aReadMark[pWal->readLock]. The reader will
55963 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
55964 ** Or if pWal->readLock==0, then the reader will ignore the WAL
55965 ** completely and get all content directly from the database file.
55966 ** If the useWal parameter is 1 then the WAL will never be ignored and
55967 ** this routine will always set pWal->readLock>0 on success.
55968 ** When the read transaction is completed, the caller must release the
55969 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
55970 **
55971 ** This routine uses the nBackfill and aReadMark[] fields of the header
55972 ** to select a particular WAL_READ_LOCK() that strives to let the
55973 ** checkpoint process do as much work as possible. This routine might
55974 ** update values of the aReadMark[] array in the header, but if it does
55975 ** so it takes care to hold an exclusive lock on the corresponding
55976 ** WAL_READ_LOCK() while changing values.
55977 */
55978 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
55979  volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
55980  u32 mxReadMark; /* Largest aReadMark[] value */
55981  int mxI; /* Index of largest aReadMark[] value */
55982  int i; /* Loop counter */
55983  int rc = SQLITE_OK; /* Return code */
55984  u32 mxFrame; /* Wal frame to lock to */
55985 
55986  assert( pWal->readLock<0 ); /* Not currently locked */
55987 
55988  /* Take steps to avoid spinning forever if there is a protocol error.
55989  **
55990  ** Circumstances that cause a RETRY should only last for the briefest
55991  ** instances of time. No I/O or other system calls are done while the
55992  ** locks are held, so the locks should not be held for very long. But
55993  ** if we are unlucky, another process that is holding a lock might get
55994  ** paged out or take a page-fault that is time-consuming to resolve,
55995  ** during the few nanoseconds that it is holding the lock. In that case,
55996  ** it might take longer than normal for the lock to free.
55997  **
55998  ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
55999  ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
56000  ** is more of a scheduler yield than an actual delay. But on the 10th
56001  ** an subsequent retries, the delays start becoming longer and longer,
56002  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
56003  ** The total delay time before giving up is less than 10 seconds.
56004  */
56005  if( cnt>5 ){
56006  int nDelay = 1; /* Pause time in microseconds */
56007  if( cnt>100 ){
56008  VVA_ONLY( pWal->lockError = 1; )
56009  return SQLITE_PROTOCOL;
56010  }
56011  if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
56012  sqlite3OsSleep(pWal->pVfs, nDelay);
56013  }
56014 
56015  if( !useWal ){
56016  rc = walIndexReadHdr(pWal, pChanged);
56017  if( rc==SQLITE_BUSY ){
56018  /* If there is not a recovery running in another thread or process
56019  ** then convert BUSY errors to WAL_RETRY. If recovery is known to
56020  ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
56021  ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
56022  ** would be technically correct. But the race is benign since with
56023  ** WAL_RETRY this routine will be called again and will probably be
56024  ** right on the second iteration.
56025  */
56026  if( pWal->apWiData[0]==0 ){
56027  /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
56028  ** We assume this is a transient condition, so return WAL_RETRY. The
56029  ** xShmMap() implementation used by the default unix and win32 VFS
56030  ** modules may return SQLITE_BUSY due to a race condition in the
56031  ** code that determines whether or not the shared-memory region
56032  ** must be zeroed before the requested page is returned.
56033  */
56034  rc = WAL_RETRY;
56035  }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
56036  walUnlockShared(pWal, WAL_RECOVER_LOCK);
56037  rc = WAL_RETRY;
56038  }else if( rc==SQLITE_BUSY ){
56039  rc = SQLITE_BUSY_RECOVERY;
56040  }
56041  }
56042  if( rc!=SQLITE_OK ){
56043  return rc;
56044  }
56045  }
56046 
56047  pInfo = walCkptInfo(pWal);
56048  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
56049 #ifdef SQLITE_ENABLE_SNAPSHOT
56050  && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
56051  || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
56052 #endif
56053  ){
56054  /* The WAL has been completely backfilled (or it is empty).
56055  ** and can be safely ignored.
56056  */
56057  rc = walLockShared(pWal, WAL_READ_LOCK(0));
56058  walShmBarrier(pWal);
56059  if( rc==SQLITE_OK ){
56060  if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
56061  /* It is not safe to allow the reader to continue here if frames
56062  ** may have been appended to the log before READ_LOCK(0) was obtained.
56063  ** When holding READ_LOCK(0), the reader ignores the entire log file,
56064  ** which implies that the database file contains a trustworthy
56065  ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
56066  ** happening, this is usually correct.
56067  **
56068  ** However, if frames have been appended to the log (or if the log
56069  ** is wrapped and written for that matter) before the READ_LOCK(0)
56070  ** is obtained, that is not necessarily true. A checkpointer may
56071  ** have started to backfill the appended frames but crashed before
56072  ** it finished. Leaving a corrupt image in the database file.
56073  */
56074  walUnlockShared(pWal, WAL_READ_LOCK(0));
56075  return WAL_RETRY;
56076  }
56077  pWal->readLock = 0;
56078  return SQLITE_OK;
56079  }else if( rc!=SQLITE_BUSY ){
56080  return rc;
56081  }
56082  }
56083 
56084  /* If we get this far, it means that the reader will want to use
56085  ** the WAL to get at content from recent commits. The job now is
56086  ** to select one of the aReadMark[] entries that is closest to
56087  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
56088  */
56089  mxReadMark = 0;
56090  mxI = 0;
56091  mxFrame = pWal->hdr.mxFrame;
56092 #ifdef SQLITE_ENABLE_SNAPSHOT
56093  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
56094  mxFrame = pWal->pSnapshot->mxFrame;
56095  }
56096 #endif
56097  for(i=1; i<WAL_NREADER; i++){
56098  u32 thisMark = pInfo->aReadMark[i];
56099  if( mxReadMark<=thisMark && thisMark<=mxFrame ){
56100  assert( thisMark!=READMARK_NOT_USED );
56101  mxReadMark = thisMark;
56102  mxI = i;
56103  }
56104  }
56105  if( (pWal->readOnly & WAL_SHM_RDONLY)==0
56106  && (mxReadMark<mxFrame || mxI==0)
56107  ){
56108  for(i=1; i<WAL_NREADER; i++){
56109  rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
56110  if( rc==SQLITE_OK ){
56111  mxReadMark = pInfo->aReadMark[i] = mxFrame;
56112  mxI = i;
56113  walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
56114  break;
56115  }else if( rc!=SQLITE_BUSY ){
56116  return rc;
56117  }
56118  }
56119  }
56120  if( mxI==0 ){
56121  assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
56122  return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
56123  }
56124 
56125  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
56126  if( rc ){
56127  return rc==SQLITE_BUSY ? WAL_RETRY : rc;
56128  }
56129  /* Now that the read-lock has been obtained, check that neither the
56130  ** value in the aReadMark[] array or the contents of the wal-index
56131  ** header have changed.
56132  **
56133  ** It is necessary to check that the wal-index header did not change
56134  ** between the time it was read and when the shared-lock was obtained
56135  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
56136  ** that the log file may have been wrapped by a writer, or that frames
56137  ** that occur later in the log than pWal->hdr.mxFrame may have been
56138  ** copied into the database by a checkpointer. If either of these things
56139  ** happened, then reading the database with the current value of
56140  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
56141  ** instead.
56142  **
56143  ** Before checking that the live wal-index header has not changed
56144  ** since it was read, set Wal.minFrame to the first frame in the wal
56145  ** file that has not yet been checkpointed. This client will not need
56146  ** to read any frames earlier than minFrame from the wal file - they
56147  ** can be safely read directly from the database file.
56148  **
56149  ** Because a ShmBarrier() call is made between taking the copy of
56150  ** nBackfill and checking that the wal-header in shared-memory still
56151  ** matches the one cached in pWal->hdr, it is guaranteed that the
56152  ** checkpointer that set nBackfill was not working with a wal-index
56153  ** header newer than that cached in pWal->hdr. If it were, that could
56154  ** cause a problem. The checkpointer could omit to checkpoint
56155  ** a version of page X that lies before pWal->minFrame (call that version
56156  ** A) on the basis that there is a newer version (version B) of the same
56157  ** page later in the wal file. But if version B happens to like past
56158  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
56159  ** that it can read version A from the database file. However, since
56160  ** we can guarantee that the checkpointer that set nBackfill could not
56161  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
56162  */
56163  pWal->minFrame = pInfo->nBackfill+1;
56164  walShmBarrier(pWal);
56165  if( pInfo->aReadMark[mxI]!=mxReadMark
56166  || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
56167  ){
56168  walUnlockShared(pWal, WAL_READ_LOCK(mxI));
56169  return WAL_RETRY;
56170  }else{
56171  assert( mxReadMark<=pWal->hdr.mxFrame );
56172  pWal->readLock = (i16)mxI;
56173  }
56174  return rc;
56175 }
56176 
56177 /*
56178 ** Begin a read transaction on the database.
56179 **
56180 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
56181 ** it takes a snapshot of the state of the WAL and wal-index for the current
56182 ** instant in time. The current thread will continue to use this snapshot.
56183 ** Other threads might append new content to the WAL and wal-index but
56184 ** that extra content is ignored by the current thread.
56185 **
56186 ** If the database contents have changes since the previous read
56187 ** transaction, then *pChanged is set to 1 before returning. The
56188 ** Pager layer will use this to know that is cache is stale and
56189 ** needs to be flushed.
56190 */
56191 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
56192  int rc; /* Return code */
56193  int cnt = 0; /* Number of TryBeginRead attempts */
56194 
56195 #ifdef SQLITE_ENABLE_SNAPSHOT
56196  int bChanged = 0;
56197  WalIndexHdr *pSnapshot = pWal->pSnapshot;
56198  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56199  bChanged = 1;
56200  }
56201 #endif
56202 
56203  do{
56204  rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
56205  }while( rc==WAL_RETRY );
56206  testcase( (rc&0xff)==SQLITE_BUSY );
56207  testcase( (rc&0xff)==SQLITE_IOERR );
56208  testcase( rc==SQLITE_PROTOCOL );
56209  testcase( rc==SQLITE_OK );
56210 
56211 #ifdef SQLITE_ENABLE_SNAPSHOT
56212  if( rc==SQLITE_OK ){
56213  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56214  /* At this point the client has a lock on an aReadMark[] slot holding
56215  ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
56216  ** is populated with the wal-index header corresponding to the head
56217  ** of the wal file. Verify that pSnapshot is still valid before
56218  ** continuing. Reasons why pSnapshot might no longer be valid:
56219  **
56220  ** (1) The WAL file has been reset since the snapshot was taken.
56221  ** In this case, the salt will have changed.
56222  **
56223  ** (2) A checkpoint as been attempted that wrote frames past
56224  ** pSnapshot->mxFrame into the database file. Note that the
56225  ** checkpoint need not have completed for this to cause problems.
56226  */
56227  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56228 
56229  assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
56230  assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
56231 
56232  /* It is possible that there is a checkpointer thread running
56233  ** concurrent with this code. If this is the case, it may be that the
56234  ** checkpointer has already determined that it will checkpoint
56235  ** snapshot X, where X is later in the wal file than pSnapshot, but
56236  ** has not yet set the pInfo->nBackfillAttempted variable to indicate
56237  ** its intent. To avoid the race condition this leads to, ensure that
56238  ** there is no checkpointer process by taking a shared CKPT lock
56239  ** before checking pInfo->nBackfillAttempted. */
56240  rc = walLockShared(pWal, WAL_CKPT_LOCK);
56241 
56242  if( rc==SQLITE_OK ){
56243  /* Check that the wal file has not been wrapped. Assuming that it has
56244  ** not, also check that no checkpointer has attempted to checkpoint any
56245  ** frames beyond pSnapshot->mxFrame. If either of these conditions are
56246  ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
56247  ** with *pSnapshot and set *pChanged as appropriate for opening the
56248  ** snapshot. */
56249  if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
56250  && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
56251  ){
56252  assert( pWal->readLock>0 );
56253  memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
56254  *pChanged = bChanged;
56255  }else{
56256  rc = SQLITE_BUSY_SNAPSHOT;
56257  }
56258 
56259  /* Release the shared CKPT lock obtained above. */
56260  walUnlockShared(pWal, WAL_CKPT_LOCK);
56261  }
56262 
56263 
56264  if( rc!=SQLITE_OK ){
56265  sqlite3WalEndReadTransaction(pWal);
56266  }
56267  }
56268  }
56269 #endif
56270  return rc;
56271 }
56272 
56273 /*
56274 ** Finish with a read transaction. All this does is release the
56275 ** read-lock.
56276 */
56277 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
56278  sqlite3WalEndWriteTransaction(pWal);
56279  if( pWal->readLock>=0 ){
56280  walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
56281  pWal->readLock = -1;
56282  }
56283 }
56284 
56285 /*
56286 ** Search the wal file for page pgno. If found, set *piRead to the frame that
56287 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
56288 ** to zero.
56289 **
56290 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
56291 ** error does occur, the final value of *piRead is undefined.
56292 */
56293 SQLITE_PRIVATE int sqlite3WalFindFrame(
56294  Wal *pWal, /* WAL handle */
56295  Pgno pgno, /* Database page number to read data for */
56296  u32 *piRead /* OUT: Frame number (or zero) */
56297 ){
56298  u32 iRead = 0; /* If !=0, WAL frame to return data from */
56299  u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
56300  int iHash; /* Used to loop through N hash tables */
56301  int iMinHash;
56302 
56303  /* This routine is only be called from within a read transaction. */
56304  assert( pWal->readLock>=0 || pWal->lockError );
56305 
56306  /* If the "last page" field of the wal-index header snapshot is 0, then
56307  ** no data will be read from the wal under any circumstances. Return early
56308  ** in this case as an optimization. Likewise, if pWal->readLock==0,
56309  ** then the WAL is ignored by the reader so return early, as if the
56310  ** WAL were empty.
56311  */
56312  if( iLast==0 || pWal->readLock==0 ){
56313  *piRead = 0;
56314  return SQLITE_OK;
56315  }
56316 
56317  /* Search the hash table or tables for an entry matching page number
56318  ** pgno. Each iteration of the following for() loop searches one
56319  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
56320  **
56321  ** This code might run concurrently to the code in walIndexAppend()
56322  ** that adds entries to the wal-index (and possibly to this hash
56323  ** table). This means the value just read from the hash
56324  ** slot (aHash[iKey]) may have been added before or after the
56325  ** current read transaction was opened. Values added after the
56326  ** read transaction was opened may have been written incorrectly -
56327  ** i.e. these slots may contain garbage data. However, we assume
56328  ** that any slots written before the current read transaction was
56329  ** opened remain unmodified.
56330  **
56331  ** For the reasons above, the if(...) condition featured in the inner
56332  ** loop of the following block is more stringent that would be required
56333  ** if we had exclusive access to the hash-table:
56334  **
56335  ** (aPgno[iFrame]==pgno):
56336  ** This condition filters out normal hash-table collisions.
56337  **
56338  ** (iFrame<=iLast):
56339  ** This condition filters out entries that were added to the hash
56340  ** table after the current read-transaction had started.
56341  */
56342  iMinHash = walFramePage(pWal->minFrame);
56343  for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
56344  volatile ht_slot *aHash; /* Pointer to hash table */
56345  volatile u32 *aPgno; /* Pointer to array of page numbers */
56346  u32 iZero; /* Frame number corresponding to aPgno[0] */
56347  int iKey; /* Hash slot index */
56348  int nCollide; /* Number of hash collisions remaining */
56349  int rc; /* Error code */
56350 
56351  rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
56352  if( rc!=SQLITE_OK ){
56353  return rc;
56354  }
56355  nCollide = HASHTABLE_NSLOT;
56356  for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
56357  u32 iFrame = aHash[iKey] + iZero;
56358  if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
56359  assert( iFrame>iRead || CORRUPT_DB );
56360  iRead = iFrame;
56361  }
56362  if( (nCollide--)==0 ){
56363  return SQLITE_CORRUPT_BKPT;
56364  }
56365  }
56366  }
56367 
56368 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
56369  /* If expensive assert() statements are available, do a linear search
56370  ** of the wal-index file content. Make sure the results agree with the
56371  ** result obtained using the hash indexes above. */
56372  {
56373  u32 iRead2 = 0;
56374  u32 iTest;
56375  assert( pWal->minFrame>0 );
56376  for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
56377  if( walFramePgno(pWal, iTest)==pgno ){
56378  iRead2 = iTest;
56379  break;
56380  }
56381  }
56382  assert( iRead==iRead2 );
56383  }
56384 #endif
56385 
56386  *piRead = iRead;
56387  return SQLITE_OK;
56388 }
56389 
56390 /*
56391 ** Read the contents of frame iRead from the wal file into buffer pOut
56392 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
56393 ** error code otherwise.
56394 */
56395 SQLITE_PRIVATE int sqlite3WalReadFrame(
56396  Wal *pWal, /* WAL handle */
56397  u32 iRead, /* Frame to read */
56398  int nOut, /* Size of buffer pOut in bytes */
56399  u8 *pOut /* Buffer to write page data to */
56400 ){
56401  int sz;
56402  i64 iOffset;
56403  sz = pWal->hdr.szPage;
56404  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
56405  testcase( sz<=32768 );
56406  testcase( sz>=65536 );
56407  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
56408  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
56409  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
56410 }
56411 
56412 /*
56413 ** Return the size of the database in pages (or zero, if unknown).
56414 */
56415 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
56416  if( pWal && ALWAYS(pWal->readLock>=0) ){
56417  return pWal->hdr.nPage;
56418  }
56419  return 0;
56420 }
56421 
56422 
56423 /*
56424 ** This function starts a write transaction on the WAL.
56425 **
56426 ** A read transaction must have already been started by a prior call
56427 ** to sqlite3WalBeginReadTransaction().
56428 **
56429 ** If another thread or process has written into the database since
56430 ** the read transaction was started, then it is not possible for this
56431 ** thread to write as doing so would cause a fork. So this routine
56432 ** returns SQLITE_BUSY in that case and no write transaction is started.
56433 **
56434 ** There can only be a single writer active at a time.
56435 */
56436 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
56437  int rc;
56438 
56439  /* Cannot start a write transaction without first holding a read
56440  ** transaction. */
56441  assert( pWal->readLock>=0 );
56442  assert( pWal->writeLock==0 && pWal->iReCksum==0 );
56443 
56444  if( pWal->readOnly ){
56445  return SQLITE_READONLY;
56446  }
56447 
56448  /* Only one writer allowed at a time. Get the write lock. Return
56449  ** SQLITE_BUSY if unable.
56450  */
56451  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
56452  if( rc ){
56453  return rc;
56454  }
56455  pWal->writeLock = 1;
56456 
56457  /* If another connection has written to the database file since the
56458  ** time the read transaction on this connection was started, then
56459  ** the write is disallowed.
56460  */
56461  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
56462  walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
56463  pWal->writeLock = 0;
56464  rc = SQLITE_BUSY_SNAPSHOT;
56465  }
56466 
56467  return rc;
56468 }
56469 
56470 /*
56471 ** End a write transaction. The commit has already been done. This
56472 ** routine merely releases the lock.
56473 */
56474 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
56475  if( pWal->writeLock ){
56476  walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
56477  pWal->writeLock = 0;
56478  pWal->iReCksum = 0;
56479  pWal->truncateOnCommit = 0;
56480  }
56481  return SQLITE_OK;
56482 }
56483 
56484 /*
56485 ** If any data has been written (but not committed) to the log file, this
56486 ** function moves the write-pointer back to the start of the transaction.
56487 **
56488 ** Additionally, the callback function is invoked for each frame written
56489 ** to the WAL since the start of the transaction. If the callback returns
56490 ** other than SQLITE_OK, it is not invoked again and the error code is
56491 ** returned to the caller.
56492 **
56493 ** Otherwise, if the callback function does not return an error, this
56494 ** function returns SQLITE_OK.
56495 */
56496 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
56497  int rc = SQLITE_OK;
56498  if( ALWAYS(pWal->writeLock) ){
56499  Pgno iMax = pWal->hdr.mxFrame;
56500  Pgno iFrame;
56501 
56502  /* Restore the clients cache of the wal-index header to the state it
56503  ** was in before the client began writing to the database.
56504  */
56505  memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
56506 
56507  for(iFrame=pWal->hdr.mxFrame+1;
56508  ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
56509  iFrame++
56510  ){
56511  /* This call cannot fail. Unless the page for which the page number
56512  ** is passed as the second argument is (a) in the cache and
56513  ** (b) has an outstanding reference, then xUndo is either a no-op
56514  ** (if (a) is false) or simply expels the page from the cache (if (b)
56515  ** is false).
56516  **
56517  ** If the upper layer is doing a rollback, it is guaranteed that there
56518  ** are no outstanding references to any page other than page 1. And
56519  ** page 1 is never written to the log until the transaction is
56520  ** committed. As a result, the call to xUndo may not fail.
56521  */
56522  assert( walFramePgno(pWal, iFrame)!=1 );
56523  rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
56524  }
56525  if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
56526  }
56527  return rc;
56528 }
56529 
56530 /*
56531 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
56532 ** values. This function populates the array with values required to
56533 ** "rollback" the write position of the WAL handle back to the current
56534 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
56535 */
56536 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
56537  assert( pWal->writeLock );
56538  aWalData[0] = pWal->hdr.mxFrame;
56539  aWalData[1] = pWal->hdr.aFrameCksum[0];
56540  aWalData[2] = pWal->hdr.aFrameCksum[1];
56541  aWalData[3] = pWal->nCkpt;
56542 }
56543 
56544 /*
56545 ** Move the write position of the WAL back to the point identified by
56546 ** the values in the aWalData[] array. aWalData must point to an array
56547 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
56548 ** by a call to WalSavepoint().
56549 */
56550 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
56551  int rc = SQLITE_OK;
56552 
56553  assert( pWal->writeLock );
56554  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
56555 
56556  if( aWalData[3]!=pWal->nCkpt ){
56557  /* This savepoint was opened immediately after the write-transaction
56558  ** was started. Right after that, the writer decided to wrap around
56559  ** to the start of the log. Update the savepoint values to match.
56560  */
56561  aWalData[0] = 0;
56562  aWalData[3] = pWal->nCkpt;
56563  }
56564 
56565  if( aWalData[0]<pWal->hdr.mxFrame ){
56566  pWal->hdr.mxFrame = aWalData[0];
56567  pWal->hdr.aFrameCksum[0] = aWalData[1];
56568  pWal->hdr.aFrameCksum[1] = aWalData[2];
56569  walCleanupHash(pWal);
56570  }
56571 
56572  return rc;
56573 }
56574 
56575 /*
56576 ** This function is called just before writing a set of frames to the log
56577 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
56578 ** to the current log file, it is possible to overwrite the start of the
56579 ** existing log file with the new frames (i.e. "reset" the log). If so,
56580 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
56581 ** unchanged.
56582 **
56583 ** SQLITE_OK is returned if no error is encountered (regardless of whether
56584 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
56585 ** if an error occurs.
56586 */
56587 static int walRestartLog(Wal *pWal){
56588  int rc = SQLITE_OK;
56589  int cnt;
56590 
56591  if( pWal->readLock==0 ){
56592  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56593  assert( pInfo->nBackfill==pWal->hdr.mxFrame );
56594  if( pInfo->nBackfill>0 ){
56595  u32 salt1;
56596  sqlite3_randomness(4, &salt1);
56597  rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56598  if( rc==SQLITE_OK ){
56599  /* If all readers are using WAL_READ_LOCK(0) (in other words if no
56600  ** readers are currently using the WAL), then the transactions
56601  ** frames will overwrite the start of the existing log. Update the
56602  ** wal-index header to reflect this.
56603  **
56604  ** In theory it would be Ok to update the cache of the header only
56605  ** at this point. But updating the actual wal-index header is also
56606  ** safe and means there is no special case for sqlite3WalUndo()
56607  ** to handle if this transaction is rolled back. */
56608  walRestartHdr(pWal, salt1);
56609  walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56610  }else if( rc!=SQLITE_BUSY ){
56611  return rc;
56612  }
56613  }
56614  walUnlockShared(pWal, WAL_READ_LOCK(0));
56615  pWal->readLock = -1;
56616  cnt = 0;
56617  do{
56618  int notUsed;
56619  rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
56620  }while( rc==WAL_RETRY );
56621  assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
56622  testcase( (rc&0xff)==SQLITE_IOERR );
56623  testcase( rc==SQLITE_PROTOCOL );
56624  testcase( rc==SQLITE_OK );
56625  }
56626  return rc;
56627 }
56628 
56629 /*
56630 ** Information about the current state of the WAL file and where
56631 ** the next fsync should occur - passed from sqlite3WalFrames() into
56632 ** walWriteToLog().
56633 */
56634 typedef struct WalWriter {
56635  Wal *pWal; /* The complete WAL information */
56636  sqlite3_file *pFd; /* The WAL file to which we write */
56637  sqlite3_int64 iSyncPoint; /* Fsync at this offset */
56638  int syncFlags; /* Flags for the fsync */
56639  int szPage; /* Size of one page */
56640 } WalWriter;
56641 
56642 /*
56643 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
56644 ** Do a sync when crossing the p->iSyncPoint boundary.
56645 **
56646 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
56647 ** first write the part before iSyncPoint, then sync, then write the
56648 ** rest.
56649 */
56650 static int walWriteToLog(
56651  WalWriter *p, /* WAL to write to */
56652  void *pContent, /* Content to be written */
56653  int iAmt, /* Number of bytes to write */
56654  sqlite3_int64 iOffset /* Start writing at this offset */
56655 ){
56656  int rc;
56657  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
56658  int iFirstAmt = (int)(p->iSyncPoint - iOffset);
56659  rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
56660  if( rc ) return rc;
56661  iOffset += iFirstAmt;
56662  iAmt -= iFirstAmt;
56663  pContent = (void*)(iFirstAmt + (char*)pContent);
56664  assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
56665  rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
56666  if( iAmt==0 || rc ) return rc;
56667  }
56668  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
56669  return rc;
56670 }
56671 
56672 /*
56673 ** Write out a single frame of the WAL
56674 */
56675 static int walWriteOneFrame(
56676  WalWriter *p, /* Where to write the frame */
56677  PgHdr *pPage, /* The page of the frame to be written */
56678  int nTruncate, /* The commit flag. Usually 0. >0 for commit */
56679  sqlite3_int64 iOffset /* Byte offset at which to write */
56680 ){
56681  int rc; /* Result code from subfunctions */
56682  void *pData; /* Data actually written */
56683  u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
56684 #if defined(SQLITE_HAS_CODEC)
56685  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
56686 #else
56687  pData = pPage->pData;
56688 #endif
56689  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
56690  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
56691  if( rc ) return rc;
56692  /* Write the page data */
56693  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
56694  return rc;
56695 }
56696 
56697 /*
56698 ** This function is called as part of committing a transaction within which
56699 ** one or more frames have been overwritten. It updates the checksums for
56700 ** all frames written to the wal file by the current transaction starting
56701 ** with the earliest to have been overwritten.
56702 **
56703 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
56704 */
56705 static int walRewriteChecksums(Wal *pWal, u32 iLast){
56706  const int szPage = pWal->szPage;/* Database page size */
56707  int rc = SQLITE_OK; /* Return code */
56708  u8 *aBuf; /* Buffer to load data from wal file into */
56709  u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
56710  u32 iRead; /* Next frame to read from wal file */
56711  i64 iCksumOff;
56712 
56713  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
56714  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
56715 
56716  /* Find the checksum values to use as input for the recalculating the
56717  ** first checksum. If the first frame is frame 1 (implying that the current
56718  ** transaction restarted the wal file), these values must be read from the
56719  ** wal-file header. Otherwise, read them from the frame header of the
56720  ** previous frame. */
56721  assert( pWal->iReCksum>0 );
56722  if( pWal->iReCksum==1 ){
56723  iCksumOff = 24;
56724  }else{
56725  iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
56726  }
56727  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
56728  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
56729  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
56730 
56731  iRead = pWal->iReCksum;
56732  pWal->iReCksum = 0;
56733  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
56734  i64 iOff = walFrameOffset(iRead, szPage);
56735  rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
56736  if( rc==SQLITE_OK ){
56737  u32 iPgno, nDbSize;
56738  iPgno = sqlite3Get4byte(aBuf);
56739  nDbSize = sqlite3Get4byte(&aBuf[4]);
56740 
56741  walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
56742  rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
56743  }
56744  }
56745 
56746  sqlite3_free(aBuf);
56747  return rc;
56748 }
56749 
56750 /*
56751 ** Write a set of frames to the log. The caller must hold the write-lock
56752 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
56753 */
56754 SQLITE_PRIVATE int sqlite3WalFrames(
56755  Wal *pWal, /* Wal handle to write to */
56756  int szPage, /* Database page-size in bytes */
56757  PgHdr *pList, /* List of dirty pages to write */
56758  Pgno nTruncate, /* Database size after this commit */
56759  int isCommit, /* True if this is a commit */
56760  int sync_flags /* Flags to pass to OsSync() (or 0) */
56761 ){
56762  int rc; /* Used to catch return codes */
56763  u32 iFrame; /* Next frame address */
56764  PgHdr *p; /* Iterator to run through pList with. */
56765  PgHdr *pLast = 0; /* Last frame in list */
56766  int nExtra = 0; /* Number of extra copies of last page */
56767  int szFrame; /* The size of a single frame */
56768  i64 iOffset; /* Next byte to write in WAL file */
56769  WalWriter w; /* The writer */
56770  u32 iFirst = 0; /* First frame that may be overwritten */
56771  WalIndexHdr *pLive; /* Pointer to shared header */
56772 
56773  assert( pList );
56774  assert( pWal->writeLock );
56775 
56776  /* If this frame set completes a transaction, then nTruncate>0. If
56777  ** nTruncate==0 then this frame set does not complete the transaction. */
56778  assert( (isCommit!=0)==(nTruncate!=0) );
56779 
56780 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
56781  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
56782  WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
56783  pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
56784  }
56785 #endif
56786 
56787  pLive = (WalIndexHdr*)walIndexHdr(pWal);
56788  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
56789  iFirst = pLive->mxFrame+1;
56790  }
56791 
56792  /* See if it is possible to write these frames into the start of the
56793  ** log file, instead of appending to it at pWal->hdr.mxFrame.
56794  */
56795  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
56796  return rc;
56797  }
56798 
56799  /* If this is the first frame written into the log, write the WAL
56800  ** header to the start of the WAL file. See comments at the top of
56801  ** this source file for a description of the WAL header format.
56802  */
56803  iFrame = pWal->hdr.mxFrame;
56804  if( iFrame==0 ){
56805  u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
56806  u32 aCksum[2]; /* Checksum for wal-header */
56807 
56808  sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
56809  sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
56810  sqlite3Put4byte(&aWalHdr[8], szPage);
56811  sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
56812  if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
56813  memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
56814  walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
56815  sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
56816  sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
56817 
56818  pWal->szPage = szPage;
56819  pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
56820  pWal->hdr.aFrameCksum[0] = aCksum[0];
56821  pWal->hdr.aFrameCksum[1] = aCksum[1];
56822  pWal->truncateOnCommit = 1;
56823 
56824  rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
56825  WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
56826  if( rc!=SQLITE_OK ){
56827  return rc;
56828  }
56829 
56830  /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
56831  ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
56832  ** an out-of-order write following a WAL restart could result in
56833  ** database corruption. See the ticket:
56834  **
56835  ** http://localhost:591/sqlite/info/ff5be73dee
56836  */
56837  if( pWal->syncHeader && sync_flags ){
56838  rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
56839  if( rc ) return rc;
56840  }
56841  }
56842  assert( (int)pWal->szPage==szPage );
56843 
56844  /* Setup information needed to write frames into the WAL */
56845  w.pWal = pWal;
56846  w.pFd = pWal->pWalFd;
56847  w.iSyncPoint = 0;
56848  w.syncFlags = sync_flags;
56849  w.szPage = szPage;
56850  iOffset = walFrameOffset(iFrame+1, szPage);
56851  szFrame = szPage + WAL_FRAME_HDRSIZE;
56852 
56853  /* Write all frames into the log file exactly once */
56854  for(p=pList; p; p=p->pDirty){
56855  int nDbSize; /* 0 normally. Positive == commit flag */
56856 
56857  /* Check if this page has already been written into the wal file by
56858  ** the current transaction. If so, overwrite the existing frame and
56859  ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
56860  ** checksums must be recomputed when the transaction is committed. */
56861  if( iFirst && (p->pDirty || isCommit==0) ){
56862  u32 iWrite = 0;
56863  VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
56864  assert( rc==SQLITE_OK || iWrite==0 );
56865  if( iWrite>=iFirst ){
56866  i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
56867  void *pData;
56868  if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
56869  pWal->iReCksum = iWrite;
56870  }
56871 #if defined(SQLITE_HAS_CODEC)
56872  if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
56873 #else
56874  pData = p->pData;
56875 #endif
56876  rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
56877  if( rc ) return rc;
56878  p->flags &= ~PGHDR_WAL_APPEND;
56879  continue;
56880  }
56881  }
56882 
56883  iFrame++;
56884  assert( iOffset==walFrameOffset(iFrame, szPage) );
56885  nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
56886  rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
56887  if( rc ) return rc;
56888  pLast = p;
56889  iOffset += szFrame;
56890  p->flags |= PGHDR_WAL_APPEND;
56891  }
56892 
56893  /* Recalculate checksums within the wal file if required. */
56894  if( isCommit && pWal->iReCksum ){
56895  rc = walRewriteChecksums(pWal, iFrame);
56896  if( rc ) return rc;
56897  }
56898 
56899  /* If this is the end of a transaction, then we might need to pad
56900  ** the transaction and/or sync the WAL file.
56901  **
56902  ** Padding and syncing only occur if this set of frames complete a
56903  ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
56904  ** or synchronous==OFF, then no padding or syncing are needed.
56905  **
56906  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
56907  ** needed and only the sync is done. If padding is needed, then the
56908  ** final frame is repeated (with its commit mark) until the next sector
56909  ** boundary is crossed. Only the part of the WAL prior to the last
56910  ** sector boundary is synced; the part of the last frame that extends
56911  ** past the sector boundary is written after the sync.
56912  */
56913  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
56914  int bSync = 1;
56915  if( pWal->padToSectorBoundary ){
56916  int sectorSize = sqlite3SectorSize(pWal->pWalFd);
56917  w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
56918  bSync = (w.iSyncPoint==iOffset);
56919  testcase( bSync );
56920  while( iOffset<w.iSyncPoint ){
56921  rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
56922  if( rc ) return rc;
56923  iOffset += szFrame;
56924  nExtra++;
56925  }
56926  }
56927  if( bSync ){
56928  assert( rc==SQLITE_OK );
56929  rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
56930  }
56931  }
56932 
56933  /* If this frame set completes the first transaction in the WAL and
56934  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
56935  ** journal size limit, if possible.
56936  */
56937  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
56938  i64 sz = pWal->mxWalSize;
56939  if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
56940  sz = walFrameOffset(iFrame+nExtra+1, szPage);
56941  }
56942  walLimitSize(pWal, sz);
56943  pWal->truncateOnCommit = 0;
56944  }
56945 
56946  /* Append data to the wal-index. It is not necessary to lock the
56947  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
56948  ** guarantees that there are no other writers, and no data that may
56949  ** be in use by existing readers is being overwritten.
56950  */
56951  iFrame = pWal->hdr.mxFrame;
56952  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
56953  if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
56954  iFrame++;
56955  rc = walIndexAppend(pWal, iFrame, p->pgno);
56956  }
56957  while( rc==SQLITE_OK && nExtra>0 ){
56958  iFrame++;
56959  nExtra--;
56960  rc = walIndexAppend(pWal, iFrame, pLast->pgno);
56961  }
56962 
56963  if( rc==SQLITE_OK ){
56964  /* Update the private copy of the header. */
56965  pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
56966  testcase( szPage<=32768 );
56967  testcase( szPage>=65536 );
56968  pWal->hdr.mxFrame = iFrame;
56969  if( isCommit ){
56970  pWal->hdr.iChange++;
56971  pWal->hdr.nPage = nTruncate;
56972  }
56973  /* If this is a commit, update the wal-index header too. */
56974  if( isCommit ){
56975  walIndexWriteHdr(pWal);
56976  pWal->iCallback = iFrame;
56977  }
56978  }
56979 
56980  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
56981  return rc;
56982 }
56983 
56984 /*
56985 ** This routine is called to implement sqlite3_wal_checkpoint() and
56986 ** related interfaces.
56987 **
56988 ** Obtain a CHECKPOINT lock and then backfill as much information as
56989 ** we can from WAL into the database.
56990 **
56991 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
56992 ** callback. In this case this function runs a blocking checkpoint.
56993 */
56994 SQLITE_PRIVATE int sqlite3WalCheckpoint(
56995  Wal *pWal, /* Wal connection */
56996  int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
56997  int (*xBusy)(void*), /* Function to call when busy */
56998  void *pBusyArg, /* Context argument for xBusyHandler */
56999  int sync_flags, /* Flags to sync db file with (or 0) */
57000  int nBuf, /* Size of temporary buffer */
57001  u8 *zBuf, /* Temporary buffer to use */
57002  int *pnLog, /* OUT: Number of frames in WAL */
57003  int *pnCkpt /* OUT: Number of backfilled frames in WAL */
57004 ){
57005  int rc; /* Return code */
57006  int isChanged = 0; /* True if a new wal-index header is loaded */
57007  int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
57008  int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
57009 
57010  assert( pWal->ckptLock==0 );
57011  assert( pWal->writeLock==0 );
57012 
57013  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
57014  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
57015  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
57016 
57017  if( pWal->readOnly ) return SQLITE_READONLY;
57018  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
57019 
57020  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
57021  ** "checkpoint" lock on the database file. */
57022  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
57023  if( rc ){
57024  /* EVIDENCE-OF: R-10421-19736 If any other process is running a
57025  ** checkpoint operation at the same time, the lock cannot be obtained and
57026  ** SQLITE_BUSY is returned.
57027  ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
57028  ** it will not be invoked in this case.
57029  */
57030  testcase( rc==SQLITE_BUSY );
57031  testcase( xBusy!=0 );
57032  return rc;
57033  }
57034  pWal->ckptLock = 1;
57035 
57036  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
57037  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
57038  ** file.
57039  **
57040  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
57041  ** immediately, and a busy-handler is configured, it is invoked and the
57042  ** writer lock retried until either the busy-handler returns 0 or the
57043  ** lock is successfully obtained.
57044  */
57045  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
57046  rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
57047  if( rc==SQLITE_OK ){
57048  pWal->writeLock = 1;
57049  }else if( rc==SQLITE_BUSY ){
57050  eMode2 = SQLITE_CHECKPOINT_PASSIVE;
57051  xBusy2 = 0;
57052  rc = SQLITE_OK;
57053  }
57054  }
57055 
57056  /* Read the wal-index header. */
57057  if( rc==SQLITE_OK ){
57058  rc = walIndexReadHdr(pWal, &isChanged);
57059  if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
57060  sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
57061  }
57062  }
57063 
57064  /* Copy data from the log to the database file. */
57065  if( rc==SQLITE_OK ){
57066 
57067  if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
57068  rc = SQLITE_CORRUPT_BKPT;
57069  }else{
57070  rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
57071  }
57072 
57073  /* If no error occurred, set the output variables. */
57074  if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
57075  if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
57076  if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
57077  }
57078  }
57079 
57080  if( isChanged ){
57081  /* If a new wal-index header was loaded before the checkpoint was
57082  ** performed, then the pager-cache associated with pWal is now
57083  ** out of date. So zero the cached wal-index header to ensure that
57084  ** next time the pager opens a snapshot on this database it knows that
57085  ** the cache needs to be reset.
57086  */
57087  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
57088  }
57089 
57090  /* Release the locks. */
57091  sqlite3WalEndWriteTransaction(pWal);
57092  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
57093  pWal->ckptLock = 0;
57094  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
57095  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
57096 }
57097 
57098 /* Return the value to pass to a sqlite3_wal_hook callback, the
57099 ** number of frames in the WAL at the point of the last commit since
57100 ** sqlite3WalCallback() was called. If no commits have occurred since
57101 ** the last call, then return 0.
57102 */
57103 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
57104  u32 ret = 0;
57105  if( pWal ){
57106  ret = pWal->iCallback;
57107  pWal->iCallback = 0;
57108  }
57109  return (int)ret;
57110 }
57111 
57112 /*
57113 ** This function is called to change the WAL subsystem into or out
57114 ** of locking_mode=EXCLUSIVE.
57115 **
57116 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
57117 ** into locking_mode=NORMAL. This means that we must acquire a lock
57118 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
57119 ** or if the acquisition of the lock fails, then return 0. If the
57120 ** transition out of exclusive-mode is successful, return 1. This
57121 ** operation must occur while the pager is still holding the exclusive
57122 ** lock on the main database file.
57123 **
57124 ** If op is one, then change from locking_mode=NORMAL into
57125 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
57126 ** be released. Return 1 if the transition is made and 0 if the
57127 ** WAL is already in exclusive-locking mode - meaning that this
57128 ** routine is a no-op. The pager must already hold the exclusive lock
57129 ** on the main database file before invoking this operation.
57130 **
57131 ** If op is negative, then do a dry-run of the op==1 case but do
57132 ** not actually change anything. The pager uses this to see if it
57133 ** should acquire the database exclusive lock prior to invoking
57134 ** the op==1 case.
57135 */
57136 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
57137  int rc;
57138  assert( pWal->writeLock==0 );
57139  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
57140 
57141  /* pWal->readLock is usually set, but might be -1 if there was a
57142  ** prior error while attempting to acquire are read-lock. This cannot
57143  ** happen if the connection is actually in exclusive mode (as no xShmLock
57144  ** locks are taken in this case). Nor should the pager attempt to
57145  ** upgrade to exclusive-mode following such an error.
57146  */
57147  assert( pWal->readLock>=0 || pWal->lockError );
57148  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
57149 
57150  if( op==0 ){
57151  if( pWal->exclusiveMode ){
57152  pWal->exclusiveMode = 0;
57153  if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
57154  pWal->exclusiveMode = 1;
57155  }
57156  rc = pWal->exclusiveMode==0;
57157  }else{
57158  /* Already in locking_mode=NORMAL */
57159  rc = 0;
57160  }
57161  }else if( op>0 ){
57162  assert( pWal->exclusiveMode==0 );
57163  assert( pWal->readLock>=0 );
57164  walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
57165  pWal->exclusiveMode = 1;
57166  rc = 1;
57167  }else{
57168  rc = pWal->exclusiveMode==0;
57169  }
57170  return rc;
57171 }
57172 
57173 /*
57174 ** Return true if the argument is non-NULL and the WAL module is using
57175 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
57176 ** WAL module is using shared-memory, return false.
57177 */
57178 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
57179  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
57180 }
57181 
57182 #ifdef SQLITE_ENABLE_SNAPSHOT
57183 /* Create a snapshot object. The content of a snapshot is opaque to
57184 ** every other subsystem, so the WAL module can put whatever it needs
57185 ** in the object.
57186 */
57187 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
57188  int rc = SQLITE_OK;
57189  WalIndexHdr *pRet;
57190 
57191  assert( pWal->readLock>=0 && pWal->writeLock==0 );
57192 
57193  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
57194  if( pRet==0 ){
57195  rc = SQLITE_NOMEM_BKPT;
57196  }else{
57197  memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
57198  *ppSnapshot = (sqlite3_snapshot*)pRet;
57199  }
57200 
57201  return rc;
57202 }
57203 
57204 /* Try to open on pSnapshot when the next read-transaction starts
57205 */
57206 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
57207  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
57208 }
57209 
57210 /*
57211 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
57212 ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
57213 */
57214 SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
57215  WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
57216  WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
57217 
57218  /* aSalt[0] is a copy of the value stored in the wal file header. It
57219  ** is incremented each time the wal file is restarted. */
57220  if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
57221  if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
57222  if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
57223  if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
57224  return 0;
57225 }
57226 #endif /* SQLITE_ENABLE_SNAPSHOT */
57227 
57228 #ifdef SQLITE_ENABLE_ZIPVFS
57229 /*
57230 ** If the argument is not NULL, it points to a Wal object that holds a
57231 ** read-lock. This function returns the database page-size if it is known,
57232 ** or zero if it is not (or if pWal is NULL).
57233 */
57234 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
57235  assert( pWal==0 || pWal->readLock>=0 );
57236  return (pWal ? pWal->szPage : 0);
57237 }
57238 #endif
57239 
57240 /* Return the sqlite3_file object for the WAL file
57241 */
57242 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
57243  return pWal->pWalFd;
57244 }
57245 
57246 #endif /* #ifndef SQLITE_OMIT_WAL */
57247 
57248 /************** End of wal.c *************************************************/
57249 /************** Begin file btmutex.c *****************************************/
57250 /*
57251 ** 2007 August 27
57252 **
57253 ** The author disclaims copyright to this source code. In place of
57254 ** a legal notice, here is a blessing:
57255 **
57256 ** May you do good and not evil.
57257 ** May you find forgiveness for yourself and forgive others.
57258 ** May you share freely, never taking more than you give.
57259 **
57260 *************************************************************************
57261 **
57262 ** This file contains code used to implement mutexes on Btree objects.
57263 ** This code really belongs in btree.c. But btree.c is getting too
57264 ** big and we want to break it down some. This packaged seemed like
57265 ** a good breakout.
57266 */
57267 /************** Include btreeInt.h in the middle of btmutex.c ****************/
57268 /************** Begin file btreeInt.h ****************************************/
57269 /*
57270 ** 2004 April 6
57271 **
57272 ** The author disclaims copyright to this source code. In place of
57273 ** a legal notice, here is a blessing:
57274 **
57275 ** May you do good and not evil.
57276 ** May you find forgiveness for yourself and forgive others.
57277 ** May you share freely, never taking more than you give.
57278 **
57279 *************************************************************************
57280 ** This file implements an external (disk-based) database using BTrees.
57281 ** For a detailed discussion of BTrees, refer to
57282 **
57283 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
57284 ** "Sorting And Searching", pages 473-480. Addison-Wesley
57285 ** Publishing Company, Reading, Massachusetts.
57286 **
57287 ** The basic idea is that each page of the file contains N database
57288 ** entries and N+1 pointers to subpages.
57289 **
57290 ** ----------------------------------------------------------------
57291 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
57292 ** ----------------------------------------------------------------
57293 **
57294 ** All of the keys on the page that Ptr(0) points to have values less
57295 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
57296 ** values greater than Key(0) and less than Key(1). All of the keys
57297 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
57298 ** so forth.
57299 **
57300 ** Finding a particular key requires reading O(log(M)) pages from the
57301 ** disk where M is the number of entries in the tree.
57302 **
57303 ** In this implementation, a single file can hold one or more separate
57304 ** BTrees. Each BTree is identified by the index of its root page. The
57305 ** key and data for any entry are combined to form the "payload". A
57306 ** fixed amount of payload can be carried directly on the database
57307 ** page. If the payload is larger than the preset amount then surplus
57308 ** bytes are stored on overflow pages. The payload for an entry
57309 ** and the preceding pointer are combined to form a "Cell". Each
57310 ** page has a small header which contains the Ptr(N) pointer and other
57311 ** information such as the size of key and data.
57312 **
57313 ** FORMAT DETAILS
57314 **
57315 ** The file is divided into pages. The first page is called page 1,
57316 ** the second is page 2, and so forth. A page number of zero indicates
57317 ** "no such page". The page size can be any power of 2 between 512 and 65536.
57318 ** Each page can be either a btree page, a freelist page, an overflow
57319 ** page, or a pointer-map page.
57320 **
57321 ** The first page is always a btree page. The first 100 bytes of the first
57322 ** page contain a special header (the "file header") that describes the file.
57323 ** The format of the file header is as follows:
57324 **
57325 ** OFFSET SIZE DESCRIPTION
57326 ** 0 16 Header string: "SQLite format 3\000"
57327 ** 16 2 Page size in bytes. (1 means 65536)
57328 ** 18 1 File format write version
57329 ** 19 1 File format read version
57330 ** 20 1 Bytes of unused space at the end of each page
57331 ** 21 1 Max embedded payload fraction (must be 64)
57332 ** 22 1 Min embedded payload fraction (must be 32)
57333 ** 23 1 Min leaf payload fraction (must be 32)
57334 ** 24 4 File change counter
57335 ** 28 4 Reserved for future use
57336 ** 32 4 First freelist page
57337 ** 36 4 Number of freelist pages in the file
57338 ** 40 60 15 4-byte meta values passed to higher layers
57339 **
57340 ** 40 4 Schema cookie
57341 ** 44 4 File format of schema layer
57342 ** 48 4 Size of page cache
57343 ** 52 4 Largest root-page (auto/incr_vacuum)
57344 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
57345 ** 60 4 User version
57346 ** 64 4 Incremental vacuum mode
57347 ** 68 4 Application-ID
57348 ** 72 20 unused
57349 ** 92 4 The version-valid-for number
57350 ** 96 4 SQLITE_VERSION_NUMBER
57351 **
57352 ** All of the integer values are big-endian (most significant byte first).
57353 **
57354 ** The file change counter is incremented when the database is changed
57355 ** This counter allows other processes to know when the file has changed
57356 ** and thus when they need to flush their cache.
57357 **
57358 ** The max embedded payload fraction is the amount of the total usable
57359 ** space in a page that can be consumed by a single cell for standard
57360 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
57361 ** is to limit the maximum cell size so that at least 4 cells will fit
57362 ** on one page. Thus the default max embedded payload fraction is 64.
57363 **
57364 ** If the payload for a cell is larger than the max payload, then extra
57365 ** payload is spilled to overflow pages. Once an overflow page is allocated,
57366 ** as many bytes as possible are moved into the overflow pages without letting
57367 ** the cell size drop below the min embedded payload fraction.
57368 **
57369 ** The min leaf payload fraction is like the min embedded payload fraction
57370 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
57371 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
57372 ** not specified in the header.
57373 **
57374 ** Each btree pages is divided into three sections: The header, the
57375 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
57376 ** file header that occurs before the page header.
57377 **
57378 ** |----------------|
57379 ** | file header | 100 bytes. Page 1 only.
57380 ** |----------------|
57381 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
57382 ** |----------------|
57383 ** | cell pointer | | 2 bytes per cell. Sorted order.
57384 ** | array | | Grows downward
57385 ** | | v
57386 ** |----------------|
57387 ** | unallocated |
57388 ** | space |
57389 ** |----------------| ^ Grows upwards
57390 ** | cell content | | Arbitrary order interspersed with freeblocks.
57391 ** | area | | and free space fragments.
57392 ** |----------------|
57393 **
57394 ** The page headers looks like this:
57395 **
57396 ** OFFSET SIZE DESCRIPTION
57397 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
57398 ** 1 2 byte offset to the first freeblock
57399 ** 3 2 number of cells on this page
57400 ** 5 2 first byte of the cell content area
57401 ** 7 1 number of fragmented free bytes
57402 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
57403 **
57404 ** The flags define the format of this btree page. The leaf flag means that
57405 ** this page has no children. The zerodata flag means that this page carries
57406 ** only keys and no data. The intkey flag means that the key is an integer
57407 ** which is stored in the key size entry of the cell header rather than in
57408 ** the payload area.
57409 **
57410 ** The cell pointer array begins on the first byte after the page header.
57411 ** The cell pointer array contains zero or more 2-byte numbers which are
57412 ** offsets from the beginning of the page to the cell content in the cell
57413 ** content area. The cell pointers occur in sorted order. The system strives
57414 ** to keep free space after the last cell pointer so that new cells can
57415 ** be easily added without having to defragment the page.
57416 **
57417 ** Cell content is stored at the very end of the page and grows toward the
57418 ** beginning of the page.
57419 **
57420 ** Unused space within the cell content area is collected into a linked list of
57421 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
57422 ** to the first freeblock is given in the header. Freeblocks occur in
57423 ** increasing order. Because a freeblock must be at least 4 bytes in size,
57424 ** any group of 3 or fewer unused bytes in the cell content area cannot
57425 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
57426 ** a fragment. The total number of bytes in all fragments is recorded.
57427 ** in the page header at offset 7.
57428 **
57429 ** SIZE DESCRIPTION
57430 ** 2 Byte offset of the next freeblock
57431 ** 2 Bytes in this freeblock
57432 **
57433 ** Cells are of variable length. Cells are stored in the cell content area at
57434 ** the end of the page. Pointers to the cells are in the cell pointer array
57435 ** that immediately follows the page header. Cells is not necessarily
57436 ** contiguous or in order, but cell pointers are contiguous and in order.
57437 **
57438 ** Cell content makes use of variable length integers. A variable
57439 ** length integer is 1 to 9 bytes where the lower 7 bits of each
57440 ** byte are used. The integer consists of all bytes that have bit 8 set and
57441 ** the first byte with bit 8 clear. The most significant byte of the integer
57442 ** appears first. A variable-length integer may not be more than 9 bytes long.
57443 ** As a special case, all 8 bytes of the 9th byte are used as data. This
57444 ** allows a 64-bit integer to be encoded in 9 bytes.
57445 **
57446 ** 0x00 becomes 0x00000000
57447 ** 0x7f becomes 0x0000007f
57448 ** 0x81 0x00 becomes 0x00000080
57449 ** 0x82 0x00 becomes 0x00000100
57450 ** 0x80 0x7f becomes 0x0000007f
57451 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
57452 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
57453 **
57454 ** Variable length integers are used for rowids and to hold the number of
57455 ** bytes of key and data in a btree cell.
57456 **
57457 ** The content of a cell looks like this:
57458 **
57459 ** SIZE DESCRIPTION
57460 ** 4 Page number of the left child. Omitted if leaf flag is set.
57461 ** var Number of bytes of data. Omitted if the zerodata flag is set.
57462 ** var Number of bytes of key. Or the key itself if intkey flag is set.
57463 ** * Payload
57464 ** 4 First page of the overflow chain. Omitted if no overflow
57465 **
57466 ** Overflow pages form a linked list. Each page except the last is completely
57467 ** filled with data (pagesize - 4 bytes). The last page can have as little
57468 ** as 1 byte of data.
57469 **
57470 ** SIZE DESCRIPTION
57471 ** 4 Page number of next overflow page
57472 ** * Data
57473 **
57474 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
57475 ** file header points to the first in a linked list of trunk page. Each trunk
57476 ** page points to multiple leaf pages. The content of a leaf page is
57477 ** unspecified. A trunk page looks like this:
57478 **
57479 ** SIZE DESCRIPTION
57480 ** 4 Page number of next trunk page
57481 ** 4 Number of leaf pointers on this page
57482 ** * zero or more pages numbers of leaves
57483 */
57484 /* #include "sqliteInt.h" */
57485 
57486 
57487 /* The following value is the maximum cell size assuming a maximum page
57488 ** size give above.
57489 */
57490 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
57491 
57492 /* The maximum number of cells on a single page of the database. This
57493 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
57494 ** plus 2 bytes for the index to the cell in the page header). Such
57495 ** small cells will be rare, but they are possible.
57496 */
57497 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
57498 
57499 /* Forward declarations */
57500 typedef struct MemPage MemPage;
57501 typedef struct BtLock BtLock;
57502 typedef struct CellInfo CellInfo;
57503 
57504 /*
57505 ** This is a magic string that appears at the beginning of every
57506 ** SQLite database in order to identify the file as a real database.
57507 **
57508 ** You can change this value at compile-time by specifying a
57509 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
57510 ** header must be exactly 16 bytes including the zero-terminator so
57511 ** the string itself should be 15 characters long. If you change
57512 ** the header, then your custom library will not be able to read
57513 ** databases generated by the standard tools and the standard tools
57514 ** will not be able to read databases created by your custom library.
57515 */
57516 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
57517 # define SQLITE_FILE_HEADER "SQLite format 3"
57518 #endif
57519 
57520 /*
57521 ** Page type flags. An ORed combination of these flags appear as the
57522 ** first byte of on-disk image of every BTree page.
57523 */
57524 #define PTF_INTKEY 0x01
57525 #define PTF_ZERODATA 0x02
57526 #define PTF_LEAFDATA 0x04
57527 #define PTF_LEAF 0x08
57528 
57529 /*
57530 ** As each page of the file is loaded into memory, an instance of the following
57531 ** structure is appended and initialized to zero. This structure stores
57532 ** information about the page that is decoded from the raw file page.
57533 **
57534 ** The pParent field points back to the parent page. This allows us to
57535 ** walk up the BTree from any leaf to the root. Care must be taken to
57536 ** unref() the parent page pointer when this page is no longer referenced.
57537 ** The pageDestructor() routine handles that chore.
57538 **
57539 ** Access to all fields of this structure is controlled by the mutex
57540 ** stored in MemPage.pBt->mutex.
57541 */
57542 struct MemPage {
57543  u8 isInit; /* True if previously initialized. MUST BE FIRST! */
57544  u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
57545  u8 intKey; /* True if table b-trees. False for index b-trees */
57546  u8 intKeyLeaf; /* True if the leaf of an intKey table */
57547  u8 leaf; /* True if a leaf page */
57548  u8 hdrOffset; /* 100 for page 1. 0 otherwise */
57549  u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
57550  u8 max1bytePayload; /* min(maxLocal,127) */
57551  u8 bBusy; /* Prevent endless loops on corrupt database files */
57552  u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
57553  u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
57554  u16 cellOffset; /* Index in aData of first cell pointer */
57555  u16 nFree; /* Number of free bytes on the page */
57556  u16 nCell; /* Number of cells on this page, local and ovfl */
57557  u16 maskPage; /* Mask for page offset */
57558  u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
57559  ** non-overflow cell */
57560  u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
57561  BtShared *pBt; /* Pointer to BtShared that this page is part of */
57562  u8 *aData; /* Pointer to disk image of the page data */
57563  u8 *aDataEnd; /* One byte past the end of usable data */
57564  u8 *aCellIdx; /* The cell index area */
57565  u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
57566  DbPage *pDbPage; /* Pager page handle */
57567  u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
57568  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
57569  Pgno pgno; /* Page number for this page */
57570 };
57571 
57572 /*
57573 ** The in-memory image of a disk page has the auxiliary information appended
57574 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
57575 ** that extra information.
57576 */
57577 #define EXTRA_SIZE sizeof(MemPage)
57578 
57579 /*
57580 ** A linked list of the following structures is stored at BtShared.pLock.
57581 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
57582 ** is opened on the table with root page BtShared.iTable. Locks are removed
57583 ** from this list when a transaction is committed or rolled back, or when
57584 ** a btree handle is closed.
57585 */
57586 struct BtLock {
57587  Btree *pBtree; /* Btree handle holding this lock */
57588  Pgno iTable; /* Root page of table */
57589  u8 eLock; /* READ_LOCK or WRITE_LOCK */
57590  BtLock *pNext; /* Next in BtShared.pLock list */
57591 };
57592 
57593 /* Candidate values for BtLock.eLock */
57594 #define READ_LOCK 1
57595 #define WRITE_LOCK 2
57596 
57597 /* A Btree handle
57598 **
57599 ** A database connection contains a pointer to an instance of
57600 ** this object for every database file that it has open. This structure
57601 ** is opaque to the database connection. The database connection cannot
57602 ** see the internals of this structure and only deals with pointers to
57603 ** this structure.
57604 **
57605 ** For some database files, the same underlying database cache might be
57606 ** shared between multiple connections. In that case, each connection
57607 ** has it own instance of this object. But each instance of this object
57608 ** points to the same BtShared object. The database cache and the
57609 ** schema associated with the database file are all contained within
57610 ** the BtShared object.
57611 **
57612 ** All fields in this structure are accessed under sqlite3.mutex.
57613 ** The pBt pointer itself may not be changed while there exists cursors
57614 ** in the referenced BtShared that point back to this Btree since those
57615 ** cursors have to go through this Btree to find their BtShared and
57616 ** they often do so without holding sqlite3.mutex.
57617 */
57618 struct Btree {
57619  sqlite3 *db; /* The database connection holding this btree */
57620  BtShared *pBt; /* Sharable content of this btree */
57621  u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
57622  u8 sharable; /* True if we can share pBt with another db */
57623  u8 locked; /* True if db currently has pBt locked */
57624  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
57625  int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
57626  int nBackup; /* Number of backup operations reading this btree */
57627  u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
57628  Btree *pNext; /* List of other sharable Btrees from the same db */
57629  Btree *pPrev; /* Back pointer of the same list */
57630 #ifndef SQLITE_OMIT_SHARED_CACHE
57631  BtLock lock; /* Object used to lock page 1 */
57632 #endif
57633 };
57634 
57635 /*
57636 ** Btree.inTrans may take one of the following values.
57637 **
57638 ** If the shared-data extension is enabled, there may be multiple users
57639 ** of the Btree structure. At most one of these may open a write transaction,
57640 ** but any number may have active read transactions.
57641 */
57642 #define TRANS_NONE 0
57643 #define TRANS_READ 1
57644 #define TRANS_WRITE 2
57645 
57646 /*
57647 ** An instance of this object represents a single database file.
57648 **
57649 ** A single database file can be in use at the same time by two
57650 ** or more database connections. When two or more connections are
57651 ** sharing the same database file, each connection has it own
57652 ** private Btree object for the file and each of those Btrees points
57653 ** to this one BtShared object. BtShared.nRef is the number of
57654 ** connections currently sharing this database file.
57655 **
57656 ** Fields in this structure are accessed under the BtShared.mutex
57657 ** mutex, except for nRef and pNext which are accessed under the
57658 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
57659 ** may not be modified once it is initially set as long as nRef>0.
57660 ** The pSchema field may be set once under BtShared.mutex and
57661 ** thereafter is unchanged as long as nRef>0.
57662 **
57663 ** isPending:
57664 **
57665 ** If a BtShared client fails to obtain a write-lock on a database
57666 ** table (because there exists one or more read-locks on the table),
57667 ** the shared-cache enters 'pending-lock' state and isPending is
57668 ** set to true.
57669 **
57670 ** The shared-cache leaves the 'pending lock' state when either of
57671 ** the following occur:
57672 **
57673 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
57674 ** 2) The number of locks held by other connections drops to zero.
57675 **
57676 ** while in the 'pending-lock' state, no connection may start a new
57677 ** transaction.
57678 **
57679 ** This feature is included to help prevent writer-starvation.
57680 */
57681 struct BtShared {
57682  Pager *pPager; /* The page cache */
57683  sqlite3 *db; /* Database connection currently using this Btree */
57684  BtCursor *pCursor; /* A list of all open cursors */
57685  MemPage *pPage1; /* First page of the database */
57686  u8 openFlags; /* Flags to sqlite3BtreeOpen() */
57687 #ifndef SQLITE_OMIT_AUTOVACUUM
57688  u8 autoVacuum; /* True if auto-vacuum is enabled */
57689  u8 incrVacuum; /* True if incr-vacuum is enabled */
57690  u8 bDoTruncate; /* True to truncate db on commit */
57691 #endif
57692  u8 inTransaction; /* Transaction state */
57693  u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
57694 #ifdef SQLITE_HAS_CODEC
57695  u8 optimalReserve; /* Desired amount of reserved space per page */
57696 #endif
57697  u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
57698  u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
57699  u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
57700  u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
57701  u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
57702  u32 pageSize; /* Total number of bytes on a page */
57703  u32 usableSize; /* Number of usable bytes on each page */
57704  int nTransaction; /* Number of open transactions (read + write) */
57705  u32 nPage; /* Number of pages in the database */
57706  void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
57707  void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
57708  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
57709  Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
57710 #ifndef SQLITE_OMIT_SHARED_CACHE
57711  int nRef; /* Number of references to this structure */
57712  BtShared *pNext; /* Next on a list of sharable BtShared structs */
57713  BtLock *pLock; /* List of locks held on this shared-btree struct */
57714  Btree *pWriter; /* Btree with currently open write transaction */
57715 #endif
57716  u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
57717 };
57718 
57719 /*
57720 ** Allowed values for BtShared.btsFlags
57721 */
57722 #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
57723 #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
57724 #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
57725 #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
57726 #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
57727 #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
57728 #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
57729 
57730 /*
57731 ** An instance of the following structure is used to hold information
57732 ** about a cell. The parseCellPtr() function fills in this structure
57733 ** based on information extract from the raw disk page.
57734 */
57735 struct CellInfo {
57736  i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
57737  u8 *pPayload; /* Pointer to the start of payload */
57738  u32 nPayload; /* Bytes of payload */
57739  u16 nLocal; /* Amount of payload held locally, not on overflow */
57740  u16 nSize; /* Size of the cell content on the main b-tree page */
57741 };
57742 
57743 /*
57744 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
57745 ** this will be declared corrupt. This value is calculated based on a
57746 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
57747 ** root-node and 3 for all other internal nodes.
57748 **
57749 ** If a tree that appears to be taller than this is encountered, it is
57750 ** assumed that the database is corrupt.
57751 */
57752 #define BTCURSOR_MAX_DEPTH 20
57753 
57754 /*
57755 ** A cursor is a pointer to a particular entry within a particular
57756 ** b-tree within a database file.
57757 **
57758 ** The entry is identified by its MemPage and the index in
57759 ** MemPage.aCell[] of the entry.
57760 **
57761 ** A single database file can be shared by two more database connections,
57762 ** but cursors cannot be shared. Each cursor is associated with a
57763 ** particular database connection identified BtCursor.pBtree.db.
57764 **
57765 ** Fields in this structure are accessed under the BtShared.mutex
57766 ** found at self->pBt->mutex.
57767 **
57768 ** skipNext meaning:
57769 ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
57770 ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
57771 ** eState==FAULT: Cursor fault with skipNext as error code.
57772 */
57773 struct BtCursor {
57774  Btree *pBtree; /* The Btree to which this cursor belongs */
57775  BtShared *pBt; /* The BtShared this cursor points to */
57776  BtCursor *pNext; /* Forms a linked list of all cursors */
57777  Pgno *aOverflow; /* Cache of overflow page locations */
57778  CellInfo info; /* A parse of the cell we are pointing at */
57779  i64 nKey; /* Size of pKey, or last integer key */
57780  void *pKey; /* Saved key that was cursor last known position */
57781  Pgno pgnoRoot; /* The root page of this tree */
57782  int nOvflAlloc; /* Allocated size of aOverflow[] array */
57783  int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
57784  ** Error code if eState==CURSOR_FAULT */
57785  u8 curFlags; /* zero or more BTCF_* flags defined below */
57786  u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
57787  u8 eState; /* One of the CURSOR_XXX constants (see below) */
57788  u8 hints; /* As configured by CursorSetHints() */
57789  /* All fields above are zeroed when the cursor is allocated. See
57790  ** sqlite3BtreeCursorZero(). Fields that follow must be manually
57791  ** initialized. */
57792  i8 iPage; /* Index of current page in apPage */
57793  u8 curIntKey; /* Value of apPage[0]->intKey */
57794  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
57795  void *padding1; /* Make object size a multiple of 16 */
57796  u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
57797  MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
57798 };
57799 
57800 /*
57801 ** Legal values for BtCursor.curFlags
57802 */
57803 #define BTCF_WriteFlag 0x01 /* True if a write cursor */
57804 #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
57805 #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
57806 #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
57807 #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
57808 #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
57809 
57810 /*
57811 ** Potential values for BtCursor.eState.
57812 **
57813 ** CURSOR_INVALID:
57814 ** Cursor does not point to a valid entry. This can happen (for example)
57815 ** because the table is empty or because BtreeCursorFirst() has not been
57816 ** called.
57817 **
57818 ** CURSOR_VALID:
57819 ** Cursor points to a valid entry. getPayload() etc. may be called.
57820 **
57821 ** CURSOR_SKIPNEXT:
57822 ** Cursor is valid except that the Cursor.skipNext field is non-zero
57823 ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
57824 ** operation should be a no-op.
57825 **
57826 ** CURSOR_REQUIRESEEK:
57827 ** The table that this cursor was opened on still exists, but has been
57828 ** modified since the cursor was last used. The cursor position is saved
57829 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
57830 ** this state, restoreCursorPosition() can be called to attempt to
57831 ** seek the cursor to the saved position.
57832 **
57833 ** CURSOR_FAULT:
57834 ** An unrecoverable error (an I/O error or a malloc failure) has occurred
57835 ** on a different connection that shares the BtShared cache with this
57836 ** cursor. The error has left the cache in an inconsistent state.
57837 ** Do nothing else with this cursor. Any attempt to use the cursor
57838 ** should return the error code stored in BtCursor.skipNext
57839 */
57840 #define CURSOR_INVALID 0
57841 #define CURSOR_VALID 1
57842 #define CURSOR_SKIPNEXT 2
57843 #define CURSOR_REQUIRESEEK 3
57844 #define CURSOR_FAULT 4
57845 
57846 /*
57847 ** The database page the PENDING_BYTE occupies. This page is never used.
57848 */
57849 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
57850 
57851 /*
57852 ** These macros define the location of the pointer-map entry for a
57853 ** database page. The first argument to each is the number of usable
57854 ** bytes on each page of the database (often 1024). The second is the
57855 ** page number to look up in the pointer map.
57856 **
57857 ** PTRMAP_PAGENO returns the database page number of the pointer-map
57858 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
57859 ** the offset of the requested map entry.
57860 **
57861 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
57862 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
57863 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
57864 ** this test.
57865 */
57866 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
57867 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
57868 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
57869 
57870 /*
57871 ** The pointer map is a lookup table that identifies the parent page for
57872 ** each child page in the database file. The parent page is the page that
57873 ** contains a pointer to the child. Every page in the database contains
57874 ** 0 or 1 parent pages. (In this context 'database page' refers
57875 ** to any page that is not part of the pointer map itself.) Each pointer map
57876 ** entry consists of a single byte 'type' and a 4 byte parent page number.
57877 ** The PTRMAP_XXX identifiers below are the valid types.
57878 **
57879 ** The purpose of the pointer map is to facility moving pages from one
57880 ** position in the file to another as part of autovacuum. When a page
57881 ** is moved, the pointer in its parent must be updated to point to the
57882 ** new location. The pointer map is used to locate the parent page quickly.
57883 **
57884 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
57885 ** used in this case.
57886 **
57887 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
57888 ** is not used in this case.
57889 **
57890 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
57891 ** overflow pages. The page number identifies the page that
57892 ** contains the cell with a pointer to this overflow page.
57893 **
57894 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
57895 ** overflow pages. The page-number identifies the previous
57896 ** page in the overflow page list.
57897 **
57898 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
57899 ** identifies the parent page in the btree.
57900 */
57901 #define PTRMAP_ROOTPAGE 1
57902 #define PTRMAP_FREEPAGE 2
57903 #define PTRMAP_OVERFLOW1 3
57904 #define PTRMAP_OVERFLOW2 4
57905 #define PTRMAP_BTREE 5
57906 
57907 /* A bunch of assert() statements to check the transaction state variables
57908 ** of handle p (type Btree*) are internally consistent.
57909 */
57910 #define btreeIntegrity(p) \
57911  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
57912  assert( p->pBt->inTransaction>=p->inTrans );
57913 
57914 
57915 /*
57916 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
57917 ** if the database supports auto-vacuum or not. Because it is used
57918 ** within an expression that is an argument to another macro
57919 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
57920 ** So, this macro is defined instead.
57921 */
57922 #ifndef SQLITE_OMIT_AUTOVACUUM
57923 #define ISAUTOVACUUM (pBt->autoVacuum)
57924 #else
57925 #define ISAUTOVACUUM 0
57926 #endif
57927 
57928 
57929 /*
57930 ** This structure is passed around through all the sanity checking routines
57931 ** in order to keep track of some global state information.
57932 **
57933 ** The aRef[] array is allocated so that there is 1 bit for each page in
57934 ** the database. As the integrity-check proceeds, for each page used in
57935 ** the database the corresponding bit is set. This allows integrity-check to
57936 ** detect pages that are used twice and orphaned pages (both of which
57937 ** indicate corruption).
57938 */
57939 typedef struct IntegrityCk IntegrityCk;
57940 struct IntegrityCk {
57941  BtShared *pBt; /* The tree being checked out */
57942  Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
57943  u8 *aPgRef; /* 1 bit per page in the db (see above) */
57944  Pgno nPage; /* Number of pages in the database */
57945  int mxErr; /* Stop accumulating errors when this reaches zero */
57946  int nErr; /* Number of messages written to zErrMsg so far */
57947  int mallocFailed; /* A memory allocation error has occurred */
57948  const char *zPfx; /* Error message prefix */
57949  int v1, v2; /* Values for up to two %d fields in zPfx */
57950  StrAccum errMsg; /* Accumulate the error message text here */
57951  u32 *heap; /* Min-heap used for analyzing cell coverage */
57952 };
57953 
57954 /*
57955 ** Routines to read or write a two- and four-byte big-endian integer values.
57956 */
57957 #define get2byte(x) ((x)[0]<<8 | (x)[1])
57958 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
57959 #define get4byte sqlite3Get4byte
57960 #define put4byte sqlite3Put4byte
57961 
57962 /*
57963 ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
57964 ** two-byte aligned address. get2bytea() is only used for accessing the
57965 ** cell addresses in a btree header.
57966 */
57967 #if SQLITE_BYTEORDER==4321
57968 # define get2byteAligned(x) (*(u16*)(x))
57969 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57970  && GCC_VERSION>=4008000
57971 # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
57972 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57973  && defined(_MSC_VER) && _MSC_VER>=1300
57974 # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
57975 #else
57976 # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
57977 #endif
57978 
57979 /************** End of btreeInt.h ********************************************/
57980 /************** Continuing where we left off in btmutex.c ********************/
57981 #ifndef SQLITE_OMIT_SHARED_CACHE
57982 #if SQLITE_THREADSAFE
57983 
57984 /*
57985 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
57986 ** set BtShared.db to the database handle associated with p and the
57987 ** p->locked boolean to true.
57988 */
57989 static void lockBtreeMutex(Btree *p){
57990  assert( p->locked==0 );
57991  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
57992  assert( sqlite3_mutex_held(p->db->mutex) );
57993 
57994  sqlite3_mutex_enter(p->pBt->mutex);
57995  p->pBt->db = p->db;
57996  p->locked = 1;
57997 }
57998 
57999 /*
58000 ** Release the BtShared mutex associated with B-Tree handle p and
58001 ** clear the p->locked boolean.
58002 */
58003 static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
58004  BtShared *pBt = p->pBt;
58005  assert( p->locked==1 );
58006  assert( sqlite3_mutex_held(pBt->mutex) );
58007  assert( sqlite3_mutex_held(p->db->mutex) );
58008  assert( p->db==pBt->db );
58009 
58010  sqlite3_mutex_leave(pBt->mutex);
58011  p->locked = 0;
58012 }
58013 
58014 /* Forward reference */
58015 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
58016 
58017 /*
58018 ** Enter a mutex on the given BTree object.
58019 **
58020 ** If the object is not sharable, then no mutex is ever required
58021 ** and this routine is a no-op. The underlying mutex is non-recursive.
58022 ** But we keep a reference count in Btree.wantToLock so the behavior
58023 ** of this interface is recursive.
58024 **
58025 ** To avoid deadlocks, multiple Btrees are locked in the same order
58026 ** by all database connections. The p->pNext is a list of other
58027 ** Btrees belonging to the same database connection as the p Btree
58028 ** which need to be locked after p. If we cannot get a lock on
58029 ** p, then first unlock all of the others on p->pNext, then wait
58030 ** for the lock to become available on p, then relock all of the
58031 ** subsequent Btrees that desire a lock.
58032 */
58033 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
58034  /* Some basic sanity checking on the Btree. The list of Btrees
58035  ** connected by pNext and pPrev should be in sorted order by
58036  ** Btree.pBt value. All elements of the list should belong to
58037  ** the same connection. Only shared Btrees are on the list. */
58038  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
58039  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
58040  assert( p->pNext==0 || p->pNext->db==p->db );
58041  assert( p->pPrev==0 || p->pPrev->db==p->db );
58042  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
58043 
58044  /* Check for locking consistency */
58045  assert( !p->locked || p->wantToLock>0 );
58046  assert( p->sharable || p->wantToLock==0 );
58047 
58048  /* We should already hold a lock on the database connection */
58049  assert( sqlite3_mutex_held(p->db->mutex) );
58050 
58051  /* Unless the database is sharable and unlocked, then BtShared.db
58052  ** should already be set correctly. */
58053  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
58054 
58055  if( !p->sharable ) return;
58056  p->wantToLock++;
58057  if( p->locked ) return;
58058  btreeLockCarefully(p);
58059 }
58060 
58061 /* This is a helper function for sqlite3BtreeLock(). By moving
58062 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
58063 ** into this routine, we avoid unnecessary stack pointer changes
58064 ** and thus help the sqlite3BtreeLock() routine to run much faster
58065 ** in the common case.
58066 */
58067 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
58068  Btree *pLater;
58069 
58070  /* In most cases, we should be able to acquire the lock we
58071  ** want without having to go through the ascending lock
58072  ** procedure that follows. Just be sure not to block.
58073  */
58074  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
58075  p->pBt->db = p->db;
58076  p->locked = 1;
58077  return;
58078  }
58079 
58080  /* To avoid deadlock, first release all locks with a larger
58081  ** BtShared address. Then acquire our lock. Then reacquire
58082  ** the other BtShared locks that we used to hold in ascending
58083  ** order.
58084  */
58085  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
58086  assert( pLater->sharable );
58087  assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
58088  assert( !pLater->locked || pLater->wantToLock>0 );
58089  if( pLater->locked ){
58090  unlockBtreeMutex(pLater);
58091  }
58092  }
58093  lockBtreeMutex(p);
58094  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
58095  if( pLater->wantToLock ){
58096  lockBtreeMutex(pLater);
58097  }
58098  }
58099 }
58100 
58101 
58102 /*
58103 ** Exit the recursive mutex on a Btree.
58104 */
58105 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
58106  assert( sqlite3_mutex_held(p->db->mutex) );
58107  if( p->sharable ){
58108  assert( p->wantToLock>0 );
58109  p->wantToLock--;
58110  if( p->wantToLock==0 ){
58111  unlockBtreeMutex(p);
58112  }
58113  }
58114 }
58115 
58116 #ifndef NDEBUG
58117 /*
58118 ** Return true if the BtShared mutex is held on the btree, or if the
58119 ** B-Tree is not marked as sharable.
58120 **
58121 ** This routine is used only from within assert() statements.
58122 */
58123 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
58124  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
58125  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
58126  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
58127  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
58128 
58129  return (p->sharable==0 || p->locked);
58130 }
58131 #endif
58132 
58133 
58134 /*
58135 ** Enter the mutex on every Btree associated with a database
58136 ** connection. This is needed (for example) prior to parsing
58137 ** a statement since we will be comparing table and column names
58138 ** against all schemas and we do not want those schemas being
58139 ** reset out from under us.
58140 **
58141 ** There is a corresponding leave-all procedures.
58142 **
58143 ** Enter the mutexes in accending order by BtShared pointer address
58144 ** to avoid the possibility of deadlock when two threads with
58145 ** two or more btrees in common both try to lock all their btrees
58146 ** at the same instant.
58147 */
58148 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58149  int i;
58150  Btree *p;
58151  assert( sqlite3_mutex_held(db->mutex) );
58152  for(i=0; i<db->nDb; i++){
58153  p = db->aDb[i].pBt;
58154  if( p ) sqlite3BtreeEnter(p);
58155  }
58156 }
58157 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
58158  int i;
58159  Btree *p;
58160  assert( sqlite3_mutex_held(db->mutex) );
58161  for(i=0; i<db->nDb; i++){
58162  p = db->aDb[i].pBt;
58163  if( p ) sqlite3BtreeLeave(p);
58164  }
58165 }
58166 
58167 #ifndef NDEBUG
58168 /*
58169 ** Return true if the current thread holds the database connection
58170 ** mutex and all required BtShared mutexes.
58171 **
58172 ** This routine is used inside assert() statements only.
58173 */
58174 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
58175  int i;
58176  if( !sqlite3_mutex_held(db->mutex) ){
58177  return 0;
58178  }
58179  for(i=0; i<db->nDb; i++){
58180  Btree *p;
58181  p = db->aDb[i].pBt;
58182  if( p && p->sharable &&
58183  (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
58184  return 0;
58185  }
58186  }
58187  return 1;
58188 }
58189 #endif /* NDEBUG */
58190 
58191 #ifndef NDEBUG
58192 /*
58193 ** Return true if the correct mutexes are held for accessing the
58194 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
58195 ** access are:
58196 **
58197 ** (1) The mutex on db
58198 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
58199 **
58200 ** If pSchema is not NULL, then iDb is computed from pSchema and
58201 ** db using sqlite3SchemaToIndex().
58202 */
58203 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
58204  Btree *p;
58205  assert( db!=0 );
58206  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
58207  assert( iDb>=0 && iDb<db->nDb );
58208  if( !sqlite3_mutex_held(db->mutex) ) return 0;
58209  if( iDb==1 ) return 1;
58210  p = db->aDb[iDb].pBt;
58211  assert( p!=0 );
58212  return p->sharable==0 || p->locked==1;
58213 }
58214 #endif /* NDEBUG */
58215 
58216 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
58217 /*
58218 ** The following are special cases for mutex enter routines for use
58219 ** in single threaded applications that use shared cache. Except for
58220 ** these two routines, all mutex operations are no-ops in that case and
58221 ** are null #defines in btree.h.
58222 **
58223 ** If shared cache is disabled, then all btree mutex routines, including
58224 ** the ones below, are no-ops and are null #defines in btree.h.
58225 */
58226 
58227 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
58228  p->pBt->db = p->db;
58229 }
58230 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58231  int i;
58232  for(i=0; i<db->nDb; i++){
58233  Btree *p = db->aDb[i].pBt;
58234  if( p ){
58235  p->pBt->db = p->db;
58236  }
58237  }
58238 }
58239 #endif /* if SQLITE_THREADSAFE */
58240 
58241 #ifndef SQLITE_OMIT_INCRBLOB
58242 /*
58243 ** Enter a mutex on a Btree given a cursor owned by that Btree.
58244 **
58245 ** These entry points are used by incremental I/O only. Enter() is required
58246 ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
58247 ** the build is threadsafe. Leave() is only required by threadsafe builds.
58248 */
58249 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
58250  sqlite3BtreeEnter(pCur->pBtree);
58251 }
58252 # if SQLITE_THREADSAFE
58253 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
58254  sqlite3BtreeLeave(pCur->pBtree);
58255 }
58256 # endif
58257 #endif /* ifndef SQLITE_OMIT_INCRBLOB */
58258 
58259 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
58260 
58261 /************** End of btmutex.c *********************************************/
58262 /************** Begin file btree.c *******************************************/
58263 /*
58264 ** 2004 April 6
58265 **
58266 ** The author disclaims copyright to this source code. In place of
58267 ** a legal notice, here is a blessing:
58268 **
58269 ** May you do good and not evil.
58270 ** May you find forgiveness for yourself and forgive others.
58271 ** May you share freely, never taking more than you give.
58272 **
58273 *************************************************************************
58274 ** This file implements an external (disk-based) database using BTrees.
58275 ** See the header comment on "btreeInt.h" for additional information.
58276 ** Including a description of file format and an overview of operation.
58277 */
58278 /* #include "btreeInt.h" */
58279 
58280 /*
58281 ** The header string that appears at the beginning of every
58282 ** SQLite database.
58283 */
58284 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
58285 
58286 /*
58287 ** Set this global variable to 1 to enable tracing using the TRACE
58288 ** macro.
58289 */
58290 #if 0
58291 int sqlite3BtreeTrace=1; /* True to enable tracing */
58292 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
58293 #else
58294 # define TRACE(X)
58295 #endif
58296 
58297 /*
58298 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
58299 ** But if the value is zero, make it 65536.
58300 **
58301 ** This routine is used to extract the "offset to cell content area" value
58302 ** from the header of a btree page. If the page size is 65536 and the page
58303 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
58304 ** This routine makes the necessary adjustment to 65536.
58305 */
58306 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
58307 
58308 /*
58309 ** Values passed as the 5th argument to allocateBtreePage()
58310 */
58311 #define BTALLOC_ANY 0 /* Allocate any page */
58312 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
58313 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
58314 
58315 /*
58316 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
58317 ** defined, or 0 if it is. For example:
58318 **
58319 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
58320 */
58321 #ifndef SQLITE_OMIT_AUTOVACUUM
58322 #define IfNotOmitAV(expr) (expr)
58323 #else
58324 #define IfNotOmitAV(expr) 0
58325 #endif
58326 
58327 #ifndef SQLITE_OMIT_SHARED_CACHE
58328 /*
58329 ** A list of BtShared objects that are eligible for participation
58330 ** in shared cache. This variable has file scope during normal builds,
58331 ** but the test harness needs to access it so we make it global for
58332 ** test builds.
58333 **
58334 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
58335 */
58336 #ifdef SQLITE_TEST
58337 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
58338 #else
58339 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
58340 #endif
58341 #endif /* SQLITE_OMIT_SHARED_CACHE */
58342 
58343 #ifndef SQLITE_OMIT_SHARED_CACHE
58344 /*
58345 ** Enable or disable the shared pager and schema features.
58346 **
58347 ** This routine has no effect on existing database connections.
58348 ** The shared cache setting effects only future calls to
58349 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
58350 */
58351 SQLITE_API int sqlite3_enable_shared_cache(int enable){
58352  sqlite3GlobalConfig.sharedCacheEnabled = enable;
58353  return SQLITE_OK;
58354 }
58355 #endif
58356 
58357 
58358 
58359 #ifdef SQLITE_OMIT_SHARED_CACHE
58360  /*
58361  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
58362  ** and clearAllSharedCacheTableLocks()
58363  ** manipulate entries in the BtShared.pLock linked list used to store
58364  ** shared-cache table level locks. If the library is compiled with the
58365  ** shared-cache feature disabled, then there is only ever one user
58366  ** of each BtShared structure and so this locking is not necessary.
58367  ** So define the lock related functions as no-ops.
58368  */
58369  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
58370  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
58371  #define clearAllSharedCacheTableLocks(a)
58372  #define downgradeAllSharedCacheTableLocks(a)
58373  #define hasSharedCacheTableLock(a,b,c,d) 1
58374  #define hasReadConflicts(a, b) 0
58375 #endif
58376 
58377 #ifndef SQLITE_OMIT_SHARED_CACHE
58378 
58379 #ifdef SQLITE_DEBUG
58380 /*
58381 **** This function is only used as part of an assert() statement. ***
58382 **
58383 ** Check to see if pBtree holds the required locks to read or write to the
58384 ** table with root page iRoot. Return 1 if it does and 0 if not.
58385 **
58386 ** For example, when writing to a table with root-page iRoot via
58387 ** Btree connection pBtree:
58388 **
58389 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
58390 **
58391 ** When writing to an index that resides in a sharable database, the
58392 ** caller should have first obtained a lock specifying the root page of
58393 ** the corresponding table. This makes things a bit more complicated,
58394 ** as this module treats each table as a separate structure. To determine
58395 ** the table corresponding to the index being written, this
58396 ** function has to search through the database schema.
58397 **
58398 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
58399 ** hold a write-lock on the schema table (root page 1). This is also
58400 ** acceptable.
58401 */
58402 static int hasSharedCacheTableLock(
58403  Btree *pBtree, /* Handle that must hold lock */
58404  Pgno iRoot, /* Root page of b-tree */
58405  int isIndex, /* True if iRoot is the root of an index b-tree */
58406  int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
58407 ){
58408  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
58409  Pgno iTab = 0;
58410  BtLock *pLock;
58411 
58412  /* If this database is not shareable, or if the client is reading
58413  ** and has the read-uncommitted flag set, then no lock is required.
58414  ** Return true immediately.
58415  */
58416  if( (pBtree->sharable==0)
58417  || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
58418  ){
58419  return 1;
58420  }
58421 
58422  /* If the client is reading or writing an index and the schema is
58423  ** not loaded, then it is too difficult to actually check to see if
58424  ** the correct locks are held. So do not bother - just return true.
58425  ** This case does not come up very often anyhow.
58426  */
58427  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
58428  return 1;
58429  }
58430 
58431  /* Figure out the root-page that the lock should be held on. For table
58432  ** b-trees, this is just the root page of the b-tree being read or
58433  ** written. For index b-trees, it is the root page of the associated
58434  ** table. */
58435  if( isIndex ){
58436  HashElem *p;
58437  for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
58438  Index *pIdx = (Index *)sqliteHashData(p);
58439  if( pIdx->tnum==(int)iRoot ){
58440  if( iTab ){
58441  /* Two or more indexes share the same root page. There must
58442  ** be imposter tables. So just return true. The assert is not
58443  ** useful in that case. */
58444  return 1;
58445  }
58446  iTab = pIdx->pTable->tnum;
58447  }
58448  }
58449  }else{
58450  iTab = iRoot;
58451  }
58452 
58453  /* Search for the required lock. Either a write-lock on root-page iTab, a
58454  ** write-lock on the schema table, or (if the client is reading) a
58455  ** read-lock on iTab will suffice. Return 1 if any of these are found. */
58456  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
58457  if( pLock->pBtree==pBtree
58458  && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
58459  && pLock->eLock>=eLockType
58460  ){
58461  return 1;
58462  }
58463  }
58464 
58465  /* Failed to find the required lock. */
58466  return 0;
58467 }
58468 #endif /* SQLITE_DEBUG */
58469 
58470 #ifdef SQLITE_DEBUG
58471 /*
58472 **** This function may be used as part of assert() statements only. ****
58473 **
58474 ** Return true if it would be illegal for pBtree to write into the
58475 ** table or index rooted at iRoot because other shared connections are
58476 ** simultaneously reading that same table or index.
58477 **
58478 ** It is illegal for pBtree to write if some other Btree object that
58479 ** shares the same BtShared object is currently reading or writing
58480 ** the iRoot table. Except, if the other Btree object has the
58481 ** read-uncommitted flag set, then it is OK for the other object to
58482 ** have a read cursor.
58483 **
58484 ** For example, before writing to any part of the table or index
58485 ** rooted at page iRoot, one should call:
58486 **
58487 ** assert( !hasReadConflicts(pBtree, iRoot) );
58488 */
58489 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
58490  BtCursor *p;
58491  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58492  if( p->pgnoRoot==iRoot
58493  && p->pBtree!=pBtree
58494  && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
58495  ){
58496  return 1;
58497  }
58498  }
58499  return 0;
58500 }
58501 #endif /* #ifdef SQLITE_DEBUG */
58502 
58503 /*
58504 ** Query to see if Btree handle p may obtain a lock of type eLock
58505 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
58506 ** SQLITE_OK if the lock may be obtained (by calling
58507 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
58508 */
58509 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
58510  BtShared *pBt = p->pBt;
58511  BtLock *pIter;
58512 
58513  assert( sqlite3BtreeHoldsMutex(p) );
58514  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58515  assert( p->db!=0 );
58516  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
58517 
58518  /* If requesting a write-lock, then the Btree must have an open write
58519  ** transaction on this file. And, obviously, for this to be so there
58520  ** must be an open write transaction on the file itself.
58521  */
58522  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
58523  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
58524 
58525  /* This routine is a no-op if the shared-cache is not enabled */
58526  if( !p->sharable ){
58527  return SQLITE_OK;
58528  }
58529 
58530  /* If some other connection is holding an exclusive lock, the
58531  ** requested lock may not be obtained.
58532  */
58533  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
58534  sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
58535  return SQLITE_LOCKED_SHAREDCACHE;
58536  }
58537 
58538  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58539  /* The condition (pIter->eLock!=eLock) in the following if(...)
58540  ** statement is a simplification of:
58541  **
58542  ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
58543  **
58544  ** since we know that if eLock==WRITE_LOCK, then no other connection
58545  ** may hold a WRITE_LOCK on any table in this file (since there can
58546  ** only be a single writer).
58547  */
58548  assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
58549  assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
58550  if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
58551  sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
58552  if( eLock==WRITE_LOCK ){
58553  assert( p==pBt->pWriter );
58554  pBt->btsFlags |= BTS_PENDING;
58555  }
58556  return SQLITE_LOCKED_SHAREDCACHE;
58557  }
58558  }
58559  return SQLITE_OK;
58560 }
58561 #endif /* !SQLITE_OMIT_SHARED_CACHE */
58562 
58563 #ifndef SQLITE_OMIT_SHARED_CACHE
58564 /*
58565 ** Add a lock on the table with root-page iTable to the shared-btree used
58566 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
58567 ** WRITE_LOCK.
58568 **
58569 ** This function assumes the following:
58570 **
58571 ** (a) The specified Btree object p is connected to a sharable
58572 ** database (one with the BtShared.sharable flag set), and
58573 **
58574 ** (b) No other Btree objects hold a lock that conflicts
58575 ** with the requested lock (i.e. querySharedCacheTableLock() has
58576 ** already been called and returned SQLITE_OK).
58577 **
58578 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
58579 ** is returned if a malloc attempt fails.
58580 */
58581 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
58582  BtShared *pBt = p->pBt;
58583  BtLock *pLock = 0;
58584  BtLock *pIter;
58585 
58586  assert( sqlite3BtreeHoldsMutex(p) );
58587  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58588  assert( p->db!=0 );
58589 
58590  /* A connection with the read-uncommitted flag set will never try to
58591  ** obtain a read-lock using this function. The only read-lock obtained
58592  ** by a connection in read-uncommitted mode is on the sqlite_master
58593  ** table, and that lock is obtained in BtreeBeginTrans(). */
58594  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
58595 
58596  /* This function should only be called on a sharable b-tree after it
58597  ** has been determined that no other b-tree holds a conflicting lock. */
58598  assert( p->sharable );
58599  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
58600 
58601  /* First search the list for an existing lock on this table. */
58602  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58603  if( pIter->iTable==iTable && pIter->pBtree==p ){
58604  pLock = pIter;
58605  break;
58606  }
58607  }
58608 
58609  /* If the above search did not find a BtLock struct associating Btree p
58610  ** with table iTable, allocate one and link it into the list.
58611  */
58612  if( !pLock ){
58613  pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
58614  if( !pLock ){
58615  return SQLITE_NOMEM_BKPT;
58616  }
58617  pLock->iTable = iTable;
58618  pLock->pBtree = p;
58619  pLock->pNext = pBt->pLock;
58620  pBt->pLock = pLock;
58621  }
58622 
58623  /* Set the BtLock.eLock variable to the maximum of the current lock
58624  ** and the requested lock. This means if a write-lock was already held
58625  ** and a read-lock requested, we don't incorrectly downgrade the lock.
58626  */
58627  assert( WRITE_LOCK>READ_LOCK );
58628  if( eLock>pLock->eLock ){
58629  pLock->eLock = eLock;
58630  }
58631 
58632  return SQLITE_OK;
58633 }
58634 #endif /* !SQLITE_OMIT_SHARED_CACHE */
58635 
58636 #ifndef SQLITE_OMIT_SHARED_CACHE
58637 /*
58638 ** Release all the table locks (locks obtained via calls to
58639 ** the setSharedCacheTableLock() procedure) held by Btree object p.
58640 **
58641 ** This function assumes that Btree p has an open read or write
58642 ** transaction. If it does not, then the BTS_PENDING flag
58643 ** may be incorrectly cleared.
58644 */
58645 static void clearAllSharedCacheTableLocks(Btree *p){
58646  BtShared *pBt = p->pBt;
58647  BtLock **ppIter = &pBt->pLock;
58648 
58649  assert( sqlite3BtreeHoldsMutex(p) );
58650  assert( p->sharable || 0==*ppIter );
58651  assert( p->inTrans>0 );
58652 
58653  while( *ppIter ){
58654  BtLock *pLock = *ppIter;
58655  assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
58656  assert( pLock->pBtree->inTrans>=pLock->eLock );
58657  if( pLock->pBtree==p ){
58658  *ppIter = pLock->pNext;
58659  assert( pLock->iTable!=1 || pLock==&p->lock );
58660  if( pLock->iTable!=1 ){
58661  sqlite3_free(pLock);
58662  }
58663  }else{
58664  ppIter = &pLock->pNext;
58665  }
58666  }
58667 
58668  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
58669  if( pBt->pWriter==p ){
58670  pBt->pWriter = 0;
58671  pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58672  }else if( pBt->nTransaction==2 ){
58673  /* This function is called when Btree p is concluding its
58674  ** transaction. If there currently exists a writer, and p is not
58675  ** that writer, then the number of locks held by connections other
58676  ** than the writer must be about to drop to zero. In this case
58677  ** set the BTS_PENDING flag to 0.
58678  **
58679  ** If there is not currently a writer, then BTS_PENDING must
58680  ** be zero already. So this next line is harmless in that case.
58681  */
58682  pBt->btsFlags &= ~BTS_PENDING;
58683  }
58684 }
58685 
58686 /*
58687 ** This function changes all write-locks held by Btree p into read-locks.
58688 */
58689 static void downgradeAllSharedCacheTableLocks(Btree *p){
58690  BtShared *pBt = p->pBt;
58691  if( pBt->pWriter==p ){
58692  BtLock *pLock;
58693  pBt->pWriter = 0;
58694  pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58695  for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
58696  assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
58697  pLock->eLock = READ_LOCK;
58698  }
58699  }
58700 }
58701 
58702 #endif /* SQLITE_OMIT_SHARED_CACHE */
58703 
58704 static void releasePage(MemPage *pPage); /* Forward reference */
58705 
58706 /*
58707 ***** This routine is used inside of assert() only ****
58708 **
58709 ** Verify that the cursor holds the mutex on its BtShared
58710 */
58711 #ifdef SQLITE_DEBUG
58712 static int cursorHoldsMutex(BtCursor *p){
58713  return sqlite3_mutex_held(p->pBt->mutex);
58714 }
58715 
58716 /* Verify that the cursor and the BtShared agree about what is the current
58717 ** database connetion. This is important in shared-cache mode. If the database
58718 ** connection pointers get out-of-sync, it is possible for routines like
58719 ** btreeInitPage() to reference an stale connection pointer that references a
58720 ** a connection that has already closed. This routine is used inside assert()
58721 ** statements only and for the purpose of double-checking that the btree code
58722 ** does keep the database connection pointers up-to-date.
58723 */
58724 static int cursorOwnsBtShared(BtCursor *p){
58725  assert( cursorHoldsMutex(p) );
58726  return (p->pBtree->db==p->pBt->db);
58727 }
58728 #endif
58729 
58730 /*
58731 ** Invalidate the overflow cache of the cursor passed as the first argument.
58732 ** on the shared btree structure pBt.
58733 */
58734 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
58735 
58736 /*
58737 ** Invalidate the overflow page-list cache for all cursors opened
58738 ** on the shared btree structure pBt.
58739 */
58740 static void invalidateAllOverflowCache(BtShared *pBt){
58741  BtCursor *p;
58742  assert( sqlite3_mutex_held(pBt->mutex) );
58743  for(p=pBt->pCursor; p; p=p->pNext){
58744  invalidateOverflowCache(p);
58745  }
58746 }
58747 
58748 #ifndef SQLITE_OMIT_INCRBLOB
58749 /*
58750 ** This function is called before modifying the contents of a table
58751 ** to invalidate any incrblob cursors that are open on the
58752 ** row or one of the rows being modified.
58753 **
58754 ** If argument isClearTable is true, then the entire contents of the
58755 ** table is about to be deleted. In this case invalidate all incrblob
58756 ** cursors open on any row within the table with root-page pgnoRoot.
58757 **
58758 ** Otherwise, if argument isClearTable is false, then the row with
58759 ** rowid iRow is being replaced or deleted. In this case invalidate
58760 ** only those incrblob cursors open on that specific row.
58761 */
58762 static void invalidateIncrblobCursors(
58763  Btree *pBtree, /* The database file to check */
58764  i64 iRow, /* The rowid that might be changing */
58765  int isClearTable /* True if all rows are being deleted */
58766 ){
58767  BtCursor *p;
58768  if( pBtree->hasIncrblobCur==0 ) return;
58769  assert( sqlite3BtreeHoldsMutex(pBtree) );
58770  pBtree->hasIncrblobCur = 0;
58771  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58772  if( (p->curFlags & BTCF_Incrblob)!=0 ){
58773  pBtree->hasIncrblobCur = 1;
58774  if( isClearTable || p->info.nKey==iRow ){
58775  p->eState = CURSOR_INVALID;
58776  }
58777  }
58778  }
58779 }
58780 
58781 #else
58782  /* Stub function when INCRBLOB is omitted */
58783  #define invalidateIncrblobCursors(x,y,z)
58784 #endif /* SQLITE_OMIT_INCRBLOB */
58785 
58786 /*
58787 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
58788 ** when a page that previously contained data becomes a free-list leaf
58789 ** page.
58790 **
58791 ** The BtShared.pHasContent bitvec exists to work around an obscure
58792 ** bug caused by the interaction of two useful IO optimizations surrounding
58793 ** free-list leaf pages:
58794 **
58795 ** 1) When all data is deleted from a page and the page becomes
58796 ** a free-list leaf page, the page is not written to the database
58797 ** (as free-list leaf pages contain no meaningful data). Sometimes
58798 ** such a page is not even journalled (as it will not be modified,
58799 ** why bother journalling it?).
58800 **
58801 ** 2) When a free-list leaf page is reused, its content is not read
58802 ** from the database or written to the journal file (why should it
58803 ** be, if it is not at all meaningful?).
58804 **
58805 ** By themselves, these optimizations work fine and provide a handy
58806 ** performance boost to bulk delete or insert operations. However, if
58807 ** a page is moved to the free-list and then reused within the same
58808 ** transaction, a problem comes up. If the page is not journalled when
58809 ** it is moved to the free-list and it is also not journalled when it
58810 ** is extracted from the free-list and reused, then the original data
58811 ** may be lost. In the event of a rollback, it may not be possible
58812 ** to restore the database to its original configuration.
58813 **
58814 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
58815 ** moved to become a free-list leaf page, the corresponding bit is
58816 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
58817 ** optimization 2 above is omitted if the corresponding bit is already
58818 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
58819 ** at the end of every transaction.
58820 */
58821 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
58822  int rc = SQLITE_OK;
58823  if( !pBt->pHasContent ){
58824  assert( pgno<=pBt->nPage );
58825  pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
58826  if( !pBt->pHasContent ){
58827  rc = SQLITE_NOMEM_BKPT;
58828  }
58829  }
58830  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
58831  rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
58832  }
58833  return rc;
58834 }
58835 
58836 /*
58837 ** Query the BtShared.pHasContent vector.
58838 **
58839 ** This function is called when a free-list leaf page is removed from the
58840 ** free-list for reuse. It returns false if it is safe to retrieve the
58841 ** page from the pager layer with the 'no-content' flag set. True otherwise.
58842 */
58843 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
58844  Bitvec *p = pBt->pHasContent;
58845  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
58846 }
58847 
58848 /*
58849 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
58850 ** invoked at the conclusion of each write-transaction.
58851 */
58852 static void btreeClearHasContent(BtShared *pBt){
58853  sqlite3BitvecDestroy(pBt->pHasContent);
58854  pBt->pHasContent = 0;
58855 }
58856 
58857 /*
58858 ** Release all of the apPage[] pages for a cursor.
58859 */
58860 static void btreeReleaseAllCursorPages(BtCursor *pCur){
58861  int i;
58862  for(i=0; i<=pCur->iPage; i++){
58863  releasePage(pCur->apPage[i]);
58864  pCur->apPage[i] = 0;
58865  }
58866  pCur->iPage = -1;
58867 }
58868 
58869 /*
58870 ** The cursor passed as the only argument must point to a valid entry
58871 ** when this function is called (i.e. have eState==CURSOR_VALID). This
58872 ** function saves the current cursor key in variables pCur->nKey and
58873 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
58874 ** code otherwise.
58875 **
58876 ** If the cursor is open on an intkey table, then the integer key
58877 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
58878 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
58879 ** set to point to a malloced buffer pCur->nKey bytes in size containing
58880 ** the key.
58881 */
58882 static int saveCursorKey(BtCursor *pCur){
58883  int rc = SQLITE_OK;
58884  assert( CURSOR_VALID==pCur->eState );
58885  assert( 0==pCur->pKey );
58886  assert( cursorHoldsMutex(pCur) );
58887 
58888  if( pCur->curIntKey ){
58889  /* Only the rowid is required for a table btree */
58890  pCur->nKey = sqlite3BtreeIntegerKey(pCur);
58891  }else{
58892  /* For an index btree, save the complete key content */
58893  void *pKey;
58894  pCur->nKey = sqlite3BtreePayloadSize(pCur);
58895  pKey = sqlite3Malloc( pCur->nKey );
58896  if( pKey ){
58897  rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
58898  if( rc==SQLITE_OK ){
58899  pCur->pKey = pKey;
58900  }else{
58901  sqlite3_free(pKey);
58902  }
58903  }else{
58904  rc = SQLITE_NOMEM_BKPT;
58905  }
58906  }
58907  assert( !pCur->curIntKey || !pCur->pKey );
58908  return rc;
58909 }
58910 
58911 /*
58912 ** Save the current cursor position in the variables BtCursor.nKey
58913 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
58914 **
58915 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
58916 ** prior to calling this routine.
58917 */
58918 static int saveCursorPosition(BtCursor *pCur){
58919  int rc;
58920 
58921  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
58922  assert( 0==pCur->pKey );
58923  assert( cursorHoldsMutex(pCur) );
58924 
58925  if( pCur->eState==CURSOR_SKIPNEXT ){
58926  pCur->eState = CURSOR_VALID;
58927  }else{
58928  pCur->skipNext = 0;
58929  }
58930 
58931  rc = saveCursorKey(pCur);
58932  if( rc==SQLITE_OK ){
58933  btreeReleaseAllCursorPages(pCur);
58934  pCur->eState = CURSOR_REQUIRESEEK;
58935  }
58936 
58937  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
58938  return rc;
58939 }
58940 
58941 /* Forward reference */
58942 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
58943 
58944 /*
58945 ** Save the positions of all cursors (except pExcept) that are open on
58946 ** the table with root-page iRoot. "Saving the cursor position" means that
58947 ** the location in the btree is remembered in such a way that it can be
58948 ** moved back to the same spot after the btree has been modified. This
58949 ** routine is called just before cursor pExcept is used to modify the
58950 ** table, for example in BtreeDelete() or BtreeInsert().
58951 **
58952 ** If there are two or more cursors on the same btree, then all such
58953 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
58954 ** routine enforces that rule. This routine only needs to be called in
58955 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
58956 **
58957 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
58958 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
58959 ** pointless call to this routine.
58960 **
58961 ** Implementation note: This routine merely checks to see if any cursors
58962 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
58963 ** event that cursors are in need to being saved.
58964 */
58965 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
58966  BtCursor *p;
58967  assert( sqlite3_mutex_held(pBt->mutex) );
58968  assert( pExcept==0 || pExcept->pBt==pBt );
58969  for(p=pBt->pCursor; p; p=p->pNext){
58970  if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
58971  }
58972  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
58973  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
58974  return SQLITE_OK;
58975 }
58976 
58977 /* This helper routine to saveAllCursors does the actual work of saving
58978 ** the cursors if and when a cursor is found that actually requires saving.
58979 ** The common case is that no cursors need to be saved, so this routine is
58980 ** broken out from its caller to avoid unnecessary stack pointer movement.
58981 */
58982 static int SQLITE_NOINLINE saveCursorsOnList(
58983  BtCursor *p, /* The first cursor that needs saving */
58984  Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
58985  BtCursor *pExcept /* Do not save this cursor */
58986 ){
58987  do{
58988  if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
58989  if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
58990  int rc = saveCursorPosition(p);
58991  if( SQLITE_OK!=rc ){
58992  return rc;
58993  }
58994  }else{
58995  testcase( p->iPage>0 );
58996  btreeReleaseAllCursorPages(p);
58997  }
58998  }
58999  p = p->pNext;
59000  }while( p );
59001  return SQLITE_OK;
59002 }
59003 
59004 /*
59005 ** Clear the current cursor position.
59006 */
59007 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
59008  assert( cursorHoldsMutex(pCur) );
59009  sqlite3_free(pCur->pKey);
59010  pCur->pKey = 0;
59011  pCur->eState = CURSOR_INVALID;
59012 }
59013 
59014 /*
59015 ** In this version of BtreeMoveto, pKey is a packed index record
59016 ** such as is generated by the OP_MakeRecord opcode. Unpack the
59017 ** record and then call BtreeMovetoUnpacked() to do the work.
59018 */
59019 static int btreeMoveto(
59020  BtCursor *pCur, /* Cursor open on the btree to be searched */
59021  const void *pKey, /* Packed key if the btree is an index */
59022  i64 nKey, /* Integer key for tables. Size of pKey for indices */
59023  int bias, /* Bias search to the high end */
59024  int *pRes /* Write search results here */
59025 ){
59026  int rc; /* Status code */
59027  UnpackedRecord *pIdxKey; /* Unpacked index key */
59028  char aSpace[384]; /* Temp space for pIdxKey - to avoid a malloc */
59029  char *pFree = 0;
59030 
59031  if( pKey ){
59032  assert( nKey==(i64)(int)nKey );
59033  pIdxKey = sqlite3VdbeAllocUnpackedRecord(
59034  pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
59035  );
59036  if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
59037  sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
59038  if( pIdxKey->nField==0 ){
59039  sqlite3DbFree(pCur->pKeyInfo->db, pFree);
59040  return SQLITE_CORRUPT_BKPT;
59041  }
59042  }else{
59043  pIdxKey = 0;
59044  }
59045  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
59046  if( pFree ){
59047  sqlite3DbFree(pCur->pKeyInfo->db, pFree);
59048  }
59049  return rc;
59050 }
59051 
59052 /*
59053 ** Restore the cursor to the position it was in (or as close to as possible)
59054 ** when saveCursorPosition() was called. Note that this call deletes the
59055 ** saved position info stored by saveCursorPosition(), so there can be
59056 ** at most one effective restoreCursorPosition() call after each
59057 ** saveCursorPosition().
59058 */
59059 static int btreeRestoreCursorPosition(BtCursor *pCur){
59060  int rc;
59061  int skipNext;
59062  assert( cursorOwnsBtShared(pCur) );
59063  assert( pCur->eState>=CURSOR_REQUIRESEEK );
59064  if( pCur->eState==CURSOR_FAULT ){
59065  return pCur->skipNext;
59066  }
59067  pCur->eState = CURSOR_INVALID;
59068  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
59069  if( rc==SQLITE_OK ){
59070  sqlite3_free(pCur->pKey);
59071  pCur->pKey = 0;
59072  assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
59073  pCur->skipNext |= skipNext;
59074  if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
59075  pCur->eState = CURSOR_SKIPNEXT;
59076  }
59077  }
59078  return rc;
59079 }
59080 
59081 #define restoreCursorPosition(p) \
59082  (p->eState>=CURSOR_REQUIRESEEK ? \
59083  btreeRestoreCursorPosition(p) : \
59084  SQLITE_OK)
59085 
59086 /*
59087 ** Determine whether or not a cursor has moved from the position where
59088 ** it was last placed, or has been invalidated for any other reason.
59089 ** Cursors can move when the row they are pointing at is deleted out
59090 ** from under them, for example. Cursor might also move if a btree
59091 ** is rebalanced.
59092 **
59093 ** Calling this routine with a NULL cursor pointer returns false.
59094 **
59095 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
59096 ** back to where it ought to be if this routine returns true.
59097 */
59098 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
59099  return pCur->eState!=CURSOR_VALID;
59100 }
59101 
59102 /*
59103 ** This routine restores a cursor back to its original position after it
59104 ** has been moved by some outside activity (such as a btree rebalance or
59105 ** a row having been deleted out from under the cursor).
59106 **
59107 ** On success, the *pDifferentRow parameter is false if the cursor is left
59108 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
59109 ** was pointing to has been deleted, forcing the cursor to point to some
59110 ** nearby row.
59111 **
59112 ** This routine should only be called for a cursor that just returned
59113 ** TRUE from sqlite3BtreeCursorHasMoved().
59114 */
59115 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
59116  int rc;
59117 
59118  assert( pCur!=0 );
59119  assert( pCur->eState!=CURSOR_VALID );
59120  rc = restoreCursorPosition(pCur);
59121  if( rc ){
59122  *pDifferentRow = 1;
59123  return rc;
59124  }
59125  if( pCur->eState!=CURSOR_VALID ){
59126  *pDifferentRow = 1;
59127  }else{
59128  assert( pCur->skipNext==0 );
59129  *pDifferentRow = 0;
59130  }
59131  return SQLITE_OK;
59132 }
59133 
59134 #ifdef SQLITE_ENABLE_CURSOR_HINTS
59135 /*
59136 ** Provide hints to the cursor. The particular hint given (and the type
59137 ** and number of the varargs parameters) is determined by the eHintType
59138 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
59139 */
59140 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
59141  /* Used only by system that substitute their own storage engine */
59142 }
59143 #endif
59144 
59145 /*
59146 ** Provide flag hints to the cursor.
59147 */
59148 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
59149  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
59150  pCur->hints = x;
59151 }
59152 
59153 
59154 #ifndef SQLITE_OMIT_AUTOVACUUM
59155 /*
59156 ** Given a page number of a regular database page, return the page
59157 ** number for the pointer-map page that contains the entry for the
59158 ** input page number.
59159 **
59160 ** Return 0 (not a valid page) for pgno==1 since there is
59161 ** no pointer map associated with page 1. The integrity_check logic
59162 ** requires that ptrmapPageno(*,1)!=1.
59163 */
59164 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
59165  int nPagesPerMapPage;
59166  Pgno iPtrMap, ret;
59167  assert( sqlite3_mutex_held(pBt->mutex) );
59168  if( pgno<2 ) return 0;
59169  nPagesPerMapPage = (pBt->usableSize/5)+1;
59170  iPtrMap = (pgno-2)/nPagesPerMapPage;
59171  ret = (iPtrMap*nPagesPerMapPage) + 2;
59172  if( ret==PENDING_BYTE_PAGE(pBt) ){
59173  ret++;
59174  }
59175  return ret;
59176 }
59177 
59178 /*
59179 ** Write an entry into the pointer map.
59180 **
59181 ** This routine updates the pointer map entry for page number 'key'
59182 ** so that it maps to type 'eType' and parent page number 'pgno'.
59183 **
59184 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
59185 ** a no-op. If an error occurs, the appropriate error code is written
59186 ** into *pRC.
59187 */
59188 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
59189  DbPage *pDbPage; /* The pointer map page */
59190  u8 *pPtrmap; /* The pointer map data */
59191  Pgno iPtrmap; /* The pointer map page number */
59192  int offset; /* Offset in pointer map page */
59193  int rc; /* Return code from subfunctions */
59194 
59195  if( *pRC ) return;
59196 
59197  assert( sqlite3_mutex_held(pBt->mutex) );
59198  /* The master-journal page number must never be used as a pointer map page */
59199  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
59200 
59201  assert( pBt->autoVacuum );
59202  if( key==0 ){
59203  *pRC = SQLITE_CORRUPT_BKPT;
59204  return;
59205  }
59206  iPtrmap = PTRMAP_PAGENO(pBt, key);
59207  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59208  if( rc!=SQLITE_OK ){
59209  *pRC = rc;
59210  return;
59211  }
59212  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59213  if( offset<0 ){
59214  *pRC = SQLITE_CORRUPT_BKPT;
59215  goto ptrmap_exit;
59216  }
59217  assert( offset <= (int)pBt->usableSize-5 );
59218  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59219 
59220  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
59221  TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
59222  *pRC= rc = sqlite3PagerWrite(pDbPage);
59223  if( rc==SQLITE_OK ){
59224  pPtrmap[offset] = eType;
59225  put4byte(&pPtrmap[offset+1], parent);
59226  }
59227  }
59228 
59229 ptrmap_exit:
59230  sqlite3PagerUnref(pDbPage);
59231 }
59232 
59233 /*
59234 ** Read an entry from the pointer map.
59235 **
59236 ** This routine retrieves the pointer map entry for page 'key', writing
59237 ** the type and parent page number to *pEType and *pPgno respectively.
59238 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
59239 */
59240 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
59241  DbPage *pDbPage; /* The pointer map page */
59242  int iPtrmap; /* Pointer map page index */
59243  u8 *pPtrmap; /* Pointer map page data */
59244  int offset; /* Offset of entry in pointer map */
59245  int rc;
59246 
59247  assert( sqlite3_mutex_held(pBt->mutex) );
59248 
59249  iPtrmap = PTRMAP_PAGENO(pBt, key);
59250  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59251  if( rc!=0 ){
59252  return rc;
59253  }
59254  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59255 
59256  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59257  if( offset<0 ){
59258  sqlite3PagerUnref(pDbPage);
59259  return SQLITE_CORRUPT_BKPT;
59260  }
59261  assert( offset <= (int)pBt->usableSize-5 );
59262  assert( pEType!=0 );
59263  *pEType = pPtrmap[offset];
59264  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
59265 
59266  sqlite3PagerUnref(pDbPage);
59267  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
59268  return SQLITE_OK;
59269 }
59270 
59271 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
59272  #define ptrmapPut(w,x,y,z,rc)
59273  #define ptrmapGet(w,x,y,z) SQLITE_OK
59274  #define ptrmapPutOvflPtr(x, y, rc)
59275 #endif
59276 
59277 /*
59278 ** Given a btree page and a cell index (0 means the first cell on
59279 ** the page, 1 means the second cell, and so forth) return a pointer
59280 ** to the cell content.
59281 **
59282 ** findCellPastPtr() does the same except it skips past the initial
59283 ** 4-byte child pointer found on interior pages, if there is one.
59284 **
59285 ** This routine works only for pages that do not contain overflow cells.
59286 */
59287 #define findCell(P,I) \
59288  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59289 #define findCellPastPtr(P,I) \
59290  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59291 
59292 
59293 /*
59294 ** This is common tail processing for btreeParseCellPtr() and
59295 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
59296 ** on a single B-tree page. Make necessary adjustments to the CellInfo
59297 ** structure.
59298 */
59299 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
59300  MemPage *pPage, /* Page containing the cell */
59301  u8 *pCell, /* Pointer to the cell text. */
59302  CellInfo *pInfo /* Fill in this structure */
59303 ){
59304  /* If the payload will not fit completely on the local page, we have
59305  ** to decide how much to store locally and how much to spill onto
59306  ** overflow pages. The strategy is to minimize the amount of unused
59307  ** space on overflow pages while keeping the amount of local storage
59308  ** in between minLocal and maxLocal.
59309  **
59310  ** Warning: changing the way overflow payload is distributed in any
59311  ** way will result in an incompatible file format.
59312  */
59313  int minLocal; /* Minimum amount of payload held locally */
59314  int maxLocal; /* Maximum amount of payload held locally */
59315  int surplus; /* Overflow payload available for local storage */
59316 
59317  minLocal = pPage->minLocal;
59318  maxLocal = pPage->maxLocal;
59319  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
59320  testcase( surplus==maxLocal );
59321  testcase( surplus==maxLocal+1 );
59322  if( surplus <= maxLocal ){
59323  pInfo->nLocal = (u16)surplus;
59324  }else{
59325  pInfo->nLocal = (u16)minLocal;
59326  }
59327  pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
59328 }
59329 
59330 /*
59331 ** The following routines are implementations of the MemPage.xParseCell()
59332 ** method.
59333 **
59334 ** Parse a cell content block and fill in the CellInfo structure.
59335 **
59336 ** btreeParseCellPtr() => table btree leaf nodes
59337 ** btreeParseCellNoPayload() => table btree internal nodes
59338 ** btreeParseCellPtrIndex() => index btree nodes
59339 **
59340 ** There is also a wrapper function btreeParseCell() that works for
59341 ** all MemPage types and that references the cell by index rather than
59342 ** by pointer.
59343 */
59344 static void btreeParseCellPtrNoPayload(
59345  MemPage *pPage, /* Page containing the cell */
59346  u8 *pCell, /* Pointer to the cell text. */
59347  CellInfo *pInfo /* Fill in this structure */
59348 ){
59349  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59350  assert( pPage->leaf==0 );
59351  assert( pPage->childPtrSize==4 );
59352 #ifndef SQLITE_DEBUG
59353  UNUSED_PARAMETER(pPage);
59354 #endif
59355  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
59356  pInfo->nPayload = 0;
59357  pInfo->nLocal = 0;
59358  pInfo->pPayload = 0;
59359  return;
59360 }
59361 static void btreeParseCellPtr(
59362  MemPage *pPage, /* Page containing the cell */
59363  u8 *pCell, /* Pointer to the cell text. */
59364  CellInfo *pInfo /* Fill in this structure */
59365 ){
59366  u8 *pIter; /* For scanning through pCell */
59367  u32 nPayload; /* Number of bytes of cell payload */
59368  u64 iKey; /* Extracted Key value */
59369 
59370  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59371  assert( pPage->leaf==0 || pPage->leaf==1 );
59372  assert( pPage->intKeyLeaf );
59373  assert( pPage->childPtrSize==0 );
59374  pIter = pCell;
59375 
59376  /* The next block of code is equivalent to:
59377  **
59378  ** pIter += getVarint32(pIter, nPayload);
59379  **
59380  ** The code is inlined to avoid a function call.
59381  */
59382  nPayload = *pIter;
59383  if( nPayload>=0x80 ){
59384  u8 *pEnd = &pIter[8];
59385  nPayload &= 0x7f;
59386  do{
59387  nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59388  }while( (*pIter)>=0x80 && pIter<pEnd );
59389  }
59390  pIter++;
59391 
59392  /* The next block of code is equivalent to:
59393  **
59394  ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
59395  **
59396  ** The code is inlined to avoid a function call.
59397  */
59398  iKey = *pIter;
59399  if( iKey>=0x80 ){
59400  u8 *pEnd = &pIter[7];
59401  iKey &= 0x7f;
59402  while(1){
59403  iKey = (iKey<<7) | (*++pIter & 0x7f);
59404  if( (*pIter)<0x80 ) break;
59405  if( pIter>=pEnd ){
59406  iKey = (iKey<<8) | *++pIter;
59407  break;
59408  }
59409  }
59410  }
59411  pIter++;
59412 
59413  pInfo->nKey = *(i64*)&iKey;
59414  pInfo->nPayload = nPayload;
59415  pInfo->pPayload = pIter;
59416  testcase( nPayload==pPage->maxLocal );
59417  testcase( nPayload==pPage->maxLocal+1 );
59418  if( nPayload<=pPage->maxLocal ){
59419  /* This is the (easy) common case where the entire payload fits
59420  ** on the local page. No overflow is required.
59421  */
59422  pInfo->nSize = nPayload + (u16)(pIter - pCell);
59423  if( pInfo->nSize<4 ) pInfo->nSize = 4;
59424  pInfo->nLocal = (u16)nPayload;
59425  }else{
59426  btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59427  }
59428 }
59429 static void btreeParseCellPtrIndex(
59430  MemPage *pPage, /* Page containing the cell */
59431  u8 *pCell, /* Pointer to the cell text. */
59432  CellInfo *pInfo /* Fill in this structure */
59433 ){
59434  u8 *pIter; /* For scanning through pCell */
59435  u32 nPayload; /* Number of bytes of cell payload */
59436 
59437  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59438  assert( pPage->leaf==0 || pPage->leaf==1 );
59439  assert( pPage->intKeyLeaf==0 );
59440  pIter = pCell + pPage->childPtrSize;
59441  nPayload = *pIter;
59442  if( nPayload>=0x80 ){
59443  u8 *pEnd = &pIter[8];
59444  nPayload &= 0x7f;
59445  do{
59446  nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59447  }while( *(pIter)>=0x80 && pIter<pEnd );
59448  }
59449  pIter++;
59450  pInfo->nKey = nPayload;
59451  pInfo->nPayload = nPayload;
59452  pInfo->pPayload = pIter;
59453  testcase( nPayload==pPage->maxLocal );
59454  testcase( nPayload==pPage->maxLocal+1 );
59455  if( nPayload<=pPage->maxLocal ){
59456  /* This is the (easy) common case where the entire payload fits
59457  ** on the local page. No overflow is required.
59458  */
59459  pInfo->nSize = nPayload + (u16)(pIter - pCell);
59460  if( pInfo->nSize<4 ) pInfo->nSize = 4;
59461  pInfo->nLocal = (u16)nPayload;
59462  }else{
59463  btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59464  }
59465 }
59466 static void btreeParseCell(
59467  MemPage *pPage, /* Page containing the cell */
59468  int iCell, /* The cell index. First cell is 0 */
59469  CellInfo *pInfo /* Fill in this structure */
59470 ){
59471  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
59472 }
59473 
59474 /*
59475 ** The following routines are implementations of the MemPage.xCellSize
59476 ** method.
59477 **
59478 ** Compute the total number of bytes that a Cell needs in the cell
59479 ** data area of the btree-page. The return number includes the cell
59480 ** data header and the local payload, but not any overflow page or
59481 ** the space used by the cell pointer.
59482 **
59483 ** cellSizePtrNoPayload() => table internal nodes
59484 ** cellSizePtr() => all index nodes & table leaf nodes
59485 */
59486 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
59487  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
59488  u8 *pEnd; /* End mark for a varint */
59489  u32 nSize; /* Size value to return */
59490 
59491 #ifdef SQLITE_DEBUG
59492  /* The value returned by this function should always be the same as
59493  ** the (CellInfo.nSize) value found by doing a full parse of the
59494  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59495  ** this function verifies that this invariant is not violated. */
59496  CellInfo debuginfo;
59497  pPage->xParseCell(pPage, pCell, &debuginfo);
59498 #endif
59499 
59500  nSize = *pIter;
59501  if( nSize>=0x80 ){
59502  pEnd = &pIter[8];
59503  nSize &= 0x7f;
59504  do{
59505  nSize = (nSize<<7) | (*++pIter & 0x7f);
59506  }while( *(pIter)>=0x80 && pIter<pEnd );
59507  }
59508  pIter++;
59509  if( pPage->intKey ){
59510  /* pIter now points at the 64-bit integer key value, a variable length
59511  ** integer. The following block moves pIter to point at the first byte
59512  ** past the end of the key value. */
59513  pEnd = &pIter[9];
59514  while( (*pIter++)&0x80 && pIter<pEnd );
59515  }
59516  testcase( nSize==pPage->maxLocal );
59517  testcase( nSize==pPage->maxLocal+1 );
59518  if( nSize<=pPage->maxLocal ){
59519  nSize += (u32)(pIter - pCell);
59520  if( nSize<4 ) nSize = 4;
59521  }else{
59522  int minLocal = pPage->minLocal;
59523  nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
59524  testcase( nSize==pPage->maxLocal );
59525  testcase( nSize==pPage->maxLocal+1 );
59526  if( nSize>pPage->maxLocal ){
59527  nSize = minLocal;
59528  }
59529  nSize += 4 + (u16)(pIter - pCell);
59530  }
59531  assert( nSize==debuginfo.nSize || CORRUPT_DB );
59532  return (u16)nSize;
59533 }
59534 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
59535  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
59536  u8 *pEnd; /* End mark for a varint */
59537 
59538 #ifdef SQLITE_DEBUG
59539  /* The value returned by this function should always be the same as
59540  ** the (CellInfo.nSize) value found by doing a full parse of the
59541  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59542  ** this function verifies that this invariant is not violated. */
59543  CellInfo debuginfo;
59544  pPage->xParseCell(pPage, pCell, &debuginfo);
59545 #else
59546  UNUSED_PARAMETER(pPage);
59547 #endif
59548 
59549  assert( pPage->childPtrSize==4 );
59550  pEnd = pIter + 9;
59551  while( (*pIter++)&0x80 && pIter<pEnd );
59552  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
59553  return (u16)(pIter - pCell);
59554 }
59555 
59556 
59557 #ifdef SQLITE_DEBUG
59558 /* This variation on cellSizePtr() is used inside of assert() statements
59559 ** only. */
59560 static u16 cellSize(MemPage *pPage, int iCell){
59561  return pPage->xCellSize(pPage, findCell(pPage, iCell));
59562 }
59563 #endif
59564 
59565 #ifndef SQLITE_OMIT_AUTOVACUUM
59566 /*
59567 ** If the cell pCell, part of page pPage contains a pointer
59568 ** to an overflow page, insert an entry into the pointer-map
59569 ** for the overflow page.
59570 */
59571 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
59572  CellInfo info;
59573  if( *pRC ) return;
59574  assert( pCell!=0 );
59575  pPage->xParseCell(pPage, pCell, &info);
59576  if( info.nLocal<info.nPayload ){
59577  Pgno ovfl = get4byte(&pCell[info.nSize-4]);
59578  ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
59579  }
59580 }
59581 #endif
59582 
59583 
59584 /*
59585 ** Defragment the page given. All Cells are moved to the
59586 ** end of the page and all free space is collected into one
59587 ** big FreeBlk that occurs in between the header and cell
59588 ** pointer array and the cell content area.
59589 **
59590 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
59591 ** b-tree page so that there are no freeblocks or fragment bytes, all
59592 ** unused bytes are contained in the unallocated space region, and all
59593 ** cells are packed tightly at the end of the page.
59594 */
59595 static int defragmentPage(MemPage *pPage){
59596  int i; /* Loop counter */
59597  int pc; /* Address of the i-th cell */
59598  int hdr; /* Offset to the page header */
59599  int size; /* Size of a cell */
59600  int usableSize; /* Number of usable bytes on a page */
59601  int cellOffset; /* Offset to the cell pointer array */
59602  int cbrk; /* Offset to the cell content area */
59603  int nCell; /* Number of cells on the page */
59604  unsigned char *data; /* The page data */
59605  unsigned char *temp; /* Temp area for cell content */
59606  unsigned char *src; /* Source of content */
59607  int iCellFirst; /* First allowable cell index */
59608  int iCellLast; /* Last possible cell index */
59609 
59610 
59611  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59612  assert( pPage->pBt!=0 );
59613  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
59614  assert( pPage->nOverflow==0 );
59615  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59616  temp = 0;
59617  src = data = pPage->aData;
59618  hdr = pPage->hdrOffset;
59619  cellOffset = pPage->cellOffset;
59620  nCell = pPage->nCell;
59621  assert( nCell==get2byte(&data[hdr+3]) );
59622  usableSize = pPage->pBt->usableSize;
59623  cbrk = usableSize;
59624  iCellFirst = cellOffset + 2*nCell;
59625  iCellLast = usableSize - 4;
59626  for(i=0; i<nCell; i++){
59627  u8 *pAddr; /* The i-th cell pointer */
59628  pAddr = &data[cellOffset + i*2];
59629  pc = get2byte(pAddr);
59630  testcase( pc==iCellFirst );
59631  testcase( pc==iCellLast );
59632  /* These conditions have already been verified in btreeInitPage()
59633  ** if PRAGMA cell_size_check=ON.
59634  */
59635  if( pc<iCellFirst || pc>iCellLast ){
59636  return SQLITE_CORRUPT_BKPT;
59637  }
59638  assert( pc>=iCellFirst && pc<=iCellLast );
59639  size = pPage->xCellSize(pPage, &src[pc]);
59640  cbrk -= size;
59641  if( cbrk<iCellFirst || pc+size>usableSize ){
59642  return SQLITE_CORRUPT_BKPT;
59643  }
59644  assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
59645  testcase( cbrk+size==usableSize );
59646  testcase( pc+size==usableSize );
59647  put2byte(pAddr, cbrk);
59648  if( temp==0 ){
59649  int x;
59650  if( cbrk==pc ) continue;
59651  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
59652  x = get2byte(&data[hdr+5]);
59653  memcpy(&temp[x], &data[x], (cbrk+size) - x);
59654  src = temp;
59655  }
59656  memcpy(&data[cbrk], &src[pc], size);
59657  }
59658  assert( cbrk>=iCellFirst );
59659  put2byte(&data[hdr+5], cbrk);
59660  data[hdr+1] = 0;
59661  data[hdr+2] = 0;
59662  data[hdr+7] = 0;
59663  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
59664  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59665  if( cbrk-iCellFirst!=pPage->nFree ){
59666  return SQLITE_CORRUPT_BKPT;
59667  }
59668  return SQLITE_OK;
59669 }
59670 
59671 /*
59672 ** Search the free-list on page pPg for space to store a cell nByte bytes in
59673 ** size. If one can be found, return a pointer to the space and remove it
59674 ** from the free-list.
59675 **
59676 ** If no suitable space can be found on the free-list, return NULL.
59677 **
59678 ** This function may detect corruption within pPg. If corruption is
59679 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
59680 **
59681 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
59682 ** will be ignored if adding the extra space to the fragmentation count
59683 ** causes the fragmentation count to exceed 60.
59684 */
59685 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
59686  const int hdr = pPg->hdrOffset;
59687  u8 * const aData = pPg->aData;
59688  int iAddr = hdr + 1;
59689  int pc = get2byte(&aData[iAddr]);
59690  int x;
59691  int usableSize = pPg->pBt->usableSize;
59692 
59693  assert( pc>0 );
59694  do{
59695  int size; /* Size of the free slot */
59696  /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
59697  ** increasing offset. */
59698  if( pc>usableSize-4 || pc<iAddr+4 ){
59699  *pRc = SQLITE_CORRUPT_BKPT;
59700  return 0;
59701  }
59702  /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
59703  ** freeblock form a big-endian integer which is the size of the freeblock
59704  ** in bytes, including the 4-byte header. */
59705  size = get2byte(&aData[pc+2]);
59706  if( (x = size - nByte)>=0 ){
59707  testcase( x==4 );
59708  testcase( x==3 );
59709  if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
59710  *pRc = SQLITE_CORRUPT_BKPT;
59711  return 0;
59712  }else if( x<4 ){
59713  /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
59714  ** number of bytes in fragments may not exceed 60. */
59715  if( aData[hdr+7]>57 ) return 0;
59716 
59717  /* Remove the slot from the free-list. Update the number of
59718  ** fragmented bytes within the page. */
59719  memcpy(&aData[iAddr], &aData[pc], 2);
59720  aData[hdr+7] += (u8)x;
59721  }else{
59722  /* The slot remains on the free-list. Reduce its size to account
59723  ** for the portion used by the new allocation. */
59724  put2byte(&aData[pc+2], x);
59725  }
59726  return &aData[pc + x];
59727  }
59728  iAddr = pc;
59729  pc = get2byte(&aData[pc]);
59730  }while( pc );
59731 
59732  return 0;
59733 }
59734 
59735 /*
59736 ** Allocate nByte bytes of space from within the B-Tree page passed
59737 ** as the first argument. Write into *pIdx the index into pPage->aData[]
59738 ** of the first byte of allocated space. Return either SQLITE_OK or
59739 ** an error code (usually SQLITE_CORRUPT).
59740 **
59741 ** The caller guarantees that there is sufficient space to make the
59742 ** allocation. This routine might need to defragment in order to bring
59743 ** all the space together, however. This routine will avoid using
59744 ** the first two bytes past the cell pointer area since presumably this
59745 ** allocation is being made in order to insert a new cell, so we will
59746 ** also end up needing a new cell pointer.
59747 */
59748 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
59749  const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
59750  u8 * const data = pPage->aData; /* Local cache of pPage->aData */
59751  int top; /* First byte of cell content area */
59752  int rc = SQLITE_OK; /* Integer return code */
59753  int gap; /* First byte of gap between cell pointers and cell content */
59754 
59755  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59756  assert( pPage->pBt );
59757  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59758  assert( nByte>=0 ); /* Minimum cell size is 4 */
59759  assert( pPage->nFree>=nByte );
59760  assert( pPage->nOverflow==0 );
59761  assert( nByte < (int)(pPage->pBt->usableSize-8) );
59762 
59763  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
59764  gap = pPage->cellOffset + 2*pPage->nCell;
59765  assert( gap<=65536 );
59766  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
59767  ** and the reserved space is zero (the usual value for reserved space)
59768  ** then the cell content offset of an empty page wants to be 65536.
59769  ** However, that integer is too large to be stored in a 2-byte unsigned
59770  ** integer, so a value of 0 is used in its place. */
59771  top = get2byte(&data[hdr+5]);
59772  assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
59773  if( gap>top ){
59774  if( top==0 && pPage->pBt->usableSize==65536 ){
59775  top = 65536;
59776  }else{
59777  return SQLITE_CORRUPT_BKPT;
59778  }
59779  }
59780 
59781  /* If there is enough space between gap and top for one more cell pointer
59782  ** array entry offset, and if the freelist is not empty, then search the
59783  ** freelist looking for a free slot big enough to satisfy the request.
59784  */
59785  testcase( gap+2==top );
59786  testcase( gap+1==top );
59787  testcase( gap==top );
59788  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
59789  u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
59790  if( pSpace ){
59791  assert( pSpace>=data && (pSpace - data)<65536 );
59792  *pIdx = (int)(pSpace - data);
59793  return SQLITE_OK;
59794  }else if( rc ){
59795  return rc;
59796  }
59797  }
59798 
59799  /* The request could not be fulfilled using a freelist slot. Check
59800  ** to see if defragmentation is necessary.
59801  */
59802  testcase( gap+2+nByte==top );
59803  if( gap+2+nByte>top ){
59804  assert( pPage->nCell>0 || CORRUPT_DB );
59805  rc = defragmentPage(pPage);
59806  if( rc ) return rc;
59807  top = get2byteNotZero(&data[hdr+5]);
59808  assert( gap+nByte<=top );
59809  }
59810 
59811 
59812  /* Allocate memory from the gap in between the cell pointer array
59813  ** and the cell content area. The btreeInitPage() call has already
59814  ** validated the freelist. Given that the freelist is valid, there
59815  ** is no way that the allocation can extend off the end of the page.
59816  ** The assert() below verifies the previous sentence.
59817  */
59818  top -= nByte;
59819  put2byte(&data[hdr+5], top);
59820  assert( top+nByte <= (int)pPage->pBt->usableSize );
59821  *pIdx = top;
59822  return SQLITE_OK;
59823 }
59824 
59825 /*
59826 ** Return a section of the pPage->aData to the freelist.
59827 ** The first byte of the new free block is pPage->aData[iStart]
59828 ** and the size of the block is iSize bytes.
59829 **
59830 ** Adjacent freeblocks are coalesced.
59831 **
59832 ** Note that even though the freeblock list was checked by btreeInitPage(),
59833 ** that routine will not detect overlap between cells or freeblocks. Nor
59834 ** does it detect cells or freeblocks that encrouch into the reserved bytes
59835 ** at the end of the page. So do additional corruption checks inside this
59836 ** routine and return SQLITE_CORRUPT if any problems are found.
59837 */
59838 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
59839  u16 iPtr; /* Address of ptr to next freeblock */
59840  u16 iFreeBlk; /* Address of the next freeblock */
59841  u8 hdr; /* Page header size. 0 or 100 */
59842  u8 nFrag = 0; /* Reduction in fragmentation */
59843  u16 iOrigSize = iSize; /* Original value of iSize */
59844  u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
59845  u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
59846  unsigned char *data = pPage->aData; /* Page content */
59847 
59848  assert( pPage->pBt!=0 );
59849  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59850  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
59851  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
59852  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59853  assert( iSize>=4 ); /* Minimum cell size is 4 */
59854  assert( iStart<=iLast );
59855 
59856  /* Overwrite deleted information with zeros when the secure_delete
59857  ** option is enabled */
59858  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
59859  memset(&data[iStart], 0, iSize);
59860  }
59861 
59862  /* The list of freeblocks must be in ascending order. Find the
59863  ** spot on the list where iStart should be inserted.
59864  */
59865  hdr = pPage->hdrOffset;
59866  iPtr = hdr + 1;
59867  if( data[iPtr+1]==0 && data[iPtr]==0 ){
59868  iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
59869  }else{
59870  while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
59871  if( iFreeBlk<iPtr+4 ){
59872  if( iFreeBlk==0 ) break;
59873  return SQLITE_CORRUPT_BKPT;
59874  }
59875  iPtr = iFreeBlk;
59876  }
59877  if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
59878  assert( iFreeBlk>iPtr || iFreeBlk==0 );
59879 
59880  /* At this point:
59881  ** iFreeBlk: First freeblock after iStart, or zero if none
59882  ** iPtr: The address of a pointer to iFreeBlk
59883  **
59884  ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
59885  */
59886  if( iFreeBlk && iEnd+3>=iFreeBlk ){
59887  nFrag = iFreeBlk - iEnd;
59888  if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
59889  iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
59890  if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
59891  iSize = iEnd - iStart;
59892  iFreeBlk = get2byte(&data[iFreeBlk]);
59893  }
59894 
59895  /* If iPtr is another freeblock (that is, if iPtr is not the freelist
59896  ** pointer in the page header) then check to see if iStart should be
59897  ** coalesced onto the end of iPtr.
59898  */
59899  if( iPtr>hdr+1 ){
59900  int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
59901  if( iPtrEnd+3>=iStart ){
59902  if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
59903  nFrag += iStart - iPtrEnd;
59904  iSize = iEnd - iPtr;
59905  iStart = iPtr;
59906  }
59907  }
59908  if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
59909  data[hdr+7] -= nFrag;
59910  }
59911  if( iStart==get2byte(&data[hdr+5]) ){
59912  /* The new freeblock is at the beginning of the cell content area,
59913  ** so just extend the cell content area rather than create another
59914  ** freelist entry */
59915  if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
59916  put2byte(&data[hdr+1], iFreeBlk);
59917  put2byte(&data[hdr+5], iEnd);
59918  }else{
59919  /* Insert the new freeblock into the freelist */
59920  put2byte(&data[iPtr], iStart);
59921  put2byte(&data[iStart], iFreeBlk);
59922  put2byte(&data[iStart+2], iSize);
59923  }
59924  pPage->nFree += iOrigSize;
59925  return SQLITE_OK;
59926 }
59927 
59928 /*
59929 ** Decode the flags byte (the first byte of the header) for a page
59930 ** and initialize fields of the MemPage structure accordingly.
59931 **
59932 ** Only the following combinations are supported. Anything different
59933 ** indicates a corrupt database files:
59934 **
59935 ** PTF_ZERODATA
59936 ** PTF_ZERODATA | PTF_LEAF
59937 ** PTF_LEAFDATA | PTF_INTKEY
59938 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
59939 */
59940 static int decodeFlags(MemPage *pPage, int flagByte){
59941  BtShared *pBt; /* A copy of pPage->pBt */
59942 
59943  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
59944  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59945  pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
59946  flagByte &= ~PTF_LEAF;
59947  pPage->childPtrSize = 4-4*pPage->leaf;
59948  pPage->xCellSize = cellSizePtr;
59949  pBt = pPage->pBt;
59950  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
59951  /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
59952  ** interior table b-tree page. */
59953  assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
59954  /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
59955  ** leaf table b-tree page. */
59956  assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
59957  pPage->intKey = 1;
59958  if( pPage->leaf ){
59959  pPage->intKeyLeaf = 1;
59960  pPage->xParseCell = btreeParseCellPtr;
59961  }else{
59962  pPage->intKeyLeaf = 0;
59963  pPage->xCellSize = cellSizePtrNoPayload;
59964  pPage->xParseCell = btreeParseCellPtrNoPayload;
59965  }
59966  pPage->maxLocal = pBt->maxLeaf;
59967  pPage->minLocal = pBt->minLeaf;
59968  }else if( flagByte==PTF_ZERODATA ){
59969  /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
59970  ** interior index b-tree page. */
59971  assert( (PTF_ZERODATA)==2 );
59972  /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
59973  ** leaf index b-tree page. */
59974  assert( (PTF_ZERODATA|PTF_LEAF)==10 );
59975  pPage->intKey = 0;
59976  pPage->intKeyLeaf = 0;
59977  pPage->xParseCell = btreeParseCellPtrIndex;
59978  pPage->maxLocal = pBt->maxLocal;
59979  pPage->minLocal = pBt->minLocal;
59980  }else{
59981  /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
59982  ** an error. */
59983  return SQLITE_CORRUPT_BKPT;
59984  }
59985  pPage->max1bytePayload = pBt->max1bytePayload;
59986  return SQLITE_OK;
59987 }
59988 
59989 /*
59990 ** Initialize the auxiliary information for a disk block.
59991 **
59992 ** Return SQLITE_OK on success. If we see that the page does
59993 ** not contain a well-formed database page, then return
59994 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
59995 ** guarantee that the page is well-formed. It only shows that
59996 ** we failed to detect any corruption.
59997 */
59998 static int btreeInitPage(MemPage *pPage){
59999 
60000  assert( pPage->pBt!=0 );
60001  assert( pPage->pBt->db!=0 );
60002  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60003  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
60004  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
60005  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
60006 
60007  if( !pPage->isInit ){
60008  u16 pc; /* Address of a freeblock within pPage->aData[] */
60009  u8 hdr; /* Offset to beginning of page header */
60010  u8 *data; /* Equal to pPage->aData */
60011  BtShared *pBt; /* The main btree structure */
60012  int usableSize; /* Amount of usable space on each page */
60013  u16 cellOffset; /* Offset from start of page to first cell pointer */
60014  int nFree; /* Number of unused bytes on the page */
60015  int top; /* First byte of the cell content area */
60016  int iCellFirst; /* First allowable cell or freeblock offset */
60017  int iCellLast; /* Last possible cell or freeblock offset */
60018 
60019  pBt = pPage->pBt;
60020 
60021  hdr = pPage->hdrOffset;
60022  data = pPage->aData;
60023  /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
60024  ** the b-tree page type. */
60025  if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
60026  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
60027  pPage->maskPage = (u16)(pBt->pageSize - 1);
60028  pPage->nOverflow = 0;
60029  usableSize = pBt->usableSize;
60030  pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
60031  pPage->aDataEnd = &data[usableSize];
60032  pPage->aCellIdx = &data[cellOffset];
60033  pPage->aDataOfst = &data[pPage->childPtrSize];
60034  /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
60035  ** the start of the cell content area. A zero value for this integer is
60036  ** interpreted as 65536. */
60037  top = get2byteNotZero(&data[hdr+5]);
60038  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
60039  ** number of cells on the page. */
60040  pPage->nCell = get2byte(&data[hdr+3]);
60041  if( pPage->nCell>MX_CELL(pBt) ){
60042  /* To many cells for a single page. The page must be corrupt */
60043  return SQLITE_CORRUPT_BKPT;
60044  }
60045  testcase( pPage->nCell==MX_CELL(pBt) );
60046  /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
60047  ** possible for a root page of a table that contains no rows) then the
60048  ** offset to the cell content area will equal the page size minus the
60049  ** bytes of reserved space. */
60050  assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
60051 
60052  /* A malformed database page might cause us to read past the end
60053  ** of page when parsing a cell.
60054  **
60055  ** The following block of code checks early to see if a cell extends
60056  ** past the end of a page boundary and causes SQLITE_CORRUPT to be
60057  ** returned if it does.
60058  */
60059  iCellFirst = cellOffset + 2*pPage->nCell;
60060  iCellLast = usableSize - 4;
60061  if( pBt->db->flags & SQLITE_CellSizeCk ){
60062  int i; /* Index into the cell pointer array */
60063  int sz; /* Size of a cell */
60064 
60065  if( !pPage->leaf ) iCellLast--;
60066  for(i=0; i<pPage->nCell; i++){
60067  pc = get2byteAligned(&data[cellOffset+i*2]);
60068  testcase( pc==iCellFirst );
60069  testcase( pc==iCellLast );
60070  if( pc<iCellFirst || pc>iCellLast ){
60071  return SQLITE_CORRUPT_BKPT;
60072  }
60073  sz = pPage->xCellSize(pPage, &data[pc]);
60074  testcase( pc+sz==usableSize );
60075  if( pc+sz>usableSize ){
60076  return SQLITE_CORRUPT_BKPT;
60077  }
60078  }
60079  if( !pPage->leaf ) iCellLast++;
60080  }
60081 
60082  /* Compute the total free space on the page
60083  ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
60084  ** start of the first freeblock on the page, or is zero if there are no
60085  ** freeblocks. */
60086  pc = get2byte(&data[hdr+1]);
60087  nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
60088  while( pc>0 ){
60089  u16 next, size;
60090  if( pc<iCellFirst || pc>iCellLast ){
60091  /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
60092  ** always be at least one cell before the first freeblock.
60093  **
60094  ** Or, the freeblock is off the end of the page
60095  */
60096  return SQLITE_CORRUPT_BKPT;
60097  }
60098  next = get2byte(&data[pc]);
60099  size = get2byte(&data[pc+2]);
60100  if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
60101  /* Free blocks must be in ascending order. And the last byte of
60102  ** the free-block must lie on the database page. */
60103  return SQLITE_CORRUPT_BKPT;
60104  }
60105  nFree = nFree + size;
60106  pc = next;
60107  }
60108 
60109  /* At this point, nFree contains the sum of the offset to the start
60110  ** of the cell-content area plus the number of free bytes within
60111  ** the cell-content area. If this is greater than the usable-size
60112  ** of the page, then the page must be corrupted. This check also
60113  ** serves to verify that the offset to the start of the cell-content
60114  ** area, according to the page header, lies within the page.
60115  */
60116  if( nFree>usableSize ){
60117  return SQLITE_CORRUPT_BKPT;
60118  }
60119  pPage->nFree = (u16)(nFree - iCellFirst);
60120  pPage->isInit = 1;
60121  }
60122  return SQLITE_OK;
60123 }
60124 
60125 /*
60126 ** Set up a raw page so that it looks like a database page holding
60127 ** no entries.
60128 */
60129 static void zeroPage(MemPage *pPage, int flags){
60130  unsigned char *data = pPage->aData;
60131  BtShared *pBt = pPage->pBt;
60132  u8 hdr = pPage->hdrOffset;
60133  u16 first;
60134 
60135  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
60136  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60137  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
60138  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60139  assert( sqlite3_mutex_held(pBt->mutex) );
60140  if( pBt->btsFlags & BTS_SECURE_DELETE ){
60141  memset(&data[hdr], 0, pBt->usableSize - hdr);
60142  }
60143  data[hdr] = (char)flags;
60144  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
60145  memset(&data[hdr+1], 0, 4);
60146  data[hdr+7] = 0;
60147  put2byte(&data[hdr+5], pBt->usableSize);
60148  pPage->nFree = (u16)(pBt->usableSize - first);
60149  decodeFlags(pPage, flags);
60150  pPage->cellOffset = first;
60151  pPage->aDataEnd = &data[pBt->usableSize];
60152  pPage->aCellIdx = &data[first];
60153  pPage->aDataOfst = &data[pPage->childPtrSize];
60154  pPage->nOverflow = 0;
60155  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
60156  pPage->maskPage = (u16)(pBt->pageSize - 1);
60157  pPage->nCell = 0;
60158  pPage->isInit = 1;
60159 }
60160 
60161 
60162 /*
60163 ** Convert a DbPage obtained from the pager into a MemPage used by
60164 ** the btree layer.
60165 */
60166 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
60167  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60168  if( pgno!=pPage->pgno ){
60169  pPage->aData = sqlite3PagerGetData(pDbPage);
60170  pPage->pDbPage = pDbPage;
60171  pPage->pBt = pBt;
60172  pPage->pgno = pgno;
60173  pPage->hdrOffset = pgno==1 ? 100 : 0;
60174  }
60175  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
60176  return pPage;
60177 }
60178 
60179 /*
60180 ** Get a page from the pager. Initialize the MemPage.pBt and
60181 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
60182 **
60183 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
60184 ** about the content of the page at this time. So do not go to the disk
60185 ** to fetch the content. Just fill in the content with zeros for now.
60186 ** If in the future we call sqlite3PagerWrite() on this page, that
60187 ** means we have started to be concerned about content and the disk
60188 ** read should occur at that point.
60189 */
60190 static int btreeGetPage(
60191  BtShared *pBt, /* The btree */
60192  Pgno pgno, /* Number of the page to fetch */
60193  MemPage **ppPage, /* Return the page in this parameter */
60194  int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60195 ){
60196  int rc;
60197  DbPage *pDbPage;
60198 
60199  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
60200  assert( sqlite3_mutex_held(pBt->mutex) );
60201  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
60202  if( rc ) return rc;
60203  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
60204  return SQLITE_OK;
60205 }
60206 
60207 /*
60208 ** Retrieve a page from the pager cache. If the requested page is not
60209 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
60210 ** MemPage.aData elements if needed.
60211 */
60212 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
60213  DbPage *pDbPage;
60214  assert( sqlite3_mutex_held(pBt->mutex) );
60215  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
60216  if( pDbPage ){
60217  return btreePageFromDbPage(pDbPage, pgno, pBt);
60218  }
60219  return 0;
60220 }
60221 
60222 /*
60223 ** Return the size of the database file in pages. If there is any kind of
60224 ** error, return ((unsigned int)-1).
60225 */
60226 static Pgno btreePagecount(BtShared *pBt){
60227  return pBt->nPage;
60228 }
60229 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
60230  assert( sqlite3BtreeHoldsMutex(p) );
60231  assert( ((p->pBt->nPage)&0x8000000)==0 );
60232  return btreePagecount(p->pBt);
60233 }
60234 
60235 /*
60236 ** Get a page from the pager and initialize it.
60237 **
60238 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
60239 ** call. Do additional sanity checking on the page in this case.
60240 ** And if the fetch fails, this routine must decrement pCur->iPage.
60241 **
60242 ** The page is fetched as read-write unless pCur is not NULL and is
60243 ** a read-only cursor.
60244 **
60245 ** If an error occurs, then *ppPage is undefined. It
60246 ** may remain unchanged, or it may be set to an invalid value.
60247 */
60248 static int getAndInitPage(
60249  BtShared *pBt, /* The database file */
60250  Pgno pgno, /* Number of the page to get */
60251  MemPage **ppPage, /* Write the page pointer here */
60252  BtCursor *pCur, /* Cursor to receive the page, or NULL */
60253  int bReadOnly /* True for a read-only page */
60254 ){
60255  int rc;
60256  DbPage *pDbPage;
60257  assert( sqlite3_mutex_held(pBt->mutex) );
60258  assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
60259  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
60260  assert( pCur==0 || pCur->iPage>0 );
60261 
60262  if( pgno>btreePagecount(pBt) ){
60263  rc = SQLITE_CORRUPT_BKPT;
60264  goto getAndInitPage_error;
60265  }
60266  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
60267  if( rc ){
60268  goto getAndInitPage_error;
60269  }
60270  *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60271  if( (*ppPage)->isInit==0 ){
60272  btreePageFromDbPage(pDbPage, pgno, pBt);
60273  rc = btreeInitPage(*ppPage);
60274  if( rc!=SQLITE_OK ){
60275  releasePage(*ppPage);
60276  goto getAndInitPage_error;
60277  }
60278  }
60279  assert( (*ppPage)->pgno==pgno );
60280  assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
60281 
60282  /* If obtaining a child page for a cursor, we must verify that the page is
60283  ** compatible with the root page. */
60284  if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
60285  rc = SQLITE_CORRUPT_BKPT;
60286  releasePage(*ppPage);
60287  goto getAndInitPage_error;
60288  }
60289  return SQLITE_OK;
60290 
60291 getAndInitPage_error:
60292  if( pCur ) pCur->iPage--;
60293  testcase( pgno==0 );
60294  assert( pgno!=0 || rc==SQLITE_CORRUPT );
60295  return rc;
60296 }
60297 
60298 /*
60299 ** Release a MemPage. This should be called once for each prior
60300 ** call to btreeGetPage.
60301 */
60302 static void releasePageNotNull(MemPage *pPage){
60303  assert( pPage->aData );
60304  assert( pPage->pBt );
60305  assert( pPage->pDbPage!=0 );
60306  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60307  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
60308  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60309  sqlite3PagerUnrefNotNull(pPage->pDbPage);
60310 }
60311 static void releasePage(MemPage *pPage){
60312  if( pPage ) releasePageNotNull(pPage);
60313 }
60314 
60315 /*
60316 ** Get an unused page.
60317 **
60318 ** This works just like btreeGetPage() with the addition:
60319 **
60320 ** * If the page is already in use for some other purpose, immediately
60321 ** release it and return an SQLITE_CURRUPT error.
60322 ** * Make sure the isInit flag is clear
60323 */
60324 static int btreeGetUnusedPage(
60325  BtShared *pBt, /* The btree */
60326  Pgno pgno, /* Number of the page to fetch */
60327  MemPage **ppPage, /* Return the page in this parameter */
60328  int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60329 ){
60330  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
60331  if( rc==SQLITE_OK ){
60332  if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
60333  releasePage(*ppPage);
60334  *ppPage = 0;
60335  return SQLITE_CORRUPT_BKPT;
60336  }
60337  (*ppPage)->isInit = 0;
60338  }else{
60339  *ppPage = 0;
60340  }
60341  return rc;
60342 }
60343 
60344 
60345 /*
60346 ** During a rollback, when the pager reloads information into the cache
60347 ** so that the cache is restored to its original state at the start of
60348 ** the transaction, for each page restored this routine is called.
60349 **
60350 ** This routine needs to reset the extra data section at the end of the
60351 ** page to agree with the restored data.
60352 */
60353 static void pageReinit(DbPage *pData){
60354  MemPage *pPage;
60355  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
60356  assert( sqlite3PagerPageRefcount(pData)>0 );
60357  if( pPage->isInit ){
60358  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60359  pPage->isInit = 0;
60360  if( sqlite3PagerPageRefcount(pData)>1 ){
60361  /* pPage might not be a btree page; it might be an overflow page
60362  ** or ptrmap page or a free page. In those cases, the following
60363  ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
60364  ** But no harm is done by this. And it is very important that
60365  ** btreeInitPage() be called on every btree page so we make
60366  ** the call for every page that comes in for re-initing. */
60367  btreeInitPage(pPage);
60368  }
60369  }
60370 }
60371 
60372 /*
60373 ** Invoke the busy handler for a btree.
60374 */
60375 static int btreeInvokeBusyHandler(void *pArg){
60376  BtShared *pBt = (BtShared*)pArg;
60377  assert( pBt->db );
60378  assert( sqlite3_mutex_held(pBt->db->mutex) );
60379  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
60380 }
60381 
60382 /*
60383 ** Open a database file.
60384 **
60385 ** zFilename is the name of the database file. If zFilename is NULL
60386 ** then an ephemeral database is created. The ephemeral database might
60387 ** be exclusively in memory, or it might use a disk-based memory cache.
60388 ** Either way, the ephemeral database will be automatically deleted
60389 ** when sqlite3BtreeClose() is called.
60390 **
60391 ** If zFilename is ":memory:" then an in-memory database is created
60392 ** that is automatically destroyed when it is closed.
60393 **
60394 ** The "flags" parameter is a bitmask that might contain bits like
60395 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
60396 **
60397 ** If the database is already opened in the same database connection
60398 ** and we are in shared cache mode, then the open will fail with an
60399 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
60400 ** objects in the same database connection since doing so will lead
60401 ** to problems with locking.
60402 */
60403 SQLITE_PRIVATE int sqlite3BtreeOpen(
60404  sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
60405  const char *zFilename, /* Name of the file containing the BTree database */
60406  sqlite3 *db, /* Associated database handle */
60407  Btree **ppBtree, /* Pointer to new Btree object written here */
60408  int flags, /* Options */
60409  int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
60410 ){
60411  BtShared *pBt = 0; /* Shared part of btree structure */
60412  Btree *p; /* Handle to return */
60413  sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
60414  int rc = SQLITE_OK; /* Result code from this function */
60415  u8 nReserve; /* Byte of unused space on each page */
60416  unsigned char zDbHeader[100]; /* Database header content */
60417 
60418  /* True if opening an ephemeral, temporary database */
60419  const int isTempDb = zFilename==0 || zFilename[0]==0;
60420 
60421  /* Set the variable isMemdb to true for an in-memory database, or
60422  ** false for a file-based database.
60423  */
60424 #ifdef SQLITE_OMIT_MEMORYDB
60425  const int isMemdb = 0;
60426 #else
60427  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
60428  || (isTempDb && sqlite3TempInMemory(db))
60429  || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
60430 #endif
60431 
60432  assert( db!=0 );
60433  assert( pVfs!=0 );
60434  assert( sqlite3_mutex_held(db->mutex) );
60435  assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
60436 
60437  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
60438  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
60439 
60440  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
60441  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
60442 
60443  if( isMemdb ){
60444  flags |= BTREE_MEMORY;
60445  }
60446  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
60447  vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
60448  }
60449  p = sqlite3MallocZero(sizeof(Btree));
60450  if( !p ){
60451  return SQLITE_NOMEM_BKPT;
60452  }
60453  p->inTrans = TRANS_NONE;
60454  p->db = db;
60455 #ifndef SQLITE_OMIT_SHARED_CACHE
60456  p->lock.pBtree = p;
60457  p->lock.iTable = 1;
60458 #endif
60459 
60460 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60461  /*
60462  ** If this Btree is a candidate for shared cache, try to find an
60463  ** existing BtShared object that we can share with
60464  */
60465  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
60466  if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
60467  int nFilename = sqlite3Strlen30(zFilename)+1;
60468  int nFullPathname = pVfs->mxPathname+1;
60469  char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
60470  MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60471 
60472  p->sharable = 1;
60473  if( !zFullPathname ){
60474  sqlite3_free(p);
60475  return SQLITE_NOMEM_BKPT;
60476  }
60477  if( isMemdb ){
60478  memcpy(zFullPathname, zFilename, nFilename);
60479  }else{
60480  rc = sqlite3OsFullPathname(pVfs, zFilename,
60481  nFullPathname, zFullPathname);
60482  if( rc ){
60483  sqlite3_free(zFullPathname);
60484  sqlite3_free(p);
60485  return rc;
60486  }
60487  }
60488 #if SQLITE_THREADSAFE
60489  mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
60490  sqlite3_mutex_enter(mutexOpen);
60491  mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
60492  sqlite3_mutex_enter(mutexShared);
60493 #endif
60494  for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
60495  assert( pBt->nRef>0 );
60496  if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
60497  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
60498  int iDb;
60499  for(iDb=db->nDb-1; iDb>=0; iDb--){
60500  Btree *pExisting = db->aDb[iDb].pBt;
60501  if( pExisting && pExisting->pBt==pBt ){
60502  sqlite3_mutex_leave(mutexShared);
60503  sqlite3_mutex_leave(mutexOpen);
60504  sqlite3_free(zFullPathname);
60505  sqlite3_free(p);
60506  return SQLITE_CONSTRAINT;
60507  }
60508  }
60509  p->pBt = pBt;
60510  pBt->nRef++;
60511  break;
60512  }
60513  }
60514  sqlite3_mutex_leave(mutexShared);
60515  sqlite3_free(zFullPathname);
60516  }
60517 #ifdef SQLITE_DEBUG
60518  else{
60519  /* In debug mode, we mark all persistent databases as sharable
60520  ** even when they are not. This exercises the locking code and
60521  ** gives more opportunity for asserts(sqlite3_mutex_held())
60522  ** statements to find locking problems.
60523  */
60524  p->sharable = 1;
60525  }
60526 #endif
60527  }
60528 #endif
60529  if( pBt==0 ){
60530  /*
60531  ** The following asserts make sure that structures used by the btree are
60532  ** the right size. This is to guard against size changes that result
60533  ** when compiling on a different architecture.
60534  */
60535  assert( sizeof(i64)==8 );
60536  assert( sizeof(u64)==8 );
60537  assert( sizeof(u32)==4 );
60538  assert( sizeof(u16)==2 );
60539  assert( sizeof(Pgno)==4 );
60540 
60541  pBt = sqlite3MallocZero( sizeof(*pBt) );
60542  if( pBt==0 ){
60543  rc = SQLITE_NOMEM_BKPT;
60544  goto btree_open_out;
60545  }
60546  rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
60547  EXTRA_SIZE, flags, vfsFlags, pageReinit);
60548  if( rc==SQLITE_OK ){
60549  sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
60550  rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
60551  }
60552  if( rc!=SQLITE_OK ){
60553  goto btree_open_out;
60554  }
60555  pBt->openFlags = (u8)flags;
60556  pBt->db = db;
60557  sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
60558  p->pBt = pBt;
60559 
60560  pBt->pCursor = 0;
60561  pBt->pPage1 = 0;
60562  if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
60563 #ifdef SQLITE_SECURE_DELETE
60564  pBt->btsFlags |= BTS_SECURE_DELETE;
60565 #endif
60566  /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
60567  ** determined by the 2-byte integer located at an offset of 16 bytes from
60568  ** the beginning of the database file. */
60569  pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
60570  if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
60571  || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
60572  pBt->pageSize = 0;
60573 #ifndef SQLITE_OMIT_AUTOVACUUM
60574  /* If the magic name ":memory:" will create an in-memory database, then
60575  ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
60576  ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
60577  ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
60578  ** regular file-name. In this case the auto-vacuum applies as per normal.
60579  */
60580  if( zFilename && !isMemdb ){
60581  pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
60582  pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
60583  }
60584 #endif
60585  nReserve = 0;
60586  }else{
60587  /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
60588  ** determined by the one-byte unsigned integer found at an offset of 20
60589  ** into the database file header. */
60590  nReserve = zDbHeader[20];
60591  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60592 #ifndef SQLITE_OMIT_AUTOVACUUM
60593  pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
60594  pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
60595 #endif
60596  }
60597  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60598  if( rc ) goto btree_open_out;
60599  pBt->usableSize = pBt->pageSize - nReserve;
60600  assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
60601 
60602 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60603  /* Add the new BtShared object to the linked list sharable BtShareds.
60604  */
60605  pBt->nRef = 1;
60606  if( p->sharable ){
60607  MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60608  MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
60609  if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
60610  pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
60611  if( pBt->mutex==0 ){
60612  rc = SQLITE_NOMEM_BKPT;
60613  goto btree_open_out;
60614  }
60615  }
60616  sqlite3_mutex_enter(mutexShared);
60617  pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
60618  GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
60619  sqlite3_mutex_leave(mutexShared);
60620  }
60621 #endif
60622  }
60623 
60624 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60625  /* If the new Btree uses a sharable pBtShared, then link the new
60626  ** Btree into the list of all sharable Btrees for the same connection.
60627  ** The list is kept in ascending order by pBt address.
60628  */
60629  if( p->sharable ){
60630  int i;
60631  Btree *pSib;
60632  for(i=0; i<db->nDb; i++){
60633  if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
60634  while( pSib->pPrev ){ pSib = pSib->pPrev; }
60635  if( (uptr)p->pBt<(uptr)pSib->pBt ){
60636  p->pNext = pSib;
60637  p->pPrev = 0;
60638  pSib->pPrev = p;
60639  }else{
60640  while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
60641  pSib = pSib->pNext;
60642  }
60643  p->pNext = pSib->pNext;
60644  p->pPrev = pSib;
60645  if( p->pNext ){
60646  p->pNext->pPrev = p;
60647  }
60648  pSib->pNext = p;
60649  }
60650  break;
60651  }
60652  }
60653  }
60654 #endif
60655  *ppBtree = p;
60656 
60657 btree_open_out:
60658  if( rc!=SQLITE_OK ){
60659  if( pBt && pBt->pPager ){
60660  sqlite3PagerClose(pBt->pPager);
60661  }
60662  sqlite3_free(pBt);
60663  sqlite3_free(p);
60664  *ppBtree = 0;
60665  }else{
60666  /* If the B-Tree was successfully opened, set the pager-cache size to the
60667  ** default value. Except, when opening on an existing shared pager-cache,
60668  ** do not change the pager-cache size.
60669  */
60670  if( sqlite3BtreeSchema(p, 0, 0)==0 ){
60671  sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
60672  }
60673  }
60674  if( mutexOpen ){
60675  assert( sqlite3_mutex_held(mutexOpen) );
60676  sqlite3_mutex_leave(mutexOpen);
60677  }
60678  assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
60679  return rc;
60680 }
60681 
60682 /*
60683 ** Decrement the BtShared.nRef counter. When it reaches zero,
60684 ** remove the BtShared structure from the sharing list. Return
60685 ** true if the BtShared.nRef counter reaches zero and return
60686 ** false if it is still positive.
60687 */
60688 static int removeFromSharingList(BtShared *pBt){
60689 #ifndef SQLITE_OMIT_SHARED_CACHE
60690  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
60691  BtShared *pList;
60692  int removed = 0;
60693 
60694  assert( sqlite3_mutex_notheld(pBt->mutex) );
60695  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
60696  sqlite3_mutex_enter(pMaster);
60697  pBt->nRef--;
60698  if( pBt->nRef<=0 ){
60699  if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
60700  GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
60701  }else{
60702  pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
60703  while( ALWAYS(pList) && pList->pNext!=pBt ){
60704  pList=pList->pNext;
60705  }
60706  if( ALWAYS(pList) ){
60707  pList->pNext = pBt->pNext;
60708  }
60709  }
60710  if( SQLITE_THREADSAFE ){
60711  sqlite3_mutex_free(pBt->mutex);
60712  }
60713  removed = 1;
60714  }
60715  sqlite3_mutex_leave(pMaster);
60716  return removed;
60717 #else
60718  return 1;
60719 #endif
60720 }
60721 
60722 /*
60723 ** Make sure pBt->pTmpSpace points to an allocation of
60724 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
60725 ** pointer.
60726 */
60727 static void allocateTempSpace(BtShared *pBt){
60728  if( !pBt->pTmpSpace ){
60729  pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
60730 
60731  /* One of the uses of pBt->pTmpSpace is to format cells before
60732  ** inserting them into a leaf page (function fillInCell()). If
60733  ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
60734  ** by the various routines that manipulate binary cells. Which
60735  ** can mean that fillInCell() only initializes the first 2 or 3
60736  ** bytes of pTmpSpace, but that the first 4 bytes are copied from
60737  ** it into a database page. This is not actually a problem, but it
60738  ** does cause a valgrind error when the 1 or 2 bytes of unitialized
60739  ** data is passed to system call write(). So to avoid this error,
60740  ** zero the first 4 bytes of temp space here.
60741  **
60742  ** Also: Provide four bytes of initialized space before the
60743  ** beginning of pTmpSpace as an area available to prepend the
60744  ** left-child pointer to the beginning of a cell.
60745  */
60746  if( pBt->pTmpSpace ){
60747  memset(pBt->pTmpSpace, 0, 8);
60748  pBt->pTmpSpace += 4;
60749  }
60750  }
60751 }
60752 
60753 /*
60754 ** Free the pBt->pTmpSpace allocation
60755 */
60756 static void freeTempSpace(BtShared *pBt){
60757  if( pBt->pTmpSpace ){
60758  pBt->pTmpSpace -= 4;
60759  sqlite3PageFree(pBt->pTmpSpace);
60760  pBt->pTmpSpace = 0;
60761  }
60762 }
60763 
60764 /*
60765 ** Close an open database and invalidate all cursors.
60766 */
60767 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
60768  BtShared *pBt = p->pBt;
60769  BtCursor *pCur;
60770 
60771  /* Close all cursors opened via this handle. */
60772  assert( sqlite3_mutex_held(p->db->mutex) );
60773  sqlite3BtreeEnter(p);
60774  pCur = pBt->pCursor;
60775  while( pCur ){
60776  BtCursor *pTmp = pCur;
60777  pCur = pCur->pNext;
60778  if( pTmp->pBtree==p ){
60779  sqlite3BtreeCloseCursor(pTmp);
60780  }
60781  }
60782 
60783  /* Rollback any active transaction and free the handle structure.
60784  ** The call to sqlite3BtreeRollback() drops any table-locks held by
60785  ** this handle.
60786  */
60787  sqlite3BtreeRollback(p, SQLITE_OK, 0);
60788  sqlite3BtreeLeave(p);
60789 
60790  /* If there are still other outstanding references to the shared-btree
60791  ** structure, return now. The remainder of this procedure cleans
60792  ** up the shared-btree.
60793  */
60794  assert( p->wantToLock==0 && p->locked==0 );
60795  if( !p->sharable || removeFromSharingList(pBt) ){
60796  /* The pBt is no longer on the sharing list, so we can access
60797  ** it without having to hold the mutex.
60798  **
60799  ** Clean out and delete the BtShared object.
60800  */
60801  assert( !pBt->pCursor );
60802  sqlite3PagerClose(pBt->pPager);
60803  if( pBt->xFreeSchema && pBt->pSchema ){
60804  pBt->xFreeSchema(pBt->pSchema);
60805  }
60806  sqlite3DbFree(0, pBt->pSchema);
60807  freeTempSpace(pBt);
60808  sqlite3_free(pBt);
60809  }
60810 
60811 #ifndef SQLITE_OMIT_SHARED_CACHE
60812  assert( p->wantToLock==0 );
60813  assert( p->locked==0 );
60814  if( p->pPrev ) p->pPrev->pNext = p->pNext;
60815  if( p->pNext ) p->pNext->pPrev = p->pPrev;
60816 #endif
60817 
60818  sqlite3_free(p);
60819  return SQLITE_OK;
60820 }
60821 
60822 /*
60823 ** Change the "soft" limit on the number of pages in the cache.
60824 ** Unused and unmodified pages will be recycled when the number of
60825 ** pages in the cache exceeds this soft limit. But the size of the
60826 ** cache is allowed to grow larger than this limit if it contains
60827 ** dirty pages or pages still in active use.
60828 */
60829 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
60830  BtShared *pBt = p->pBt;
60831  assert( sqlite3_mutex_held(p->db->mutex) );
60832  sqlite3BtreeEnter(p);
60833  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
60834  sqlite3BtreeLeave(p);
60835  return SQLITE_OK;
60836 }
60837 
60838 /*
60839 ** Change the "spill" limit on the number of pages in the cache.
60840 ** If the number of pages exceeds this limit during a write transaction,
60841 ** the pager might attempt to "spill" pages to the journal early in
60842 ** order to free up memory.
60843 **
60844 ** The value returned is the current spill size. If zero is passed
60845 ** as an argument, no changes are made to the spill size setting, so
60846 ** using mxPage of 0 is a way to query the current spill size.
60847 */
60848 SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
60849  BtShared *pBt = p->pBt;
60850  int res;
60851  assert( sqlite3_mutex_held(p->db->mutex) );
60852  sqlite3BtreeEnter(p);
60853  res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
60854  sqlite3BtreeLeave(p);
60855  return res;
60856 }
60857 
60858 #if SQLITE_MAX_MMAP_SIZE>0
60859 /*
60860 ** Change the limit on the amount of the database file that may be
60861 ** memory mapped.
60862 */
60863 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
60864  BtShared *pBt = p->pBt;
60865  assert( sqlite3_mutex_held(p->db->mutex) );
60866  sqlite3BtreeEnter(p);
60867  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
60868  sqlite3BtreeLeave(p);
60869  return SQLITE_OK;
60870 }
60871 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
60872 
60873 /*
60874 ** Change the way data is synced to disk in order to increase or decrease
60875 ** how well the database resists damage due to OS crashes and power
60876 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
60877 ** there is a high probability of damage) Level 2 is the default. There
60878 ** is a very low but non-zero probability of damage. Level 3 reduces the
60879 ** probability of damage to near zero but with a write performance reduction.
60880 */
60881 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
60882 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
60883  Btree *p, /* The btree to set the safety level on */
60884  unsigned pgFlags /* Various PAGER_* flags */
60885 ){
60886  BtShared *pBt = p->pBt;
60887  assert( sqlite3_mutex_held(p->db->mutex) );
60888  sqlite3BtreeEnter(p);
60889  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
60890  sqlite3BtreeLeave(p);
60891  return SQLITE_OK;
60892 }
60893 #endif
60894 
60895 /*
60896 ** Change the default pages size and the number of reserved bytes per page.
60897 ** Or, if the page size has already been fixed, return SQLITE_READONLY
60898 ** without changing anything.
60899 **
60900 ** The page size must be a power of 2 between 512 and 65536. If the page
60901 ** size supplied does not meet this constraint then the page size is not
60902 ** changed.
60903 **
60904 ** Page sizes are constrained to be a power of two so that the region
60905 ** of the database file used for locking (beginning at PENDING_BYTE,
60906 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
60907 ** at the beginning of a page.
60908 **
60909 ** If parameter nReserve is less than zero, then the number of reserved
60910 ** bytes per page is left unchanged.
60911 **
60912 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
60913 ** and autovacuum mode can no longer be changed.
60914 */
60915 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
60916  int rc = SQLITE_OK;
60917  BtShared *pBt = p->pBt;
60918  assert( nReserve>=-1 && nReserve<=255 );
60919  sqlite3BtreeEnter(p);
60920 #if SQLITE_HAS_CODEC
60921  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
60922 #endif
60923  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
60924  sqlite3BtreeLeave(p);
60925  return SQLITE_READONLY;
60926  }
60927  if( nReserve<0 ){
60928  nReserve = pBt->pageSize - pBt->usableSize;
60929  }
60930  assert( nReserve>=0 && nReserve<=255 );
60931  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
60932  ((pageSize-1)&pageSize)==0 ){
60933  assert( (pageSize & 7)==0 );
60934  assert( !pBt->pCursor );
60935  pBt->pageSize = (u32)pageSize;
60936  freeTempSpace(pBt);
60937  }
60938  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60939  pBt->usableSize = pBt->pageSize - (u16)nReserve;
60940  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60941  sqlite3BtreeLeave(p);
60942  return rc;
60943 }
60944 
60945 /*
60946 ** Return the currently defined page size
60947 */
60948 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
60949  return p->pBt->pageSize;
60950 }
60951 
60952 /*
60953 ** This function is similar to sqlite3BtreeGetReserve(), except that it
60954 ** may only be called if it is guaranteed that the b-tree mutex is already
60955 ** held.
60956 **
60957 ** This is useful in one special case in the backup API code where it is
60958 ** known that the shared b-tree mutex is held, but the mutex on the
60959 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
60960 ** were to be called, it might collide with some other operation on the
60961 ** database handle that owns *p, causing undefined behavior.
60962 */
60963 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
60964  int n;
60965  assert( sqlite3_mutex_held(p->pBt->mutex) );
60966  n = p->pBt->pageSize - p->pBt->usableSize;
60967  return n;
60968 }
60969 
60970 /*
60971 ** Return the number of bytes of space at the end of every page that
60972 ** are intentually left unused. This is the "reserved" space that is
60973 ** sometimes used by extensions.
60974 **
60975 ** If SQLITE_HAS_MUTEX is defined then the number returned is the
60976 ** greater of the current reserved space and the maximum requested
60977 ** reserve space.
60978 */
60979 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
60980  int n;
60981  sqlite3BtreeEnter(p);
60982  n = sqlite3BtreeGetReserveNoMutex(p);
60983 #ifdef SQLITE_HAS_CODEC
60984  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
60985 #endif
60986  sqlite3BtreeLeave(p);
60987  return n;
60988 }
60989 
60990 
60991 /*
60992 ** Set the maximum page count for a database if mxPage is positive.
60993 ** No changes are made if mxPage is 0 or negative.
60994 ** Regardless of the value of mxPage, return the maximum page count.
60995 */
60996 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
60997  int n;
60998  sqlite3BtreeEnter(p);
60999  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
61000  sqlite3BtreeLeave(p);
61001  return n;
61002 }
61003 
61004 /*
61005 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
61006 ** then make no changes. Always return the value of the BTS_SECURE_DELETE
61007 ** setting after the change.
61008 */
61009 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
61010  int b;
61011  if( p==0 ) return 0;
61012  sqlite3BtreeEnter(p);
61013  if( newFlag>=0 ){
61014  p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
61015  if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
61016  }
61017  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
61018  sqlite3BtreeLeave(p);
61019  return b;
61020 }
61021 
61022 /*
61023 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
61024 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
61025 ** is disabled. The default value for the auto-vacuum property is
61026 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
61027 */
61028 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
61029 #ifdef SQLITE_OMIT_AUTOVACUUM
61030  return SQLITE_READONLY;
61031 #else
61032  BtShared *pBt = p->pBt;
61033  int rc = SQLITE_OK;
61034  u8 av = (u8)autoVacuum;
61035 
61036  sqlite3BtreeEnter(p);
61037  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
61038  rc = SQLITE_READONLY;
61039  }else{
61040  pBt->autoVacuum = av ?1:0;
61041  pBt->incrVacuum = av==2 ?1:0;
61042  }
61043  sqlite3BtreeLeave(p);
61044  return rc;
61045 #endif
61046 }
61047 
61048 /*
61049 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
61050 ** enabled 1 is returned. Otherwise 0.
61051 */
61052 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
61053 #ifdef SQLITE_OMIT_AUTOVACUUM
61054  return BTREE_AUTOVACUUM_NONE;
61055 #else
61056  int rc;
61057  sqlite3BtreeEnter(p);
61058  rc = (
61059  (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
61060  (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
61061  BTREE_AUTOVACUUM_INCR
61062  );
61063  sqlite3BtreeLeave(p);
61064  return rc;
61065 #endif
61066 }
61067 
61068 
61069 /*
61070 ** Get a reference to pPage1 of the database file. This will
61071 ** also acquire a readlock on that file.
61072 **
61073 ** SQLITE_OK is returned on success. If the file is not a
61074 ** well-formed database file, then SQLITE_CORRUPT is returned.
61075 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
61076 ** is returned if we run out of memory.
61077 */
61078 static int lockBtree(BtShared *pBt){
61079  int rc; /* Result code from subfunctions */
61080  MemPage *pPage1; /* Page 1 of the database file */
61081  int nPage; /* Number of pages in the database */
61082  int nPageFile = 0; /* Number of pages in the database file */
61083  int nPageHeader; /* Number of pages in the database according to hdr */
61084 
61085  assert( sqlite3_mutex_held(pBt->mutex) );
61086  assert( pBt->pPage1==0 );
61087  rc = sqlite3PagerSharedLock(pBt->pPager);
61088  if( rc!=SQLITE_OK ) return rc;
61089  rc = btreeGetPage(pBt, 1, &pPage1, 0);
61090  if( rc!=SQLITE_OK ) return rc;
61091 
61092  /* Do some checking to help insure the file we opened really is
61093  ** a valid database file.
61094  */
61095  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
61096  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
61097  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
61098  nPage = nPageFile;
61099  }
61100  if( nPage>0 ){
61101  u32 pageSize;
61102  u32 usableSize;
61103  u8 *page1 = pPage1->aData;
61104  rc = SQLITE_NOTADB;
61105  /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
61106  ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
61107  ** 61 74 20 33 00. */
61108  if( memcmp(page1, zMagicHeader, 16)!=0 ){
61109  goto page1_init_failed;
61110  }
61111 
61112 #ifdef SQLITE_OMIT_WAL
61113  if( page1[18]>1 ){
61114  pBt->btsFlags |= BTS_READ_ONLY;
61115  }
61116  if( page1[19]>1 ){
61117  goto page1_init_failed;
61118  }
61119 #else
61120  if( page1[18]>2 ){
61121  pBt->btsFlags |= BTS_READ_ONLY;
61122  }
61123  if( page1[19]>2 ){
61124  goto page1_init_failed;
61125  }
61126 
61127  /* If the write version is set to 2, this database should be accessed
61128  ** in WAL mode. If the log is not already open, open it now. Then
61129  ** return SQLITE_OK and return without populating BtShared.pPage1.
61130  ** The caller detects this and calls this function again. This is
61131  ** required as the version of page 1 currently in the page1 buffer
61132  ** may not be the latest version - there may be a newer one in the log
61133  ** file.
61134  */
61135  if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
61136  int isOpen = 0;
61137  rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
61138  if( rc!=SQLITE_OK ){
61139  goto page1_init_failed;
61140  }else{
61141 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
61142  sqlite3 *db;
61143  Db *pDb;
61144  if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
61145  while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
61146  if( pDb->bSyncSet==0
61147  && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1
61148  ){
61149  pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1;
61150  sqlite3PagerSetFlags(pBt->pPager,
61151  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
61152  }
61153  }
61154 #endif
61155  if( isOpen==0 ){
61156  releasePage(pPage1);
61157  return SQLITE_OK;
61158  }
61159  }
61160  rc = SQLITE_NOTADB;
61161  }
61162 #endif
61163 
61164  /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
61165  ** fractions and the leaf payload fraction values must be 64, 32, and 32.
61166  **
61167  ** The original design allowed these amounts to vary, but as of
61168  ** version 3.6.0, we require them to be fixed.
61169  */
61170  if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
61171  goto page1_init_failed;
61172  }
61173  /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
61174  ** determined by the 2-byte integer located at an offset of 16 bytes from
61175  ** the beginning of the database file. */
61176  pageSize = (page1[16]<<8) | (page1[17]<<16);
61177  /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
61178  ** between 512 and 65536 inclusive. */
61179  if( ((pageSize-1)&pageSize)!=0
61180  || pageSize>SQLITE_MAX_PAGE_SIZE
61181  || pageSize<=256
61182  ){
61183  goto page1_init_failed;
61184  }
61185  assert( (pageSize & 7)==0 );
61186  /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
61187  ** integer at offset 20 is the number of bytes of space at the end of
61188  ** each page to reserve for extensions.
61189  **
61190  ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
61191  ** determined by the one-byte unsigned integer found at an offset of 20
61192  ** into the database file header. */
61193  usableSize = pageSize - page1[20];
61194  if( (u32)pageSize!=pBt->pageSize ){
61195  /* After reading the first page of the database assuming a page size
61196  ** of BtShared.pageSize, we have discovered that the page-size is
61197  ** actually pageSize. Unlock the database, leave pBt->pPage1 at
61198  ** zero and return SQLITE_OK. The caller will call this function
61199  ** again with the correct page-size.
61200  */
61201  releasePage(pPage1);
61202  pBt->usableSize = usableSize;
61203  pBt->pageSize = pageSize;
61204  freeTempSpace(pBt);
61205  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
61206  pageSize-usableSize);
61207  return rc;
61208  }
61209  if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
61210  rc = SQLITE_CORRUPT_BKPT;
61211  goto page1_init_failed;
61212  }
61213  /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
61214  ** be less than 480. In other words, if the page size is 512, then the
61215  ** reserved space size cannot exceed 32. */
61216  if( usableSize<480 ){
61217  goto page1_init_failed;
61218  }
61219  pBt->pageSize = pageSize;
61220  pBt->usableSize = usableSize;
61221 #ifndef SQLITE_OMIT_AUTOVACUUM
61222  pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
61223  pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
61224 #endif
61225  }
61226 
61227  /* maxLocal is the maximum amount of payload to store locally for
61228  ** a cell. Make sure it is small enough so that at least minFanout
61229  ** cells can will fit on one page. We assume a 10-byte page header.
61230  ** Besides the payload, the cell must store:
61231  ** 2-byte pointer to the cell
61232  ** 4-byte child pointer
61233  ** 9-byte nKey value
61234  ** 4-byte nData value
61235  ** 4-byte overflow page pointer
61236  ** So a cell consists of a 2-byte pointer, a header which is as much as
61237  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
61238  ** page pointer.
61239  */
61240  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
61241  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
61242  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
61243  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
61244  if( pBt->maxLocal>127 ){
61245  pBt->max1bytePayload = 127;
61246  }else{
61247  pBt->max1bytePayload = (u8)pBt->maxLocal;
61248  }
61249  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
61250  pBt->pPage1 = pPage1;
61251  pBt->nPage = nPage;
61252  return SQLITE_OK;
61253 
61254 page1_init_failed:
61255  releasePage(pPage1);
61256  pBt->pPage1 = 0;
61257  return rc;
61258 }
61259 
61260 #ifndef NDEBUG
61261 /*
61262 ** Return the number of cursors open on pBt. This is for use
61263 ** in assert() expressions, so it is only compiled if NDEBUG is not
61264 ** defined.
61265 **
61266 ** Only write cursors are counted if wrOnly is true. If wrOnly is
61267 ** false then all cursors are counted.
61268 **
61269 ** For the purposes of this routine, a cursor is any cursor that
61270 ** is capable of reading or writing to the database. Cursors that
61271 ** have been tripped into the CURSOR_FAULT state are not counted.
61272 */
61273 static int countValidCursors(BtShared *pBt, int wrOnly){
61274  BtCursor *pCur;
61275  int r = 0;
61276  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
61277  if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
61278  && pCur->eState!=CURSOR_FAULT ) r++;
61279  }
61280  return r;
61281 }
61282 #endif
61283 
61284 /*
61285 ** If there are no outstanding cursors and we are not in the middle
61286 ** of a transaction but there is a read lock on the database, then
61287 ** this routine unrefs the first page of the database file which
61288 ** has the effect of releasing the read lock.
61289 **
61290 ** If there is a transaction in progress, this routine is a no-op.
61291 */
61292 static void unlockBtreeIfUnused(BtShared *pBt){
61293  assert( sqlite3_mutex_held(pBt->mutex) );
61294  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
61295  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
61296  MemPage *pPage1 = pBt->pPage1;
61297  assert( pPage1->aData );
61298  assert( sqlite3PagerRefcount(pBt->pPager)==1 );
61299  pBt->pPage1 = 0;
61300  releasePageNotNull(pPage1);
61301  }
61302 }
61303 
61304 /*
61305 ** If pBt points to an empty file then convert that empty file
61306 ** into a new empty database by initializing the first page of
61307 ** the database.
61308 */
61309 static int newDatabase(BtShared *pBt){
61310  MemPage *pP1;
61311  unsigned char *data;
61312  int rc;
61313 
61314  assert( sqlite3_mutex_held(pBt->mutex) );
61315  if( pBt->nPage>0 ){
61316  return SQLITE_OK;
61317  }
61318  pP1 = pBt->pPage1;
61319  assert( pP1!=0 );
61320  data = pP1->aData;
61321  rc = sqlite3PagerWrite(pP1->pDbPage);
61322  if( rc ) return rc;
61323  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
61324  assert( sizeof(zMagicHeader)==16 );
61325  data[16] = (u8)((pBt->pageSize>>8)&0xff);
61326  data[17] = (u8)((pBt->pageSize>>16)&0xff);
61327  data[18] = 1;
61328  data[19] = 1;
61329  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
61330  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
61331  data[21] = 64;
61332  data[22] = 32;
61333  data[23] = 32;
61334  memset(&data[24], 0, 100-24);
61335  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
61336  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
61337 #ifndef SQLITE_OMIT_AUTOVACUUM
61338  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
61339  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
61340  put4byte(&data[36 + 4*4], pBt->autoVacuum);
61341  put4byte(&data[36 + 7*4], pBt->incrVacuum);
61342 #endif
61343  pBt->nPage = 1;
61344  data[31] = 1;
61345  return SQLITE_OK;
61346 }
61347 
61348 /*
61349 ** Initialize the first page of the database file (creating a database
61350 ** consisting of a single page and no schema objects). Return SQLITE_OK
61351 ** if successful, or an SQLite error code otherwise.
61352 */
61353 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
61354  int rc;
61355  sqlite3BtreeEnter(p);
61356  p->pBt->nPage = 0;
61357  rc = newDatabase(p->pBt);
61358  sqlite3BtreeLeave(p);
61359  return rc;
61360 }
61361 
61362 /*
61363 ** Attempt to start a new transaction. A write-transaction
61364 ** is started if the second argument is nonzero, otherwise a read-
61365 ** transaction. If the second argument is 2 or more and exclusive
61366 ** transaction is started, meaning that no other process is allowed
61367 ** to access the database. A preexisting transaction may not be
61368 ** upgraded to exclusive by calling this routine a second time - the
61369 ** exclusivity flag only works for a new transaction.
61370 **
61371 ** A write-transaction must be started before attempting any
61372 ** changes to the database. None of the following routines
61373 ** will work unless a transaction is started first:
61374 **
61375 ** sqlite3BtreeCreateTable()
61376 ** sqlite3BtreeCreateIndex()
61377 ** sqlite3BtreeClearTable()
61378 ** sqlite3BtreeDropTable()
61379 ** sqlite3BtreeInsert()
61380 ** sqlite3BtreeDelete()
61381 ** sqlite3BtreeUpdateMeta()
61382 **
61383 ** If an initial attempt to acquire the lock fails because of lock contention
61384 ** and the database was previously unlocked, then invoke the busy handler
61385 ** if there is one. But if there was previously a read-lock, do not
61386 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
61387 ** returned when there is already a read-lock in order to avoid a deadlock.
61388 **
61389 ** Suppose there are two processes A and B. A has a read lock and B has
61390 ** a reserved lock. B tries to promote to exclusive but is blocked because
61391 ** of A's read lock. A tries to promote to reserved but is blocked by B.
61392 ** One or the other of the two processes must give way or there can be
61393 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
61394 ** when A already has a read lock, we encourage A to give up and let B
61395 ** proceed.
61396 */
61397 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
61398  BtShared *pBt = p->pBt;
61399  int rc = SQLITE_OK;
61400 
61401  sqlite3BtreeEnter(p);
61402  btreeIntegrity(p);
61403 
61404  /* If the btree is already in a write-transaction, or it
61405  ** is already in a read-transaction and a read-transaction
61406  ** is requested, this is a no-op.
61407  */
61408  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
61409  goto trans_begun;
61410  }
61411  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
61412 
61413  /* Write transactions are not possible on a read-only database */
61414  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
61415  rc = SQLITE_READONLY;
61416  goto trans_begun;
61417  }
61418 
61419 #ifndef SQLITE_OMIT_SHARED_CACHE
61420  {
61421  sqlite3 *pBlock = 0;
61422  /* If another database handle has already opened a write transaction
61423  ** on this shared-btree structure and a second write transaction is
61424  ** requested, return SQLITE_LOCKED.
61425  */
61426  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
61427  || (pBt->btsFlags & BTS_PENDING)!=0
61428  ){
61429  pBlock = pBt->pWriter->db;
61430  }else if( wrflag>1 ){
61431  BtLock *pIter;
61432  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
61433  if( pIter->pBtree!=p ){
61434  pBlock = pIter->pBtree->db;
61435  break;
61436  }
61437  }
61438  }
61439  if( pBlock ){
61440  sqlite3ConnectionBlocked(p->db, pBlock);
61441  rc = SQLITE_LOCKED_SHAREDCACHE;
61442  goto trans_begun;
61443  }
61444  }
61445 #endif
61446 
61447  /* Any read-only or read-write transaction implies a read-lock on
61448  ** page 1. So if some other shared-cache client already has a write-lock
61449  ** on page 1, the transaction cannot be opened. */
61450  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
61451  if( SQLITE_OK!=rc ) goto trans_begun;
61452 
61453  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
61454  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
61455  do {
61456  /* Call lockBtree() until either pBt->pPage1 is populated or
61457  ** lockBtree() returns something other than SQLITE_OK. lockBtree()
61458  ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
61459  ** reading page 1 it discovers that the page-size of the database
61460  ** file is not pBt->pageSize. In this case lockBtree() will update
61461  ** pBt->pageSize to the page-size of the file on disk.
61462  */
61463  while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
61464 
61465  if( rc==SQLITE_OK && wrflag ){
61466  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
61467  rc = SQLITE_READONLY;
61468  }else{
61469  rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
61470  if( rc==SQLITE_OK ){
61471  rc = newDatabase(pBt);
61472  }
61473  }
61474  }
61475 
61476  if( rc!=SQLITE_OK ){
61477  unlockBtreeIfUnused(pBt);
61478  }
61479  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
61480  btreeInvokeBusyHandler(pBt) );
61481 
61482  if( rc==SQLITE_OK ){
61483  if( p->inTrans==TRANS_NONE ){
61484  pBt->nTransaction++;
61485 #ifndef SQLITE_OMIT_SHARED_CACHE
61486  if( p->sharable ){
61487  assert( p->lock.pBtree==p && p->lock.iTable==1 );
61488  p->lock.eLock = READ_LOCK;
61489  p->lock.pNext = pBt->pLock;
61490  pBt->pLock = &p->lock;
61491  }
61492 #endif
61493  }
61494  p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
61495  if( p->inTrans>pBt->inTransaction ){
61496  pBt->inTransaction = p->inTrans;
61497  }
61498  if( wrflag ){
61499  MemPage *pPage1 = pBt->pPage1;
61500 #ifndef SQLITE_OMIT_SHARED_CACHE
61501  assert( !pBt->pWriter );
61502  pBt->pWriter = p;
61503  pBt->btsFlags &= ~BTS_EXCLUSIVE;
61504  if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
61505 #endif
61506 
61507  /* If the db-size header field is incorrect (as it may be if an old
61508  ** client has been writing the database file), update it now. Doing
61509  ** this sooner rather than later means the database size can safely
61510  ** re-read the database size from page 1 if a savepoint or transaction
61511  ** rollback occurs within the transaction.
61512  */
61513  if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
61514  rc = sqlite3PagerWrite(pPage1->pDbPage);
61515  if( rc==SQLITE_OK ){
61516  put4byte(&pPage1->aData[28], pBt->nPage);
61517  }
61518  }
61519  }
61520  }
61521 
61522 
61523 trans_begun:
61524  if( rc==SQLITE_OK && wrflag ){
61525  /* This call makes sure that the pager has the correct number of
61526  ** open savepoints. If the second parameter is greater than 0 and
61527  ** the sub-journal is not already open, then it will be opened here.
61528  */
61529  rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
61530  }
61531 
61532  btreeIntegrity(p);
61533  sqlite3BtreeLeave(p);
61534  return rc;
61535 }
61536 
61537 #ifndef SQLITE_OMIT_AUTOVACUUM
61538 
61539 /*
61540 ** Set the pointer-map entries for all children of page pPage. Also, if
61541 ** pPage contains cells that point to overflow pages, set the pointer
61542 ** map entries for the overflow pages as well.
61543 */
61544 static int setChildPtrmaps(MemPage *pPage){
61545  int i; /* Counter variable */
61546  int nCell; /* Number of cells in page pPage */
61547  int rc; /* Return code */
61548  BtShared *pBt = pPage->pBt;
61549  u8 isInitOrig = pPage->isInit;
61550  Pgno pgno = pPage->pgno;
61551 
61552  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61553  rc = btreeInitPage(pPage);
61554  if( rc!=SQLITE_OK ){
61555  goto set_child_ptrmaps_out;
61556  }
61557  nCell = pPage->nCell;
61558 
61559  for(i=0; i<nCell; i++){
61560  u8 *pCell = findCell(pPage, i);
61561 
61562  ptrmapPutOvflPtr(pPage, pCell, &rc);
61563 
61564  if( !pPage->leaf ){
61565  Pgno childPgno = get4byte(pCell);
61566  ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61567  }
61568  }
61569 
61570  if( !pPage->leaf ){
61571  Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
61572  ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61573  }
61574 
61575 set_child_ptrmaps_out:
61576  pPage->isInit = isInitOrig;
61577  return rc;
61578 }
61579 
61580 /*
61581 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
61582 ** that it points to iTo. Parameter eType describes the type of pointer to
61583 ** be modified, as follows:
61584 **
61585 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
61586 ** page of pPage.
61587 **
61588 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
61589 ** page pointed to by one of the cells on pPage.
61590 **
61591 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
61592 ** overflow page in the list.
61593 */
61594 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
61595  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61596  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61597  if( eType==PTRMAP_OVERFLOW2 ){
61598  /* The pointer is always the first 4 bytes of the page in this case. */
61599  if( get4byte(pPage->aData)!=iFrom ){
61600  return SQLITE_CORRUPT_BKPT;
61601  }
61602  put4byte(pPage->aData, iTo);
61603  }else{
61604  u8 isInitOrig = pPage->isInit;
61605  int i;
61606  int nCell;
61607  int rc;
61608 
61609  rc = btreeInitPage(pPage);
61610  if( rc ) return rc;
61611  nCell = pPage->nCell;
61612 
61613  for(i=0; i<nCell; i++){
61614  u8 *pCell = findCell(pPage, i);
61615  if( eType==PTRMAP_OVERFLOW1 ){
61616  CellInfo info;
61617  pPage->xParseCell(pPage, pCell, &info);
61618  if( info.nLocal<info.nPayload
61619  && pCell+info.nSize-1<=pPage->aData+pPage->maskPage
61620  && iFrom==get4byte(pCell+info.nSize-4)
61621  ){
61622  put4byte(pCell+info.nSize-4, iTo);
61623  break;
61624  }
61625  }else{
61626  if( get4byte(pCell)==iFrom ){
61627  put4byte(pCell, iTo);
61628  break;
61629  }
61630  }
61631  }
61632 
61633  if( i==nCell ){
61634  if( eType!=PTRMAP_BTREE ||
61635  get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
61636  return SQLITE_CORRUPT_BKPT;
61637  }
61638  put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
61639  }
61640 
61641  pPage->isInit = isInitOrig;
61642  }
61643  return SQLITE_OK;
61644 }
61645 
61646 
61647 /*
61648 ** Move the open database page pDbPage to location iFreePage in the
61649 ** database. The pDbPage reference remains valid.
61650 **
61651 ** The isCommit flag indicates that there is no need to remember that
61652 ** the journal needs to be sync()ed before database page pDbPage->pgno
61653 ** can be written to. The caller has already promised not to write to that
61654 ** page.
61655 */
61656 static int relocatePage(
61657  BtShared *pBt, /* Btree */
61658  MemPage *pDbPage, /* Open page to move */
61659  u8 eType, /* Pointer map 'type' entry for pDbPage */
61660  Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
61661  Pgno iFreePage, /* The location to move pDbPage to */
61662  int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
61663 ){
61664  MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
61665  Pgno iDbPage = pDbPage->pgno;
61666  Pager *pPager = pBt->pPager;
61667  int rc;
61668 
61669  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
61670  eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
61671  assert( sqlite3_mutex_held(pBt->mutex) );
61672  assert( pDbPage->pBt==pBt );
61673 
61674  /* Move page iDbPage from its current location to page number iFreePage */
61675  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
61676  iDbPage, iFreePage, iPtrPage, eType));
61677  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
61678  if( rc!=SQLITE_OK ){
61679  return rc;
61680  }
61681  pDbPage->pgno = iFreePage;
61682 
61683  /* If pDbPage was a btree-page, then it may have child pages and/or cells
61684  ** that point to overflow pages. The pointer map entries for all these
61685  ** pages need to be changed.
61686  **
61687  ** If pDbPage is an overflow page, then the first 4 bytes may store a
61688  ** pointer to a subsequent overflow page. If this is the case, then
61689  ** the pointer map needs to be updated for the subsequent overflow page.
61690  */
61691  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
61692  rc = setChildPtrmaps(pDbPage);
61693  if( rc!=SQLITE_OK ){
61694  return rc;
61695  }
61696  }else{
61697  Pgno nextOvfl = get4byte(pDbPage->aData);
61698  if( nextOvfl!=0 ){
61699  ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
61700  if( rc!=SQLITE_OK ){
61701  return rc;
61702  }
61703  }
61704  }
61705 
61706  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
61707  ** that it points at iFreePage. Also fix the pointer map entry for
61708  ** iPtrPage.
61709  */
61710  if( eType!=PTRMAP_ROOTPAGE ){
61711  rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
61712  if( rc!=SQLITE_OK ){
61713  return rc;
61714  }
61715  rc = sqlite3PagerWrite(pPtrPage->pDbPage);
61716  if( rc!=SQLITE_OK ){
61717  releasePage(pPtrPage);
61718  return rc;
61719  }
61720  rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
61721  releasePage(pPtrPage);
61722  if( rc==SQLITE_OK ){
61723  ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
61724  }
61725  }
61726  return rc;
61727 }
61728 
61729 /* Forward declaration required by incrVacuumStep(). */
61730 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
61731 
61732 /*
61733 ** Perform a single step of an incremental-vacuum. If successful, return
61734 ** SQLITE_OK. If there is no work to do (and therefore no point in
61735 ** calling this function again), return SQLITE_DONE. Or, if an error
61736 ** occurs, return some other error code.
61737 **
61738 ** More specifically, this function attempts to re-organize the database so
61739 ** that the last page of the file currently in use is no longer in use.
61740 **
61741 ** Parameter nFin is the number of pages that this database would contain
61742 ** were this function called until it returns SQLITE_DONE.
61743 **
61744 ** If the bCommit parameter is non-zero, this function assumes that the
61745 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
61746 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
61747 ** operation, or false for an incremental vacuum.
61748 */
61749 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
61750  Pgno nFreeList; /* Number of pages still on the free-list */
61751  int rc;
61752 
61753  assert( sqlite3_mutex_held(pBt->mutex) );
61754  assert( iLastPg>nFin );
61755 
61756  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
61757  u8 eType;
61758  Pgno iPtrPage;
61759 
61760  nFreeList = get4byte(&pBt->pPage1->aData[36]);
61761  if( nFreeList==0 ){
61762  return SQLITE_DONE;
61763  }
61764 
61765  rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
61766  if( rc!=SQLITE_OK ){
61767  return rc;
61768  }
61769  if( eType==PTRMAP_ROOTPAGE ){
61770  return SQLITE_CORRUPT_BKPT;
61771  }
61772 
61773  if( eType==PTRMAP_FREEPAGE ){
61774  if( bCommit==0 ){
61775  /* Remove the page from the files free-list. This is not required
61776  ** if bCommit is non-zero. In that case, the free-list will be
61777  ** truncated to zero after this function returns, so it doesn't
61778  ** matter if it still contains some garbage entries.
61779  */
61780  Pgno iFreePg;
61781  MemPage *pFreePg;
61782  rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
61783  if( rc!=SQLITE_OK ){
61784  return rc;
61785  }
61786  assert( iFreePg==iLastPg );
61787  releasePage(pFreePg);
61788  }
61789  } else {
61790  Pgno iFreePg; /* Index of free page to move pLastPg to */
61791  MemPage *pLastPg;
61792  u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
61793  Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
61794 
61795  rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
61796  if( rc!=SQLITE_OK ){
61797  return rc;
61798  }
61799 
61800  /* If bCommit is zero, this loop runs exactly once and page pLastPg
61801  ** is swapped with the first free page pulled off the free list.
61802  **
61803  ** On the other hand, if bCommit is greater than zero, then keep
61804  ** looping until a free-page located within the first nFin pages
61805  ** of the file is found.
61806  */
61807  if( bCommit==0 ){
61808  eMode = BTALLOC_LE;
61809  iNear = nFin;
61810  }
61811  do {
61812  MemPage *pFreePg;
61813  rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
61814  if( rc!=SQLITE_OK ){
61815  releasePage(pLastPg);
61816  return rc;
61817  }
61818  releasePage(pFreePg);
61819  }while( bCommit && iFreePg>nFin );
61820  assert( iFreePg<iLastPg );
61821 
61822  rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
61823  releasePage(pLastPg);
61824  if( rc!=SQLITE_OK ){
61825  return rc;
61826  }
61827  }
61828  }
61829 
61830  if( bCommit==0 ){
61831  do {
61832  iLastPg--;
61833  }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
61834  pBt->bDoTruncate = 1;
61835  pBt->nPage = iLastPg;
61836  }
61837  return SQLITE_OK;
61838 }
61839 
61840 /*
61841 ** The database opened by the first argument is an auto-vacuum database
61842 ** nOrig pages in size containing nFree free pages. Return the expected
61843 ** size of the database in pages following an auto-vacuum operation.
61844 */
61845 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
61846  int nEntry; /* Number of entries on one ptrmap page */
61847  Pgno nPtrmap; /* Number of PtrMap pages to be freed */
61848  Pgno nFin; /* Return value */
61849 
61850  nEntry = pBt->usableSize/5;
61851  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
61852  nFin = nOrig - nFree - nPtrmap;
61853  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
61854  nFin--;
61855  }
61856  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
61857  nFin--;
61858  }
61859 
61860  return nFin;
61861 }
61862 
61863 /*
61864 ** A write-transaction must be opened before calling this function.
61865 ** It performs a single unit of work towards an incremental vacuum.
61866 **
61867 ** If the incremental vacuum is finished after this function has run,
61868 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
61869 ** SQLITE_OK is returned. Otherwise an SQLite error code.
61870 */
61871 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
61872  int rc;
61873  BtShared *pBt = p->pBt;
61874 
61875  sqlite3BtreeEnter(p);
61876  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
61877  if( !pBt->autoVacuum ){
61878  rc = SQLITE_DONE;
61879  }else{
61880  Pgno nOrig = btreePagecount(pBt);
61881  Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
61882  Pgno nFin = finalDbSize(pBt, nOrig, nFree);
61883 
61884  if( nOrig<nFin ){
61885  rc = SQLITE_CORRUPT_BKPT;
61886  }else if( nFree>0 ){
61887  rc = saveAllCursors(pBt, 0, 0);
61888  if( rc==SQLITE_OK ){
61889  invalidateAllOverflowCache(pBt);
61890  rc = incrVacuumStep(pBt, nFin, nOrig, 0);
61891  }
61892  if( rc==SQLITE_OK ){
61893  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61894  put4byte(&pBt->pPage1->aData[28], pBt->nPage);
61895  }
61896  }else{
61897  rc = SQLITE_DONE;
61898  }
61899  }
61900  sqlite3BtreeLeave(p);
61901  return rc;
61902 }
61903 
61904 /*
61905 ** This routine is called prior to sqlite3PagerCommit when a transaction
61906 ** is committed for an auto-vacuum database.
61907 **
61908 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
61909 ** the database file should be truncated to during the commit process.
61910 ** i.e. the database has been reorganized so that only the first *pnTrunc
61911 ** pages are in use.
61912 */
61913 static int autoVacuumCommit(BtShared *pBt){
61914  int rc = SQLITE_OK;
61915  Pager *pPager = pBt->pPager;
61916  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
61917 
61918  assert( sqlite3_mutex_held(pBt->mutex) );
61919  invalidateAllOverflowCache(pBt);
61920  assert(pBt->autoVacuum);
61921  if( !pBt->incrVacuum ){
61922  Pgno nFin; /* Number of pages in database after autovacuuming */
61923  Pgno nFree; /* Number of pages on the freelist initially */
61924  Pgno iFree; /* The next page to be freed */
61925  Pgno nOrig; /* Database size before freeing */
61926 
61927  nOrig = btreePagecount(pBt);
61928  if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
61929  /* It is not possible to create a database for which the final page
61930  ** is either a pointer-map page or the pending-byte page. If one
61931  ** is encountered, this indicates corruption.
61932  */
61933  return SQLITE_CORRUPT_BKPT;
61934  }
61935 
61936  nFree = get4byte(&pBt->pPage1->aData[36]);
61937  nFin = finalDbSize(pBt, nOrig, nFree);
61938  if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
61939  if( nFin<nOrig ){
61940  rc = saveAllCursors(pBt, 0, 0);
61941  }
61942  for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
61943  rc = incrVacuumStep(pBt, nFin, iFree, 1);
61944  }
61945  if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
61946  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61947  put4byte(&pBt->pPage1->aData[32], 0);
61948  put4byte(&pBt->pPage1->aData[36], 0);
61949  put4byte(&pBt->pPage1->aData[28], nFin);
61950  pBt->bDoTruncate = 1;
61951  pBt->nPage = nFin;
61952  }
61953  if( rc!=SQLITE_OK ){
61954  sqlite3PagerRollback(pPager);
61955  }
61956  }
61957 
61958  assert( nRef>=sqlite3PagerRefcount(pPager) );
61959  return rc;
61960 }
61961 
61962 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
61963 # define setChildPtrmaps(x) SQLITE_OK
61964 #endif
61965 
61966 /*
61967 ** This routine does the first phase of a two-phase commit. This routine
61968 ** causes a rollback journal to be created (if it does not already exist)
61969 ** and populated with enough information so that if a power loss occurs
61970 ** the database can be restored to its original state by playing back
61971 ** the journal. Then the contents of the journal are flushed out to
61972 ** the disk. After the journal is safely on oxide, the changes to the
61973 ** database are written into the database file and flushed to oxide.
61974 ** At the end of this call, the rollback journal still exists on the
61975 ** disk and we are still holding all locks, so the transaction has not
61976 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
61977 ** commit process.
61978 **
61979 ** This call is a no-op if no write-transaction is currently active on pBt.
61980 **
61981 ** Otherwise, sync the database file for the btree pBt. zMaster points to
61982 ** the name of a master journal file that should be written into the
61983 ** individual journal file, or is NULL, indicating no master journal file
61984 ** (single database transaction).
61985 **
61986 ** When this is called, the master journal should already have been
61987 ** created, populated with this journal pointer and synced to disk.
61988 **
61989 ** Once this is routine has returned, the only thing required to commit
61990 ** the write-transaction for this database file is to delete the journal.
61991 */
61992 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
61993  int rc = SQLITE_OK;
61994  if( p->inTrans==TRANS_WRITE ){
61995  BtShared *pBt = p->pBt;
61996  sqlite3BtreeEnter(p);
61997 #ifndef SQLITE_OMIT_AUTOVACUUM
61998  if( pBt->autoVacuum ){
61999  rc = autoVacuumCommit(pBt);
62000  if( rc!=SQLITE_OK ){
62001  sqlite3BtreeLeave(p);
62002  return rc;
62003  }
62004  }
62005  if( pBt->bDoTruncate ){
62006  sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
62007  }
62008 #endif
62009  rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
62010  sqlite3BtreeLeave(p);
62011  }
62012  return rc;
62013 }
62014 
62015 /*
62016 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
62017 ** at the conclusion of a transaction.
62018 */
62019 static void btreeEndTransaction(Btree *p){
62020  BtShared *pBt = p->pBt;
62021  sqlite3 *db = p->db;
62022  assert( sqlite3BtreeHoldsMutex(p) );
62023 
62024 #ifndef SQLITE_OMIT_AUTOVACUUM
62025  pBt->bDoTruncate = 0;
62026 #endif
62027  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
62028  /* If there are other active statements that belong to this database
62029  ** handle, downgrade to a read-only transaction. The other statements
62030  ** may still be reading from the database. */
62031  downgradeAllSharedCacheTableLocks(p);
62032  p->inTrans = TRANS_READ;
62033  }else{
62034  /* If the handle had any kind of transaction open, decrement the
62035  ** transaction count of the shared btree. If the transaction count
62036  ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
62037  ** call below will unlock the pager. */
62038  if( p->inTrans!=TRANS_NONE ){
62039  clearAllSharedCacheTableLocks(p);
62040  pBt->nTransaction--;
62041  if( 0==pBt->nTransaction ){
62042  pBt->inTransaction = TRANS_NONE;
62043  }
62044  }
62045 
62046  /* Set the current transaction state to TRANS_NONE and unlock the
62047  ** pager if this call closed the only read or write transaction. */
62048  p->inTrans = TRANS_NONE;
62049  unlockBtreeIfUnused(pBt);
62050  }
62051 
62052  btreeIntegrity(p);
62053 }
62054 
62055 /*
62056 ** Commit the transaction currently in progress.
62057 **
62058 ** This routine implements the second phase of a 2-phase commit. The
62059 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
62060 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
62061 ** routine did all the work of writing information out to disk and flushing the
62062 ** contents so that they are written onto the disk platter. All this
62063 ** routine has to do is delete or truncate or zero the header in the
62064 ** the rollback journal (which causes the transaction to commit) and
62065 ** drop locks.
62066 **
62067 ** Normally, if an error occurs while the pager layer is attempting to
62068 ** finalize the underlying journal file, this function returns an error and
62069 ** the upper layer will attempt a rollback. However, if the second argument
62070 ** is non-zero then this b-tree transaction is part of a multi-file
62071 ** transaction. In this case, the transaction has already been committed
62072 ** (by deleting a master journal file) and the caller will ignore this
62073 ** functions return code. So, even if an error occurs in the pager layer,
62074 ** reset the b-tree objects internal state to indicate that the write
62075 ** transaction has been closed. This is quite safe, as the pager will have
62076 ** transitioned to the error state.
62077 **
62078 ** This will release the write lock on the database file. If there
62079 ** are no active cursors, it also releases the read lock.
62080 */
62081 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
62082 
62083  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
62084  sqlite3BtreeEnter(p);
62085  btreeIntegrity(p);
62086 
62087  /* If the handle has a write-transaction open, commit the shared-btrees
62088  ** transaction and set the shared state to TRANS_READ.
62089  */
62090  if( p->inTrans==TRANS_WRITE ){
62091  int rc;
62092  BtShared *pBt = p->pBt;
62093  assert( pBt->inTransaction==TRANS_WRITE );
62094  assert( pBt->nTransaction>0 );
62095  rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
62096  if( rc!=SQLITE_OK && bCleanup==0 ){
62097  sqlite3BtreeLeave(p);
62098  return rc;
62099  }
62100  p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
62101  pBt->inTransaction = TRANS_READ;
62102  btreeClearHasContent(pBt);
62103  }
62104 
62105  btreeEndTransaction(p);
62106  sqlite3BtreeLeave(p);
62107  return SQLITE_OK;
62108 }
62109 
62110 /*
62111 ** Do both phases of a commit.
62112 */
62113 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
62114  int rc;
62115  sqlite3BtreeEnter(p);
62116  rc = sqlite3BtreeCommitPhaseOne(p, 0);
62117  if( rc==SQLITE_OK ){
62118  rc = sqlite3BtreeCommitPhaseTwo(p, 0);
62119  }
62120  sqlite3BtreeLeave(p);
62121  return rc;
62122 }
62123 
62124 /*
62125 ** This routine sets the state to CURSOR_FAULT and the error
62126 ** code to errCode for every cursor on any BtShared that pBtree
62127 ** references. Or if the writeOnly flag is set to 1, then only
62128 ** trip write cursors and leave read cursors unchanged.
62129 **
62130 ** Every cursor is a candidate to be tripped, including cursors
62131 ** that belong to other database connections that happen to be
62132 ** sharing the cache with pBtree.
62133 **
62134 ** This routine gets called when a rollback occurs. If the writeOnly
62135 ** flag is true, then only write-cursors need be tripped - read-only
62136 ** cursors save their current positions so that they may continue
62137 ** following the rollback. Or, if writeOnly is false, all cursors are
62138 ** tripped. In general, writeOnly is false if the transaction being
62139 ** rolled back modified the database schema. In this case b-tree root
62140 ** pages may be moved or deleted from the database altogether, making
62141 ** it unsafe for read cursors to continue.
62142 **
62143 ** If the writeOnly flag is true and an error is encountered while
62144 ** saving the current position of a read-only cursor, all cursors,
62145 ** including all read-cursors are tripped.
62146 **
62147 ** SQLITE_OK is returned if successful, or if an error occurs while
62148 ** saving a cursor position, an SQLite error code.
62149 */
62150 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
62151  BtCursor *p;
62152  int rc = SQLITE_OK;
62153 
62154  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
62155  if( pBtree ){
62156  sqlite3BtreeEnter(pBtree);
62157  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
62158  int i;
62159  if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
62160  if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
62161  rc = saveCursorPosition(p);
62162  if( rc!=SQLITE_OK ){
62163  (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
62164  break;
62165  }
62166  }
62167  }else{
62168  sqlite3BtreeClearCursor(p);
62169  p->eState = CURSOR_FAULT;
62170  p->skipNext = errCode;
62171  }
62172  for(i=0; i<=p->iPage; i++){
62173  releasePage(p->apPage[i]);
62174  p->apPage[i] = 0;
62175  }
62176  }
62177  sqlite3BtreeLeave(pBtree);
62178  }
62179  return rc;
62180 }
62181 
62182 /*
62183 ** Rollback the transaction in progress.
62184 **
62185 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
62186 ** Only write cursors are tripped if writeOnly is true but all cursors are
62187 ** tripped if writeOnly is false. Any attempt to use
62188 ** a tripped cursor will result in an error.
62189 **
62190 ** This will release the write lock on the database file. If there
62191 ** are no active cursors, it also releases the read lock.
62192 */
62193 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
62194  int rc;
62195  BtShared *pBt = p->pBt;
62196  MemPage *pPage1;
62197 
62198  assert( writeOnly==1 || writeOnly==0 );
62199  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
62200  sqlite3BtreeEnter(p);
62201  if( tripCode==SQLITE_OK ){
62202  rc = tripCode = saveAllCursors(pBt, 0, 0);
62203  if( rc ) writeOnly = 0;
62204  }else{
62205  rc = SQLITE_OK;
62206  }
62207  if( tripCode ){
62208  int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
62209  assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
62210  if( rc2!=SQLITE_OK ) rc = rc2;
62211  }
62212  btreeIntegrity(p);
62213 
62214  if( p->inTrans==TRANS_WRITE ){
62215  int rc2;
62216 
62217  assert( TRANS_WRITE==pBt->inTransaction );
62218  rc2 = sqlite3PagerRollback(pBt->pPager);
62219  if( rc2!=SQLITE_OK ){
62220  rc = rc2;
62221  }
62222 
62223  /* The rollback may have destroyed the pPage1->aData value. So
62224  ** call btreeGetPage() on page 1 again to make
62225  ** sure pPage1->aData is set correctly. */
62226  if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
62227  int nPage = get4byte(28+(u8*)pPage1->aData);
62228  testcase( nPage==0 );
62229  if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
62230  testcase( pBt->nPage!=nPage );
62231  pBt->nPage = nPage;
62232  releasePage(pPage1);
62233  }
62234  assert( countValidCursors(pBt, 1)==0 );
62235  pBt->inTransaction = TRANS_READ;
62236  btreeClearHasContent(pBt);
62237  }
62238 
62239  btreeEndTransaction(p);
62240  sqlite3BtreeLeave(p);
62241  return rc;
62242 }
62243 
62244 /*
62245 ** Start a statement subtransaction. The subtransaction can be rolled
62246 ** back independently of the main transaction. You must start a transaction
62247 ** before starting a subtransaction. The subtransaction is ended automatically
62248 ** if the main transaction commits or rolls back.
62249 **
62250 ** Statement subtransactions are used around individual SQL statements
62251 ** that are contained within a BEGIN...COMMIT block. If a constraint
62252 ** error occurs within the statement, the effect of that one statement
62253 ** can be rolled back without having to rollback the entire transaction.
62254 **
62255 ** A statement sub-transaction is implemented as an anonymous savepoint. The
62256 ** value passed as the second parameter is the total number of savepoints,
62257 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
62258 ** are no active savepoints and no other statement-transactions open,
62259 ** iStatement is 1. This anonymous savepoint can be released or rolled back
62260 ** using the sqlite3BtreeSavepoint() function.
62261 */
62262 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
62263  int rc;
62264  BtShared *pBt = p->pBt;
62265  sqlite3BtreeEnter(p);
62266  assert( p->inTrans==TRANS_WRITE );
62267  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
62268  assert( iStatement>0 );
62269  assert( iStatement>p->db->nSavepoint );
62270  assert( pBt->inTransaction==TRANS_WRITE );
62271  /* At the pager level, a statement transaction is a savepoint with
62272  ** an index greater than all savepoints created explicitly using
62273  ** SQL statements. It is illegal to open, release or rollback any
62274  ** such savepoints while the statement transaction savepoint is active.
62275  */
62276  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
62277  sqlite3BtreeLeave(p);
62278  return rc;
62279 }
62280 
62281 /*
62282 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
62283 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
62284 ** savepoint identified by parameter iSavepoint, depending on the value
62285 ** of op.
62286 **
62287 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
62288 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
62289 ** contents of the entire transaction are rolled back. This is different
62290 ** from a normal transaction rollback, as no locks are released and the
62291 ** transaction remains open.
62292 */
62293 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
62294  int rc = SQLITE_OK;
62295  if( p && p->inTrans==TRANS_WRITE ){
62296  BtShared *pBt = p->pBt;
62297  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
62298  assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
62299  sqlite3BtreeEnter(p);
62300  rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
62301  if( rc==SQLITE_OK ){
62302  if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
62303  pBt->nPage = 0;
62304  }
62305  rc = newDatabase(pBt);
62306  pBt->nPage = get4byte(28 + pBt->pPage1->aData);
62307 
62308  /* The database size was written into the offset 28 of the header
62309  ** when the transaction started, so we know that the value at offset
62310  ** 28 is nonzero. */
62311  assert( pBt->nPage>0 );
62312  }
62313  sqlite3BtreeLeave(p);
62314  }
62315  return rc;
62316 }
62317 
62318 /*
62319 ** Create a new cursor for the BTree whose root is on the page
62320 ** iTable. If a read-only cursor is requested, it is assumed that
62321 ** the caller already has at least a read-only transaction open
62322 ** on the database already. If a write-cursor is requested, then
62323 ** the caller is assumed to have an open write transaction.
62324 **
62325 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
62326 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
62327 ** can be used for reading or for writing if other conditions for writing
62328 ** are also met. These are the conditions that must be met in order
62329 ** for writing to be allowed:
62330 **
62331 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
62332 **
62333 ** 2: Other database connections that share the same pager cache
62334 ** but which are not in the READ_UNCOMMITTED state may not have
62335 ** cursors open with wrFlag==0 on the same table. Otherwise
62336 ** the changes made by this write cursor would be visible to
62337 ** the read cursors in the other database connection.
62338 **
62339 ** 3: The database must be writable (not on read-only media)
62340 **
62341 ** 4: There must be an active transaction.
62342 **
62343 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
62344 ** is set. If FORDELETE is set, that is a hint to the implementation that
62345 ** this cursor will only be used to seek to and delete entries of an index
62346 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
62347 ** this implementation. But in a hypothetical alternative storage engine
62348 ** in which index entries are automatically deleted when corresponding table
62349 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
62350 ** operations on this cursor can be no-ops and all READ operations can
62351 ** return a null row (2-bytes: 0x01 0x00).
62352 **
62353 ** No checking is done to make sure that page iTable really is the
62354 ** root page of a b-tree. If it is not, then the cursor acquired
62355 ** will not work correctly.
62356 **
62357 ** It is assumed that the sqlite3BtreeCursorZero() has been called
62358 ** on pCur to initialize the memory space prior to invoking this routine.
62359 */
62360 static int btreeCursor(
62361  Btree *p, /* The btree */
62362  int iTable, /* Root page of table to open */
62363  int wrFlag, /* 1 to write. 0 read-only */
62364  struct KeyInfo *pKeyInfo, /* First arg to comparison function */
62365  BtCursor *pCur /* Space for new cursor */
62366 ){
62367  BtShared *pBt = p->pBt; /* Shared b-tree handle */
62368  BtCursor *pX; /* Looping over other all cursors */
62369 
62370  assert( sqlite3BtreeHoldsMutex(p) );
62371  assert( wrFlag==0
62372  || wrFlag==BTREE_WRCSR
62373  || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
62374  );
62375 
62376  /* The following assert statements verify that if this is a sharable
62377  ** b-tree database, the connection is holding the required table locks,
62378  ** and that no other connection has any open cursor that conflicts with
62379  ** this lock. */
62380  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
62381  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
62382 
62383  /* Assert that the caller has opened the required transaction. */
62384  assert( p->inTrans>TRANS_NONE );
62385  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
62386  assert( pBt->pPage1 && pBt->pPage1->aData );
62387  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
62388 
62389  if( wrFlag ){
62390  allocateTempSpace(pBt);
62391  if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
62392  }
62393  if( iTable==1 && btreePagecount(pBt)==0 ){
62394  assert( wrFlag==0 );
62395  iTable = 0;
62396  }
62397 
62398  /* Now that no other errors can occur, finish filling in the BtCursor
62399  ** variables and link the cursor into the BtShared list. */
62400  pCur->pgnoRoot = (Pgno)iTable;
62401  pCur->iPage = -1;
62402  pCur->pKeyInfo = pKeyInfo;
62403  pCur->pBtree = p;
62404  pCur->pBt = pBt;
62405  pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
62406  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
62407  /* If there are two or more cursors on the same btree, then all such
62408  ** cursors *must* have the BTCF_Multiple flag set. */
62409  for(pX=pBt->pCursor; pX; pX=pX->pNext){
62410  if( pX->pgnoRoot==(Pgno)iTable ){
62411  pX->curFlags |= BTCF_Multiple;
62412  pCur->curFlags |= BTCF_Multiple;
62413  }
62414  }
62415  pCur->pNext = pBt->pCursor;
62416  pBt->pCursor = pCur;
62417  pCur->eState = CURSOR_INVALID;
62418  return SQLITE_OK;
62419 }
62420 SQLITE_PRIVATE int sqlite3BtreeCursor(
62421  Btree *p, /* The btree */
62422  int iTable, /* Root page of table to open */
62423  int wrFlag, /* 1 to write. 0 read-only */
62424  struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
62425  BtCursor *pCur /* Write new cursor here */
62426 ){
62427  int rc;
62428  if( iTable<1 ){
62429  rc = SQLITE_CORRUPT_BKPT;
62430  }else{
62431  sqlite3BtreeEnter(p);
62432  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
62433  sqlite3BtreeLeave(p);
62434  }
62435  return rc;
62436 }
62437 
62438 /*
62439 ** Return the size of a BtCursor object in bytes.
62440 **
62441 ** This interfaces is needed so that users of cursors can preallocate
62442 ** sufficient storage to hold a cursor. The BtCursor object is opaque
62443 ** to users so they cannot do the sizeof() themselves - they must call
62444 ** this routine.
62445 */
62446 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
62447  return ROUND8(sizeof(BtCursor));
62448 }
62449 
62450 /*
62451 ** Initialize memory that will be converted into a BtCursor object.
62452 **
62453 ** The simple approach here would be to memset() the entire object
62454 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
62455 ** do not need to be zeroed and they are large, so we can save a lot
62456 ** of run-time by skipping the initialization of those elements.
62457 */
62458 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
62459  memset(p, 0, offsetof(BtCursor, iPage));
62460 }
62461 
62462 /*
62463 ** Close a cursor. The read lock on the database file is released
62464 ** when the last cursor is closed.
62465 */
62466 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
62467  Btree *pBtree = pCur->pBtree;
62468  if( pBtree ){
62469  int i;
62470  BtShared *pBt = pCur->pBt;
62471  sqlite3BtreeEnter(pBtree);
62472  sqlite3BtreeClearCursor(pCur);
62473  assert( pBt->pCursor!=0 );
62474  if( pBt->pCursor==pCur ){
62475  pBt->pCursor = pCur->pNext;
62476  }else{
62477  BtCursor *pPrev = pBt->pCursor;
62478  do{
62479  if( pPrev->pNext==pCur ){
62480  pPrev->pNext = pCur->pNext;
62481  break;
62482  }
62483  pPrev = pPrev->pNext;
62484  }while( ALWAYS(pPrev) );
62485  }
62486  for(i=0; i<=pCur->iPage; i++){
62487  releasePage(pCur->apPage[i]);
62488  }
62489  unlockBtreeIfUnused(pBt);
62490  sqlite3_free(pCur->aOverflow);
62491  /* sqlite3_free(pCur); */
62492  sqlite3BtreeLeave(pBtree);
62493  }
62494  return SQLITE_OK;
62495 }
62496 
62497 /*
62498 ** Make sure the BtCursor* given in the argument has a valid
62499 ** BtCursor.info structure. If it is not already valid, call
62500 ** btreeParseCell() to fill it in.
62501 **
62502 ** BtCursor.info is a cache of the information in the current cell.
62503 ** Using this cache reduces the number of calls to btreeParseCell().
62504 */
62505 #ifndef NDEBUG
62506  static void assertCellInfo(BtCursor *pCur){
62507  CellInfo info;
62508  int iPage = pCur->iPage;
62509  memset(&info, 0, sizeof(info));
62510  btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
62511  assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
62512  }
62513 #else
62514  #define assertCellInfo(x)
62515 #endif
62516 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
62517  if( pCur->info.nSize==0 ){
62518  int iPage = pCur->iPage;
62519  pCur->curFlags |= BTCF_ValidNKey;
62520  btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
62521  }else{
62522  assertCellInfo(pCur);
62523  }
62524 }
62525 
62526 #ifndef NDEBUG /* The next routine used only within assert() statements */
62527 /*
62528 ** Return true if the given BtCursor is valid. A valid cursor is one
62529 ** that is currently pointing to a row in a (non-empty) table.
62530 ** This is a verification routine is used only within assert() statements.
62531 */
62532 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
62533  return pCur && pCur->eState==CURSOR_VALID;
62534 }
62535 #endif /* NDEBUG */
62536 
62537 /*
62538 ** Return the value of the integer key or "rowid" for a table btree.
62539 ** This routine is only valid for a cursor that is pointing into a
62540 ** ordinary table btree. If the cursor points to an index btree or
62541 ** is invalid, the result of this routine is undefined.
62542 */
62543 SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
62544  assert( cursorHoldsMutex(pCur) );
62545  assert( pCur->eState==CURSOR_VALID );
62546  assert( pCur->curIntKey );
62547  getCellInfo(pCur);
62548  return pCur->info.nKey;
62549 }
62550 
62551 /*
62552 ** Return the number of bytes of payload for the entry that pCur is
62553 ** currently pointing to. For table btrees, this will be the amount
62554 ** of data. For index btrees, this will be the size of the key.
62555 **
62556 ** The caller must guarantee that the cursor is pointing to a non-NULL
62557 ** valid entry. In other words, the calling procedure must guarantee
62558 ** that the cursor has Cursor.eState==CURSOR_VALID.
62559 */
62560 SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
62561  assert( cursorHoldsMutex(pCur) );
62562  assert( pCur->eState==CURSOR_VALID );
62563  getCellInfo(pCur);
62564  return pCur->info.nPayload;
62565 }
62566 
62567 /*
62568 ** Given the page number of an overflow page in the database (parameter
62569 ** ovfl), this function finds the page number of the next page in the
62570 ** linked list of overflow pages. If possible, it uses the auto-vacuum
62571 ** pointer-map data instead of reading the content of page ovfl to do so.
62572 **
62573 ** If an error occurs an SQLite error code is returned. Otherwise:
62574 **
62575 ** The page number of the next overflow page in the linked list is
62576 ** written to *pPgnoNext. If page ovfl is the last page in its linked
62577 ** list, *pPgnoNext is set to zero.
62578 **
62579 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
62580 ** to page number pOvfl was obtained, then *ppPage is set to point to that
62581 ** reference. It is the responsibility of the caller to call releasePage()
62582 ** on *ppPage to free the reference. In no reference was obtained (because
62583 ** the pointer-map was used to obtain the value for *pPgnoNext), then
62584 ** *ppPage is set to zero.
62585 */
62586 static int getOverflowPage(
62587  BtShared *pBt, /* The database file */
62588  Pgno ovfl, /* Current overflow page number */
62589  MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
62590  Pgno *pPgnoNext /* OUT: Next overflow page number */
62591 ){
62592  Pgno next = 0;
62593  MemPage *pPage = 0;
62594  int rc = SQLITE_OK;
62595 
62596  assert( sqlite3_mutex_held(pBt->mutex) );
62597  assert(pPgnoNext);
62598 
62599 #ifndef SQLITE_OMIT_AUTOVACUUM
62600  /* Try to find the next page in the overflow list using the
62601  ** autovacuum pointer-map pages. Guess that the next page in
62602  ** the overflow list is page number (ovfl+1). If that guess turns
62603  ** out to be wrong, fall back to loading the data of page
62604  ** number ovfl to determine the next page number.
62605  */
62606  if( pBt->autoVacuum ){
62607  Pgno pgno;
62608  Pgno iGuess = ovfl+1;
62609  u8 eType;
62610 
62611  while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
62612  iGuess++;
62613  }
62614 
62615  if( iGuess<=btreePagecount(pBt) ){
62616  rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
62617  if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
62618  next = iGuess;
62619  rc = SQLITE_DONE;
62620  }
62621  }
62622  }
62623 #endif
62624 
62625  assert( next==0 || rc==SQLITE_DONE );
62626  if( rc==SQLITE_OK ){
62627  rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
62628  assert( rc==SQLITE_OK || pPage==0 );
62629  if( rc==SQLITE_OK ){
62630  next = get4byte(pPage->aData);
62631  }
62632  }
62633 
62634  *pPgnoNext = next;
62635  if( ppPage ){
62636  *ppPage = pPage;
62637  }else{
62638  releasePage(pPage);
62639  }
62640  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
62641 }
62642 
62643 /*
62644 ** Copy data from a buffer to a page, or from a page to a buffer.
62645 **
62646 ** pPayload is a pointer to data stored on database page pDbPage.
62647 ** If argument eOp is false, then nByte bytes of data are copied
62648 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
62649 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
62650 ** of data are copied from the buffer pBuf to pPayload.
62651 **
62652 ** SQLITE_OK is returned on success, otherwise an error code.
62653 */
62654 static int copyPayload(
62655  void *pPayload, /* Pointer to page data */
62656  void *pBuf, /* Pointer to buffer */
62657  int nByte, /* Number of bytes to copy */
62658  int eOp, /* 0 -> copy from page, 1 -> copy to page */
62659  DbPage *pDbPage /* Page containing pPayload */
62660 ){
62661  if( eOp ){
62662  /* Copy data from buffer to page (a write operation) */
62663  int rc = sqlite3PagerWrite(pDbPage);
62664  if( rc!=SQLITE_OK ){
62665  return rc;
62666  }
62667  memcpy(pPayload, pBuf, nByte);
62668  }else{
62669  /* Copy data from page to buffer (a read operation) */
62670  memcpy(pBuf, pPayload, nByte);
62671  }
62672  return SQLITE_OK;
62673 }
62674 
62675 /*
62676 ** This function is used to read or overwrite payload information
62677 ** for the entry that the pCur cursor is pointing to. The eOp
62678 ** argument is interpreted as follows:
62679 **
62680 ** 0: The operation is a read. Populate the overflow cache.
62681 ** 1: The operation is a write. Populate the overflow cache.
62682 ** 2: The operation is a read. Do not populate the overflow cache.
62683 **
62684 ** A total of "amt" bytes are read or written beginning at "offset".
62685 ** Data is read to or from the buffer pBuf.
62686 **
62687 ** The content being read or written might appear on the main page
62688 ** or be scattered out on multiple overflow pages.
62689 **
62690 ** If the current cursor entry uses one or more overflow pages and the
62691 ** eOp argument is not 2, this function may allocate space for and lazily
62692 ** populates the overflow page-list cache array (BtCursor.aOverflow).
62693 ** Subsequent calls use this cache to make seeking to the supplied offset
62694 ** more efficient.
62695 **
62696 ** Once an overflow page-list cache has been allocated, it may be
62697 ** invalidated if some other cursor writes to the same table, or if
62698 ** the cursor is moved to a different row. Additionally, in auto-vacuum
62699 ** mode, the following events may invalidate an overflow page-list cache.
62700 **
62701 ** * An incremental vacuum,
62702 ** * A commit in auto_vacuum="full" mode,
62703 ** * Creating a table (may require moving an overflow page).
62704 */
62705 static int accessPayload(
62706  BtCursor *pCur, /* Cursor pointing to entry to read from */
62707  u32 offset, /* Begin reading this far into payload */
62708  u32 amt, /* Read this many bytes */
62709  unsigned char *pBuf, /* Write the bytes into this buffer */
62710  int eOp /* zero to read. non-zero to write. */
62711 ){
62712  unsigned char *aPayload;
62713  int rc = SQLITE_OK;
62714  int iIdx = 0;
62715  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
62716  BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
62717 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62718  unsigned char * const pBufStart = pBuf;
62719  int bEnd; /* True if reading to end of data */
62720 #endif
62721 
62722  assert( pPage );
62723  assert( pCur->eState==CURSOR_VALID );
62724  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
62725  assert( cursorHoldsMutex(pCur) );
62726  assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
62727 
62728  getCellInfo(pCur);
62729  aPayload = pCur->info.pPayload;
62730 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62731  bEnd = offset+amt==pCur->info.nPayload;
62732 #endif
62733  assert( offset+amt <= pCur->info.nPayload );
62734 
62735  assert( aPayload > pPage->aData );
62736  if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
62737  /* Trying to read or write past the end of the data is an error. The
62738  ** conditional above is really:
62739  ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
62740  ** but is recast into its current form to avoid integer overflow problems
62741  */
62742  return SQLITE_CORRUPT_BKPT;
62743  }
62744 
62745  /* Check if data must be read/written to/from the btree page itself. */
62746  if( offset<pCur->info.nLocal ){
62747  int a = amt;
62748  if( a+offset>pCur->info.nLocal ){
62749  a = pCur->info.nLocal - offset;
62750  }
62751  rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
62752  offset = 0;
62753  pBuf += a;
62754  amt -= a;
62755  }else{
62756  offset -= pCur->info.nLocal;
62757  }
62758 
62759 
62760  if( rc==SQLITE_OK && amt>0 ){
62761  const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
62762  Pgno nextPage;
62763 
62764  nextPage = get4byte(&aPayload[pCur->info.nLocal]);
62765 
62766  /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
62767  ** Except, do not allocate aOverflow[] for eOp==2.
62768  **
62769  ** The aOverflow[] array is sized at one entry for each overflow page
62770  ** in the overflow chain. The page number of the first overflow page is
62771  ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
62772  ** means "not yet known" (the cache is lazily populated).
62773  */
62774  if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
62775  int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
62776  if( nOvfl>pCur->nOvflAlloc ){
62777  Pgno *aNew = (Pgno*)sqlite3Realloc(
62778  pCur->aOverflow, nOvfl*2*sizeof(Pgno)
62779  );
62780  if( aNew==0 ){
62781  rc = SQLITE_NOMEM_BKPT;
62782  }else{
62783  pCur->nOvflAlloc = nOvfl*2;
62784  pCur->aOverflow = aNew;
62785  }
62786  }
62787  if( rc==SQLITE_OK ){
62788  memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
62789  pCur->curFlags |= BTCF_ValidOvfl;
62790  }
62791  }
62792 
62793  /* If the overflow page-list cache has been allocated and the
62794  ** entry for the first required overflow page is valid, skip
62795  ** directly to it.
62796  */
62797  if( (pCur->curFlags & BTCF_ValidOvfl)!=0
62798  && pCur->aOverflow[offset/ovflSize]
62799  ){
62800  iIdx = (offset/ovflSize);
62801  nextPage = pCur->aOverflow[iIdx];
62802  offset = (offset%ovflSize);
62803  }
62804 
62805  for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
62806 
62807  /* If required, populate the overflow page-list cache. */
62808  if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
62809  assert( pCur->aOverflow[iIdx]==0
62810  || pCur->aOverflow[iIdx]==nextPage
62811  || CORRUPT_DB );
62812  pCur->aOverflow[iIdx] = nextPage;
62813  }
62814 
62815  if( offset>=ovflSize ){
62816  /* The only reason to read this page is to obtain the page
62817  ** number for the next page in the overflow chain. The page
62818  ** data is not required. So first try to lookup the overflow
62819  ** page-list cache, if any, then fall back to the getOverflowPage()
62820  ** function.
62821  **
62822  ** Note that the aOverflow[] array must be allocated because eOp!=2
62823  ** here. If eOp==2, then offset==0 and this branch is never taken.
62824  */
62825  assert( eOp!=2 );
62826  assert( pCur->curFlags & BTCF_ValidOvfl );
62827  assert( pCur->pBtree->db==pBt->db );
62828  if( pCur->aOverflow[iIdx+1] ){
62829  nextPage = pCur->aOverflow[iIdx+1];
62830  }else{
62831  rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
62832  }
62833  offset -= ovflSize;
62834  }else{
62835  /* Need to read this page properly. It contains some of the
62836  ** range of data that is being read (eOp==0) or written (eOp!=0).
62837  */
62838 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62839  sqlite3_file *fd;
62840 #endif
62841  int a = amt;
62842  if( a + offset > ovflSize ){
62843  a = ovflSize - offset;
62844  }
62845 
62846 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62847  /* If all the following are true:
62848  **
62849  ** 1) this is a read operation, and
62850  ** 2) data is required from the start of this overflow page, and
62851  ** 3) the database is file-backed, and
62852  ** 4) there is no open write-transaction, and
62853  ** 5) the database is not a WAL database,
62854  ** 6) all data from the page is being read.
62855  ** 7) at least 4 bytes have already been read into the output buffer
62856  **
62857  ** then data can be read directly from the database file into the
62858  ** output buffer, bypassing the page-cache altogether. This speeds
62859  ** up loading large records that span many overflow pages.
62860  */
62861  if( (eOp&0x01)==0 /* (1) */
62862  && offset==0 /* (2) */
62863  && (bEnd || a==ovflSize) /* (6) */
62864  && pBt->inTransaction==TRANS_READ /* (4) */
62865  && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
62866  && 0==sqlite3PagerUseWal(pBt->pPager) /* (5) */
62867  && &pBuf[-4]>=pBufStart /* (7) */
62868  ){
62869  u8 aSave[4];
62870  u8 *aWrite = &pBuf[-4];
62871  assert( aWrite>=pBufStart ); /* hence (7) */
62872  memcpy(aSave, aWrite, 4);
62873  rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
62874  nextPage = get4byte(aWrite);
62875  memcpy(aWrite, aSave, 4);
62876  }else
62877 #endif
62878 
62879  {
62880  DbPage *pDbPage;
62881  rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
62882  ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
62883  );
62884  if( rc==SQLITE_OK ){
62885  aPayload = sqlite3PagerGetData(pDbPage);
62886  nextPage = get4byte(aPayload);
62887  rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
62888  sqlite3PagerUnref(pDbPage);
62889  offset = 0;
62890  }
62891  }
62892  amt -= a;
62893  pBuf += a;
62894  }
62895  }
62896  }
62897 
62898  if( rc==SQLITE_OK && amt>0 ){
62899  return SQLITE_CORRUPT_BKPT;
62900  }
62901  return rc;
62902 }
62903 
62904 /*
62905 ** Read part of the key associated with cursor pCur. Exactly
62906 ** "amt" bytes will be transferred into pBuf[]. The transfer
62907 ** begins at "offset".
62908 **
62909 ** The caller must ensure that pCur is pointing to a valid row
62910 ** in the table.
62911 **
62912 ** Return SQLITE_OK on success or an error code if anything goes
62913 ** wrong. An error is returned if "offset+amt" is larger than
62914 ** the available payload.
62915 */
62916 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62917  assert( cursorHoldsMutex(pCur) );
62918  assert( pCur->eState==CURSOR_VALID );
62919  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62920  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62921  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
62922 }
62923 
62924 /*
62925 ** Read part of the data associated with cursor pCur. Exactly
62926 ** "amt" bytes will be transfered into pBuf[]. The transfer
62927 ** begins at "offset".
62928 **
62929 ** Return SQLITE_OK on success or an error code if anything goes
62930 ** wrong. An error is returned if "offset+amt" is larger than
62931 ** the available payload.
62932 */
62933 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62934  int rc;
62935 
62936 #ifndef SQLITE_OMIT_INCRBLOB
62937  if ( pCur->eState==CURSOR_INVALID ){
62938  return SQLITE_ABORT;
62939  }
62940 #endif
62941 
62942  assert( cursorOwnsBtShared(pCur) );
62943  rc = restoreCursorPosition(pCur);
62944  if( rc==SQLITE_OK ){
62945  assert( pCur->eState==CURSOR_VALID );
62946  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62947  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62948  rc = accessPayload(pCur, offset, amt, pBuf, 0);
62949  }
62950  return rc;
62951 }
62952 
62953 /*
62954 ** Return a pointer to payload information from the entry that the
62955 ** pCur cursor is pointing to. The pointer is to the beginning of
62956 ** the key if index btrees (pPage->intKey==0) and is the data for
62957 ** table btrees (pPage->intKey==1). The number of bytes of available
62958 ** key/data is written into *pAmt. If *pAmt==0, then the value
62959 ** returned will not be a valid pointer.
62960 **
62961 ** This routine is an optimization. It is common for the entire key
62962 ** and data to fit on the local page and for there to be no overflow
62963 ** pages. When that is so, this routine can be used to access the
62964 ** key and data without making a copy. If the key and/or data spills
62965 ** onto overflow pages, then accessPayload() must be used to reassemble
62966 ** the key/data and copy it into a preallocated buffer.
62967 **
62968 ** The pointer returned by this routine looks directly into the cached
62969 ** page of the database. The data might change or move the next time
62970 ** any btree routine is called.
62971 */
62972 static const void *fetchPayload(
62973  BtCursor *pCur, /* Cursor pointing to entry to read from */
62974  u32 *pAmt /* Write the number of available bytes here */
62975 ){
62976  u32 amt;
62977  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
62978  assert( pCur->eState==CURSOR_VALID );
62979  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
62980  assert( cursorOwnsBtShared(pCur) );
62981  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62982  assert( pCur->info.nSize>0 );
62983  assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
62984  assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
62985  amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
62986  if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
62987  *pAmt = amt;
62988  return (void*)pCur->info.pPayload;
62989 }
62990 
62991 
62992 /*
62993 ** For the entry that cursor pCur is point to, return as
62994 ** many bytes of the key or data as are available on the local
62995 ** b-tree page. Write the number of available bytes into *pAmt.
62996 **
62997 ** The pointer returned is ephemeral. The key/data may move
62998 ** or be destroyed on the next call to any Btree routine,
62999 ** including calls from other threads against the same cache.
63000 ** Hence, a mutex on the BtShared should be held prior to calling
63001 ** this routine.
63002 **
63003 ** These routines is used to get quick access to key and data
63004 ** in the common case where no overflow pages are used.
63005 */
63006 SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
63007  return fetchPayload(pCur, pAmt);
63008 }
63009 
63010 
63011 /*
63012 ** Move the cursor down to a new child page. The newPgno argument is the
63013 ** page number of the child page to move to.
63014 **
63015 ** This function returns SQLITE_CORRUPT if the page-header flags field of
63016 ** the new child page does not match the flags field of the parent (i.e.
63017 ** if an intkey page appears to be the parent of a non-intkey page, or
63018 ** vice-versa).
63019 */
63020 static int moveToChild(BtCursor *pCur, u32 newPgno){
63021  BtShared *pBt = pCur->pBt;
63022 
63023  assert( cursorOwnsBtShared(pCur) );
63024  assert( pCur->eState==CURSOR_VALID );
63025  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
63026  assert( pCur->iPage>=0 );
63027  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
63028  return SQLITE_CORRUPT_BKPT;
63029  }
63030  pCur->info.nSize = 0;
63031  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63032  pCur->iPage++;
63033  pCur->aiIdx[pCur->iPage] = 0;
63034  return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
63035  pCur, pCur->curPagerFlags);
63036 }
63037 
63038 #if SQLITE_DEBUG
63039 /*
63040 ** Page pParent is an internal (non-leaf) tree page. This function
63041 ** asserts that page number iChild is the left-child if the iIdx'th
63042 ** cell in page pParent. Or, if iIdx is equal to the total number of
63043 ** cells in pParent, that page number iChild is the right-child of
63044 ** the page.
63045 */
63046 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
63047  if( CORRUPT_DB ) return; /* The conditions tested below might not be true
63048  ** in a corrupt database */
63049  assert( iIdx<=pParent->nCell );
63050  if( iIdx==pParent->nCell ){
63051  assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
63052  }else{
63053  assert( get4byte(findCell(pParent, iIdx))==iChild );
63054  }
63055 }
63056 #else
63057 # define assertParentIndex(x,y,z)
63058 #endif
63059 
63060 /*
63061 ** Move the cursor up to the parent page.
63062 **
63063 ** pCur->idx is set to the cell index that contains the pointer
63064 ** to the page we are coming from. If we are coming from the
63065 ** right-most child page then pCur->idx is set to one more than
63066 ** the largest cell index.
63067 */
63068 static void moveToParent(BtCursor *pCur){
63069  assert( cursorOwnsBtShared(pCur) );
63070  assert( pCur->eState==CURSOR_VALID );
63071  assert( pCur->iPage>0 );
63072  assert( pCur->apPage[pCur->iPage] );
63073  assertParentIndex(
63074  pCur->apPage[pCur->iPage-1],
63075  pCur->aiIdx[pCur->iPage-1],
63076  pCur->apPage[pCur->iPage]->pgno
63077  );
63078  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
63079  pCur->info.nSize = 0;
63080  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63081  releasePageNotNull(pCur->apPage[pCur->iPage--]);
63082 }
63083 
63084 /*
63085 ** Move the cursor to point to the root page of its b-tree structure.
63086 **
63087 ** If the table has a virtual root page, then the cursor is moved to point
63088 ** to the virtual root page instead of the actual root page. A table has a
63089 ** virtual root page when the actual root page contains no cells and a
63090 ** single child page. This can only happen with the table rooted at page 1.
63091 **
63092 ** If the b-tree structure is empty, the cursor state is set to
63093 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
63094 ** cell located on the root (or virtual root) page and the cursor state
63095 ** is set to CURSOR_VALID.
63096 **
63097 ** If this function returns successfully, it may be assumed that the
63098 ** page-header flags indicate that the [virtual] root-page is the expected
63099 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
63100 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
63101 ** indicating a table b-tree, or if the caller did specify a KeyInfo
63102 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
63103 ** b-tree).
63104 */
63105 static int moveToRoot(BtCursor *pCur){
63106  MemPage *pRoot;
63107  int rc = SQLITE_OK;
63108 
63109  assert( cursorOwnsBtShared(pCur) );
63110  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
63111  assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
63112  assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
63113  if( pCur->eState>=CURSOR_REQUIRESEEK ){
63114  if( pCur->eState==CURSOR_FAULT ){
63115  assert( pCur->skipNext!=SQLITE_OK );
63116  return pCur->skipNext;
63117  }
63118  sqlite3BtreeClearCursor(pCur);
63119  }
63120 
63121  if( pCur->iPage>=0 ){
63122  while( pCur->iPage ){
63123  assert( pCur->apPage[pCur->iPage]!=0 );
63124  releasePageNotNull(pCur->apPage[pCur->iPage--]);
63125  }
63126  }else if( pCur->pgnoRoot==0 ){
63127  pCur->eState = CURSOR_INVALID;
63128  return SQLITE_OK;
63129  }else{
63130  assert( pCur->iPage==(-1) );
63131  rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
63132  0, pCur->curPagerFlags);
63133  if( rc!=SQLITE_OK ){
63134  pCur->eState = CURSOR_INVALID;
63135  return rc;
63136  }
63137  pCur->iPage = 0;
63138  pCur->curIntKey = pCur->apPage[0]->intKey;
63139  }
63140  pRoot = pCur->apPage[0];
63141  assert( pRoot->pgno==pCur->pgnoRoot );
63142 
63143  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
63144  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
63145  ** NULL, the caller expects a table b-tree. If this is not the case,
63146  ** return an SQLITE_CORRUPT error.
63147  **
63148  ** Earlier versions of SQLite assumed that this test could not fail
63149  ** if the root page was already loaded when this function was called (i.e.
63150  ** if pCur->iPage>=0). But this is not so if the database is corrupted
63151  ** in such a way that page pRoot is linked into a second b-tree table
63152  ** (or the freelist). */
63153  assert( pRoot->intKey==1 || pRoot->intKey==0 );
63154  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
63155  return SQLITE_CORRUPT_BKPT;
63156  }
63157 
63158  pCur->aiIdx[0] = 0;
63159  pCur->info.nSize = 0;
63160  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
63161 
63162  if( pRoot->nCell>0 ){
63163  pCur->eState = CURSOR_VALID;
63164  }else if( !pRoot->leaf ){
63165  Pgno subpage;
63166  if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
63167  subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
63168  pCur->eState = CURSOR_VALID;
63169  rc = moveToChild(pCur, subpage);
63170  }else{
63171  pCur->eState = CURSOR_INVALID;
63172  }
63173  return rc;
63174 }
63175 
63176 /*
63177 ** Move the cursor down to the left-most leaf entry beneath the
63178 ** entry to which it is currently pointing.
63179 **
63180 ** The left-most leaf is the one with the smallest key - the first
63181 ** in ascending order.
63182 */
63183 static int moveToLeftmost(BtCursor *pCur){
63184  Pgno pgno;
63185  int rc = SQLITE_OK;
63186  MemPage *pPage;
63187 
63188  assert( cursorOwnsBtShared(pCur) );
63189  assert( pCur->eState==CURSOR_VALID );
63190  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63191  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
63192  pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
63193  rc = moveToChild(pCur, pgno);
63194  }
63195  return rc;
63196 }
63197 
63198 /*
63199 ** Move the cursor down to the right-most leaf entry beneath the
63200 ** page to which it is currently pointing. Notice the difference
63201 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
63202 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
63203 ** finds the right-most entry beneath the *page*.
63204 **
63205 ** The right-most entry is the one with the largest key - the last
63206 ** key in ascending order.
63207 */
63208 static int moveToRightmost(BtCursor *pCur){
63209  Pgno pgno;
63210  int rc = SQLITE_OK;
63211  MemPage *pPage = 0;
63212 
63213  assert( cursorOwnsBtShared(pCur) );
63214  assert( pCur->eState==CURSOR_VALID );
63215  while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63216  pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63217  pCur->aiIdx[pCur->iPage] = pPage->nCell;
63218  rc = moveToChild(pCur, pgno);
63219  if( rc ) return rc;
63220  }
63221  pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
63222  assert( pCur->info.nSize==0 );
63223  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
63224  return SQLITE_OK;
63225 }
63226 
63227 /* Move the cursor to the first entry in the table. Return SQLITE_OK
63228 ** on success. Set *pRes to 0 if the cursor actually points to something
63229 ** or set *pRes to 1 if the table is empty.
63230 */
63231 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
63232  int rc;
63233 
63234  assert( cursorOwnsBtShared(pCur) );
63235  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63236  rc = moveToRoot(pCur);
63237  if( rc==SQLITE_OK ){
63238  if( pCur->eState==CURSOR_INVALID ){
63239  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63240  *pRes = 1;
63241  }else{
63242  assert( pCur->apPage[pCur->iPage]->nCell>0 );
63243  *pRes = 0;
63244  rc = moveToLeftmost(pCur);
63245  }
63246  }
63247  return rc;
63248 }
63249 
63250 /* Move the cursor to the last entry in the table. Return SQLITE_OK
63251 ** on success. Set *pRes to 0 if the cursor actually points to something
63252 ** or set *pRes to 1 if the table is empty.
63253 */
63254 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
63255  int rc;
63256 
63257  assert( cursorOwnsBtShared(pCur) );
63258  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63259 
63260  /* If the cursor already points to the last entry, this is a no-op. */
63261  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
63262 #ifdef SQLITE_DEBUG
63263  /* This block serves to assert() that the cursor really does point
63264  ** to the last entry in the b-tree. */
63265  int ii;
63266  for(ii=0; ii<pCur->iPage; ii++){
63267  assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
63268  }
63269  assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
63270  assert( pCur->apPage[pCur->iPage]->leaf );
63271 #endif
63272  return SQLITE_OK;
63273  }
63274 
63275  rc = moveToRoot(pCur);
63276  if( rc==SQLITE_OK ){
63277  if( CURSOR_INVALID==pCur->eState ){
63278  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63279  *pRes = 1;
63280  }else{
63281  assert( pCur->eState==CURSOR_VALID );
63282  *pRes = 0;
63283  rc = moveToRightmost(pCur);
63284  if( rc==SQLITE_OK ){
63285  pCur->curFlags |= BTCF_AtLast;
63286  }else{
63287  pCur->curFlags &= ~BTCF_AtLast;
63288  }
63289 
63290  }
63291  }
63292  return rc;
63293 }
63294 
63295 /* Move the cursor so that it points to an entry near the key
63296 ** specified by pIdxKey or intKey. Return a success code.
63297 **
63298 ** For INTKEY tables, the intKey parameter is used. pIdxKey
63299 ** must be NULL. For index tables, pIdxKey is used and intKey
63300 ** is ignored.
63301 **
63302 ** If an exact match is not found, then the cursor is always
63303 ** left pointing at a leaf page which would hold the entry if it
63304 ** were present. The cursor might point to an entry that comes
63305 ** before or after the key.
63306 **
63307 ** An integer is written into *pRes which is the result of
63308 ** comparing the key with the entry to which the cursor is
63309 ** pointing. The meaning of the integer written into
63310 ** *pRes is as follows:
63311 **
63312 ** *pRes<0 The cursor is left pointing at an entry that
63313 ** is smaller than intKey/pIdxKey or if the table is empty
63314 ** and the cursor is therefore left point to nothing.
63315 **
63316 ** *pRes==0 The cursor is left pointing at an entry that
63317 ** exactly matches intKey/pIdxKey.
63318 **
63319 ** *pRes>0 The cursor is left pointing at an entry that
63320 ** is larger than intKey/pIdxKey.
63321 **
63322 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
63323 ** exists an entry in the table that exactly matches pIdxKey.
63324 */
63325 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
63326  BtCursor *pCur, /* The cursor to be moved */
63327  UnpackedRecord *pIdxKey, /* Unpacked index key */
63328  i64 intKey, /* The table key */
63329  int biasRight, /* If true, bias the search to the high end */
63330  int *pRes /* Write search results here */
63331 ){
63332  int rc;
63333  RecordCompare xRecordCompare;
63334 
63335  assert( cursorOwnsBtShared(pCur) );
63336  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63337  assert( pRes );
63338  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
63339  assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
63340 
63341  /* If the cursor is already positioned at the point we are trying
63342  ** to move to, then just return without doing any work */
63343  if( pIdxKey==0
63344  && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
63345  ){
63346  if( pCur->info.nKey==intKey ){
63347  *pRes = 0;
63348  return SQLITE_OK;
63349  }
63350  if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
63351  *pRes = -1;
63352  return SQLITE_OK;
63353  }
63354  }
63355 
63356  if( pIdxKey ){
63357  xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
63358  pIdxKey->errCode = 0;
63359  assert( pIdxKey->default_rc==1
63360  || pIdxKey->default_rc==0
63361  || pIdxKey->default_rc==-1
63362  );
63363  }else{
63364  xRecordCompare = 0; /* All keys are integers */
63365  }
63366 
63367  rc = moveToRoot(pCur);
63368  if( rc ){
63369  return rc;
63370  }
63371  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
63372  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
63373  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
63374  if( pCur->eState==CURSOR_INVALID ){
63375  *pRes = -1;
63376  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63377  return SQLITE_OK;
63378  }
63379  assert( pCur->apPage[0]->intKey==pCur->curIntKey );
63380  assert( pCur->curIntKey || pIdxKey );
63381  for(;;){
63382  int lwr, upr, idx, c;
63383  Pgno chldPg;
63384  MemPage *pPage = pCur->apPage[pCur->iPage];
63385  u8 *pCell; /* Pointer to current cell in pPage */
63386 
63387  /* pPage->nCell must be greater than zero. If this is the root-page
63388  ** the cursor would have been INVALID above and this for(;;) loop
63389  ** not run. If this is not the root-page, then the moveToChild() routine
63390  ** would have already detected db corruption. Similarly, pPage must
63391  ** be the right kind (index or table) of b-tree page. Otherwise
63392  ** a moveToChild() or moveToRoot() call would have detected corruption. */
63393  assert( pPage->nCell>0 );
63394  assert( pPage->intKey==(pIdxKey==0) );
63395  lwr = 0;
63396  upr = pPage->nCell-1;
63397  assert( biasRight==0 || biasRight==1 );
63398  idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
63399  pCur->aiIdx[pCur->iPage] = (u16)idx;
63400  if( xRecordCompare==0 ){
63401  for(;;){
63402  i64 nCellKey;
63403  pCell = findCellPastPtr(pPage, idx);
63404  if( pPage->intKeyLeaf ){
63405  while( 0x80 <= *(pCell++) ){
63406  if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
63407  }
63408  }
63409  getVarint(pCell, (u64*)&nCellKey);
63410  if( nCellKey<intKey ){
63411  lwr = idx+1;
63412  if( lwr>upr ){ c = -1; break; }
63413  }else if( nCellKey>intKey ){
63414  upr = idx-1;
63415  if( lwr>upr ){ c = +1; break; }
63416  }else{
63417  assert( nCellKey==intKey );
63418  pCur->curFlags |= BTCF_ValidNKey;
63419  pCur->info.nKey = nCellKey;
63420  pCur->aiIdx[pCur->iPage] = (u16)idx;
63421  if( !pPage->leaf ){
63422  lwr = idx;
63423  goto moveto_next_layer;
63424  }else{
63425  *pRes = 0;
63426  rc = SQLITE_OK;
63427  goto moveto_finish;
63428  }
63429  }
63430  assert( lwr+upr>=0 );
63431  idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
63432  }
63433  }else{
63434  for(;;){
63435  int nCell; /* Size of the pCell cell in bytes */
63436  pCell = findCellPastPtr(pPage, idx);
63437 
63438  /* The maximum supported page-size is 65536 bytes. This means that
63439  ** the maximum number of record bytes stored on an index B-Tree
63440  ** page is less than 16384 bytes and may be stored as a 2-byte
63441  ** varint. This information is used to attempt to avoid parsing
63442  ** the entire cell by checking for the cases where the record is
63443  ** stored entirely within the b-tree page by inspecting the first
63444  ** 2 bytes of the cell.
63445  */
63446  nCell = pCell[0];
63447  if( nCell<=pPage->max1bytePayload ){
63448  /* This branch runs if the record-size field of the cell is a
63449  ** single byte varint and the record fits entirely on the main
63450  ** b-tree page. */
63451  testcase( pCell+nCell+1==pPage->aDataEnd );
63452  c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
63453  }else if( !(pCell[1] & 0x80)
63454  && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
63455  ){
63456  /* The record-size field is a 2 byte varint and the record
63457  ** fits entirely on the main b-tree page. */
63458  testcase( pCell+nCell+2==pPage->aDataEnd );
63459  c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
63460  }else{
63461  /* The record flows over onto one or more overflow pages. In
63462  ** this case the whole cell needs to be parsed, a buffer allocated
63463  ** and accessPayload() used to retrieve the record into the
63464  ** buffer before VdbeRecordCompare() can be called.
63465  **
63466  ** If the record is corrupt, the xRecordCompare routine may read
63467  ** up to two varints past the end of the buffer. An extra 18
63468  ** bytes of padding is allocated at the end of the buffer in
63469  ** case this happens. */
63470  void *pCellKey;
63471  u8 * const pCellBody = pCell - pPage->childPtrSize;
63472  pPage->xParseCell(pPage, pCellBody, &pCur->info);
63473  nCell = (int)pCur->info.nKey;
63474  testcase( nCell<0 ); /* True if key size is 2^32 or more */
63475  testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
63476  testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
63477  testcase( nCell==2 ); /* Minimum legal index key size */
63478  if( nCell<2 ){
63479  rc = SQLITE_CORRUPT_BKPT;
63480  goto moveto_finish;
63481  }
63482  pCellKey = sqlite3Malloc( nCell+18 );
63483  if( pCellKey==0 ){
63484  rc = SQLITE_NOMEM_BKPT;
63485  goto moveto_finish;
63486  }
63487  pCur->aiIdx[pCur->iPage] = (u16)idx;
63488  rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
63489  if( rc ){
63490  sqlite3_free(pCellKey);
63491  goto moveto_finish;
63492  }
63493  c = xRecordCompare(nCell, pCellKey, pIdxKey);
63494  sqlite3_free(pCellKey);
63495  }
63496  assert(
63497  (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
63498  && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
63499  );
63500  if( c<0 ){
63501  lwr = idx+1;
63502  }else if( c>0 ){
63503  upr = idx-1;
63504  }else{
63505  assert( c==0 );
63506  *pRes = 0;
63507  rc = SQLITE_OK;
63508  pCur->aiIdx[pCur->iPage] = (u16)idx;
63509  if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
63510  goto moveto_finish;
63511  }
63512  if( lwr>upr ) break;
63513  assert( lwr+upr>=0 );
63514  idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
63515  }
63516  }
63517  assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
63518  assert( pPage->isInit );
63519  if( pPage->leaf ){
63520  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
63521  pCur->aiIdx[pCur->iPage] = (u16)idx;
63522  *pRes = c;
63523  rc = SQLITE_OK;
63524  goto moveto_finish;
63525  }
63526 moveto_next_layer:
63527  if( lwr>=pPage->nCell ){
63528  chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63529  }else{
63530  chldPg = get4byte(findCell(pPage, lwr));
63531  }
63532  pCur->aiIdx[pCur->iPage] = (u16)lwr;
63533  rc = moveToChild(pCur, chldPg);
63534  if( rc ) break;
63535  }
63536 moveto_finish:
63537  pCur->info.nSize = 0;
63538  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63539  return rc;
63540 }
63541 
63542 
63543 /*
63544 ** Return TRUE if the cursor is not pointing at an entry of the table.
63545 **
63546 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
63547 ** past the last entry in the table or sqlite3BtreePrev() moves past
63548 ** the first entry. TRUE is also returned if the table is empty.
63549 */
63550 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
63551  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
63552  ** have been deleted? This API will need to change to return an error code
63553  ** as well as the boolean result value.
63554  */
63555  return (CURSOR_VALID!=pCur->eState);
63556 }
63557 
63558 /*
63559 ** Advance the cursor to the next entry in the database. If
63560 ** successful then set *pRes=0. If the cursor
63561 ** was already pointing to the last entry in the database before
63562 ** this routine was called, then set *pRes=1.
63563 **
63564 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
63565 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
63566 ** to the next cell on the current page. The (slower) btreeNext() helper
63567 ** routine is called when it is necessary to move to a different page or
63568 ** to restore the cursor.
63569 **
63570 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
63571 ** will be 1 if the cursor being stepped corresponds to an SQL index and
63572 ** if this routine could have been skipped if that SQL index had been
63573 ** a unique index. Otherwise the caller will have set *pRes to zero.
63574 ** Zero is the common case. The btree implementation is free to use the
63575 ** initial *pRes value as a hint to improve performance, but the current
63576 ** SQLite btree implementation does not. (Note that the comdb2 btree
63577 ** implementation does use this hint, however.)
63578 */
63579 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
63580  int rc;
63581  int idx;
63582  MemPage *pPage;
63583 
63584  assert( cursorOwnsBtShared(pCur) );
63585  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63586  assert( *pRes==0 );
63587  if( pCur->eState!=CURSOR_VALID ){
63588  assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
63589  rc = restoreCursorPosition(pCur);
63590  if( rc!=SQLITE_OK ){
63591  return rc;
63592  }
63593  if( CURSOR_INVALID==pCur->eState ){
63594  *pRes = 1;
63595  return SQLITE_OK;
63596  }
63597  if( pCur->skipNext ){
63598  assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63599  pCur->eState = CURSOR_VALID;
63600  if( pCur->skipNext>0 ){
63601  pCur->skipNext = 0;
63602  return SQLITE_OK;
63603  }
63604  pCur->skipNext = 0;
63605  }
63606  }
63607 
63608  pPage = pCur->apPage[pCur->iPage];
63609  idx = ++pCur->aiIdx[pCur->iPage];
63610  assert( pPage->isInit );
63611 
63612  /* If the database file is corrupt, it is possible for the value of idx
63613  ** to be invalid here. This can only occur if a second cursor modifies
63614  ** the page while cursor pCur is holding a reference to it. Which can
63615  ** only happen if the database is corrupt in such a way as to link the
63616  ** page into more than one b-tree structure. */
63617  testcase( idx>pPage->nCell );
63618 
63619  if( idx>=pPage->nCell ){
63620  if( !pPage->leaf ){
63621  rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
63622  if( rc ) return rc;
63623  return moveToLeftmost(pCur);
63624  }
63625  do{
63626  if( pCur->iPage==0 ){
63627  *pRes = 1;
63628  pCur->eState = CURSOR_INVALID;
63629  return SQLITE_OK;
63630  }
63631  moveToParent(pCur);
63632  pPage = pCur->apPage[pCur->iPage];
63633  }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
63634  if( pPage->intKey ){
63635  return sqlite3BtreeNext(pCur, pRes);
63636  }else{
63637  return SQLITE_OK;
63638  }
63639  }
63640  if( pPage->leaf ){
63641  return SQLITE_OK;
63642  }else{
63643  return moveToLeftmost(pCur);
63644  }
63645 }
63646 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
63647  MemPage *pPage;
63648  assert( cursorOwnsBtShared(pCur) );
63649  assert( pRes!=0 );
63650  assert( *pRes==0 || *pRes==1 );
63651  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63652  pCur->info.nSize = 0;
63653  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63654  *pRes = 0;
63655  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
63656  pPage = pCur->apPage[pCur->iPage];
63657  if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
63658  pCur->aiIdx[pCur->iPage]--;
63659  return btreeNext(pCur, pRes);
63660  }
63661  if( pPage->leaf ){
63662  return SQLITE_OK;
63663  }else{
63664  return moveToLeftmost(pCur);
63665  }
63666 }
63667 
63668 /*
63669 ** Step the cursor to the back to the previous entry in the database. If
63670 ** successful then set *pRes=0. If the cursor
63671 ** was already pointing to the first entry in the database before
63672 ** this routine was called, then set *pRes=1.
63673 **
63674 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
63675 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
63676 ** to the previous cell on the current page. The (slower) btreePrevious()
63677 ** helper routine is called when it is necessary to move to a different page
63678 ** or to restore the cursor.
63679 **
63680 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
63681 ** will be 1 if the cursor being stepped corresponds to an SQL index and
63682 ** if this routine could have been skipped if that SQL index had been
63683 ** a unique index. Otherwise the caller will have set *pRes to zero.
63684 ** Zero is the common case. The btree implementation is free to use the
63685 ** initial *pRes value as a hint to improve performance, but the current
63686 ** SQLite btree implementation does not. (Note that the comdb2 btree
63687 ** implementation does use this hint, however.)
63688 */
63689 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
63690  int rc;
63691  MemPage *pPage;
63692 
63693  assert( cursorOwnsBtShared(pCur) );
63694  assert( pRes!=0 );
63695  assert( *pRes==0 );
63696  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63697  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
63698  assert( pCur->info.nSize==0 );
63699  if( pCur->eState!=CURSOR_VALID ){
63700  rc = restoreCursorPosition(pCur);
63701  if( rc!=SQLITE_OK ){
63702  return rc;
63703  }
63704  if( CURSOR_INVALID==pCur->eState ){
63705  *pRes = 1;
63706  return SQLITE_OK;
63707  }
63708  if( pCur->skipNext ){
63709  assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63710  pCur->eState = CURSOR_VALID;
63711  if( pCur->skipNext<0 ){
63712  pCur->skipNext = 0;
63713  return SQLITE_OK;
63714  }
63715  pCur->skipNext = 0;
63716  }
63717  }
63718 
63719  pPage = pCur->apPage[pCur->iPage];
63720  assert( pPage->isInit );
63721  if( !pPage->leaf ){
63722  int idx = pCur->aiIdx[pCur->iPage];
63723  rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
63724  if( rc ) return rc;
63725  rc = moveToRightmost(pCur);
63726  }else{
63727  while( pCur->aiIdx[pCur->iPage]==0 ){
63728  if( pCur->iPage==0 ){
63729  pCur->eState = CURSOR_INVALID;
63730  *pRes = 1;
63731  return SQLITE_OK;
63732  }
63733  moveToParent(pCur);
63734  }
63735  assert( pCur->info.nSize==0 );
63736  assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
63737 
63738  pCur->aiIdx[pCur->iPage]--;
63739  pPage = pCur->apPage[pCur->iPage];
63740  if( pPage->intKey && !pPage->leaf ){
63741  rc = sqlite3BtreePrevious(pCur, pRes);
63742  }else{
63743  rc = SQLITE_OK;
63744  }
63745  }
63746  return rc;
63747 }
63748 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
63749  assert( cursorOwnsBtShared(pCur) );
63750  assert( pRes!=0 );
63751  assert( *pRes==0 || *pRes==1 );
63752  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63753  *pRes = 0;
63754  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
63755  pCur->info.nSize = 0;
63756  if( pCur->eState!=CURSOR_VALID
63757  || pCur->aiIdx[pCur->iPage]==0
63758  || pCur->apPage[pCur->iPage]->leaf==0
63759  ){
63760  return btreePrevious(pCur, pRes);
63761  }
63762  pCur->aiIdx[pCur->iPage]--;
63763  return SQLITE_OK;
63764 }
63765 
63766 /*
63767 ** Allocate a new page from the database file.
63768 **
63769 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
63770 ** has already been called on the new page.) The new page has also
63771 ** been referenced and the calling routine is responsible for calling
63772 ** sqlite3PagerUnref() on the new page when it is done.
63773 **
63774 ** SQLITE_OK is returned on success. Any other return value indicates
63775 ** an error. *ppPage is set to NULL in the event of an error.
63776 **
63777 ** If the "nearby" parameter is not 0, then an effort is made to
63778 ** locate a page close to the page number "nearby". This can be used in an
63779 ** attempt to keep related pages close to each other in the database file,
63780 ** which in turn can make database access faster.
63781 **
63782 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
63783 ** anywhere on the free-list, then it is guaranteed to be returned. If
63784 ** eMode is BTALLOC_LT then the page returned will be less than or equal
63785 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
63786 ** are no restrictions on which page is returned.
63787 */
63788 static int allocateBtreePage(
63789  BtShared *pBt, /* The btree */
63790  MemPage **ppPage, /* Store pointer to the allocated page here */
63791  Pgno *pPgno, /* Store the page number here */
63792  Pgno nearby, /* Search for a page near this one */
63793  u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
63794 ){
63795  MemPage *pPage1;
63796  int rc;
63797  u32 n; /* Number of pages on the freelist */
63798  u32 k; /* Number of leaves on the trunk of the freelist */
63799  MemPage *pTrunk = 0;
63800  MemPage *pPrevTrunk = 0;
63801  Pgno mxPage; /* Total size of the database file */
63802 
63803  assert( sqlite3_mutex_held(pBt->mutex) );
63804  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
63805  pPage1 = pBt->pPage1;
63806  mxPage = btreePagecount(pBt);
63807  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
63808  ** stores stores the total number of pages on the freelist. */
63809  n = get4byte(&pPage1->aData[36]);
63810  testcase( n==mxPage-1 );
63811  if( n>=mxPage ){
63812  return SQLITE_CORRUPT_BKPT;
63813  }
63814  if( n>0 ){
63815  /* There are pages on the freelist. Reuse one of those pages. */
63816  Pgno iTrunk;
63817  u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
63818  u32 nSearch = 0; /* Count of the number of search attempts */
63819 
63820  /* If eMode==BTALLOC_EXACT and a query of the pointer-map
63821  ** shows that the page 'nearby' is somewhere on the free-list, then
63822  ** the entire-list will be searched for that page.
63823  */
63824 #ifndef SQLITE_OMIT_AUTOVACUUM
63825  if( eMode==BTALLOC_EXACT ){
63826  if( nearby<=mxPage ){
63827  u8 eType;
63828  assert( nearby>0 );
63829  assert( pBt->autoVacuum );
63830  rc = ptrmapGet(pBt, nearby, &eType, 0);
63831  if( rc ) return rc;
63832  if( eType==PTRMAP_FREEPAGE ){
63833  searchList = 1;
63834  }
63835  }
63836  }else if( eMode==BTALLOC_LE ){
63837  searchList = 1;
63838  }
63839 #endif
63840 
63841  /* Decrement the free-list count by 1. Set iTrunk to the index of the
63842  ** first free-list trunk page. iPrevTrunk is initially 1.
63843  */
63844  rc = sqlite3PagerWrite(pPage1->pDbPage);
63845  if( rc ) return rc;
63846  put4byte(&pPage1->aData[36], n-1);
63847 
63848  /* The code within this loop is run only once if the 'searchList' variable
63849  ** is not true. Otherwise, it runs once for each trunk-page on the
63850  ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
63851  ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
63852  */
63853  do {
63854  pPrevTrunk = pTrunk;
63855  if( pPrevTrunk ){
63856  /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
63857  ** is the page number of the next freelist trunk page in the list or
63858  ** zero if this is the last freelist trunk page. */
63859  iTrunk = get4byte(&pPrevTrunk->aData[0]);
63860  }else{
63861  /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
63862  ** stores the page number of the first page of the freelist, or zero if
63863  ** the freelist is empty. */
63864  iTrunk = get4byte(&pPage1->aData[32]);
63865  }
63866  testcase( iTrunk==mxPage );
63867  if( iTrunk>mxPage || nSearch++ > n ){
63868  rc = SQLITE_CORRUPT_BKPT;
63869  }else{
63870  rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
63871  }
63872  if( rc ){
63873  pTrunk = 0;
63874  goto end_allocate_page;
63875  }
63876  assert( pTrunk!=0 );
63877  assert( pTrunk->aData!=0 );
63878  /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
63879  ** is the number of leaf page pointers to follow. */
63880  k = get4byte(&pTrunk->aData[4]);
63881  if( k==0 && !searchList ){
63882  /* The trunk has no leaves and the list is not being searched.
63883  ** So extract the trunk page itself and use it as the newly
63884  ** allocated page */
63885  assert( pPrevTrunk==0 );
63886  rc = sqlite3PagerWrite(pTrunk->pDbPage);
63887  if( rc ){
63888  goto end_allocate_page;
63889  }
63890  *pPgno = iTrunk;
63891  memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63892  *ppPage = pTrunk;
63893  pTrunk = 0;
63894  TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63895  }else if( k>(u32)(pBt->usableSize/4 - 2) ){
63896  /* Value of k is out of range. Database corruption */
63897  rc = SQLITE_CORRUPT_BKPT;
63898  goto end_allocate_page;
63899 #ifndef SQLITE_OMIT_AUTOVACUUM
63900  }else if( searchList
63901  && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
63902  ){
63903  /* The list is being searched and this trunk page is the page
63904  ** to allocate, regardless of whether it has leaves.
63905  */
63906  *pPgno = iTrunk;
63907  *ppPage = pTrunk;
63908  searchList = 0;
63909  rc = sqlite3PagerWrite(pTrunk->pDbPage);
63910  if( rc ){
63911  goto end_allocate_page;
63912  }
63913  if( k==0 ){
63914  if( !pPrevTrunk ){
63915  memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63916  }else{
63917  rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63918  if( rc!=SQLITE_OK ){
63919  goto end_allocate_page;
63920  }
63921  memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
63922  }
63923  }else{
63924  /* The trunk page is required by the caller but it contains
63925  ** pointers to free-list leaves. The first leaf becomes a trunk
63926  ** page in this case.
63927  */
63928  MemPage *pNewTrunk;
63929  Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
63930  if( iNewTrunk>mxPage ){
63931  rc = SQLITE_CORRUPT_BKPT;
63932  goto end_allocate_page;
63933  }
63934  testcase( iNewTrunk==mxPage );
63935  rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
63936  if( rc!=SQLITE_OK ){
63937  goto end_allocate_page;
63938  }
63939  rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
63940  if( rc!=SQLITE_OK ){
63941  releasePage(pNewTrunk);
63942  goto end_allocate_page;
63943  }
63944  memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
63945  put4byte(&pNewTrunk->aData[4], k-1);
63946  memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
63947  releasePage(pNewTrunk);
63948  if( !pPrevTrunk ){
63949  assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
63950  put4byte(&pPage1->aData[32], iNewTrunk);
63951  }else{
63952  rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63953  if( rc ){
63954  goto end_allocate_page;
63955  }
63956  put4byte(&pPrevTrunk->aData[0], iNewTrunk);
63957  }
63958  }
63959  pTrunk = 0;
63960  TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63961 #endif
63962  }else if( k>0 ){
63963  /* Extract a leaf from the trunk */
63964  u32 closest;
63965  Pgno iPage;
63966  unsigned char *aData = pTrunk->aData;
63967  if( nearby>0 ){
63968  u32 i;
63969  closest = 0;
63970  if( eMode==BTALLOC_LE ){
63971  for(i=0; i<k; i++){
63972  iPage = get4byte(&aData[8+i*4]);
63973  if( iPage<=nearby ){
63974  closest = i;
63975  break;
63976  }
63977  }
63978  }else{
63979  int dist;
63980  dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
63981  for(i=1; i<k; i++){
63982  int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
63983  if( d2<dist ){
63984  closest = i;
63985  dist = d2;
63986  }
63987  }
63988  }
63989  }else{
63990  closest = 0;
63991  }
63992 
63993  iPage = get4byte(&aData[8+closest*4]);
63994  testcase( iPage==mxPage );
63995  if( iPage>mxPage ){
63996  rc = SQLITE_CORRUPT_BKPT;
63997  goto end_allocate_page;
63998  }
63999  testcase( iPage==mxPage );
64000  if( !searchList
64001  || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
64002  ){
64003  int noContent;
64004  *pPgno = iPage;
64005  TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
64006  ": %d more free pages\n",
64007  *pPgno, closest+1, k, pTrunk->pgno, n-1));
64008  rc = sqlite3PagerWrite(pTrunk->pDbPage);
64009  if( rc ) goto end_allocate_page;
64010  if( closest<k-1 ){
64011  memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
64012  }
64013  put4byte(&aData[4], k-1);
64014  noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
64015  rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
64016  if( rc==SQLITE_OK ){
64017  rc = sqlite3PagerWrite((*ppPage)->pDbPage);
64018  if( rc!=SQLITE_OK ){
64019  releasePage(*ppPage);
64020  *ppPage = 0;
64021  }
64022  }
64023  searchList = 0;
64024  }
64025  }
64026  releasePage(pPrevTrunk);
64027  pPrevTrunk = 0;
64028  }while( searchList );
64029  }else{
64030  /* There are no pages on the freelist, so append a new page to the
64031  ** database image.
64032  **
64033  ** Normally, new pages allocated by this block can be requested from the
64034  ** pager layer with the 'no-content' flag set. This prevents the pager
64035  ** from trying to read the pages content from disk. However, if the
64036  ** current transaction has already run one or more incremental-vacuum
64037  ** steps, then the page we are about to allocate may contain content
64038  ** that is required in the event of a rollback. In this case, do
64039  ** not set the no-content flag. This causes the pager to load and journal
64040  ** the current page content before overwriting it.
64041  **
64042  ** Note that the pager will not actually attempt to load or journal
64043  ** content for any page that really does lie past the end of the database
64044  ** file on disk. So the effects of disabling the no-content optimization
64045  ** here are confined to those pages that lie between the end of the
64046  ** database image and the end of the database file.
64047  */
64048  int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
64049 
64050  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
64051  if( rc ) return rc;
64052  pBt->nPage++;
64053  if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
64054 
64055 #ifndef SQLITE_OMIT_AUTOVACUUM
64056  if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
64057  /* If *pPgno refers to a pointer-map page, allocate two new pages
64058  ** at the end of the file instead of one. The first allocated page
64059  ** becomes a new pointer-map page, the second is used by the caller.
64060  */
64061  MemPage *pPg = 0;
64062  TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
64063  assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
64064  rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
64065  if( rc==SQLITE_OK ){
64066  rc = sqlite3PagerWrite(pPg->pDbPage);
64067  releasePage(pPg);
64068  }
64069  if( rc ) return rc;
64070  pBt->nPage++;
64071  if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
64072  }
64073 #endif
64074  put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
64075  *pPgno = pBt->nPage;
64076 
64077  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
64078  rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
64079  if( rc ) return rc;
64080  rc = sqlite3PagerWrite((*ppPage)->pDbPage);
64081  if( rc!=SQLITE_OK ){
64082  releasePage(*ppPage);
64083  *ppPage = 0;
64084  }
64085  TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
64086  }
64087 
64088  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
64089 
64090 end_allocate_page:
64091  releasePage(pTrunk);
64092  releasePage(pPrevTrunk);
64093  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
64094  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
64095  return rc;
64096 }
64097 
64098 /*
64099 ** This function is used to add page iPage to the database file free-list.
64100 ** It is assumed that the page is not already a part of the free-list.
64101 **
64102 ** The value passed as the second argument to this function is optional.
64103 ** If the caller happens to have a pointer to the MemPage object
64104 ** corresponding to page iPage handy, it may pass it as the second value.
64105 ** Otherwise, it may pass NULL.
64106 **
64107 ** If a pointer to a MemPage object is passed as the second argument,
64108 ** its reference count is not altered by this function.
64109 */
64110 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
64111  MemPage *pTrunk = 0; /* Free-list trunk page */
64112  Pgno iTrunk = 0; /* Page number of free-list trunk page */
64113  MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
64114  MemPage *pPage; /* Page being freed. May be NULL. */
64115  int rc; /* Return Code */
64116  int nFree; /* Initial number of pages on free-list */
64117 
64118  assert( sqlite3_mutex_held(pBt->mutex) );
64119  assert( CORRUPT_DB || iPage>1 );
64120  assert( !pMemPage || pMemPage->pgno==iPage );
64121 
64122  if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
64123  if( pMemPage ){
64124  pPage = pMemPage;
64125  sqlite3PagerRef(pPage->pDbPage);
64126  }else{
64127  pPage = btreePageLookup(pBt, iPage);
64128  }
64129 
64130  /* Increment the free page count on pPage1 */
64131  rc = sqlite3PagerWrite(pPage1->pDbPage);
64132  if( rc ) goto freepage_out;
64133  nFree = get4byte(&pPage1->aData[36]);
64134  put4byte(&pPage1->aData[36], nFree+1);
64135 
64136  if( pBt->btsFlags & BTS_SECURE_DELETE ){
64137  /* If the secure_delete option is enabled, then
64138  ** always fully overwrite deleted information with zeros.
64139  */
64140  if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
64141  || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
64142  ){
64143  goto freepage_out;
64144  }
64145  memset(pPage->aData, 0, pPage->pBt->pageSize);
64146  }
64147 
64148  /* If the database supports auto-vacuum, write an entry in the pointer-map
64149  ** to indicate that the page is free.
64150  */
64151  if( ISAUTOVACUUM ){
64152  ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
64153  if( rc ) goto freepage_out;
64154  }
64155 
64156  /* Now manipulate the actual database free-list structure. There are two
64157  ** possibilities. If the free-list is currently empty, or if the first
64158  ** trunk page in the free-list is full, then this page will become a
64159  ** new free-list trunk page. Otherwise, it will become a leaf of the
64160  ** first trunk page in the current free-list. This block tests if it
64161  ** is possible to add the page as a new free-list leaf.
64162  */
64163  if( nFree!=0 ){
64164  u32 nLeaf; /* Initial number of leaf cells on trunk page */
64165 
64166  iTrunk = get4byte(&pPage1->aData[32]);
64167  rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
64168  if( rc!=SQLITE_OK ){
64169  goto freepage_out;
64170  }
64171 
64172  nLeaf = get4byte(&pTrunk->aData[4]);
64173  assert( pBt->usableSize>32 );
64174  if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
64175  rc = SQLITE_CORRUPT_BKPT;
64176  goto freepage_out;
64177  }
64178  if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
64179  /* In this case there is room on the trunk page to insert the page
64180  ** being freed as a new leaf.
64181  **
64182  ** Note that the trunk page is not really full until it contains
64183  ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
64184  ** coded. But due to a coding error in versions of SQLite prior to
64185  ** 3.6.0, databases with freelist trunk pages holding more than
64186  ** usableSize/4 - 8 entries will be reported as corrupt. In order
64187  ** to maintain backwards compatibility with older versions of SQLite,
64188  ** we will continue to restrict the number of entries to usableSize/4 - 8
64189  ** for now. At some point in the future (once everyone has upgraded
64190  ** to 3.6.0 or later) we should consider fixing the conditional above
64191  ** to read "usableSize/4-2" instead of "usableSize/4-8".
64192  **
64193  ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
64194  ** avoid using the last six entries in the freelist trunk page array in
64195  ** order that database files created by newer versions of SQLite can be
64196  ** read by older versions of SQLite.
64197  */
64198  rc = sqlite3PagerWrite(pTrunk->pDbPage);
64199  if( rc==SQLITE_OK ){
64200  put4byte(&pTrunk->aData[4], nLeaf+1);
64201  put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
64202  if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
64203  sqlite3PagerDontWrite(pPage->pDbPage);
64204  }
64205  rc = btreeSetHasContent(pBt, iPage);
64206  }
64207  TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
64208  goto freepage_out;
64209  }
64210  }
64211 
64212  /* If control flows to this point, then it was not possible to add the
64213  ** the page being freed as a leaf page of the first trunk in the free-list.
64214  ** Possibly because the free-list is empty, or possibly because the
64215  ** first trunk in the free-list is full. Either way, the page being freed
64216  ** will become the new first trunk page in the free-list.
64217  */
64218  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
64219  goto freepage_out;
64220  }
64221  rc = sqlite3PagerWrite(pPage->pDbPage);
64222  if( rc!=SQLITE_OK ){
64223  goto freepage_out;
64224  }
64225  put4byte(pPage->aData, iTrunk);
64226  put4byte(&pPage->aData[4], 0);
64227  put4byte(&pPage1->aData[32], iPage);
64228  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
64229 
64230 freepage_out:
64231  if( pPage ){
64232  pPage->isInit = 0;
64233  }
64234  releasePage(pPage);
64235  releasePage(pTrunk);
64236  return rc;
64237 }
64238 static void freePage(MemPage *pPage, int *pRC){
64239  if( (*pRC)==SQLITE_OK ){
64240  *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
64241  }
64242 }
64243 
64244 /*
64245 ** Free any overflow pages associated with the given Cell. Write the
64246 ** local Cell size (the number of bytes on the original page, omitting
64247 ** overflow) into *pnSize.
64248 */
64249 static int clearCell(
64250  MemPage *pPage, /* The page that contains the Cell */
64251  unsigned char *pCell, /* First byte of the Cell */
64252  u16 *pnSize /* Write the size of the Cell here */
64253 ){
64254  BtShared *pBt = pPage->pBt;
64255  CellInfo info;
64256  Pgno ovflPgno;
64257  int rc;
64258  int nOvfl;
64259  u32 ovflPageSize;
64260 
64261  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64262  pPage->xParseCell(pPage, pCell, &info);
64263  *pnSize = info.nSize;
64264  if( info.nLocal==info.nPayload ){
64265  return SQLITE_OK; /* No overflow pages. Return without doing anything */
64266  }
64267  if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){
64268  return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
64269  }
64270  ovflPgno = get4byte(pCell + info.nSize - 4);
64271  assert( pBt->usableSize > 4 );
64272  ovflPageSize = pBt->usableSize - 4;
64273  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
64274  assert( nOvfl>0 ||
64275  (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
64276  );
64277  while( nOvfl-- ){
64278  Pgno iNext = 0;
64279  MemPage *pOvfl = 0;
64280  if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
64281  /* 0 is not a legal page number and page 1 cannot be an
64282  ** overflow page. Therefore if ovflPgno<2 or past the end of the
64283  ** file the database must be corrupt. */
64284  return SQLITE_CORRUPT_BKPT;
64285  }
64286  if( nOvfl ){
64287  rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
64288  if( rc ) return rc;
64289  }
64290 
64291  if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
64292  && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
64293  ){
64294  /* There is no reason any cursor should have an outstanding reference
64295  ** to an overflow page belonging to a cell that is being deleted/updated.
64296  ** So if there exists more than one reference to this page, then it
64297  ** must not really be an overflow page and the database must be corrupt.
64298  ** It is helpful to detect this before calling freePage2(), as
64299  ** freePage2() may zero the page contents if secure-delete mode is
64300  ** enabled. If this 'overflow' page happens to be a page that the
64301  ** caller is iterating through or using in some other way, this
64302  ** can be problematic.
64303  */
64304  rc = SQLITE_CORRUPT_BKPT;
64305  }else{
64306  rc = freePage2(pBt, pOvfl, ovflPgno);
64307  }
64308 
64309  if( pOvfl ){
64310  sqlite3PagerUnref(pOvfl->pDbPage);
64311  }
64312  if( rc ) return rc;
64313  ovflPgno = iNext;
64314  }
64315  return SQLITE_OK;
64316 }
64317 
64318 /*
64319 ** Create the byte sequence used to represent a cell on page pPage
64320 ** and write that byte sequence into pCell[]. Overflow pages are
64321 ** allocated and filled in as necessary. The calling procedure
64322 ** is responsible for making sure sufficient space has been allocated
64323 ** for pCell[].
64324 **
64325 ** Note that pCell does not necessary need to point to the pPage->aData
64326 ** area. pCell might point to some temporary storage. The cell will
64327 ** be constructed in this temporary area then copied into pPage->aData
64328 ** later.
64329 */
64330 static int fillInCell(
64331  MemPage *pPage, /* The page that contains the cell */
64332  unsigned char *pCell, /* Complete text of the cell */
64333  const BtreePayload *pX, /* Payload with which to construct the cell */
64334  int *pnSize /* Write cell size here */
64335 ){
64336  int nPayload;
64337  const u8 *pSrc;
64338  int nSrc, n, rc;
64339  int spaceLeft;
64340  MemPage *pOvfl = 0;
64341  MemPage *pToRelease = 0;
64342  unsigned char *pPrior;
64343  unsigned char *pPayload;
64344  BtShared *pBt = pPage->pBt;
64345  Pgno pgnoOvfl = 0;
64346  int nHeader;
64347 
64348  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64349 
64350  /* pPage is not necessarily writeable since pCell might be auxiliary
64351  ** buffer space that is separate from the pPage buffer area */
64352  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
64353  || sqlite3PagerIswriteable(pPage->pDbPage) );
64354 
64355  /* Fill in the header. */
64356  nHeader = pPage->childPtrSize;
64357  if( pPage->intKey ){
64358  nPayload = pX->nData + pX->nZero;
64359  pSrc = pX->pData;
64360  nSrc = pX->nData;
64361  assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
64362  nHeader += putVarint32(&pCell[nHeader], nPayload);
64363  nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
64364  }else{
64365  assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
64366  nSrc = nPayload = (int)pX->nKey;
64367  pSrc = pX->pKey;
64368  nHeader += putVarint32(&pCell[nHeader], nPayload);
64369  }
64370 
64371  /* Fill in the payload */
64372  if( nPayload<=pPage->maxLocal ){
64373  n = nHeader + nPayload;
64374  testcase( n==3 );
64375  testcase( n==4 );
64376  if( n<4 ) n = 4;
64377  *pnSize = n;
64378  spaceLeft = nPayload;
64379  pPrior = pCell;
64380  }else{
64381  int mn = pPage->minLocal;
64382  n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
64383  testcase( n==pPage->maxLocal );
64384  testcase( n==pPage->maxLocal+1 );
64385  if( n > pPage->maxLocal ) n = mn;
64386  spaceLeft = n;
64387  *pnSize = n + nHeader + 4;
64388  pPrior = &pCell[nHeader+n];
64389  }
64390  pPayload = &pCell[nHeader];
64391 
64392  /* At this point variables should be set as follows:
64393  **
64394  ** nPayload Total payload size in bytes
64395  ** pPayload Begin writing payload here
64396  ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
64397  ** that means content must spill into overflow pages.
64398  ** *pnSize Size of the local cell (not counting overflow pages)
64399  ** pPrior Where to write the pgno of the first overflow page
64400  **
64401  ** Use a call to btreeParseCellPtr() to verify that the values above
64402  ** were computed correctly.
64403  */
64404 #if SQLITE_DEBUG
64405  {
64406  CellInfo info;
64407  pPage->xParseCell(pPage, pCell, &info);
64408  assert( nHeader==(int)(info.pPayload - pCell) );
64409  assert( info.nKey==pX->nKey );
64410  assert( *pnSize == info.nSize );
64411  assert( spaceLeft == info.nLocal );
64412  }
64413 #endif
64414 
64415  /* Write the payload into the local Cell and any extra into overflow pages */
64416  while( nPayload>0 ){
64417  if( spaceLeft==0 ){
64418 #ifndef SQLITE_OMIT_AUTOVACUUM
64419  Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
64420  if( pBt->autoVacuum ){
64421  do{
64422  pgnoOvfl++;
64423  } while(
64424  PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
64425  );
64426  }
64427 #endif
64428  rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
64429 #ifndef SQLITE_OMIT_AUTOVACUUM
64430  /* If the database supports auto-vacuum, and the second or subsequent
64431  ** overflow page is being allocated, add an entry to the pointer-map
64432  ** for that page now.
64433  **
64434  ** If this is the first overflow page, then write a partial entry
64435  ** to the pointer-map. If we write nothing to this pointer-map slot,
64436  ** then the optimistic overflow chain processing in clearCell()
64437  ** may misinterpret the uninitialized values and delete the
64438  ** wrong pages from the database.
64439  */
64440  if( pBt->autoVacuum && rc==SQLITE_OK ){
64441  u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
64442  ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
64443  if( rc ){
64444  releasePage(pOvfl);
64445  }
64446  }
64447 #endif
64448  if( rc ){
64449  releasePage(pToRelease);
64450  return rc;
64451  }
64452 
64453  /* If pToRelease is not zero than pPrior points into the data area
64454  ** of pToRelease. Make sure pToRelease is still writeable. */
64455  assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64456 
64457  /* If pPrior is part of the data area of pPage, then make sure pPage
64458  ** is still writeable */
64459  assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
64460  || sqlite3PagerIswriteable(pPage->pDbPage) );
64461 
64462  put4byte(pPrior, pgnoOvfl);
64463  releasePage(pToRelease);
64464  pToRelease = pOvfl;
64465  pPrior = pOvfl->aData;
64466  put4byte(pPrior, 0);
64467  pPayload = &pOvfl->aData[4];
64468  spaceLeft = pBt->usableSize - 4;
64469  }
64470  n = nPayload;
64471  if( n>spaceLeft ) n = spaceLeft;
64472 
64473  /* If pToRelease is not zero than pPayload points into the data area
64474  ** of pToRelease. Make sure pToRelease is still writeable. */
64475  assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64476 
64477  /* If pPayload is part of the data area of pPage, then make sure pPage
64478  ** is still writeable */
64479  assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
64480  || sqlite3PagerIswriteable(pPage->pDbPage) );
64481 
64482  if( nSrc>0 ){
64483  if( n>nSrc ) n = nSrc;
64484  assert( pSrc );
64485  memcpy(pPayload, pSrc, n);
64486  }else{
64487  memset(pPayload, 0, n);
64488  }
64489  nPayload -= n;
64490  pPayload += n;
64491  pSrc += n;
64492  nSrc -= n;
64493  spaceLeft -= n;
64494  }
64495  releasePage(pToRelease);
64496  return SQLITE_OK;
64497 }
64498 
64499 /*
64500 ** Remove the i-th cell from pPage. This routine effects pPage only.
64501 ** The cell content is not freed or deallocated. It is assumed that
64502 ** the cell content has been copied someplace else. This routine just
64503 ** removes the reference to the cell from pPage.
64504 **
64505 ** "sz" must be the number of bytes in the cell.
64506 */
64507 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
64508  u32 pc; /* Offset to cell content of cell being deleted */
64509  u8 *data; /* pPage->aData */
64510  u8 *ptr; /* Used to move bytes around within data[] */
64511  int rc; /* The return code */
64512  int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
64513 
64514  if( *pRC ) return;
64515 
64516  assert( idx>=0 && idx<pPage->nCell );
64517  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
64518  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64519  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64520  data = pPage->aData;
64521  ptr = &pPage->aCellIdx[2*idx];
64522  pc = get2byte(ptr);
64523  hdr = pPage->hdrOffset;
64524  testcase( pc==get2byte(&data[hdr+5]) );
64525  testcase( pc+sz==pPage->pBt->usableSize );
64526  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
64527  *pRC = SQLITE_CORRUPT_BKPT;
64528  return;
64529  }
64530  rc = freeSpace(pPage, pc, sz);
64531  if( rc ){
64532  *pRC = rc;
64533  return;
64534  }
64535  pPage->nCell--;
64536  if( pPage->nCell==0 ){
64537  memset(&data[hdr+1], 0, 4);
64538  data[hdr+7] = 0;
64539  put2byte(&data[hdr+5], pPage->pBt->usableSize);
64540  pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
64541  - pPage->childPtrSize - 8;
64542  }else{
64543  memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
64544  put2byte(&data[hdr+3], pPage->nCell);
64545  pPage->nFree += 2;
64546  }
64547 }
64548 
64549 /*
64550 ** Insert a new cell on pPage at cell index "i". pCell points to the
64551 ** content of the cell.
64552 **
64553 ** If the cell content will fit on the page, then put it there. If it
64554 ** will not fit, then make a copy of the cell content into pTemp if
64555 ** pTemp is not null. Regardless of pTemp, allocate a new entry
64556 ** in pPage->apOvfl[] and make it point to the cell content (either
64557 ** in pTemp or the original pCell) and also record its index.
64558 ** Allocating a new entry in pPage->aCell[] implies that
64559 ** pPage->nOverflow is incremented.
64560 **
64561 ** *pRC must be SQLITE_OK when this routine is called.
64562 */
64563 static void insertCell(
64564  MemPage *pPage, /* Page into which we are copying */
64565  int i, /* New cell becomes the i-th cell of the page */
64566  u8 *pCell, /* Content of the new cell */
64567  int sz, /* Bytes of content in pCell */
64568  u8 *pTemp, /* Temp storage space for pCell, if needed */
64569  Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
64570  int *pRC /* Read and write return code from here */
64571 ){
64572  int idx = 0; /* Where to write new cell content in data[] */
64573  int j; /* Loop counter */
64574  u8 *data; /* The content of the whole page */
64575  u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
64576 
64577  assert( *pRC==SQLITE_OK );
64578  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
64579  assert( MX_CELL(pPage->pBt)<=10921 );
64580  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
64581  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
64582  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
64583  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64584  /* The cell should normally be sized correctly. However, when moving a
64585  ** malformed cell from a leaf page to an interior page, if the cell size
64586  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
64587  ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
64588  ** the term after the || in the following assert(). */
64589  assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
64590  if( pPage->nOverflow || sz+2>pPage->nFree ){
64591  if( pTemp ){
64592  memcpy(pTemp, pCell, sz);
64593  pCell = pTemp;
64594  }
64595  if( iChild ){
64596  put4byte(pCell, iChild);
64597  }
64598  j = pPage->nOverflow++;
64599  assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
64600  pPage->apOvfl[j] = pCell;
64601  pPage->aiOvfl[j] = (u16)i;
64602 
64603  /* When multiple overflows occur, they are always sequential and in
64604  ** sorted order. This invariants arise because multiple overflows can
64605  ** only occur when inserting divider cells into the parent page during
64606  ** balancing, and the dividers are adjacent and sorted.
64607  */
64608  assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
64609  assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
64610  }else{
64611  int rc = sqlite3PagerWrite(pPage->pDbPage);
64612  if( rc!=SQLITE_OK ){
64613  *pRC = rc;
64614  return;
64615  }
64616  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64617  data = pPage->aData;
64618  assert( &data[pPage->cellOffset]==pPage->aCellIdx );
64619  rc = allocateSpace(pPage, sz, &idx);
64620  if( rc ){ *pRC = rc; return; }
64621  /* The allocateSpace() routine guarantees the following properties
64622  ** if it returns successfully */
64623  assert( idx >= 0 );
64624  assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
64625  assert( idx+sz <= (int)pPage->pBt->usableSize );
64626  pPage->nFree -= (u16)(2 + sz);
64627  memcpy(&data[idx], pCell, sz);
64628  if( iChild ){
64629  put4byte(&data[idx], iChild);
64630  }
64631  pIns = pPage->aCellIdx + i*2;
64632  memmove(pIns+2, pIns, 2*(pPage->nCell - i));
64633  put2byte(pIns, idx);
64634  pPage->nCell++;
64635  /* increment the cell count */
64636  if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
64637  assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
64638 #ifndef SQLITE_OMIT_AUTOVACUUM
64639  if( pPage->pBt->autoVacuum ){
64640  /* The cell may contain a pointer to an overflow page. If so, write
64641  ** the entry for the overflow page into the pointer map.
64642  */
64643  ptrmapPutOvflPtr(pPage, pCell, pRC);
64644  }
64645 #endif
64646  }
64647 }
64648 
64649 /*
64650 ** A CellArray object contains a cache of pointers and sizes for a
64651 ** consecutive sequence of cells that might be held on multiple pages.
64652 */
64653 typedef struct CellArray CellArray;
64654 struct CellArray {
64655  int nCell; /* Number of cells in apCell[] */
64656  MemPage *pRef; /* Reference page */
64657  u8 **apCell; /* All cells begin balanced */
64658  u16 *szCell; /* Local size of all cells in apCell[] */
64659 };
64660 
64661 /*
64662 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
64663 ** computed.
64664 */
64665 static void populateCellCache(CellArray *p, int idx, int N){
64666  assert( idx>=0 && idx+N<=p->nCell );
64667  while( N>0 ){
64668  assert( p->apCell[idx]!=0 );
64669  if( p->szCell[idx]==0 ){
64670  p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
64671  }else{
64672  assert( CORRUPT_DB ||
64673  p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
64674  }
64675  idx++;
64676  N--;
64677  }
64678 }
64679 
64680 /*
64681 ** Return the size of the Nth element of the cell array
64682 */
64683 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
64684  assert( N>=0 && N<p->nCell );
64685  assert( p->szCell[N]==0 );
64686  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
64687  return p->szCell[N];
64688 }
64689 static u16 cachedCellSize(CellArray *p, int N){
64690  assert( N>=0 && N<p->nCell );
64691  if( p->szCell[N] ) return p->szCell[N];
64692  return computeCellSize(p, N);
64693 }
64694 
64695 /*
64696 ** Array apCell[] contains pointers to nCell b-tree page cells. The
64697 ** szCell[] array contains the size in bytes of each cell. This function
64698 ** replaces the current contents of page pPg with the contents of the cell
64699 ** array.
64700 **
64701 ** Some of the cells in apCell[] may currently be stored in pPg. This
64702 ** function works around problems caused by this by making a copy of any
64703 ** such cells before overwriting the page data.
64704 **
64705 ** The MemPage.nFree field is invalidated by this function. It is the
64706 ** responsibility of the caller to set it correctly.
64707 */
64708 static int rebuildPage(
64709  MemPage *pPg, /* Edit this page */
64710  int nCell, /* Final number of cells on page */
64711  u8 **apCell, /* Array of cells */
64712  u16 *szCell /* Array of cell sizes */
64713 ){
64714  const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
64715  u8 * const aData = pPg->aData; /* Pointer to data for pPg */
64716  const int usableSize = pPg->pBt->usableSize;
64717  u8 * const pEnd = &aData[usableSize];
64718  int i;
64719  u8 *pCellptr = pPg->aCellIdx;
64720  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64721  u8 *pData;
64722 
64723  i = get2byte(&aData[hdr+5]);
64724  memcpy(&pTmp[i], &aData[i], usableSize - i);
64725 
64726  pData = pEnd;
64727  for(i=0; i<nCell; i++){
64728  u8 *pCell = apCell[i];
64729  if( SQLITE_WITHIN(pCell,aData,pEnd) ){
64730  pCell = &pTmp[pCell - aData];
64731  }
64732  pData -= szCell[i];
64733  put2byte(pCellptr, (pData - aData));
64734  pCellptr += 2;
64735  if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
64736  memcpy(pData, pCell, szCell[i]);
64737  assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
64738  testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
64739  }
64740 
64741  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
64742  pPg->nCell = nCell;
64743  pPg->nOverflow = 0;
64744 
64745  put2byte(&aData[hdr+1], 0);
64746  put2byte(&aData[hdr+3], pPg->nCell);
64747  put2byte(&aData[hdr+5], pData - aData);
64748  aData[hdr+7] = 0x00;
64749  return SQLITE_OK;
64750 }
64751 
64752 /*
64753 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64754 ** contains the size in bytes of each such cell. This function attempts to
64755 ** add the cells stored in the array to page pPg. If it cannot (because
64756 ** the page needs to be defragmented before the cells will fit), non-zero
64757 ** is returned. Otherwise, if the cells are added successfully, zero is
64758 ** returned.
64759 **
64760 ** Argument pCellptr points to the first entry in the cell-pointer array
64761 ** (part of page pPg) to populate. After cell apCell[0] is written to the
64762 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
64763 ** cell in the array. It is the responsibility of the caller to ensure
64764 ** that it is safe to overwrite this part of the cell-pointer array.
64765 **
64766 ** When this function is called, *ppData points to the start of the
64767 ** content area on page pPg. If the size of the content area is extended,
64768 ** *ppData is updated to point to the new start of the content area
64769 ** before returning.
64770 **
64771 ** Finally, argument pBegin points to the byte immediately following the
64772 ** end of the space required by this page for the cell-pointer area (for
64773 ** all cells - not just those inserted by the current call). If the content
64774 ** area must be extended to before this point in order to accomodate all
64775 ** cells in apCell[], then the cells do not fit and non-zero is returned.
64776 */
64777 static int pageInsertArray(
64778  MemPage *pPg, /* Page to add cells to */
64779  u8 *pBegin, /* End of cell-pointer array */
64780  u8 **ppData, /* IN/OUT: Page content -area pointer */
64781  u8 *pCellptr, /* Pointer to cell-pointer area */
64782  int iFirst, /* Index of first cell to add */
64783  int nCell, /* Number of cells to add to pPg */
64784  CellArray *pCArray /* Array of cells */
64785 ){
64786  int i;
64787  u8 *aData = pPg->aData;
64788  u8 *pData = *ppData;
64789  int iEnd = iFirst + nCell;
64790  assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
64791  for(i=iFirst; i<iEnd; i++){
64792  int sz, rc;
64793  u8 *pSlot;
64794  sz = cachedCellSize(pCArray, i);
64795  if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
64796  if( (pData - pBegin)<sz ) return 1;
64797  pData -= sz;
64798  pSlot = pData;
64799  }
64800  /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
64801  ** database. But they might for a corrupt database. Hence use memmove()
64802  ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
64803  assert( (pSlot+sz)<=pCArray->apCell[i]
64804  || pSlot>=(pCArray->apCell[i]+sz)
64805  || CORRUPT_DB );
64806  memmove(pSlot, pCArray->apCell[i], sz);
64807  put2byte(pCellptr, (pSlot - aData));
64808  pCellptr += 2;
64809  }
64810  *ppData = pData;
64811  return 0;
64812 }
64813 
64814 /*
64815 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64816 ** contains the size in bytes of each such cell. This function adds the
64817 ** space associated with each cell in the array that is currently stored
64818 ** within the body of pPg to the pPg free-list. The cell-pointers and other
64819 ** fields of the page are not updated.
64820 **
64821 ** This function returns the total number of cells added to the free-list.
64822 */
64823 static int pageFreeArray(
64824  MemPage *pPg, /* Page to edit */
64825  int iFirst, /* First cell to delete */
64826  int nCell, /* Cells to delete */
64827  CellArray *pCArray /* Array of cells */
64828 ){
64829  u8 * const aData = pPg->aData;
64830  u8 * const pEnd = &aData[pPg->pBt->usableSize];
64831  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
64832  int nRet = 0;
64833  int i;
64834  int iEnd = iFirst + nCell;
64835  u8 *pFree = 0;
64836  int szFree = 0;
64837 
64838  for(i=iFirst; i<iEnd; i++){
64839  u8 *pCell = pCArray->apCell[i];
64840  if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
64841  int sz;
64842  /* No need to use cachedCellSize() here. The sizes of all cells that
64843  ** are to be freed have already been computing while deciding which
64844  ** cells need freeing */
64845  sz = pCArray->szCell[i]; assert( sz>0 );
64846  if( pFree!=(pCell + sz) ){
64847  if( pFree ){
64848  assert( pFree>aData && (pFree - aData)<65536 );
64849  freeSpace(pPg, (u16)(pFree - aData), szFree);
64850  }
64851  pFree = pCell;
64852  szFree = sz;
64853  if( pFree+sz>pEnd ) return 0;
64854  }else{
64855  pFree = pCell;
64856  szFree += sz;
64857  }
64858  nRet++;
64859  }
64860  }
64861  if( pFree ){
64862  assert( pFree>aData && (pFree - aData)<65536 );
64863  freeSpace(pPg, (u16)(pFree - aData), szFree);
64864  }
64865  return nRet;
64866 }
64867 
64868 /*
64869 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
64870 ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
64871 ** with apCell[iOld]. After balancing, this page should hold nNew cells
64872 ** starting at apCell[iNew].
64873 **
64874 ** This routine makes the necessary adjustments to pPg so that it contains
64875 ** the correct cells after being balanced.
64876 **
64877 ** The pPg->nFree field is invalid when this function returns. It is the
64878 ** responsibility of the caller to set it correctly.
64879 */
64880 static int editPage(
64881  MemPage *pPg, /* Edit this page */
64882  int iOld, /* Index of first cell currently on page */
64883  int iNew, /* Index of new first cell on page */
64884  int nNew, /* Final number of cells on page */
64885  CellArray *pCArray /* Array of cells and sizes */
64886 ){
64887  u8 * const aData = pPg->aData;
64888  const int hdr = pPg->hdrOffset;
64889  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
64890  int nCell = pPg->nCell; /* Cells stored on pPg */
64891  u8 *pData;
64892  u8 *pCellptr;
64893  int i;
64894  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
64895  int iNewEnd = iNew + nNew;
64896 
64897 #ifdef SQLITE_DEBUG
64898  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64899  memcpy(pTmp, aData, pPg->pBt->usableSize);
64900 #endif
64901 
64902  /* Remove cells from the start and end of the page */
64903  if( iOld<iNew ){
64904  int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
64905  memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
64906  nCell -= nShift;
64907  }
64908  if( iNewEnd < iOldEnd ){
64909  nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
64910  }
64911 
64912  pData = &aData[get2byteNotZero(&aData[hdr+5])];
64913  if( pData<pBegin ) goto editpage_fail;
64914 
64915  /* Add cells to the start of the page */
64916  if( iNew<iOld ){
64917  int nAdd = MIN(nNew,iOld-iNew);
64918  assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
64919  pCellptr = pPg->aCellIdx;
64920  memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
64921  if( pageInsertArray(
64922  pPg, pBegin, &pData, pCellptr,
64923  iNew, nAdd, pCArray
64924  ) ) goto editpage_fail;
64925  nCell += nAdd;
64926  }
64927 
64928  /* Add any overflow cells */
64929  for(i=0; i<pPg->nOverflow; i++){
64930  int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
64931  if( iCell>=0 && iCell<nNew ){
64932  pCellptr = &pPg->aCellIdx[iCell * 2];
64933  memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
64934  nCell++;
64935  if( pageInsertArray(
64936  pPg, pBegin, &pData, pCellptr,
64937  iCell+iNew, 1, pCArray
64938  ) ) goto editpage_fail;
64939  }
64940  }
64941 
64942  /* Append cells to the end of the page */
64943  pCellptr = &pPg->aCellIdx[nCell*2];
64944  if( pageInsertArray(
64945  pPg, pBegin, &pData, pCellptr,
64946  iNew+nCell, nNew-nCell, pCArray
64947  ) ) goto editpage_fail;
64948 
64949  pPg->nCell = nNew;
64950  pPg->nOverflow = 0;
64951 
64952  put2byte(&aData[hdr+3], pPg->nCell);
64953  put2byte(&aData[hdr+5], pData - aData);
64954 
64955 #ifdef SQLITE_DEBUG
64956  for(i=0; i<nNew && !CORRUPT_DB; i++){
64957  u8 *pCell = pCArray->apCell[i+iNew];
64958  int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
64959  if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
64960  pCell = &pTmp[pCell - aData];
64961  }
64962  assert( 0==memcmp(pCell, &aData[iOff],
64963  pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
64964  }
64965 #endif
64966 
64967  return SQLITE_OK;
64968  editpage_fail:
64969  /* Unable to edit this page. Rebuild it from scratch instead. */
64970  populateCellCache(pCArray, iNew, nNew);
64971  return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
64972 }
64973 
64974 /*
64975 ** The following parameters determine how many adjacent pages get involved
64976 ** in a balancing operation. NN is the number of neighbors on either side
64977 ** of the page that participate in the balancing operation. NB is the
64978 ** total number of pages that participate, including the target page and
64979 ** NN neighbors on either side.
64980 **
64981 ** The minimum value of NN is 1 (of course). Increasing NN above 1
64982 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
64983 ** in exchange for a larger degradation in INSERT and UPDATE performance.
64984 ** The value of NN appears to give the best results overall.
64985 */
64986 #define NN 1 /* Number of neighbors on either side of pPage */
64987 #define NB (NN*2+1) /* Total pages involved in the balance */
64988 
64989 
64990 #ifndef SQLITE_OMIT_QUICKBALANCE
64991 /*
64992 ** This version of balance() handles the common special case where
64993 ** a new entry is being inserted on the extreme right-end of the
64994 ** tree, in other words, when the new entry will become the largest
64995 ** entry in the tree.
64996 **
64997 ** Instead of trying to balance the 3 right-most leaf pages, just add
64998 ** a new page to the right-hand side and put the one new entry in
64999 ** that page. This leaves the right side of the tree somewhat
65000 ** unbalanced. But odds are that we will be inserting new entries
65001 ** at the end soon afterwards so the nearly empty page will quickly
65002 ** fill up. On average.
65003 **
65004 ** pPage is the leaf page which is the right-most page in the tree.
65005 ** pParent is its parent. pPage must have a single overflow entry
65006 ** which is also the right-most entry on the page.
65007 **
65008 ** The pSpace buffer is used to store a temporary copy of the divider
65009 ** cell that will be inserted into pParent. Such a cell consists of a 4
65010 ** byte page number followed by a variable length integer. In other
65011 ** words, at most 13 bytes. Hence the pSpace buffer must be at
65012 ** least 13 bytes in size.
65013 */
65014 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
65015  BtShared *const pBt = pPage->pBt; /* B-Tree Database */
65016  MemPage *pNew; /* Newly allocated page */
65017  int rc; /* Return Code */
65018  Pgno pgnoNew; /* Page number of pNew */
65019 
65020  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65021  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65022  assert( pPage->nOverflow==1 );
65023 
65024  /* This error condition is now caught prior to reaching this function */
65025  if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
65026 
65027  /* Allocate a new page. This page will become the right-sibling of
65028  ** pPage. Make the parent page writable, so that the new divider cell
65029  ** may be inserted. If both these operations are successful, proceed.
65030  */
65031  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
65032 
65033  if( rc==SQLITE_OK ){
65034 
65035  u8 *pOut = &pSpace[4];
65036  u8 *pCell = pPage->apOvfl[0];
65037  u16 szCell = pPage->xCellSize(pPage, pCell);
65038  u8 *pStop;
65039 
65040  assert( sqlite3PagerIswriteable(pNew->pDbPage) );
65041  assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
65042  zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
65043  rc = rebuildPage(pNew, 1, &pCell, &szCell);
65044  if( NEVER(rc) ) return rc;
65045  pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
65046 
65047  /* If this is an auto-vacuum database, update the pointer map
65048  ** with entries for the new page, and any pointer from the
65049  ** cell on the page to an overflow page. If either of these
65050  ** operations fails, the return code is set, but the contents
65051  ** of the parent page are still manipulated by thh code below.
65052  ** That is Ok, at this point the parent page is guaranteed to
65053  ** be marked as dirty. Returning an error code will cause a
65054  ** rollback, undoing any changes made to the parent page.
65055  */
65056  if( ISAUTOVACUUM ){
65057  ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
65058  if( szCell>pNew->minLocal ){
65059  ptrmapPutOvflPtr(pNew, pCell, &rc);
65060  }
65061  }
65062 
65063  /* Create a divider cell to insert into pParent. The divider cell
65064  ** consists of a 4-byte page number (the page number of pPage) and
65065  ** a variable length key value (which must be the same value as the
65066  ** largest key on pPage).
65067  **
65068  ** To find the largest key value on pPage, first find the right-most
65069  ** cell on pPage. The first two fields of this cell are the
65070  ** record-length (a variable length integer at most 32-bits in size)
65071  ** and the key value (a variable length integer, may have any value).
65072  ** The first of the while(...) loops below skips over the record-length
65073  ** field. The second while(...) loop copies the key value from the
65074  ** cell on pPage into the pSpace buffer.
65075  */
65076  pCell = findCell(pPage, pPage->nCell-1);
65077  pStop = &pCell[9];
65078  while( (*(pCell++)&0x80) && pCell<pStop );
65079  pStop = &pCell[9];
65080  while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
65081 
65082  /* Insert the new divider cell into pParent. */
65083  if( rc==SQLITE_OK ){
65084  insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
65085  0, pPage->pgno, &rc);
65086  }
65087 
65088  /* Set the right-child pointer of pParent to point to the new page. */
65089  put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
65090 
65091  /* Release the reference to the new page. */
65092  releasePage(pNew);
65093  }
65094 
65095  return rc;
65096 }
65097 #endif /* SQLITE_OMIT_QUICKBALANCE */
65098 
65099 #if 0
65100 /*
65101 ** This function does not contribute anything to the operation of SQLite.
65102 ** it is sometimes activated temporarily while debugging code responsible
65103 ** for setting pointer-map entries.
65104 */
65105 static int ptrmapCheckPages(MemPage **apPage, int nPage){
65106  int i, j;
65107  for(i=0; i<nPage; i++){
65108  Pgno n;
65109  u8 e;
65110  MemPage *pPage = apPage[i];
65111  BtShared *pBt = pPage->pBt;
65112  assert( pPage->isInit );
65113 
65114  for(j=0; j<pPage->nCell; j++){
65115  CellInfo info;
65116  u8 *z;
65117 
65118  z = findCell(pPage, j);
65119  pPage->xParseCell(pPage, z, &info);
65120  if( info.nLocal<info.nPayload ){
65121  Pgno ovfl = get4byte(&z[info.nSize-4]);
65122  ptrmapGet(pBt, ovfl, &e, &n);
65123  assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
65124  }
65125  if( !pPage->leaf ){
65126  Pgno child = get4byte(z);
65127  ptrmapGet(pBt, child, &e, &n);
65128  assert( n==pPage->pgno && e==PTRMAP_BTREE );
65129  }
65130  }
65131  if( !pPage->leaf ){
65132  Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
65133  ptrmapGet(pBt, child, &e, &n);
65134  assert( n==pPage->pgno && e==PTRMAP_BTREE );
65135  }
65136  }
65137  return 1;
65138 }
65139 #endif
65140 
65141 /*
65142 ** This function is used to copy the contents of the b-tree node stored
65143 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
65144 ** the pointer-map entries for each child page are updated so that the
65145 ** parent page stored in the pointer map is page pTo. If pFrom contained
65146 ** any cells with overflow page pointers, then the corresponding pointer
65147 ** map entries are also updated so that the parent page is page pTo.
65148 **
65149 ** If pFrom is currently carrying any overflow cells (entries in the
65150 ** MemPage.apOvfl[] array), they are not copied to pTo.
65151 **
65152 ** Before returning, page pTo is reinitialized using btreeInitPage().
65153 **
65154 ** The performance of this function is not critical. It is only used by
65155 ** the balance_shallower() and balance_deeper() procedures, neither of
65156 ** which are called often under normal circumstances.
65157 */
65158 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
65159  if( (*pRC)==SQLITE_OK ){
65160  BtShared * const pBt = pFrom->pBt;
65161  u8 * const aFrom = pFrom->aData;
65162  u8 * const aTo = pTo->aData;
65163  int const iFromHdr = pFrom->hdrOffset;
65164  int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
65165  int rc;
65166  int iData;
65167 
65168 
65169  assert( pFrom->isInit );
65170  assert( pFrom->nFree>=iToHdr );
65171  assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
65172 
65173  /* Copy the b-tree node content from page pFrom to page pTo. */
65174  iData = get2byte(&aFrom[iFromHdr+5]);
65175  memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
65176  memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
65177 
65178  /* Reinitialize page pTo so that the contents of the MemPage structure
65179  ** match the new data. The initialization of pTo can actually fail under
65180  ** fairly obscure circumstances, even though it is a copy of initialized
65181  ** page pFrom.
65182  */
65183  pTo->isInit = 0;
65184  rc = btreeInitPage(pTo);
65185  if( rc!=SQLITE_OK ){
65186  *pRC = rc;
65187  return;
65188  }
65189 
65190  /* If this is an auto-vacuum database, update the pointer-map entries
65191  ** for any b-tree or overflow pages that pTo now contains the pointers to.
65192  */
65193  if( ISAUTOVACUUM ){
65194  *pRC = setChildPtrmaps(pTo);
65195  }
65196  }
65197 }
65198 
65199 /*
65200 ** This routine redistributes cells on the iParentIdx'th child of pParent
65201 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
65202 ** same amount of free space. Usually a single sibling on either side of the
65203 ** page are used in the balancing, though both siblings might come from one
65204 ** side if the page is the first or last child of its parent. If the page
65205 ** has fewer than 2 siblings (something which can only happen if the page
65206 ** is a root page or a child of a root page) then all available siblings
65207 ** participate in the balancing.
65208 **
65209 ** The number of siblings of the page might be increased or decreased by
65210 ** one or two in an effort to keep pages nearly full but not over full.
65211 **
65212 ** Note that when this routine is called, some of the cells on the page
65213 ** might not actually be stored in MemPage.aData[]. This can happen
65214 ** if the page is overfull. This routine ensures that all cells allocated
65215 ** to the page and its siblings fit into MemPage.aData[] before returning.
65216 **
65217 ** In the course of balancing the page and its siblings, cells may be
65218 ** inserted into or removed from the parent page (pParent). Doing so
65219 ** may cause the parent page to become overfull or underfull. If this
65220 ** happens, it is the responsibility of the caller to invoke the correct
65221 ** balancing routine to fix this problem (see the balance() routine).
65222 **
65223 ** If this routine fails for any reason, it might leave the database
65224 ** in a corrupted state. So if this routine fails, the database should
65225 ** be rolled back.
65226 **
65227 ** The third argument to this function, aOvflSpace, is a pointer to a
65228 ** buffer big enough to hold one page. If while inserting cells into the parent
65229 ** page (pParent) the parent page becomes overfull, this buffer is
65230 ** used to store the parent's overflow cells. Because this function inserts
65231 ** a maximum of four divider cells into the parent page, and the maximum
65232 ** size of a cell stored within an internal node is always less than 1/4
65233 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
65234 ** enough for all overflow cells.
65235 **
65236 ** If aOvflSpace is set to a null pointer, this function returns
65237 ** SQLITE_NOMEM.
65238 */
65239 static int balance_nonroot(
65240  MemPage *pParent, /* Parent page of siblings being balanced */
65241  int iParentIdx, /* Index of "the page" in pParent */
65242  u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
65243  int isRoot, /* True if pParent is a root-page */
65244  int bBulk /* True if this call is part of a bulk load */
65245 ){
65246  BtShared *pBt; /* The whole database */
65247  int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
65248  int nNew = 0; /* Number of pages in apNew[] */
65249  int nOld; /* Number of pages in apOld[] */
65250  int i, j, k; /* Loop counters */
65251  int nxDiv; /* Next divider slot in pParent->aCell[] */
65252  int rc = SQLITE_OK; /* The return code */
65253  u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
65254  int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
65255  int usableSpace; /* Bytes in pPage beyond the header */
65256  int pageFlags; /* Value of pPage->aData[0] */
65257  int iSpace1 = 0; /* First unused byte of aSpace1[] */
65258  int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
65259  int szScratch; /* Size of scratch memory requested */
65260  MemPage *apOld[NB]; /* pPage and up to two siblings */
65261  MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
65262  u8 *pRight; /* Location in parent of right-sibling pointer */
65263  u8 *apDiv[NB-1]; /* Divider cells in pParent */
65264  int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
65265  int cntOld[NB+2]; /* Old index in b.apCell[] */
65266  int szNew[NB+2]; /* Combined size of cells placed on i-th page */
65267  u8 *aSpace1; /* Space for copies of dividers cells */
65268  Pgno pgno; /* Temp var to store a page number in */
65269  u8 abDone[NB+2]; /* True after i'th new page is populated */
65270  Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
65271  Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
65272  u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
65273  CellArray b; /* Parsed information on cells being balanced */
65274 
65275  memset(abDone, 0, sizeof(abDone));
65276  b.nCell = 0;
65277  b.apCell = 0;
65278  pBt = pParent->pBt;
65279  assert( sqlite3_mutex_held(pBt->mutex) );
65280  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65281 
65282 #if 0
65283  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
65284 #endif
65285 
65286  /* At this point pParent may have at most one overflow cell. And if
65287  ** this overflow cell is present, it must be the cell with
65288  ** index iParentIdx. This scenario comes about when this function
65289  ** is called (indirectly) from sqlite3BtreeDelete().
65290  */
65291  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
65292  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
65293 
65294  if( !aOvflSpace ){
65295  return SQLITE_NOMEM_BKPT;
65296  }
65297 
65298  /* Find the sibling pages to balance. Also locate the cells in pParent
65299  ** that divide the siblings. An attempt is made to find NN siblings on
65300  ** either side of pPage. More siblings are taken from one side, however,
65301  ** if there are fewer than NN siblings on the other side. If pParent
65302  ** has NB or fewer children then all children of pParent are taken.
65303  **
65304  ** This loop also drops the divider cells from the parent page. This
65305  ** way, the remainder of the function does not have to deal with any
65306  ** overflow cells in the parent page, since if any existed they will
65307  ** have already been removed.
65308  */
65309  i = pParent->nOverflow + pParent->nCell;
65310  if( i<2 ){
65311  nxDiv = 0;
65312  }else{
65313  assert( bBulk==0 || bBulk==1 );
65314  if( iParentIdx==0 ){
65315  nxDiv = 0;
65316  }else if( iParentIdx==i ){
65317  nxDiv = i-2+bBulk;
65318  }else{
65319  nxDiv = iParentIdx-1;
65320  }
65321  i = 2-bBulk;
65322  }
65323  nOld = i+1;
65324  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
65325  pRight = &pParent->aData[pParent->hdrOffset+8];
65326  }else{
65327  pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
65328  }
65329  pgno = get4byte(pRight);
65330  while( 1 ){
65331  rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
65332  if( rc ){
65333  memset(apOld, 0, (i+1)*sizeof(MemPage*));
65334  goto balance_cleanup;
65335  }
65336  nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
65337  if( (i--)==0 ) break;
65338 
65339  if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
65340  apDiv[i] = pParent->apOvfl[0];
65341  pgno = get4byte(apDiv[i]);
65342  szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65343  pParent->nOverflow = 0;
65344  }else{
65345  apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
65346  pgno = get4byte(apDiv[i]);
65347  szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65348 
65349  /* Drop the cell from the parent page. apDiv[i] still points to
65350  ** the cell within the parent, even though it has been dropped.
65351  ** This is safe because dropping a cell only overwrites the first
65352  ** four bytes of it, and this function does not need the first
65353  ** four bytes of the divider cell. So the pointer is safe to use
65354  ** later on.
65355  **
65356  ** But not if we are in secure-delete mode. In secure-delete mode,
65357  ** the dropCell() routine will overwrite the entire cell with zeroes.
65358  ** In this case, temporarily copy the cell into the aOvflSpace[]
65359  ** buffer. It will be copied out again as soon as the aSpace[] buffer
65360  ** is allocated. */
65361  if( pBt->btsFlags & BTS_SECURE_DELETE ){
65362  int iOff;
65363 
65364  iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
65365  if( (iOff+szNew[i])>(int)pBt->usableSize ){
65366  rc = SQLITE_CORRUPT_BKPT;
65367  memset(apOld, 0, (i+1)*sizeof(MemPage*));
65368  goto balance_cleanup;
65369  }else{
65370  memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
65371  apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
65372  }
65373  }
65374  dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
65375  }
65376  }
65377 
65378  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
65379  ** alignment */
65380  nMaxCells = (nMaxCells + 3)&~3;
65381 
65382  /*
65383  ** Allocate space for memory structures
65384  */
65385  szScratch =
65386  nMaxCells*sizeof(u8*) /* b.apCell */
65387  + nMaxCells*sizeof(u16) /* b.szCell */
65388  + pBt->pageSize; /* aSpace1 */
65389 
65390  /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
65391  ** that is more than 6 times the database page size. */
65392  assert( szScratch<=6*(int)pBt->pageSize );
65393  b.apCell = sqlite3ScratchMalloc( szScratch );
65394  if( b.apCell==0 ){
65395  rc = SQLITE_NOMEM_BKPT;
65396  goto balance_cleanup;
65397  }
65398  b.szCell = (u16*)&b.apCell[nMaxCells];
65399  aSpace1 = (u8*)&b.szCell[nMaxCells];
65400  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
65401 
65402  /*
65403  ** Load pointers to all cells on sibling pages and the divider cells
65404  ** into the local b.apCell[] array. Make copies of the divider cells
65405  ** into space obtained from aSpace1[]. The divider cells have already
65406  ** been removed from pParent.
65407  **
65408  ** If the siblings are on leaf pages, then the child pointers of the
65409  ** divider cells are stripped from the cells before they are copied
65410  ** into aSpace1[]. In this way, all cells in b.apCell[] are without
65411  ** child pointers. If siblings are not leaves, then all cell in
65412  ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
65413  ** are alike.
65414  **
65415  ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
65416  ** leafData: 1 if pPage holds key+data and pParent holds only keys.
65417  */
65418  b.pRef = apOld[0];
65419  leafCorrection = b.pRef->leaf*4;
65420  leafData = b.pRef->intKeyLeaf;
65421  for(i=0; i<nOld; i++){
65422  MemPage *pOld = apOld[i];
65423  int limit = pOld->nCell;
65424  u8 *aData = pOld->aData;
65425  u16 maskPage = pOld->maskPage;
65426  u8 *piCell = aData + pOld->cellOffset;
65427  u8 *piEnd;
65428 
65429  /* Verify that all sibling pages are of the same "type" (table-leaf,
65430  ** table-interior, index-leaf, or index-interior).
65431  */
65432  if( pOld->aData[0]!=apOld[0]->aData[0] ){
65433  rc = SQLITE_CORRUPT_BKPT;
65434  goto balance_cleanup;
65435  }
65436 
65437  /* Load b.apCell[] with pointers to all cells in pOld. If pOld
65438  ** constains overflow cells, include them in the b.apCell[] array
65439  ** in the correct spot.
65440  **
65441  ** Note that when there are multiple overflow cells, it is always the
65442  ** case that they are sequential and adjacent. This invariant arises
65443  ** because multiple overflows can only occurs when inserting divider
65444  ** cells into a parent on a prior balance, and divider cells are always
65445  ** adjacent and are inserted in order. There is an assert() tagged
65446  ** with "NOTE 1" in the overflow cell insertion loop to prove this
65447  ** invariant.
65448  **
65449  ** This must be done in advance. Once the balance starts, the cell
65450  ** offset section of the btree page will be overwritten and we will no
65451  ** long be able to find the cells if a pointer to each cell is not saved
65452  ** first.
65453  */
65454  memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
65455  if( pOld->nOverflow>0 ){
65456  limit = pOld->aiOvfl[0];
65457  for(j=0; j<limit; j++){
65458  b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65459  piCell += 2;
65460  b.nCell++;
65461  }
65462  for(k=0; k<pOld->nOverflow; k++){
65463  assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
65464  b.apCell[b.nCell] = pOld->apOvfl[k];
65465  b.nCell++;
65466  }
65467  }
65468  piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
65469  while( piCell<piEnd ){
65470  assert( b.nCell<nMaxCells );
65471  b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65472  piCell += 2;
65473  b.nCell++;
65474  }
65475 
65476  cntOld[i] = b.nCell;
65477  if( i<nOld-1 && !leafData){
65478  u16 sz = (u16)szNew[i];
65479  u8 *pTemp;
65480  assert( b.nCell<nMaxCells );
65481  b.szCell[b.nCell] = sz;
65482  pTemp = &aSpace1[iSpace1];
65483  iSpace1 += sz;
65484  assert( sz<=pBt->maxLocal+23 );
65485  assert( iSpace1 <= (int)pBt->pageSize );
65486  memcpy(pTemp, apDiv[i], sz);
65487  b.apCell[b.nCell] = pTemp+leafCorrection;
65488  assert( leafCorrection==0 || leafCorrection==4 );
65489  b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
65490  if( !pOld->leaf ){
65491  assert( leafCorrection==0 );
65492  assert( pOld->hdrOffset==0 );
65493  /* The right pointer of the child page pOld becomes the left
65494  ** pointer of the divider cell */
65495  memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
65496  }else{
65497  assert( leafCorrection==4 );
65498  while( b.szCell[b.nCell]<4 ){
65499  /* Do not allow any cells smaller than 4 bytes. If a smaller cell
65500  ** does exist, pad it with 0x00 bytes. */
65501  assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
65502  assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
65503  aSpace1[iSpace1++] = 0x00;
65504  b.szCell[b.nCell]++;
65505  }
65506  }
65507  b.nCell++;
65508  }
65509  }
65510 
65511  /*
65512  ** Figure out the number of pages needed to hold all b.nCell cells.
65513  ** Store this number in "k". Also compute szNew[] which is the total
65514  ** size of all cells on the i-th page and cntNew[] which is the index
65515  ** in b.apCell[] of the cell that divides page i from page i+1.
65516  ** cntNew[k] should equal b.nCell.
65517  **
65518  ** Values computed by this block:
65519  **
65520  ** k: The total number of sibling pages
65521  ** szNew[i]: Spaced used on the i-th sibling page.
65522  ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
65523  ** the right of the i-th sibling page.
65524  ** usableSpace: Number of bytes of space available on each sibling.
65525  **
65526  */
65527  usableSpace = pBt->usableSize - 12 + leafCorrection;
65528  for(i=0; i<nOld; i++){
65529  MemPage *p = apOld[i];
65530  szNew[i] = usableSpace - p->nFree;
65531  if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65532  for(j=0; j<p->nOverflow; j++){
65533  szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
65534  }
65535  cntNew[i] = cntOld[i];
65536  }
65537  k = nOld;
65538  for(i=0; i<k; i++){
65539  int sz;
65540  while( szNew[i]>usableSpace ){
65541  if( i+1>=k ){
65542  k = i+2;
65543  if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65544  szNew[k-1] = 0;
65545  cntNew[k-1] = b.nCell;
65546  }
65547  sz = 2 + cachedCellSize(&b, cntNew[i]-1);
65548  szNew[i] -= sz;
65549  if( !leafData ){
65550  if( cntNew[i]<b.nCell ){
65551  sz = 2 + cachedCellSize(&b, cntNew[i]);
65552  }else{
65553  sz = 0;
65554  }
65555  }
65556  szNew[i+1] += sz;
65557  cntNew[i]--;
65558  }
65559  while( cntNew[i]<b.nCell ){
65560  sz = 2 + cachedCellSize(&b, cntNew[i]);
65561  if( szNew[i]+sz>usableSpace ) break;
65562  szNew[i] += sz;
65563  cntNew[i]++;
65564  if( !leafData ){
65565  if( cntNew[i]<b.nCell ){
65566  sz = 2 + cachedCellSize(&b, cntNew[i]);
65567  }else{
65568  sz = 0;
65569  }
65570  }
65571  szNew[i+1] -= sz;
65572  }
65573  if( cntNew[i]>=b.nCell ){
65574  k = i+1;
65575  }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
65576  rc = SQLITE_CORRUPT_BKPT;
65577  goto balance_cleanup;
65578  }
65579  }
65580 
65581  /*
65582  ** The packing computed by the previous block is biased toward the siblings
65583  ** on the left side (siblings with smaller keys). The left siblings are
65584  ** always nearly full, while the right-most sibling might be nearly empty.
65585  ** The next block of code attempts to adjust the packing of siblings to
65586  ** get a better balance.
65587  **
65588  ** This adjustment is more than an optimization. The packing above might
65589  ** be so out of balance as to be illegal. For example, the right-most
65590  ** sibling might be completely empty. This adjustment is not optional.
65591  */
65592  for(i=k-1; i>0; i--){
65593  int szRight = szNew[i]; /* Size of sibling on the right */
65594  int szLeft = szNew[i-1]; /* Size of sibling on the left */
65595  int r; /* Index of right-most cell in left sibling */
65596  int d; /* Index of first cell to the left of right sibling */
65597 
65598  r = cntNew[i-1] - 1;
65599  d = r + 1 - leafData;
65600  (void)cachedCellSize(&b, d);
65601  do{
65602  assert( d<nMaxCells );
65603  assert( r<nMaxCells );
65604  (void)cachedCellSize(&b, r);
65605  if( szRight!=0
65606  && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
65607  break;
65608  }
65609  szRight += b.szCell[d] + 2;
65610  szLeft -= b.szCell[r] + 2;
65611  cntNew[i-1] = r;
65612  r--;
65613  d--;
65614  }while( r>=0 );
65615  szNew[i] = szRight;
65616  szNew[i-1] = szLeft;
65617  if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
65618  rc = SQLITE_CORRUPT_BKPT;
65619  goto balance_cleanup;
65620  }
65621  }
65622 
65623  /* Sanity check: For a non-corrupt database file one of the follwing
65624  ** must be true:
65625  ** (1) We found one or more cells (cntNew[0])>0), or
65626  ** (2) pPage is a virtual root page. A virtual root page is when
65627  ** the real root page is page 1 and we are the only child of
65628  ** that page.
65629  */
65630  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
65631  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
65632  apOld[0]->pgno, apOld[0]->nCell,
65633  nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
65634  nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
65635  ));
65636 
65637  /*
65638  ** Allocate k new pages. Reuse old pages where possible.
65639  */
65640  pageFlags = apOld[0]->aData[0];
65641  for(i=0; i<k; i++){
65642  MemPage *pNew;
65643  if( i<nOld ){
65644  pNew = apNew[i] = apOld[i];
65645  apOld[i] = 0;
65646  rc = sqlite3PagerWrite(pNew->pDbPage);
65647  nNew++;
65648  if( rc ) goto balance_cleanup;
65649  }else{
65650  assert( i>0 );
65651  rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
65652  if( rc ) goto balance_cleanup;
65653  zeroPage(pNew, pageFlags);
65654  apNew[i] = pNew;
65655  nNew++;
65656  cntOld[i] = b.nCell;
65657 
65658  /* Set the pointer-map entry for the new sibling page. */
65659  if( ISAUTOVACUUM ){
65660  ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
65661  if( rc!=SQLITE_OK ){
65662  goto balance_cleanup;
65663  }
65664  }
65665  }
65666  }
65667 
65668  /*
65669  ** Reassign page numbers so that the new pages are in ascending order.
65670  ** This helps to keep entries in the disk file in order so that a scan
65671  ** of the table is closer to a linear scan through the file. That in turn
65672  ** helps the operating system to deliver pages from the disk more rapidly.
65673  **
65674  ** An O(n^2) insertion sort algorithm is used, but since n is never more
65675  ** than (NB+2) (a small constant), that should not be a problem.
65676  **
65677  ** When NB==3, this one optimization makes the database about 25% faster
65678  ** for large insertions and deletions.
65679  */
65680  for(i=0; i<nNew; i++){
65681  aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
65682  aPgFlags[i] = apNew[i]->pDbPage->flags;
65683  for(j=0; j<i; j++){
65684  if( aPgno[j]==aPgno[i] ){
65685  /* This branch is taken if the set of sibling pages somehow contains
65686  ** duplicate entries. This can happen if the database is corrupt.
65687  ** It would be simpler to detect this as part of the loop below, but
65688  ** we do the detection here in order to avoid populating the pager
65689  ** cache with two separate objects associated with the same
65690  ** page number. */
65691  assert( CORRUPT_DB );
65692  rc = SQLITE_CORRUPT_BKPT;
65693  goto balance_cleanup;
65694  }
65695  }
65696  }
65697  for(i=0; i<nNew; i++){
65698  int iBest = 0; /* aPgno[] index of page number to use */
65699  for(j=1; j<nNew; j++){
65700  if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
65701  }
65702  pgno = aPgOrder[iBest];
65703  aPgOrder[iBest] = 0xffffffff;
65704  if( iBest!=i ){
65705  if( iBest>i ){
65706  sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
65707  }
65708  sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
65709  apNew[i]->pgno = pgno;
65710  }
65711  }
65712 
65713  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
65714  "%d(%d nc=%d) %d(%d nc=%d)\n",
65715  apNew[0]->pgno, szNew[0], cntNew[0],
65716  nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
65717  nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
65718  nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
65719  nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
65720  nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
65721  nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
65722  nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
65723  nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
65724  ));
65725 
65726  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65727  put4byte(pRight, apNew[nNew-1]->pgno);
65728 
65729  /* If the sibling pages are not leaves, ensure that the right-child pointer
65730  ** of the right-most new sibling page is set to the value that was
65731  ** originally in the same field of the right-most old sibling page. */
65732  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
65733  MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
65734  memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
65735  }
65736 
65737  /* Make any required updates to pointer map entries associated with
65738  ** cells stored on sibling pages following the balance operation. Pointer
65739  ** map entries associated with divider cells are set by the insertCell()
65740  ** routine. The associated pointer map entries are:
65741  **
65742  ** a) if the cell contains a reference to an overflow chain, the
65743  ** entry associated with the first page in the overflow chain, and
65744  **
65745  ** b) if the sibling pages are not leaves, the child page associated
65746  ** with the cell.
65747  **
65748  ** If the sibling pages are not leaves, then the pointer map entry
65749  ** associated with the right-child of each sibling may also need to be
65750  ** updated. This happens below, after the sibling pages have been
65751  ** populated, not here.
65752  */
65753  if( ISAUTOVACUUM ){
65754  MemPage *pNew = apNew[0];
65755  u8 *aOld = pNew->aData;
65756  int cntOldNext = pNew->nCell + pNew->nOverflow;
65757  int usableSize = pBt->usableSize;
65758  int iNew = 0;
65759  int iOld = 0;
65760 
65761  for(i=0; i<b.nCell; i++){
65762  u8 *pCell = b.apCell[i];
65763  if( i==cntOldNext ){
65764  MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
65765  cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
65766  aOld = pOld->aData;
65767  }
65768  if( i==cntNew[iNew] ){
65769  pNew = apNew[++iNew];
65770  if( !leafData ) continue;
65771  }
65772 
65773  /* Cell pCell is destined for new sibling page pNew. Originally, it
65774  ** was either part of sibling page iOld (possibly an overflow cell),
65775  ** or else the divider cell to the left of sibling page iOld. So,
65776  ** if sibling page iOld had the same page number as pNew, and if
65777  ** pCell really was a part of sibling page iOld (not a divider or
65778  ** overflow cell), we can skip updating the pointer map entries. */
65779  if( iOld>=nNew
65780  || pNew->pgno!=aPgno[iOld]
65781  || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
65782  ){
65783  if( !leafCorrection ){
65784  ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
65785  }
65786  if( cachedCellSize(&b,i)>pNew->minLocal ){
65787  ptrmapPutOvflPtr(pNew, pCell, &rc);
65788  }
65789  if( rc ) goto balance_cleanup;
65790  }
65791  }
65792  }
65793 
65794  /* Insert new divider cells into pParent. */
65795  for(i=0; i<nNew-1; i++){
65796  u8 *pCell;
65797  u8 *pTemp;
65798  int sz;
65799  MemPage *pNew = apNew[i];
65800  j = cntNew[i];
65801 
65802  assert( j<nMaxCells );
65803  assert( b.apCell[j]!=0 );
65804  pCell = b.apCell[j];
65805  sz = b.szCell[j] + leafCorrection;
65806  pTemp = &aOvflSpace[iOvflSpace];
65807  if( !pNew->leaf ){
65808  memcpy(&pNew->aData[8], pCell, 4);
65809  }else if( leafData ){
65810  /* If the tree is a leaf-data tree, and the siblings are leaves,
65811  ** then there is no divider cell in b.apCell[]. Instead, the divider
65812  ** cell consists of the integer key for the right-most cell of
65813  ** the sibling-page assembled above only.
65814  */
65815  CellInfo info;
65816  j--;
65817  pNew->xParseCell(pNew, b.apCell[j], &info);
65818  pCell = pTemp;
65819  sz = 4 + putVarint(&pCell[4], info.nKey);
65820  pTemp = 0;
65821  }else{
65822  pCell -= 4;
65823  /* Obscure case for non-leaf-data trees: If the cell at pCell was
65824  ** previously stored on a leaf node, and its reported size was 4
65825  ** bytes, then it may actually be smaller than this
65826  ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
65827  ** any cell). But it is important to pass the correct size to
65828  ** insertCell(), so reparse the cell now.
65829  **
65830  ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
65831  ** and WITHOUT ROWID tables with exactly one column which is the
65832  ** primary key.
65833  */
65834  if( b.szCell[j]==4 ){
65835  assert(leafCorrection==4);
65836  sz = pParent->xCellSize(pParent, pCell);
65837  }
65838  }
65839  iOvflSpace += sz;
65840  assert( sz<=pBt->maxLocal+23 );
65841  assert( iOvflSpace <= (int)pBt->pageSize );
65842  insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
65843  if( rc!=SQLITE_OK ) goto balance_cleanup;
65844  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65845  }
65846 
65847  /* Now update the actual sibling pages. The order in which they are updated
65848  ** is important, as this code needs to avoid disrupting any page from which
65849  ** cells may still to be read. In practice, this means:
65850  **
65851  ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
65852  ** then it is not safe to update page apNew[iPg] until after
65853  ** the left-hand sibling apNew[iPg-1] has been updated.
65854  **
65855  ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
65856  ** then it is not safe to update page apNew[iPg] until after
65857  ** the right-hand sibling apNew[iPg+1] has been updated.
65858  **
65859  ** If neither of the above apply, the page is safe to update.
65860  **
65861  ** The iPg value in the following loop starts at nNew-1 goes down
65862  ** to 0, then back up to nNew-1 again, thus making two passes over
65863  ** the pages. On the initial downward pass, only condition (1) above
65864  ** needs to be tested because (2) will always be true from the previous
65865  ** step. On the upward pass, both conditions are always true, so the
65866  ** upwards pass simply processes pages that were missed on the downward
65867  ** pass.
65868  */
65869  for(i=1-nNew; i<nNew; i++){
65870  int iPg = i<0 ? -i : i;
65871  assert( iPg>=0 && iPg<nNew );
65872  if( abDone[iPg] ) continue; /* Skip pages already processed */
65873  if( i>=0 /* On the upwards pass, or... */
65874  || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
65875  ){
65876  int iNew;
65877  int iOld;
65878  int nNewCell;
65879 
65880  /* Verify condition (1): If cells are moving left, update iPg
65881  ** only after iPg-1 has already been updated. */
65882  assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
65883 
65884  /* Verify condition (2): If cells are moving right, update iPg
65885  ** only after iPg+1 has already been updated. */
65886  assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
65887 
65888  if( iPg==0 ){
65889  iNew = iOld = 0;
65890  nNewCell = cntNew[0];
65891  }else{
65892  iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
65893  iNew = cntNew[iPg-1] + !leafData;
65894  nNewCell = cntNew[iPg] - iNew;
65895  }
65896 
65897  rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
65898  if( rc ) goto balance_cleanup;
65899  abDone[iPg]++;
65900  apNew[iPg]->nFree = usableSpace-szNew[iPg];
65901  assert( apNew[iPg]->nOverflow==0 );
65902  assert( apNew[iPg]->nCell==nNewCell );
65903  }
65904  }
65905 
65906  /* All pages have been processed exactly once */
65907  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
65908 
65909  assert( nOld>0 );
65910  assert( nNew>0 );
65911 
65912  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
65913  /* The root page of the b-tree now contains no cells. The only sibling
65914  ** page is the right-child of the parent. Copy the contents of the
65915  ** child page into the parent, decreasing the overall height of the
65916  ** b-tree structure by one. This is described as the "balance-shallower"
65917  ** sub-algorithm in some documentation.
65918  **
65919  ** If this is an auto-vacuum database, the call to copyNodeContent()
65920  ** sets all pointer-map entries corresponding to database image pages
65921  ** for which the pointer is stored within the content being copied.
65922  **
65923  ** It is critical that the child page be defragmented before being
65924  ** copied into the parent, because if the parent is page 1 then it will
65925  ** by smaller than the child due to the database header, and so all the
65926  ** free space needs to be up front.
65927  */
65928  assert( nNew==1 || CORRUPT_DB );
65929  rc = defragmentPage(apNew[0]);
65930  testcase( rc!=SQLITE_OK );
65931  assert( apNew[0]->nFree ==
65932  (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
65933  || rc!=SQLITE_OK
65934  );
65935  copyNodeContent(apNew[0], pParent, &rc);
65936  freePage(apNew[0], &rc);
65937  }else if( ISAUTOVACUUM && !leafCorrection ){
65938  /* Fix the pointer map entries associated with the right-child of each
65939  ** sibling page. All other pointer map entries have already been taken
65940  ** care of. */
65941  for(i=0; i<nNew; i++){
65942  u32 key = get4byte(&apNew[i]->aData[8]);
65943  ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
65944  }
65945  }
65946 
65947  assert( pParent->isInit );
65948  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
65949  nOld, nNew, b.nCell));
65950 
65951  /* Free any old pages that were not reused as new pages.
65952  */
65953  for(i=nNew; i<nOld; i++){
65954  freePage(apOld[i], &rc);
65955  }
65956 
65957 #if 0
65958  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
65959  /* The ptrmapCheckPages() contains assert() statements that verify that
65960  ** all pointer map pages are set correctly. This is helpful while
65961  ** debugging. This is usually disabled because a corrupt database may
65962  ** cause an assert() statement to fail. */
65963  ptrmapCheckPages(apNew, nNew);
65964  ptrmapCheckPages(&pParent, 1);
65965  }
65966 #endif
65967 
65968  /*
65969  ** Cleanup before returning.
65970  */
65971 balance_cleanup:
65972  sqlite3ScratchFree(b.apCell);
65973  for(i=0; i<nOld; i++){
65974  releasePage(apOld[i]);
65975  }
65976  for(i=0; i<nNew; i++){
65977  releasePage(apNew[i]);
65978  }
65979 
65980  return rc;
65981 }
65982 
65983 
65984 /*
65985 ** This function is called when the root page of a b-tree structure is
65986 ** overfull (has one or more overflow pages).
65987 **
65988 ** A new child page is allocated and the contents of the current root
65989 ** page, including overflow cells, are copied into the child. The root
65990 ** page is then overwritten to make it an empty page with the right-child
65991 ** pointer pointing to the new page.
65992 **
65993 ** Before returning, all pointer-map entries corresponding to pages
65994 ** that the new child-page now contains pointers to are updated. The
65995 ** entry corresponding to the new right-child pointer of the root
65996 ** page is also updated.
65997 **
65998 ** If successful, *ppChild is set to contain a reference to the child
65999 ** page and SQLITE_OK is returned. In this case the caller is required
66000 ** to call releasePage() on *ppChild exactly once. If an error occurs,
66001 ** an error code is returned and *ppChild is set to 0.
66002 */
66003 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
66004  int rc; /* Return value from subprocedures */
66005  MemPage *pChild = 0; /* Pointer to a new child page */
66006  Pgno pgnoChild = 0; /* Page number of the new child page */
66007  BtShared *pBt = pRoot->pBt; /* The BTree */
66008 
66009  assert( pRoot->nOverflow>0 );
66010  assert( sqlite3_mutex_held(pBt->mutex) );
66011 
66012  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
66013  ** page that will become the new right-child of pPage. Copy the contents
66014  ** of the node stored on pRoot into the new child page.
66015  */
66016  rc = sqlite3PagerWrite(pRoot->pDbPage);
66017  if( rc==SQLITE_OK ){
66018  rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
66019  copyNodeContent(pRoot, pChild, &rc);
66020  if( ISAUTOVACUUM ){
66021  ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
66022  }
66023  }
66024  if( rc ){
66025  *ppChild = 0;
66026  releasePage(pChild);
66027  return rc;
66028  }
66029  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
66030  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
66031  assert( pChild->nCell==pRoot->nCell );
66032 
66033  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
66034 
66035  /* Copy the overflow cells from pRoot to pChild */
66036  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
66037  pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
66038  memcpy(pChild->apOvfl, pRoot->apOvfl,
66039  pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
66040  pChild->nOverflow = pRoot->nOverflow;
66041 
66042  /* Zero the contents of pRoot. Then install pChild as the right-child. */
66043  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
66044  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
66045 
66046  *ppChild = pChild;
66047  return SQLITE_OK;
66048 }
66049 
66050 /*
66051 ** The page that pCur currently points to has just been modified in
66052 ** some way. This function figures out if this modification means the
66053 ** tree needs to be balanced, and if so calls the appropriate balancing
66054 ** routine. Balancing routines are:
66055 **
66056 ** balance_quick()
66057 ** balance_deeper()
66058 ** balance_nonroot()
66059 */
66060 static int balance(BtCursor *pCur){
66061  int rc = SQLITE_OK;
66062  const int nMin = pCur->pBt->usableSize * 2 / 3;
66063  u8 aBalanceQuickSpace[13];
66064  u8 *pFree = 0;
66065 
66066  VVA_ONLY( int balance_quick_called = 0 );
66067  VVA_ONLY( int balance_deeper_called = 0 );
66068 
66069  do {
66070  int iPage = pCur->iPage;
66071  MemPage *pPage = pCur->apPage[iPage];
66072 
66073  if( iPage==0 ){
66074  if( pPage->nOverflow ){
66075  /* The root page of the b-tree is overfull. In this case call the
66076  ** balance_deeper() function to create a new child for the root-page
66077  ** and copy the current contents of the root-page to it. The
66078  ** next iteration of the do-loop will balance the child page.
66079  */
66080  assert( balance_deeper_called==0 );
66081  VVA_ONLY( balance_deeper_called++ );
66082  rc = balance_deeper(pPage, &pCur->apPage[1]);
66083  if( rc==SQLITE_OK ){
66084  pCur->iPage = 1;
66085  pCur->aiIdx[0] = 0;
66086  pCur->aiIdx[1] = 0;
66087  assert( pCur->apPage[1]->nOverflow );
66088  }
66089  }else{
66090  break;
66091  }
66092  }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
66093  break;
66094  }else{
66095  MemPage * const pParent = pCur->apPage[iPage-1];
66096  int const iIdx = pCur->aiIdx[iPage-1];
66097 
66098  rc = sqlite3PagerWrite(pParent->pDbPage);
66099  if( rc==SQLITE_OK ){
66100 #ifndef SQLITE_OMIT_QUICKBALANCE
66101  if( pPage->intKeyLeaf
66102  && pPage->nOverflow==1
66103  && pPage->aiOvfl[0]==pPage->nCell
66104  && pParent->pgno!=1
66105  && pParent->nCell==iIdx
66106  ){
66107  /* Call balance_quick() to create a new sibling of pPage on which
66108  ** to store the overflow cell. balance_quick() inserts a new cell
66109  ** into pParent, which may cause pParent overflow. If this
66110  ** happens, the next iteration of the do-loop will balance pParent
66111  ** use either balance_nonroot() or balance_deeper(). Until this
66112  ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
66113  ** buffer.
66114  **
66115  ** The purpose of the following assert() is to check that only a
66116  ** single call to balance_quick() is made for each call to this
66117  ** function. If this were not verified, a subtle bug involving reuse
66118  ** of the aBalanceQuickSpace[] might sneak in.
66119  */
66120  assert( balance_quick_called==0 );
66121  VVA_ONLY( balance_quick_called++ );
66122  rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
66123  }else
66124 #endif
66125  {
66126  /* In this case, call balance_nonroot() to redistribute cells
66127  ** between pPage and up to 2 of its sibling pages. This involves
66128  ** modifying the contents of pParent, which may cause pParent to
66129  ** become overfull or underfull. The next iteration of the do-loop
66130  ** will balance the parent page to correct this.
66131  **
66132  ** If the parent page becomes overfull, the overflow cell or cells
66133  ** are stored in the pSpace buffer allocated immediately below.
66134  ** A subsequent iteration of the do-loop will deal with this by
66135  ** calling balance_nonroot() (balance_deeper() may be called first,
66136  ** but it doesn't deal with overflow cells - just moves them to a
66137  ** different page). Once this subsequent call to balance_nonroot()
66138  ** has completed, it is safe to release the pSpace buffer used by
66139  ** the previous call, as the overflow cell data will have been
66140  ** copied either into the body of a database page or into the new
66141  ** pSpace buffer passed to the latter call to balance_nonroot().
66142  */
66143  u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
66144  rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
66145  pCur->hints&BTREE_BULKLOAD);
66146  if( pFree ){
66147  /* If pFree is not NULL, it points to the pSpace buffer used
66148  ** by a previous call to balance_nonroot(). Its contents are
66149  ** now stored either on real database pages or within the
66150  ** new pSpace buffer, so it may be safely freed here. */
66151  sqlite3PageFree(pFree);
66152  }
66153 
66154  /* The pSpace buffer will be freed after the next call to
66155  ** balance_nonroot(), or just before this function returns, whichever
66156  ** comes first. */
66157  pFree = pSpace;
66158  }
66159  }
66160 
66161  pPage->nOverflow = 0;
66162 
66163  /* The next iteration of the do-loop balances the parent page. */
66164  releasePage(pPage);
66165  pCur->iPage--;
66166  assert( pCur->iPage>=0 );
66167  }
66168  }while( rc==SQLITE_OK );
66169 
66170  if( pFree ){
66171  sqlite3PageFree(pFree);
66172  }
66173  return rc;
66174 }
66175 
66176 
66177 /*
66178 ** Insert a new record into the BTree. The content of the new record
66179 ** is described by the pX object. The pCur cursor is used only to
66180 ** define what table the record should be inserted into, and is left
66181 ** pointing at a random location.
66182 **
66183 ** For a table btree (used for rowid tables), only the pX.nKey value of
66184 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
66185 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
66186 ** hold the content of the row.
66187 **
66188 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
66189 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
66190 ** pX.pData,nData,nZero fields must be zero.
66191 **
66192 ** If the seekResult parameter is non-zero, then a successful call to
66193 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
66194 ** been performed. seekResult is the search result returned (a negative
66195 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
66196 ** a positive value if pCur points at an entry that is larger than
66197 ** (pKey, nKey)).
66198 **
66199 ** If the seekResult parameter is non-zero, then the caller guarantees that
66200 ** cursor pCur is pointing at the existing copy of a row that is to be
66201 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
66202 ** point to any entry or to no entry at all and so this function has to seek
66203 ** the cursor before the new key can be inserted.
66204 */
66205 SQLITE_PRIVATE int sqlite3BtreeInsert(
66206  BtCursor *pCur, /* Insert data into the table of this cursor */
66207  const BtreePayload *pX, /* Content of the row to be inserted */
66208  int appendBias, /* True if this is likely an append */
66209  int seekResult /* Result of prior MovetoUnpacked() call */
66210 ){
66211  int rc;
66212  int loc = seekResult; /* -1: before desired location +1: after */
66213  int szNew = 0;
66214  int idx;
66215  MemPage *pPage;
66216  Btree *p = pCur->pBtree;
66217  BtShared *pBt = p->pBt;
66218  unsigned char *oldCell;
66219  unsigned char *newCell = 0;
66220 
66221  if( pCur->eState==CURSOR_FAULT ){
66222  assert( pCur->skipNext!=SQLITE_OK );
66223  return pCur->skipNext;
66224  }
66225 
66226  assert( cursorOwnsBtShared(pCur) );
66227  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
66228  && pBt->inTransaction==TRANS_WRITE
66229  && (pBt->btsFlags & BTS_READ_ONLY)==0 );
66230  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66231 
66232  /* Assert that the caller has been consistent. If this cursor was opened
66233  ** expecting an index b-tree, then the caller should be inserting blob
66234  ** keys with no associated data. If the cursor was opened expecting an
66235  ** intkey table, the caller should be inserting integer keys with a
66236  ** blob of associated data. */
66237  assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
66238 
66239  /* Save the positions of any other cursors open on this table.
66240  **
66241  ** In some cases, the call to btreeMoveto() below is a no-op. For
66242  ** example, when inserting data into a table with auto-generated integer
66243  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
66244  ** integer key to use. It then calls this function to actually insert the
66245  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
66246  ** that the cursor is already where it needs to be and returns without
66247  ** doing any work. To avoid thwarting these optimizations, it is important
66248  ** not to clear the cursor here.
66249  */
66250  if( pCur->curFlags & BTCF_Multiple ){
66251  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66252  if( rc ) return rc;
66253  }
66254 
66255  if( pCur->pKeyInfo==0 ){
66256  assert( pX->pKey==0 );
66257  /* If this is an insert into a table b-tree, invalidate any incrblob
66258  ** cursors open on the row being replaced */
66259  invalidateIncrblobCursors(p, pX->nKey, 0);
66260 
66261  /* If the cursor is currently on the last row and we are appending a
66262  ** new row onto the end, set the "loc" to avoid an unnecessary
66263  ** btreeMoveto() call */
66264  if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey>0
66265  && pCur->info.nKey==pX->nKey-1 ){
66266  loc = -1;
66267  }else if( loc==0 ){
66268  rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, appendBias, &loc);
66269  if( rc ) return rc;
66270  }
66271  }else if( loc==0 ){
66272  rc = btreeMoveto(pCur, pX->pKey, pX->nKey, appendBias, &loc);
66273  if( rc ) return rc;
66274  }
66275  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
66276 
66277  pPage = pCur->apPage[pCur->iPage];
66278  assert( pPage->intKey || pX->nKey>=0 );
66279  assert( pPage->leaf || !pPage->intKey );
66280 
66281  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
66282  pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
66283  loc==0 ? "overwrite" : "new entry"));
66284  assert( pPage->isInit );
66285  newCell = pBt->pTmpSpace;
66286  assert( newCell!=0 );
66287  rc = fillInCell(pPage, newCell, pX, &szNew);
66288  if( rc ) goto end_insert;
66289  assert( szNew==pPage->xCellSize(pPage, newCell) );
66290  assert( szNew <= MX_CELL_SIZE(pBt) );
66291  idx = pCur->aiIdx[pCur->iPage];
66292  if( loc==0 ){
66293  u16 szOld;
66294  assert( idx<pPage->nCell );
66295  rc = sqlite3PagerWrite(pPage->pDbPage);
66296  if( rc ){
66297  goto end_insert;
66298  }
66299  oldCell = findCell(pPage, idx);
66300  if( !pPage->leaf ){
66301  memcpy(newCell, oldCell, 4);
66302  }
66303  rc = clearCell(pPage, oldCell, &szOld);
66304  dropCell(pPage, idx, szOld, &rc);
66305  if( rc ) goto end_insert;
66306  }else if( loc<0 && pPage->nCell>0 ){
66307  assert( pPage->leaf );
66308  idx = ++pCur->aiIdx[pCur->iPage];
66309  }else{
66310  assert( pPage->leaf );
66311  }
66312  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
66313  assert( pPage->nOverflow==0 || rc==SQLITE_OK );
66314  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
66315 
66316  /* If no error has occurred and pPage has an overflow cell, call balance()
66317  ** to redistribute the cells within the tree. Since balance() may move
66318  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
66319  ** variables.
66320  **
66321  ** Previous versions of SQLite called moveToRoot() to move the cursor
66322  ** back to the root page as balance() used to invalidate the contents
66323  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
66324  ** set the cursor state to "invalid". This makes common insert operations
66325  ** slightly faster.
66326  **
66327  ** There is a subtle but important optimization here too. When inserting
66328  ** multiple records into an intkey b-tree using a single cursor (as can
66329  ** happen while processing an "INSERT INTO ... SELECT" statement), it
66330  ** is advantageous to leave the cursor pointing to the last entry in
66331  ** the b-tree if possible. If the cursor is left pointing to the last
66332  ** entry in the table, and the next row inserted has an integer key
66333  ** larger than the largest existing key, it is possible to insert the
66334  ** row without seeking the cursor. This can be a big performance boost.
66335  */
66336  pCur->info.nSize = 0;
66337  if( pPage->nOverflow ){
66338  assert( rc==SQLITE_OK );
66339  pCur->curFlags &= ~(BTCF_ValidNKey);
66340  rc = balance(pCur);
66341 
66342  /* Must make sure nOverflow is reset to zero even if the balance()
66343  ** fails. Internal data structure corruption will result otherwise.
66344  ** Also, set the cursor state to invalid. This stops saveCursorPosition()
66345  ** from trying to save the current position of the cursor. */
66346  pCur->apPage[pCur->iPage]->nOverflow = 0;
66347  pCur->eState = CURSOR_INVALID;
66348  }
66349  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
66350 
66351 end_insert:
66352  return rc;
66353 }
66354 
66355 /*
66356 ** Delete the entry that the cursor is pointing to.
66357 **
66358 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
66359 ** the cursor is left pointing at an arbitrary location after the delete.
66360 ** But if that bit is set, then the cursor is left in a state such that
66361 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
66362 ** as it would have been on if the call to BtreeDelete() had been omitted.
66363 **
66364 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
66365 ** associated with a single table entry and its indexes. Only one of those
66366 ** deletes is considered the "primary" delete. The primary delete occurs
66367 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
66368 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
66369 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
66370 ** but which might be used by alternative storage engines.
66371 */
66372 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
66373  Btree *p = pCur->pBtree;
66374  BtShared *pBt = p->pBt;
66375  int rc; /* Return code */
66376  MemPage *pPage; /* Page to delete cell from */
66377  unsigned char *pCell; /* Pointer to cell to delete */
66378  int iCellIdx; /* Index of cell to delete */
66379  int iCellDepth; /* Depth of node containing pCell */
66380  u16 szCell; /* Size of the cell being deleted */
66381  int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
66382  u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
66383 
66384  assert( cursorOwnsBtShared(pCur) );
66385  assert( pBt->inTransaction==TRANS_WRITE );
66386  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66387  assert( pCur->curFlags & BTCF_WriteFlag );
66388  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66389  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
66390  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
66391  assert( pCur->eState==CURSOR_VALID );
66392  assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
66393 
66394  iCellDepth = pCur->iPage;
66395  iCellIdx = pCur->aiIdx[iCellDepth];
66396  pPage = pCur->apPage[iCellDepth];
66397  pCell = findCell(pPage, iCellIdx);
66398 
66399  /* If the bPreserve flag is set to true, then the cursor position must
66400  ** be preserved following this delete operation. If the current delete
66401  ** will cause a b-tree rebalance, then this is done by saving the cursor
66402  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
66403  ** returning.
66404  **
66405  ** Or, if the current delete will not cause a rebalance, then the cursor
66406  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
66407  ** before or after the deleted entry. In this case set bSkipnext to true. */
66408  if( bPreserve ){
66409  if( !pPage->leaf
66410  || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
66411  ){
66412  /* A b-tree rebalance will be required after deleting this entry.
66413  ** Save the cursor key. */
66414  rc = saveCursorKey(pCur);
66415  if( rc ) return rc;
66416  }else{
66417  bSkipnext = 1;
66418  }
66419  }
66420 
66421  /* If the page containing the entry to delete is not a leaf page, move
66422  ** the cursor to the largest entry in the tree that is smaller than
66423  ** the entry being deleted. This cell will replace the cell being deleted
66424  ** from the internal node. The 'previous' entry is used for this instead
66425  ** of the 'next' entry, as the previous entry is always a part of the
66426  ** sub-tree headed by the child page of the cell being deleted. This makes
66427  ** balancing the tree following the delete operation easier. */
66428  if( !pPage->leaf ){
66429  int notUsed = 0;
66430  rc = sqlite3BtreePrevious(pCur, &notUsed);
66431  if( rc ) return rc;
66432  }
66433 
66434  /* Save the positions of any other cursors open on this table before
66435  ** making any modifications. */
66436  if( pCur->curFlags & BTCF_Multiple ){
66437  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66438  if( rc ) return rc;
66439  }
66440 
66441  /* If this is a delete operation to remove a row from a table b-tree,
66442  ** invalidate any incrblob cursors open on the row being deleted. */
66443  if( pCur->pKeyInfo==0 ){
66444  invalidateIncrblobCursors(p, pCur->info.nKey, 0);
66445  }
66446 
66447  /* Make the page containing the entry to be deleted writable. Then free any
66448  ** overflow pages associated with the entry and finally remove the cell
66449  ** itself from within the page. */
66450  rc = sqlite3PagerWrite(pPage->pDbPage);
66451  if( rc ) return rc;
66452  rc = clearCell(pPage, pCell, &szCell);
66453  dropCell(pPage, iCellIdx, szCell, &rc);
66454  if( rc ) return rc;
66455 
66456  /* If the cell deleted was not located on a leaf page, then the cursor
66457  ** is currently pointing to the largest entry in the sub-tree headed
66458  ** by the child-page of the cell that was just deleted from an internal
66459  ** node. The cell from the leaf node needs to be moved to the internal
66460  ** node to replace the deleted cell. */
66461  if( !pPage->leaf ){
66462  MemPage *pLeaf = pCur->apPage[pCur->iPage];
66463  int nCell;
66464  Pgno n = pCur->apPage[iCellDepth+1]->pgno;
66465  unsigned char *pTmp;
66466 
66467  pCell = findCell(pLeaf, pLeaf->nCell-1);
66468  if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
66469  nCell = pLeaf->xCellSize(pLeaf, pCell);
66470  assert( MX_CELL_SIZE(pBt) >= nCell );
66471  pTmp = pBt->pTmpSpace;
66472  assert( pTmp!=0 );
66473  rc = sqlite3PagerWrite(pLeaf->pDbPage);
66474  if( rc==SQLITE_OK ){
66475  insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
66476  }
66477  dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
66478  if( rc ) return rc;
66479  }
66480 
66481  /* Balance the tree. If the entry deleted was located on a leaf page,
66482  ** then the cursor still points to that page. In this case the first
66483  ** call to balance() repairs the tree, and the if(...) condition is
66484  ** never true.
66485  **
66486  ** Otherwise, if the entry deleted was on an internal node page, then
66487  ** pCur is pointing to the leaf page from which a cell was removed to
66488  ** replace the cell deleted from the internal node. This is slightly
66489  ** tricky as the leaf node may be underfull, and the internal node may
66490  ** be either under or overfull. In this case run the balancing algorithm
66491  ** on the leaf node first. If the balance proceeds far enough up the
66492  ** tree that we can be sure that any problem in the internal node has
66493  ** been corrected, so be it. Otherwise, after balancing the leaf node,
66494  ** walk the cursor up the tree to the internal node and balance it as
66495  ** well. */
66496  rc = balance(pCur);
66497  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
66498  while( pCur->iPage>iCellDepth ){
66499  releasePage(pCur->apPage[pCur->iPage--]);
66500  }
66501  rc = balance(pCur);
66502  }
66503 
66504  if( rc==SQLITE_OK ){
66505  if( bSkipnext ){
66506  assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
66507  assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
66508  assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
66509  pCur->eState = CURSOR_SKIPNEXT;
66510  if( iCellIdx>=pPage->nCell ){
66511  pCur->skipNext = -1;
66512  pCur->aiIdx[iCellDepth] = pPage->nCell-1;
66513  }else{
66514  pCur->skipNext = 1;
66515  }
66516  }else{
66517  rc = moveToRoot(pCur);
66518  if( bPreserve ){
66519  pCur->eState = CURSOR_REQUIRESEEK;
66520  }
66521  }
66522  }
66523  return rc;
66524 }
66525 
66526 /*
66527 ** Create a new BTree table. Write into *piTable the page
66528 ** number for the root page of the new table.
66529 **
66530 ** The type of type is determined by the flags parameter. Only the
66531 ** following values of flags are currently in use. Other values for
66532 ** flags might not work:
66533 **
66534 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
66535 ** BTREE_ZERODATA Used for SQL indices
66536 */
66537 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
66538  BtShared *pBt = p->pBt;
66539  MemPage *pRoot;
66540  Pgno pgnoRoot;
66541  int rc;
66542  int ptfFlags; /* Page-type flage for the root page of new table */
66543 
66544  assert( sqlite3BtreeHoldsMutex(p) );
66545  assert( pBt->inTransaction==TRANS_WRITE );
66546  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66547 
66548 #ifdef SQLITE_OMIT_AUTOVACUUM
66549  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66550  if( rc ){
66551  return rc;
66552  }
66553 #else
66554  if( pBt->autoVacuum ){
66555  Pgno pgnoMove; /* Move a page here to make room for the root-page */
66556  MemPage *pPageMove; /* The page to move to. */
66557 
66558  /* Creating a new table may probably require moving an existing database
66559  ** to make room for the new tables root page. In case this page turns
66560  ** out to be an overflow page, delete all overflow page-map caches
66561  ** held by open cursors.
66562  */
66563  invalidateAllOverflowCache(pBt);
66564 
66565  /* Read the value of meta[3] from the database to determine where the
66566  ** root page of the new table should go. meta[3] is the largest root-page
66567  ** created so far, so the new root-page is (meta[3]+1).
66568  */
66569  sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
66570  pgnoRoot++;
66571 
66572  /* The new root-page may not be allocated on a pointer-map page, or the
66573  ** PENDING_BYTE page.
66574  */
66575  while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
66576  pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
66577  pgnoRoot++;
66578  }
66579  assert( pgnoRoot>=3 || CORRUPT_DB );
66580  testcase( pgnoRoot<3 );
66581 
66582  /* Allocate a page. The page that currently resides at pgnoRoot will
66583  ** be moved to the allocated page (unless the allocated page happens
66584  ** to reside at pgnoRoot).
66585  */
66586  rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
66587  if( rc!=SQLITE_OK ){
66588  return rc;
66589  }
66590 
66591  if( pgnoMove!=pgnoRoot ){
66592  /* pgnoRoot is the page that will be used for the root-page of
66593  ** the new table (assuming an error did not occur). But we were
66594  ** allocated pgnoMove. If required (i.e. if it was not allocated
66595  ** by extending the file), the current page at position pgnoMove
66596  ** is already journaled.
66597  */
66598  u8 eType = 0;
66599  Pgno iPtrPage = 0;
66600 
66601  /* Save the positions of any open cursors. This is required in
66602  ** case they are holding a reference to an xFetch reference
66603  ** corresponding to page pgnoRoot. */
66604  rc = saveAllCursors(pBt, 0, 0);
66605  releasePage(pPageMove);
66606  if( rc!=SQLITE_OK ){
66607  return rc;
66608  }
66609 
66610  /* Move the page currently at pgnoRoot to pgnoMove. */
66611  rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66612  if( rc!=SQLITE_OK ){
66613  return rc;
66614  }
66615  rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
66616  if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
66617  rc = SQLITE_CORRUPT_BKPT;
66618  }
66619  if( rc!=SQLITE_OK ){
66620  releasePage(pRoot);
66621  return rc;
66622  }
66623  assert( eType!=PTRMAP_ROOTPAGE );
66624  assert( eType!=PTRMAP_FREEPAGE );
66625  rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
66626  releasePage(pRoot);
66627 
66628  /* Obtain the page at pgnoRoot */
66629  if( rc!=SQLITE_OK ){
66630  return rc;
66631  }
66632  rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66633  if( rc!=SQLITE_OK ){
66634  return rc;
66635  }
66636  rc = sqlite3PagerWrite(pRoot->pDbPage);
66637  if( rc!=SQLITE_OK ){
66638  releasePage(pRoot);
66639  return rc;
66640  }
66641  }else{
66642  pRoot = pPageMove;
66643  }
66644 
66645  /* Update the pointer-map and meta-data with the new root-page number. */
66646  ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
66647  if( rc ){
66648  releasePage(pRoot);
66649  return rc;
66650  }
66651 
66652  /* When the new root page was allocated, page 1 was made writable in
66653  ** order either to increase the database filesize, or to decrement the
66654  ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
66655  */
66656  assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
66657  rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
66658  if( NEVER(rc) ){
66659  releasePage(pRoot);
66660  return rc;
66661  }
66662 
66663  }else{
66664  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66665  if( rc ) return rc;
66666  }
66667 #endif
66668  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
66669  if( createTabFlags & BTREE_INTKEY ){
66670  ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
66671  }else{
66672  ptfFlags = PTF_ZERODATA | PTF_LEAF;
66673  }
66674  zeroPage(pRoot, ptfFlags);
66675  sqlite3PagerUnref(pRoot->pDbPage);
66676  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
66677  *piTable = (int)pgnoRoot;
66678  return SQLITE_OK;
66679 }
66680 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
66681  int rc;
66682  sqlite3BtreeEnter(p);
66683  rc = btreeCreateTable(p, piTable, flags);
66684  sqlite3BtreeLeave(p);
66685  return rc;
66686 }
66687 
66688 /*
66689 ** Erase the given database page and all its children. Return
66690 ** the page to the freelist.
66691 */
66692 static int clearDatabasePage(
66693  BtShared *pBt, /* The BTree that contains the table */
66694  Pgno pgno, /* Page number to clear */
66695  int freePageFlag, /* Deallocate page if true */
66696  int *pnChange /* Add number of Cells freed to this counter */
66697 ){
66698  MemPage *pPage;
66699  int rc;
66700  unsigned char *pCell;
66701  int i;
66702  int hdr;
66703  u16 szCell;
66704 
66705  assert( sqlite3_mutex_held(pBt->mutex) );
66706  if( pgno>btreePagecount(pBt) ){
66707  return SQLITE_CORRUPT_BKPT;
66708  }
66709  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
66710  if( rc ) return rc;
66711  if( pPage->bBusy ){
66712  rc = SQLITE_CORRUPT_BKPT;
66713  goto cleardatabasepage_out;
66714  }
66715  pPage->bBusy = 1;
66716  hdr = pPage->hdrOffset;
66717  for(i=0; i<pPage->nCell; i++){
66718  pCell = findCell(pPage, i);
66719  if( !pPage->leaf ){
66720  rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
66721  if( rc ) goto cleardatabasepage_out;
66722  }
66723  rc = clearCell(pPage, pCell, &szCell);
66724  if( rc ) goto cleardatabasepage_out;
66725  }
66726  if( !pPage->leaf ){
66727  rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
66728  if( rc ) goto cleardatabasepage_out;
66729  }else if( pnChange ){
66730  assert( pPage->intKey || CORRUPT_DB );
66731  testcase( !pPage->intKey );
66732  *pnChange += pPage->nCell;
66733  }
66734  if( freePageFlag ){
66735  freePage(pPage, &rc);
66736  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
66737  zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
66738  }
66739 
66740 cleardatabasepage_out:
66741  pPage->bBusy = 0;
66742  releasePage(pPage);
66743  return rc;
66744 }
66745 
66746 /*
66747 ** Delete all information from a single table in the database. iTable is
66748 ** the page number of the root of the table. After this routine returns,
66749 ** the root page is empty, but still exists.
66750 **
66751 ** This routine will fail with SQLITE_LOCKED if there are any open
66752 ** read cursors on the table. Open write cursors are moved to the
66753 ** root of the table.
66754 **
66755 ** If pnChange is not NULL, then table iTable must be an intkey table. The
66756 ** integer value pointed to by pnChange is incremented by the number of
66757 ** entries in the table.
66758 */
66759 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
66760  int rc;
66761  BtShared *pBt = p->pBt;
66762  sqlite3BtreeEnter(p);
66763  assert( p->inTrans==TRANS_WRITE );
66764 
66765  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
66766 
66767  if( SQLITE_OK==rc ){
66768  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
66769  ** is the root of a table b-tree - if it is not, the following call is
66770  ** a no-op). */
66771  invalidateIncrblobCursors(p, 0, 1);
66772  rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
66773  }
66774  sqlite3BtreeLeave(p);
66775  return rc;
66776 }
66777 
66778 /*
66779 ** Delete all information from the single table that pCur is open on.
66780 **
66781 ** This routine only work for pCur on an ephemeral table.
66782 */
66783 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
66784  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
66785 }
66786 
66787 /*
66788 ** Erase all information in a table and add the root of the table to
66789 ** the freelist. Except, the root of the principle table (the one on
66790 ** page 1) is never added to the freelist.
66791 **
66792 ** This routine will fail with SQLITE_LOCKED if there are any open
66793 ** cursors on the table.
66794 **
66795 ** If AUTOVACUUM is enabled and the page at iTable is not the last
66796 ** root page in the database file, then the last root page
66797 ** in the database file is moved into the slot formerly occupied by
66798 ** iTable and that last slot formerly occupied by the last root page
66799 ** is added to the freelist instead of iTable. In this say, all
66800 ** root pages are kept at the beginning of the database file, which
66801 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
66802 ** page number that used to be the last root page in the file before
66803 ** the move. If no page gets moved, *piMoved is set to 0.
66804 ** The last root page is recorded in meta[3] and the value of
66805 ** meta[3] is updated by this procedure.
66806 */
66807 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
66808  int rc;
66809  MemPage *pPage = 0;
66810  BtShared *pBt = p->pBt;
66811 
66812  assert( sqlite3BtreeHoldsMutex(p) );
66813  assert( p->inTrans==TRANS_WRITE );
66814 
66815  /* It is illegal to drop a table if any cursors are open on the
66816  ** database. This is because in auto-vacuum mode the backend may
66817  ** need to move another root-page to fill a gap left by the deleted
66818  ** root page. If an open cursor was using this page a problem would
66819  ** occur.
66820  **
66821  ** This error is caught long before control reaches this point.
66822  */
66823  if( NEVER(pBt->pCursor) ){
66824  sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
66825  return SQLITE_LOCKED_SHAREDCACHE;
66826  }
66827 
66828  /*
66829  ** It is illegal to drop the sqlite_master table on page 1. But again,
66830  ** this error is caught long before reaching this point.
66831  */
66832  if( NEVER(iTable<2) ){
66833  return SQLITE_CORRUPT_BKPT;
66834  }
66835 
66836  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
66837  if( rc ) return rc;
66838  rc = sqlite3BtreeClearTable(p, iTable, 0);
66839  if( rc ){
66840  releasePage(pPage);
66841  return rc;
66842  }
66843 
66844  *piMoved = 0;
66845 
66846 #ifdef SQLITE_OMIT_AUTOVACUUM
66847  freePage(pPage, &rc);
66848  releasePage(pPage);
66849 #else
66850  if( pBt->autoVacuum ){
66851  Pgno maxRootPgno;
66852  sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
66853 
66854  if( iTable==maxRootPgno ){
66855  /* If the table being dropped is the table with the largest root-page
66856  ** number in the database, put the root page on the free list.
66857  */
66858  freePage(pPage, &rc);
66859  releasePage(pPage);
66860  if( rc!=SQLITE_OK ){
66861  return rc;
66862  }
66863  }else{
66864  /* The table being dropped does not have the largest root-page
66865  ** number in the database. So move the page that does into the
66866  ** gap left by the deleted root-page.
66867  */
66868  MemPage *pMove;
66869  releasePage(pPage);
66870  rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66871  if( rc!=SQLITE_OK ){
66872  return rc;
66873  }
66874  rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
66875  releasePage(pMove);
66876  if( rc!=SQLITE_OK ){
66877  return rc;
66878  }
66879  pMove = 0;
66880  rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66881  freePage(pMove, &rc);
66882  releasePage(pMove);
66883  if( rc!=SQLITE_OK ){
66884  return rc;
66885  }
66886  *piMoved = maxRootPgno;
66887  }
66888 
66889  /* Set the new 'max-root-page' value in the database header. This
66890  ** is the old value less one, less one more if that happens to
66891  ** be a root-page number, less one again if that is the
66892  ** PENDING_BYTE_PAGE.
66893  */
66894  maxRootPgno--;
66895  while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
66896  || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
66897  maxRootPgno--;
66898  }
66899  assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
66900 
66901  rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
66902  }else{
66903  freePage(pPage, &rc);
66904  releasePage(pPage);
66905  }
66906 #endif
66907  return rc;
66908 }
66909 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
66910  int rc;
66911  sqlite3BtreeEnter(p);
66912  rc = btreeDropTable(p, iTable, piMoved);
66913  sqlite3BtreeLeave(p);
66914  return rc;
66915 }
66916 
66917 
66918 /*
66919 ** This function may only be called if the b-tree connection already
66920 ** has a read or write transaction open on the database.
66921 **
66922 ** Read the meta-information out of a database file. Meta[0]
66923 ** is the number of free pages currently in the database. Meta[1]
66924 ** through meta[15] are available for use by higher layers. Meta[0]
66925 ** is read-only, the others are read/write.
66926 **
66927 ** The schema layer numbers meta values differently. At the schema
66928 ** layer (and the SetCookie and ReadCookie opcodes) the number of
66929 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
66930 **
66931 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
66932 ** of reading the value out of the header, it instead loads the "DataVersion"
66933 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
66934 ** database file. It is a number computed by the pager. But its access
66935 ** pattern is the same as header meta values, and so it is convenient to
66936 ** read it from this routine.
66937 */
66938 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
66939  BtShared *pBt = p->pBt;
66940 
66941  sqlite3BtreeEnter(p);
66942  assert( p->inTrans>TRANS_NONE );
66943  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
66944  assert( pBt->pPage1 );
66945  assert( idx>=0 && idx<=15 );
66946 
66947  if( idx==BTREE_DATA_VERSION ){
66948  *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
66949  }else{
66950  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
66951  }
66952 
66953  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
66954  ** database, mark the database as read-only. */
66955 #ifdef SQLITE_OMIT_AUTOVACUUM
66956  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
66957  pBt->btsFlags |= BTS_READ_ONLY;
66958  }
66959 #endif
66960 
66961  sqlite3BtreeLeave(p);
66962 }
66963 
66964 /*
66965 ** Write meta-information back into the database. Meta[0] is
66966 ** read-only and may not be written.
66967 */
66968 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
66969  BtShared *pBt = p->pBt;
66970  unsigned char *pP1;
66971  int rc;
66972  assert( idx>=1 && idx<=15 );
66973  sqlite3BtreeEnter(p);
66974  assert( p->inTrans==TRANS_WRITE );
66975  assert( pBt->pPage1!=0 );
66976  pP1 = pBt->pPage1->aData;
66977  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
66978  if( rc==SQLITE_OK ){
66979  put4byte(&pP1[36 + idx*4], iMeta);
66980 #ifndef SQLITE_OMIT_AUTOVACUUM
66981  if( idx==BTREE_INCR_VACUUM ){
66982  assert( pBt->autoVacuum || iMeta==0 );
66983  assert( iMeta==0 || iMeta==1 );
66984  pBt->incrVacuum = (u8)iMeta;
66985  }
66986 #endif
66987  }
66988  sqlite3BtreeLeave(p);
66989  return rc;
66990 }
66991 
66992 #ifndef SQLITE_OMIT_BTREECOUNT
66993 /*
66994 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
66995 ** number of entries in the b-tree and write the result to *pnEntry.
66996 **
66997 ** SQLITE_OK is returned if the operation is successfully executed.
66998 ** Otherwise, if an error is encountered (i.e. an IO error or database
66999 ** corruption) an SQLite error code is returned.
67000 */
67001 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
67002  i64 nEntry = 0; /* Value to return in *pnEntry */
67003  int rc; /* Return code */
67004 
67005  if( pCur->pgnoRoot==0 ){
67006  *pnEntry = 0;
67007  return SQLITE_OK;
67008  }
67009  rc = moveToRoot(pCur);
67010 
67011  /* Unless an error occurs, the following loop runs one iteration for each
67012  ** page in the B-Tree structure (not including overflow pages).
67013  */
67014  while( rc==SQLITE_OK ){
67015  int iIdx; /* Index of child node in parent */
67016  MemPage *pPage; /* Current page of the b-tree */
67017 
67018  /* If this is a leaf page or the tree is not an int-key tree, then
67019  ** this page contains countable entries. Increment the entry counter
67020  ** accordingly.
67021  */
67022  pPage = pCur->apPage[pCur->iPage];
67023  if( pPage->leaf || !pPage->intKey ){
67024  nEntry += pPage->nCell;
67025  }
67026 
67027  /* pPage is a leaf node. This loop navigates the cursor so that it
67028  ** points to the first interior cell that it points to the parent of
67029  ** the next page in the tree that has not yet been visited. The
67030  ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
67031  ** of the page, or to the number of cells in the page if the next page
67032  ** to visit is the right-child of its parent.
67033  **
67034  ** If all pages in the tree have been visited, return SQLITE_OK to the
67035  ** caller.
67036  */
67037  if( pPage->leaf ){
67038  do {
67039  if( pCur->iPage==0 ){
67040  /* All pages of the b-tree have been visited. Return successfully. */
67041  *pnEntry = nEntry;
67042  return moveToRoot(pCur);
67043  }
67044  moveToParent(pCur);
67045  }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
67046 
67047  pCur->aiIdx[pCur->iPage]++;
67048  pPage = pCur->apPage[pCur->iPage];
67049  }
67050 
67051  /* Descend to the child node of the cell that the cursor currently
67052  ** points at. This is the right-child if (iIdx==pPage->nCell).
67053  */
67054  iIdx = pCur->aiIdx[pCur->iPage];
67055  if( iIdx==pPage->nCell ){
67056  rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
67057  }else{
67058  rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
67059  }
67060  }
67061 
67062  /* An error has occurred. Return an error code. */
67063  return rc;
67064 }
67065 #endif
67066 
67067 /*
67068 ** Return the pager associated with a BTree. This routine is used for
67069 ** testing and debugging only.
67070 */
67071 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
67072  return p->pBt->pPager;
67073 }
67074 
67075 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67076 /*
67077 ** Append a message to the error message string.
67078 */
67079 static void checkAppendMsg(
67080  IntegrityCk *pCheck,
67081  const char *zFormat,
67082  ...
67083 ){
67084  va_list ap;
67085  if( !pCheck->mxErr ) return;
67086  pCheck->mxErr--;
67087  pCheck->nErr++;
67088  va_start(ap, zFormat);
67089  if( pCheck->errMsg.nChar ){
67090  sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
67091  }
67092  if( pCheck->zPfx ){
67093  sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
67094  }
67095  sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
67096  va_end(ap);
67097  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
67098  pCheck->mallocFailed = 1;
67099  }
67100 }
67101 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67102 
67103 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67104 
67105 /*
67106 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
67107 ** corresponds to page iPg is already set.
67108 */
67109 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
67110  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
67111  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
67112 }
67113 
67114 /*
67115 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
67116 */
67117 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
67118  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
67119  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
67120 }
67121 
67122 
67123 /*
67124 ** Add 1 to the reference count for page iPage. If this is the second
67125 ** reference to the page, add an error message to pCheck->zErrMsg.
67126 ** Return 1 if there are 2 or more references to the page and 0 if
67127 ** if this is the first reference to the page.
67128 **
67129 ** Also check that the page number is in bounds.
67130 */
67131 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
67132  if( iPage==0 ) return 1;
67133  if( iPage>pCheck->nPage ){
67134  checkAppendMsg(pCheck, "invalid page number %d", iPage);
67135  return 1;
67136  }
67137  if( getPageReferenced(pCheck, iPage) ){
67138  checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
67139  return 1;
67140  }
67141  setPageReferenced(pCheck, iPage);
67142  return 0;
67143 }
67144 
67145 #ifndef SQLITE_OMIT_AUTOVACUUM
67146 /*
67147 ** Check that the entry in the pointer-map for page iChild maps to
67148 ** page iParent, pointer type ptrType. If not, append an error message
67149 ** to pCheck.
67150 */
67151 static void checkPtrmap(
67152  IntegrityCk *pCheck, /* Integrity check context */
67153  Pgno iChild, /* Child page number */
67154  u8 eType, /* Expected pointer map type */
67155  Pgno iParent /* Expected pointer map parent page number */
67156 ){
67157  int rc;
67158  u8 ePtrmapType;
67159  Pgno iPtrmapParent;
67160 
67161  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
67162  if( rc!=SQLITE_OK ){
67163  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
67164  checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
67165  return;
67166  }
67167 
67168  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
67169  checkAppendMsg(pCheck,
67170  "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
67171  iChild, eType, iParent, ePtrmapType, iPtrmapParent);
67172  }
67173 }
67174 #endif
67175 
67176 /*
67177 ** Check the integrity of the freelist or of an overflow page list.
67178 ** Verify that the number of pages on the list is N.
67179 */
67180 static void checkList(
67181  IntegrityCk *pCheck, /* Integrity checking context */
67182  int isFreeList, /* True for a freelist. False for overflow page list */
67183  int iPage, /* Page number for first page in the list */
67184  int N /* Expected number of pages in the list */
67185 ){
67186  int i;
67187  int expected = N;
67188  int iFirst = iPage;
67189  while( N-- > 0 && pCheck->mxErr ){
67190  DbPage *pOvflPage;
67191  unsigned char *pOvflData;
67192  if( iPage<1 ){
67193  checkAppendMsg(pCheck,
67194  "%d of %d pages missing from overflow list starting at %d",
67195  N+1, expected, iFirst);
67196  break;
67197  }
67198  if( checkRef(pCheck, iPage) ) break;
67199  if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
67200  checkAppendMsg(pCheck, "failed to get page %d", iPage);
67201  break;
67202  }
67203  pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
67204  if( isFreeList ){
67205  int n = get4byte(&pOvflData[4]);
67206 #ifndef SQLITE_OMIT_AUTOVACUUM
67207  if( pCheck->pBt->autoVacuum ){
67208  checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
67209  }
67210 #endif
67211  if( n>(int)pCheck->pBt->usableSize/4-2 ){
67212  checkAppendMsg(pCheck,
67213  "freelist leaf count too big on page %d", iPage);
67214  N--;
67215  }else{
67216  for(i=0; i<n; i++){
67217  Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
67218 #ifndef SQLITE_OMIT_AUTOVACUUM
67219  if( pCheck->pBt->autoVacuum ){
67220  checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
67221  }
67222 #endif
67223  checkRef(pCheck, iFreePage);
67224  }
67225  N -= n;
67226  }
67227  }
67228 #ifndef SQLITE_OMIT_AUTOVACUUM
67229  else{
67230  /* If this database supports auto-vacuum and iPage is not the last
67231  ** page in this overflow list, check that the pointer-map entry for
67232  ** the following page matches iPage.
67233  */
67234  if( pCheck->pBt->autoVacuum && N>0 ){
67235  i = get4byte(pOvflData);
67236  checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
67237  }
67238  }
67239 #endif
67240  iPage = get4byte(pOvflData);
67241  sqlite3PagerUnref(pOvflPage);
67242 
67243  if( isFreeList && N<(iPage!=0) ){
67244  checkAppendMsg(pCheck, "free-page count in header is too small");
67245  }
67246  }
67247 }
67248 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67249 
67250 /*
67251 ** An implementation of a min-heap.
67252 **
67253 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
67254 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
67255 ** and aHeap[N*2+1].
67256 **
67257 ** The heap property is this: Every node is less than or equal to both
67258 ** of its daughter nodes. A consequence of the heap property is that the
67259 ** root node aHeap[1] is always the minimum value currently in the heap.
67260 **
67261 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
67262 ** the heap, preserving the heap property. The btreeHeapPull() routine
67263 ** removes the root element from the heap (the minimum value in the heap)
67264 ** and then moves other nodes around as necessary to preserve the heap
67265 ** property.
67266 **
67267 ** This heap is used for cell overlap and coverage testing. Each u32
67268 ** entry represents the span of a cell or freeblock on a btree page.
67269 ** The upper 16 bits are the index of the first byte of a range and the
67270 ** lower 16 bits are the index of the last byte of that range.
67271 */
67272 static void btreeHeapInsert(u32 *aHeap, u32 x){
67273  u32 j, i = ++aHeap[0];
67274  aHeap[i] = x;
67275  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
67276  x = aHeap[j];
67277  aHeap[j] = aHeap[i];
67278  aHeap[i] = x;
67279  i = j;
67280  }
67281 }
67282 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
67283  u32 j, i, x;
67284  if( (x = aHeap[0])==0 ) return 0;
67285  *pOut = aHeap[1];
67286  aHeap[1] = aHeap[x];
67287  aHeap[x] = 0xffffffff;
67288  aHeap[0]--;
67289  i = 1;
67290  while( (j = i*2)<=aHeap[0] ){
67291  if( aHeap[j]>aHeap[j+1] ) j++;
67292  if( aHeap[i]<aHeap[j] ) break;
67293  x = aHeap[i];
67294  aHeap[i] = aHeap[j];
67295  aHeap[j] = x;
67296  i = j;
67297  }
67298  return 1;
67299 }
67300 
67301 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67302 /*
67303 ** Do various sanity checks on a single page of a tree. Return
67304 ** the tree depth. Root pages return 0. Parents of root pages
67305 ** return 1, and so forth.
67306 **
67307 ** These checks are done:
67308 **
67309 ** 1. Make sure that cells and freeblocks do not overlap
67310 ** but combine to completely cover the page.
67311 ** 2. Make sure integer cell keys are in order.
67312 ** 3. Check the integrity of overflow pages.
67313 ** 4. Recursively call checkTreePage on all children.
67314 ** 5. Verify that the depth of all children is the same.
67315 */
67316 static int checkTreePage(
67317  IntegrityCk *pCheck, /* Context for the sanity check */
67318  int iPage, /* Page number of the page to check */
67319  i64 *piMinKey, /* Write minimum integer primary key here */
67320  i64 maxKey /* Error if integer primary key greater than this */
67321 ){
67322  MemPage *pPage = 0; /* The page being analyzed */
67323  int i; /* Loop counter */
67324  int rc; /* Result code from subroutine call */
67325  int depth = -1, d2; /* Depth of a subtree */
67326  int pgno; /* Page number */
67327  int nFrag; /* Number of fragmented bytes on the page */
67328  int hdr; /* Offset to the page header */
67329  int cellStart; /* Offset to the start of the cell pointer array */
67330  int nCell; /* Number of cells */
67331  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
67332  int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
67333  ** False if IPK must be strictly less than maxKey */
67334  u8 *data; /* Page content */
67335  u8 *pCell; /* Cell content */
67336  u8 *pCellIdx; /* Next element of the cell pointer array */
67337  BtShared *pBt; /* The BtShared object that owns pPage */
67338  u32 pc; /* Address of a cell */
67339  u32 usableSize; /* Usable size of the page */
67340  u32 contentOffset; /* Offset to the start of the cell content area */
67341  u32 *heap = 0; /* Min-heap used for checking cell coverage */
67342  u32 x, prev = 0; /* Next and previous entry on the min-heap */
67343  const char *saved_zPfx = pCheck->zPfx;
67344  int saved_v1 = pCheck->v1;
67345  int saved_v2 = pCheck->v2;
67346  u8 savedIsInit = 0;
67347 
67348  /* Check that the page exists
67349  */
67350  pBt = pCheck->pBt;
67351  usableSize = pBt->usableSize;
67352  if( iPage==0 ) return 0;
67353  if( checkRef(pCheck, iPage) ) return 0;
67354  pCheck->zPfx = "Page %d: ";
67355  pCheck->v1 = iPage;
67356  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
67357  checkAppendMsg(pCheck,
67358  "unable to get the page. error code=%d", rc);
67359  goto end_of_check;
67360  }
67361 
67362  /* Clear MemPage.isInit to make sure the corruption detection code in
67363  ** btreeInitPage() is executed. */
67364  savedIsInit = pPage->isInit;
67365  pPage->isInit = 0;
67366  if( (rc = btreeInitPage(pPage))!=0 ){
67367  assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
67368  checkAppendMsg(pCheck,
67369  "btreeInitPage() returns error code %d", rc);
67370  goto end_of_check;
67371  }
67372  data = pPage->aData;
67373  hdr = pPage->hdrOffset;
67374 
67375  /* Set up for cell analysis */
67376  pCheck->zPfx = "On tree page %d cell %d: ";
67377  contentOffset = get2byteNotZero(&data[hdr+5]);
67378  assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
67379 
67380  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
67381  ** number of cells on the page. */
67382  nCell = get2byte(&data[hdr+3]);
67383  assert( pPage->nCell==nCell );
67384 
67385  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
67386  ** immediately follows the b-tree page header. */
67387  cellStart = hdr + 12 - 4*pPage->leaf;
67388  assert( pPage->aCellIdx==&data[cellStart] );
67389  pCellIdx = &data[cellStart + 2*(nCell-1)];
67390 
67391  if( !pPage->leaf ){
67392  /* Analyze the right-child page of internal pages */
67393  pgno = get4byte(&data[hdr+8]);
67394 #ifndef SQLITE_OMIT_AUTOVACUUM
67395  if( pBt->autoVacuum ){
67396  pCheck->zPfx = "On page %d at right child: ";
67397  checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67398  }
67399 #endif
67400  depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67401  keyCanBeEqual = 0;
67402  }else{
67403  /* For leaf pages, the coverage check will occur in the same loop
67404  ** as the other cell checks, so initialize the heap. */
67405  heap = pCheck->heap;
67406  heap[0] = 0;
67407  }
67408 
67409  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
67410  ** integer offsets to the cell contents. */
67411  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
67412  CellInfo info;
67413 
67414  /* Check cell size */
67415  pCheck->v2 = i;
67416  assert( pCellIdx==&data[cellStart + i*2] );
67417  pc = get2byteAligned(pCellIdx);
67418  pCellIdx -= 2;
67419  if( pc<contentOffset || pc>usableSize-4 ){
67420  checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
67421  pc, contentOffset, usableSize-4);
67422  doCoverageCheck = 0;
67423  continue;
67424  }
67425  pCell = &data[pc];
67426  pPage->xParseCell(pPage, pCell, &info);
67427  if( pc+info.nSize>usableSize ){
67428  checkAppendMsg(pCheck, "Extends off end of page");
67429  doCoverageCheck = 0;
67430  continue;
67431  }
67432 
67433  /* Check for integer primary key out of range */
67434  if( pPage->intKey ){
67435  if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
67436  checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
67437  }
67438  maxKey = info.nKey;
67439  }
67440 
67441  /* Check the content overflow list */
67442  if( info.nPayload>info.nLocal ){
67443  int nPage; /* Number of pages on the overflow chain */
67444  Pgno pgnoOvfl; /* First page of the overflow chain */
67445  assert( pc + info.nSize - 4 <= usableSize );
67446  nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
67447  pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
67448 #ifndef SQLITE_OMIT_AUTOVACUUM
67449  if( pBt->autoVacuum ){
67450  checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
67451  }
67452 #endif
67453  checkList(pCheck, 0, pgnoOvfl, nPage);
67454  }
67455 
67456  if( !pPage->leaf ){
67457  /* Check sanity of left child page for internal pages */
67458  pgno = get4byte(pCell);
67459 #ifndef SQLITE_OMIT_AUTOVACUUM
67460  if( pBt->autoVacuum ){
67461  checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67462  }
67463 #endif
67464  d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67465  keyCanBeEqual = 0;
67466  if( d2!=depth ){
67467  checkAppendMsg(pCheck, "Child page depth differs");
67468  depth = d2;
67469  }
67470  }else{
67471  /* Populate the coverage-checking heap for leaf pages */
67472  btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
67473  }
67474  }
67475  *piMinKey = maxKey;
67476 
67477  /* Check for complete coverage of the page
67478  */
67479  pCheck->zPfx = 0;
67480  if( doCoverageCheck && pCheck->mxErr>0 ){
67481  /* For leaf pages, the min-heap has already been initialized and the
67482  ** cells have already been inserted. But for internal pages, that has
67483  ** not yet been done, so do it now */
67484  if( !pPage->leaf ){
67485  heap = pCheck->heap;
67486  heap[0] = 0;
67487  for(i=nCell-1; i>=0; i--){
67488  u32 size;
67489  pc = get2byteAligned(&data[cellStart+i*2]);
67490  size = pPage->xCellSize(pPage, &data[pc]);
67491  btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
67492  }
67493  }
67494  /* Add the freeblocks to the min-heap
67495  **
67496  ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
67497  ** is the offset of the first freeblock, or zero if there are no
67498  ** freeblocks on the page.
67499  */
67500  i = get2byte(&data[hdr+1]);
67501  while( i>0 ){
67502  int size, j;
67503  assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
67504  size = get2byte(&data[i+2]);
67505  assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
67506  btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
67507  /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
67508  ** big-endian integer which is the offset in the b-tree page of the next
67509  ** freeblock in the chain, or zero if the freeblock is the last on the
67510  ** chain. */
67511  j = get2byte(&data[i]);
67512  /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
67513  ** increasing offset. */
67514  assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
67515  assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
67516  i = j;
67517  }
67518  /* Analyze the min-heap looking for overlap between cells and/or
67519  ** freeblocks, and counting the number of untracked bytes in nFrag.
67520  **
67521  ** Each min-heap entry is of the form: (start_address<<16)|end_address.
67522  ** There is an implied first entry the covers the page header, the cell
67523  ** pointer index, and the gap between the cell pointer index and the start
67524  ** of cell content.
67525  **
67526  ** The loop below pulls entries from the min-heap in order and compares
67527  ** the start_address against the previous end_address. If there is an
67528  ** overlap, that means bytes are used multiple times. If there is a gap,
67529  ** that gap is added to the fragmentation count.
67530  */
67531  nFrag = 0;
67532  prev = contentOffset - 1; /* Implied first min-heap entry */
67533  while( btreeHeapPull(heap,&x) ){
67534  if( (prev&0xffff)>=(x>>16) ){
67535  checkAppendMsg(pCheck,
67536  "Multiple uses for byte %u of page %d", x>>16, iPage);
67537  break;
67538  }else{
67539  nFrag += (x>>16) - (prev&0xffff) - 1;
67540  prev = x;
67541  }
67542  }
67543  nFrag += usableSize - (prev&0xffff) - 1;
67544  /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
67545  ** is stored in the fifth field of the b-tree page header.
67546  ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
67547  ** number of fragmented free bytes within the cell content area.
67548  */
67549  if( heap[0]==0 && nFrag!=data[hdr+7] ){
67550  checkAppendMsg(pCheck,
67551  "Fragmentation of %d bytes reported as %d on page %d",
67552  nFrag, data[hdr+7], iPage);
67553  }
67554  }
67555 
67556 end_of_check:
67557  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
67558  releasePage(pPage);
67559  pCheck->zPfx = saved_zPfx;
67560  pCheck->v1 = saved_v1;
67561  pCheck->v2 = saved_v2;
67562  return depth+1;
67563 }
67564 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67565 
67566 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67567 /*
67568 ** This routine does a complete check of the given BTree file. aRoot[] is
67569 ** an array of pages numbers were each page number is the root page of
67570 ** a table. nRoot is the number of entries in aRoot.
67571 **
67572 ** A read-only or read-write transaction must be opened before calling
67573 ** this function.
67574 **
67575 ** Write the number of error seen in *pnErr. Except for some memory
67576 ** allocation errors, an error message held in memory obtained from
67577 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
67578 ** returned. If a memory allocation error occurs, NULL is returned.
67579 */
67580 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
67581  Btree *p, /* The btree to be checked */
67582  int *aRoot, /* An array of root pages numbers for individual trees */
67583  int nRoot, /* Number of entries in aRoot[] */
67584  int mxErr, /* Stop reporting errors after this many */
67585  int *pnErr /* Write number of errors seen to this variable */
67586 ){
67587  Pgno i;
67588  IntegrityCk sCheck;
67589  BtShared *pBt = p->pBt;
67590  int savedDbFlags = pBt->db->flags;
67591  char zErr[100];
67592  VVA_ONLY( int nRef );
67593 
67594  sqlite3BtreeEnter(p);
67595  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
67596  VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
67597  assert( nRef>=0 );
67598  sCheck.pBt = pBt;
67599  sCheck.pPager = pBt->pPager;
67600  sCheck.nPage = btreePagecount(sCheck.pBt);
67601  sCheck.mxErr = mxErr;
67602  sCheck.nErr = 0;
67603  sCheck.mallocFailed = 0;
67604  sCheck.zPfx = 0;
67605  sCheck.v1 = 0;
67606  sCheck.v2 = 0;
67607  sCheck.aPgRef = 0;
67608  sCheck.heap = 0;
67609  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
67610  sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
67611  if( sCheck.nPage==0 ){
67612  goto integrity_ck_cleanup;
67613  }
67614 
67615  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
67616  if( !sCheck.aPgRef ){
67617  sCheck.mallocFailed = 1;
67618  goto integrity_ck_cleanup;
67619  }
67620  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
67621  if( sCheck.heap==0 ){
67622  sCheck.mallocFailed = 1;
67623  goto integrity_ck_cleanup;
67624  }
67625 
67626  i = PENDING_BYTE_PAGE(pBt);
67627  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
67628 
67629  /* Check the integrity of the freelist
67630  */
67631  sCheck.zPfx = "Main freelist: ";
67632  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
67633  get4byte(&pBt->pPage1->aData[36]));
67634  sCheck.zPfx = 0;
67635 
67636  /* Check all the tables.
67637  */
67638  testcase( pBt->db->flags & SQLITE_CellSizeCk );
67639  pBt->db->flags &= ~SQLITE_CellSizeCk;
67640  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
67641  i64 notUsed;
67642  if( aRoot[i]==0 ) continue;
67643 #ifndef SQLITE_OMIT_AUTOVACUUM
67644  if( pBt->autoVacuum && aRoot[i]>1 ){
67645  checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
67646  }
67647 #endif
67648  checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
67649  }
67650  pBt->db->flags = savedDbFlags;
67651 
67652  /* Make sure every page in the file is referenced
67653  */
67654  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
67655 #ifdef SQLITE_OMIT_AUTOVACUUM
67656  if( getPageReferenced(&sCheck, i)==0 ){
67657  checkAppendMsg(&sCheck, "Page %d is never used", i);
67658  }
67659 #else
67660  /* If the database supports auto-vacuum, make sure no tables contain
67661  ** references to pointer-map pages.
67662  */
67663  if( getPageReferenced(&sCheck, i)==0 &&
67664  (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
67665  checkAppendMsg(&sCheck, "Page %d is never used", i);
67666  }
67667  if( getPageReferenced(&sCheck, i)!=0 &&
67668  (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
67669  checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
67670  }
67671 #endif
67672  }
67673 
67674  /* Clean up and report errors.
67675  */
67676 integrity_ck_cleanup:
67677  sqlite3PageFree(sCheck.heap);
67678  sqlite3_free(sCheck.aPgRef);
67679  if( sCheck.mallocFailed ){
67680  sqlite3StrAccumReset(&sCheck.errMsg);
67681  sCheck.nErr++;
67682  }
67683  *pnErr = sCheck.nErr;
67684  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
67685  /* Make sure this analysis did not leave any unref() pages. */
67686  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
67687  sqlite3BtreeLeave(p);
67688  return sqlite3StrAccumFinish(&sCheck.errMsg);
67689 }
67690 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67691 
67692 /*
67693 ** Return the full pathname of the underlying database file. Return
67694 ** an empty string if the database is in-memory or a TEMP database.
67695 **
67696 ** The pager filename is invariant as long as the pager is
67697 ** open so it is safe to access without the BtShared mutex.
67698 */
67699 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
67700  assert( p->pBt->pPager!=0 );
67701  return sqlite3PagerFilename(p->pBt->pPager, 1);
67702 }
67703 
67704 /*
67705 ** Return the pathname of the journal file for this database. The return
67706 ** value of this routine is the same regardless of whether the journal file
67707 ** has been created or not.
67708 **
67709 ** The pager journal filename is invariant as long as the pager is
67710 ** open so it is safe to access without the BtShared mutex.
67711 */
67712 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
67713  assert( p->pBt->pPager!=0 );
67714  return sqlite3PagerJournalname(p->pBt->pPager);
67715 }
67716 
67717 /*
67718 ** Return non-zero if a transaction is active.
67719 */
67720 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
67721  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
67722  return (p && (p->inTrans==TRANS_WRITE));
67723 }
67724 
67725 #ifndef SQLITE_OMIT_WAL
67726 /*
67727 ** Run a checkpoint on the Btree passed as the first argument.
67728 **
67729 ** Return SQLITE_LOCKED if this or any other connection has an open
67730 ** transaction on the shared-cache the argument Btree is connected to.
67731 **
67732 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
67733 */
67734 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
67735  int rc = SQLITE_OK;
67736  if( p ){
67737  BtShared *pBt = p->pBt;
67738  sqlite3BtreeEnter(p);
67739  if( pBt->inTransaction!=TRANS_NONE ){
67740  rc = SQLITE_LOCKED;
67741  }else{
67742  rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
67743  }
67744  sqlite3BtreeLeave(p);
67745  }
67746  return rc;
67747 }
67748 #endif
67749 
67750 /*
67751 ** Return non-zero if a read (or write) transaction is active.
67752 */
67753 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
67754  assert( p );
67755  assert( sqlite3_mutex_held(p->db->mutex) );
67756  return p->inTrans!=TRANS_NONE;
67757 }
67758 
67759 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
67760  assert( p );
67761  assert( sqlite3_mutex_held(p->db->mutex) );
67762  return p->nBackup!=0;
67763 }
67764 
67765 /*
67766 ** This function returns a pointer to a blob of memory associated with
67767 ** a single shared-btree. The memory is used by client code for its own
67768 ** purposes (for example, to store a high-level schema associated with
67769 ** the shared-btree). The btree layer manages reference counting issues.
67770 **
67771 ** The first time this is called on a shared-btree, nBytes bytes of memory
67772 ** are allocated, zeroed, and returned to the caller. For each subsequent
67773 ** call the nBytes parameter is ignored and a pointer to the same blob
67774 ** of memory returned.
67775 **
67776 ** If the nBytes parameter is 0 and the blob of memory has not yet been
67777 ** allocated, a null pointer is returned. If the blob has already been
67778 ** allocated, it is returned as normal.
67779 **
67780 ** Just before the shared-btree is closed, the function passed as the
67781 ** xFree argument when the memory allocation was made is invoked on the
67782 ** blob of allocated memory. The xFree function should not call sqlite3_free()
67783 ** on the memory, the btree layer does that.
67784 */
67785 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
67786  BtShared *pBt = p->pBt;
67787  sqlite3BtreeEnter(p);
67788  if( !pBt->pSchema && nBytes ){
67789  pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
67790  pBt->xFreeSchema = xFree;
67791  }
67792  sqlite3BtreeLeave(p);
67793  return pBt->pSchema;
67794 }
67795 
67796 /*
67797 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
67798 ** btree as the argument handle holds an exclusive lock on the
67799 ** sqlite_master table. Otherwise SQLITE_OK.
67800 */
67801 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
67802  int rc;
67803  assert( sqlite3_mutex_held(p->db->mutex) );
67804  sqlite3BtreeEnter(p);
67805  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
67806  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
67807  sqlite3BtreeLeave(p);
67808  return rc;
67809 }
67810 
67811 
67812 #ifndef SQLITE_OMIT_SHARED_CACHE
67813 /*
67814 ** Obtain a lock on the table whose root page is iTab. The
67815 ** lock is a write lock if isWritelock is true or a read lock
67816 ** if it is false.
67817 */
67818 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
67819  int rc = SQLITE_OK;
67820  assert( p->inTrans!=TRANS_NONE );
67821  if( p->sharable ){
67822  u8 lockType = READ_LOCK + isWriteLock;
67823  assert( READ_LOCK+1==WRITE_LOCK );
67824  assert( isWriteLock==0 || isWriteLock==1 );
67825 
67826  sqlite3BtreeEnter(p);
67827  rc = querySharedCacheTableLock(p, iTab, lockType);
67828  if( rc==SQLITE_OK ){
67829  rc = setSharedCacheTableLock(p, iTab, lockType);
67830  }
67831  sqlite3BtreeLeave(p);
67832  }
67833  return rc;
67834 }
67835 #endif
67836 
67837 #ifndef SQLITE_OMIT_INCRBLOB
67838 /*
67839 ** Argument pCsr must be a cursor opened for writing on an
67840 ** INTKEY table currently pointing at a valid table entry.
67841 ** This function modifies the data stored as part of that entry.
67842 **
67843 ** Only the data content may only be modified, it is not possible to
67844 ** change the length of the data stored. If this function is called with
67845 ** parameters that attempt to write past the end of the existing data,
67846 ** no modifications are made and SQLITE_CORRUPT is returned.
67847 */
67848 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
67849  int rc;
67850  assert( cursorOwnsBtShared(pCsr) );
67851  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
67852  assert( pCsr->curFlags & BTCF_Incrblob );
67853 
67854  rc = restoreCursorPosition(pCsr);
67855  if( rc!=SQLITE_OK ){
67856  return rc;
67857  }
67858  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
67859  if( pCsr->eState!=CURSOR_VALID ){
67860  return SQLITE_ABORT;
67861  }
67862 
67863  /* Save the positions of all other cursors open on this table. This is
67864  ** required in case any of them are holding references to an xFetch
67865  ** version of the b-tree page modified by the accessPayload call below.
67866  **
67867  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
67868  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
67869  ** saveAllCursors can only return SQLITE_OK.
67870  */
67871  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
67872  assert( rc==SQLITE_OK );
67873 
67874  /* Check some assumptions:
67875  ** (a) the cursor is open for writing,
67876  ** (b) there is a read/write transaction open,
67877  ** (c) the connection holds a write-lock on the table (if required),
67878  ** (d) there are no conflicting read-locks, and
67879  ** (e) the cursor points at a valid row of an intKey table.
67880  */
67881  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
67882  return SQLITE_READONLY;
67883  }
67884  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
67885  && pCsr->pBt->inTransaction==TRANS_WRITE );
67886  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
67887  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
67888  assert( pCsr->apPage[pCsr->iPage]->intKey );
67889 
67890  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
67891 }
67892 
67893 /*
67894 ** Mark this cursor as an incremental blob cursor.
67895 */
67896 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
67897  pCur->curFlags |= BTCF_Incrblob;
67898  pCur->pBtree->hasIncrblobCur = 1;
67899 }
67900 #endif
67901 
67902 /*
67903 ** Set both the "read version" (single byte at byte offset 18) and
67904 ** "write version" (single byte at byte offset 19) fields in the database
67905 ** header to iVersion.
67906 */
67907 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
67908  BtShared *pBt = pBtree->pBt;
67909  int rc; /* Return code */
67910 
67911  assert( iVersion==1 || iVersion==2 );
67912 
67913  /* If setting the version fields to 1, do not automatically open the
67914  ** WAL connection, even if the version fields are currently set to 2.
67915  */
67916  pBt->btsFlags &= ~BTS_NO_WAL;
67917  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
67918 
67919  rc = sqlite3BtreeBeginTrans(pBtree, 0);
67920  if( rc==SQLITE_OK ){
67921  u8 *aData = pBt->pPage1->aData;
67922  if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
67923  rc = sqlite3BtreeBeginTrans(pBtree, 2);
67924  if( rc==SQLITE_OK ){
67925  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
67926  if( rc==SQLITE_OK ){
67927  aData[18] = (u8)iVersion;
67928  aData[19] = (u8)iVersion;
67929  }
67930  }
67931  }
67932  }
67933 
67934  pBt->btsFlags &= ~BTS_NO_WAL;
67935  return rc;
67936 }
67937 
67938 /*
67939 ** Return true if the cursor has a hint specified. This routine is
67940 ** only used from within assert() statements
67941 */
67942 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
67943  return (pCsr->hints & mask)!=0;
67944 }
67945 
67946 /*
67947 ** Return true if the given Btree is read-only.
67948 */
67949 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
67950  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
67951 }
67952 
67953 /*
67954 ** Return the size of the header added to each page by this module.
67955 */
67956 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
67957 
67958 #if !defined(SQLITE_OMIT_SHARED_CACHE)
67959 /*
67960 ** Return true if the Btree passed as the only argument is sharable.
67961 */
67962 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
67963  return p->sharable;
67964 }
67965 
67966 /*
67967 ** Return the number of connections to the BtShared object accessed by
67968 ** the Btree handle passed as the only argument. For private caches
67969 ** this is always 1. For shared caches it may be 1 or greater.
67970 */
67971 SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
67972  testcase( p->sharable );
67973  return p->pBt->nRef;
67974 }
67975 #endif
67976 
67977 /************** End of btree.c ***********************************************/
67978 /************** Begin file backup.c ******************************************/
67979 /*
67980 ** 2009 January 28
67981 **
67982 ** The author disclaims copyright to this source code. In place of
67983 ** a legal notice, here is a blessing:
67984 **
67985 ** May you do good and not evil.
67986 ** May you find forgiveness for yourself and forgive others.
67987 ** May you share freely, never taking more than you give.
67988 **
67989 *************************************************************************
67990 ** This file contains the implementation of the sqlite3_backup_XXX()
67991 ** API functions and the related features.
67992 */
67993 /* #include "sqliteInt.h" */
67994 /* #include "btreeInt.h" */
67995 
67996 /*
67997 ** Structure allocated for each backup operation.
67998 */
68000  sqlite3* pDestDb; /* Destination database handle */
68001  Btree *pDest; /* Destination b-tree file */
68002  u32 iDestSchema; /* Original schema cookie in destination */
68003  int bDestLocked; /* True once a write-transaction is open on pDest */
68004 
68005  Pgno iNext; /* Page number of the next source page to copy */
68006  sqlite3* pSrcDb; /* Source database handle */
68007  Btree *pSrc; /* Source b-tree file */
68008 
68009  int rc; /* Backup process error code */
68010 
68011  /* These two variables are set by every call to backup_step(). They are
68012  ** read by calls to backup_remaining() and backup_pagecount().
68013  */
68014  Pgno nRemaining; /* Number of pages left to copy */
68015  Pgno nPagecount; /* Total number of pages to copy */
68016 
68017  int isAttached; /* True once backup has been registered with pager */
68018  sqlite3_backup *pNext; /* Next backup associated with source pager */
68019 };
68020 
68021 /*
68022 ** THREAD SAFETY NOTES:
68023 **
68024 ** Once it has been created using backup_init(), a single sqlite3_backup
68025 ** structure may be accessed via two groups of thread-safe entry points:
68026 **
68027 ** * Via the sqlite3_backup_XXX() API function backup_step() and
68028 ** backup_finish(). Both these functions obtain the source database
68029 ** handle mutex and the mutex associated with the source BtShared
68030 ** structure, in that order.
68031 **
68032 ** * Via the BackupUpdate() and BackupRestart() functions, which are
68033 ** invoked by the pager layer to report various state changes in
68034 ** the page cache associated with the source database. The mutex
68035 ** associated with the source database BtShared structure will always
68036 ** be held when either of these functions are invoked.
68037 **
68038 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
68039 ** backup_pagecount() are not thread-safe functions. If they are called
68040 ** while some other thread is calling backup_step() or backup_finish(),
68041 ** the values returned may be invalid. There is no way for a call to
68042 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
68043 ** or backup_pagecount().
68044 **
68045 ** Depending on the SQLite configuration, the database handles and/or
68046 ** the Btree objects may have their own mutexes that require locking.
68047 ** Non-sharable Btrees (in-memory databases for example), do not have
68048 ** associated mutexes.
68049 */
68050 
68051 /*
68052 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
68053 ** in connection handle pDb. If such a database cannot be found, return
68054 ** a NULL pointer and write an error message to pErrorDb.
68055 **
68056 ** If the "temp" database is requested, it may need to be opened by this
68057 ** function. If an error occurs while doing so, return 0 and write an
68058 ** error message to pErrorDb.
68059 */
68060 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
68061  int i = sqlite3FindDbName(pDb, zDb);
68062 
68063  if( i==1 ){
68064  Parse sParse;
68065  int rc = 0;
68066  memset(&sParse, 0, sizeof(sParse));
68067  sParse.db = pDb;
68068  if( sqlite3OpenTempDatabase(&sParse) ){
68069  sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
68070  rc = SQLITE_ERROR;
68071  }
68072  sqlite3DbFree(pErrorDb, sParse.zErrMsg);
68073  sqlite3ParserReset(&sParse);
68074  if( rc ){
68075  return 0;
68076  }
68077  }
68078 
68079  if( i<0 ){
68080  sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
68081  return 0;
68082  }
68083 
68084  return pDb->aDb[i].pBt;
68085 }
68086 
68087 /*
68088 ** Attempt to set the page size of the destination to match the page size
68089 ** of the source.
68090 */
68091 static int setDestPgsz(sqlite3_backup *p){
68092  int rc;
68093  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
68094  return rc;
68095 }
68096 
68097 /*
68098 ** Check that there is no open read-transaction on the b-tree passed as the
68099 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
68100 ** is an open read-transaction, return SQLITE_ERROR and leave an error
68101 ** message in database handle db.
68102 */
68103 static int checkReadTransaction(sqlite3 *db, Btree *p){
68104  if( sqlite3BtreeIsInReadTrans(p) ){
68105  sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
68106  return SQLITE_ERROR;
68107  }
68108  return SQLITE_OK;
68109 }
68110 
68111 /*
68112 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
68113 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
68114 ** a pointer to the new sqlite3_backup object.
68115 **
68116 ** If an error occurs, NULL is returned and an error code and error message
68117 ** stored in database handle pDestDb.
68118 */
68119 SQLITE_API sqlite3_backup *sqlite3_backup_init(
68120  sqlite3* pDestDb, /* Database to write to */
68121  const char *zDestDb, /* Name of database within pDestDb */
68122  sqlite3* pSrcDb, /* Database connection to read from */
68123  const char *zSrcDb /* Name of database within pSrcDb */
68124 ){
68125  sqlite3_backup *p; /* Value to return */
68126 
68127 #ifdef SQLITE_ENABLE_API_ARMOR
68128  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
68129  (void)SQLITE_MISUSE_BKPT;
68130  return 0;
68131  }
68132 #endif
68133 
68134  /* Lock the source database handle. The destination database
68135  ** handle is not locked in this routine, but it is locked in
68136  ** sqlite3_backup_step(). The user is required to ensure that no
68137  ** other thread accesses the destination handle for the duration
68138  ** of the backup operation. Any attempt to use the destination
68139  ** database connection while a backup is in progress may cause
68140  ** a malfunction or a deadlock.
68141  */
68142  sqlite3_mutex_enter(pSrcDb->mutex);
68143  sqlite3_mutex_enter(pDestDb->mutex);
68144 
68145  if( pSrcDb==pDestDb ){
68146  sqlite3ErrorWithMsg(
68147  pDestDb, SQLITE_ERROR, "source and destination must be distinct"
68148  );
68149  p = 0;
68150  }else {
68151  /* Allocate space for a new sqlite3_backup object...
68152  ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68153  ** call to sqlite3_backup_init() and is destroyed by a call to
68154  ** sqlite3_backup_finish(). */
68155  p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
68156  if( !p ){
68157  sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
68158  }
68159  }
68160 
68161  /* If the allocation succeeded, populate the new object. */
68162  if( p ){
68163  p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
68164  p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
68165  p->pDestDb = pDestDb;
68166  p->pSrcDb = pSrcDb;
68167  p->iNext = 1;
68168  p->isAttached = 0;
68169 
68170  if( 0==p->pSrc || 0==p->pDest
68171  || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
68172  ){
68173  /* One (or both) of the named databases did not exist or an OOM
68174  ** error was hit. Or there is a transaction open on the destination
68175  ** database. The error has already been written into the pDestDb
68176  ** handle. All that is left to do here is free the sqlite3_backup
68177  ** structure. */
68178  sqlite3_free(p);
68179  p = 0;
68180  }
68181  }
68182  if( p ){
68183  p->pSrc->nBackup++;
68184  }
68185 
68186  sqlite3_mutex_leave(pDestDb->mutex);
68187  sqlite3_mutex_leave(pSrcDb->mutex);
68188  return p;
68189 }
68190 
68191 /*
68192 ** Argument rc is an SQLite error code. Return true if this error is
68193 ** considered fatal if encountered during a backup operation. All errors
68194 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
68195 */
68196 static int isFatalError(int rc){
68197  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
68198 }
68199 
68200 /*
68201 ** Parameter zSrcData points to a buffer containing the data for
68202 ** page iSrcPg from the source database. Copy this data into the
68203 ** destination database.
68204 */
68205 static int backupOnePage(
68206  sqlite3_backup *p, /* Backup handle */
68207  Pgno iSrcPg, /* Source database page to backup */
68208  const u8 *zSrcData, /* Source database page data */
68209  int bUpdate /* True for an update, false otherwise */
68210 ){
68211  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
68212  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
68213  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
68214  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
68215  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
68216 #ifdef SQLITE_HAS_CODEC
68217  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
68218  ** guaranteed that the shared-mutex is held by this thread, handle
68219  ** p->pSrc may not actually be the owner. */
68220  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
68221  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
68222 #endif
68223  int rc = SQLITE_OK;
68224  i64 iOff;
68225 
68226  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
68227  assert( p->bDestLocked );
68228  assert( !isFatalError(p->rc) );
68229  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
68230  assert( zSrcData );
68231 
68232  /* Catch the case where the destination is an in-memory database and the
68233  ** page sizes of the source and destination differ.
68234  */
68235  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
68236  rc = SQLITE_READONLY;
68237  }
68238 
68239 #ifdef SQLITE_HAS_CODEC
68240  /* Backup is not possible if the page size of the destination is changing
68241  ** and a codec is in use.
68242  */
68243  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
68244  rc = SQLITE_READONLY;
68245  }
68246 
68247  /* Backup is not possible if the number of bytes of reserve space differ
68248  ** between source and destination. If there is a difference, try to
68249  ** fix the destination to agree with the source. If that is not possible,
68250  ** then the backup cannot proceed.
68251  */
68252  if( nSrcReserve!=nDestReserve ){
68253  u32 newPgsz = nSrcPgsz;
68254  rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
68255  if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
68256  }
68257 #endif
68258 
68259  /* This loop runs once for each destination page spanned by the source
68260  ** page. For each iteration, variable iOff is set to the byte offset
68261  ** of the destination page.
68262  */
68263  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
68264  DbPage *pDestPg = 0;
68265  Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
68266  if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
68267  if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
68268  && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
68269  ){
68270  const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
68271  u8 *zDestData = sqlite3PagerGetData(pDestPg);
68272  u8 *zOut = &zDestData[iOff%nDestPgsz];
68273 
68274  /* Copy the data from the source page into the destination page.
68275  ** Then clear the Btree layer MemPage.isInit flag. Both this module
68276  ** and the pager code use this trick (clearing the first byte
68277  ** of the page 'extra' space to invalidate the Btree layers
68278  ** cached parse of the page). MemPage.isInit is marked
68279  ** "MUST BE FIRST" for this purpose.
68280  */
68281  memcpy(zOut, zIn, nCopy);
68282  ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
68283  if( iOff==0 && bUpdate==0 ){
68284  sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
68285  }
68286  }
68287  sqlite3PagerUnref(pDestPg);
68288  }
68289 
68290  return rc;
68291 }
68292 
68293 /*
68294 ** If pFile is currently larger than iSize bytes, then truncate it to
68295 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
68296 ** this function is a no-op.
68297 **
68298 ** Return SQLITE_OK if everything is successful, or an SQLite error
68299 ** code if an error occurs.
68300 */
68301 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
68302  i64 iCurrent;
68303  int rc = sqlite3OsFileSize(pFile, &iCurrent);
68304  if( rc==SQLITE_OK && iCurrent>iSize ){
68305  rc = sqlite3OsTruncate(pFile, iSize);
68306  }
68307  return rc;
68308 }
68309 
68310 /*
68311 ** Register this backup object with the associated source pager for
68312 ** callbacks when pages are changed or the cache invalidated.
68313 */
68314 static void attachBackupObject(sqlite3_backup *p){
68315  sqlite3_backup **pp;
68316  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
68317  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
68318  p->pNext = *pp;
68319  *pp = p;
68320  p->isAttached = 1;
68321 }
68322 
68323 /*
68324 ** Copy nPage pages from the source b-tree to the destination.
68325 */
68326 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
68327  int rc;
68328  int destMode; /* Destination journal mode */
68329  int pgszSrc = 0; /* Source page size */
68330  int pgszDest = 0; /* Destination page size */
68331 
68332 #ifdef SQLITE_ENABLE_API_ARMOR
68333  if( p==0 ) return SQLITE_MISUSE_BKPT;
68334 #endif
68335  sqlite3_mutex_enter(p->pSrcDb->mutex);
68336  sqlite3BtreeEnter(p->pSrc);
68337  if( p->pDestDb ){
68338  sqlite3_mutex_enter(p->pDestDb->mutex);
68339  }
68340 
68341  rc = p->rc;
68342  if( !isFatalError(rc) ){
68343  Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
68344  Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
68345  int ii; /* Iterator variable */
68346  int nSrcPage = -1; /* Size of source db in pages */
68347  int bCloseTrans = 0; /* True if src db requires unlocking */
68348 
68349  /* If the source pager is currently in a write-transaction, return
68350  ** SQLITE_BUSY immediately.
68351  */
68352  if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
68353  rc = SQLITE_BUSY;
68354  }else{
68355  rc = SQLITE_OK;
68356  }
68357 
68358  /* If there is no open read-transaction on the source database, open
68359  ** one now. If a transaction is opened here, then it will be closed
68360  ** before this function exits.
68361  */
68362  if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
68363  rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
68364  bCloseTrans = 1;
68365  }
68366 
68367  /* If the destination database has not yet been locked (i.e. if this
68368  ** is the first call to backup_step() for the current backup operation),
68369  ** try to set its page size to the same as the source database. This
68370  ** is especially important on ZipVFS systems, as in that case it is
68371  ** not possible to create a database file that uses one page size by
68372  ** writing to it with another. */
68373  if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
68374  rc = SQLITE_NOMEM;
68375  }
68376 
68377  /* Lock the destination database, if it is not locked already. */
68378  if( SQLITE_OK==rc && p->bDestLocked==0
68379  && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
68380  ){
68381  p->bDestLocked = 1;
68382  sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
68383  }
68384 
68385  /* Do not allow backup if the destination database is in WAL mode
68386  ** and the page sizes are different between source and destination */
68387  pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
68388  pgszDest = sqlite3BtreeGetPageSize(p->pDest);
68389  destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
68390  if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
68391  rc = SQLITE_READONLY;
68392  }
68393 
68394  /* Now that there is a read-lock on the source database, query the
68395  ** source pager for the number of pages in the database.
68396  */
68397  nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
68398  assert( nSrcPage>=0 );
68399  for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
68400  const Pgno iSrcPg = p->iNext; /* Source page number */
68401  if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
68402  DbPage *pSrcPg; /* Source page object */
68403  rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
68404  if( rc==SQLITE_OK ){
68405  rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
68406  sqlite3PagerUnref(pSrcPg);
68407  }
68408  }
68409  p->iNext++;
68410  }
68411  if( rc==SQLITE_OK ){
68412  p->nPagecount = nSrcPage;
68413  p->nRemaining = nSrcPage+1-p->iNext;
68414  if( p->iNext>(Pgno)nSrcPage ){
68415  rc = SQLITE_DONE;
68416  }else if( !p->isAttached ){
68417  attachBackupObject(p);
68418  }
68419  }
68420 
68421  /* Update the schema version field in the destination database. This
68422  ** is to make sure that the schema-version really does change in
68423  ** the case where the source and destination databases have the
68424  ** same schema version.
68425  */
68426  if( rc==SQLITE_DONE ){
68427  if( nSrcPage==0 ){
68428  rc = sqlite3BtreeNewDb(p->pDest);
68429  nSrcPage = 1;
68430  }
68431  if( rc==SQLITE_OK || rc==SQLITE_DONE ){
68432  rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
68433  }
68434  if( rc==SQLITE_OK ){
68435  if( p->pDestDb ){
68436  sqlite3ResetAllSchemasOfConnection(p->pDestDb);
68437  }
68438  if( destMode==PAGER_JOURNALMODE_WAL ){
68439  rc = sqlite3BtreeSetVersion(p->pDest, 2);
68440  }
68441  }
68442  if( rc==SQLITE_OK ){
68443  int nDestTruncate;
68444  /* Set nDestTruncate to the final number of pages in the destination
68445  ** database. The complication here is that the destination page
68446  ** size may be different to the source page size.
68447  **
68448  ** If the source page size is smaller than the destination page size,
68449  ** round up. In this case the call to sqlite3OsTruncate() below will
68450  ** fix the size of the file. However it is important to call
68451  ** sqlite3PagerTruncateImage() here so that any pages in the
68452  ** destination file that lie beyond the nDestTruncate page mark are
68453  ** journalled by PagerCommitPhaseOne() before they are destroyed
68454  ** by the file truncation.
68455  */
68456  assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
68457  assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
68458  if( pgszSrc<pgszDest ){
68459  int ratio = pgszDest/pgszSrc;
68460  nDestTruncate = (nSrcPage+ratio-1)/ratio;
68461  if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
68462  nDestTruncate--;
68463  }
68464  }else{
68465  nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
68466  }
68467  assert( nDestTruncate>0 );
68468 
68469  if( pgszSrc<pgszDest ){
68470  /* If the source page-size is smaller than the destination page-size,
68471  ** two extra things may need to happen:
68472  **
68473  ** * The destination may need to be truncated, and
68474  **
68475  ** * Data stored on the pages immediately following the
68476  ** pending-byte page in the source database may need to be
68477  ** copied into the destination database.
68478  */
68479  const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
68480  sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
68481  Pgno iPg;
68482  int nDstPage;
68483  i64 iOff;
68484  i64 iEnd;
68485 
68486  assert( pFile );
68487  assert( nDestTruncate==0
68488  || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
68489  nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
68490  && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
68491  ));
68492 
68493  /* This block ensures that all data required to recreate the original
68494  ** database has been stored in the journal for pDestPager and the
68495  ** journal synced to disk. So at this point we may safely modify
68496  ** the database file in any way, knowing that if a power failure
68497  ** occurs, the original database will be reconstructed from the
68498  ** journal file. */
68499  sqlite3PagerPagecount(pDestPager, &nDstPage);
68500  for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
68501  if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
68502  DbPage *pPg;
68503  rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
68504  if( rc==SQLITE_OK ){
68505  rc = sqlite3PagerWrite(pPg);
68506  sqlite3PagerUnref(pPg);
68507  }
68508  }
68509  }
68510  if( rc==SQLITE_OK ){
68511  rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
68512  }
68513 
68514  /* Write the extra pages and truncate the database file as required */
68515  iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
68516  for(
68517  iOff=PENDING_BYTE+pgszSrc;
68518  rc==SQLITE_OK && iOff<iEnd;
68519  iOff+=pgszSrc
68520  ){
68521  PgHdr *pSrcPg = 0;
68522  const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
68523  rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
68524  if( rc==SQLITE_OK ){
68525  u8 *zData = sqlite3PagerGetData(pSrcPg);
68526  rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
68527  }
68528  sqlite3PagerUnref(pSrcPg);
68529  }
68530  if( rc==SQLITE_OK ){
68531  rc = backupTruncateFile(pFile, iSize);
68532  }
68533 
68534  /* Sync the database file to disk. */
68535  if( rc==SQLITE_OK ){
68536  rc = sqlite3PagerSync(pDestPager, 0);
68537  }
68538  }else{
68539  sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
68540  rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
68541  }
68542 
68543  /* Finish committing the transaction to the destination database. */
68544  if( SQLITE_OK==rc
68545  && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
68546  ){
68547  rc = SQLITE_DONE;
68548  }
68549  }
68550  }
68551 
68552  /* If bCloseTrans is true, then this function opened a read transaction
68553  ** on the source database. Close the read transaction here. There is
68554  ** no need to check the return values of the btree methods here, as
68555  ** "committing" a read-only transaction cannot fail.
68556  */
68557  if( bCloseTrans ){
68558  TESTONLY( int rc2 );
68559  TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
68560  TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
68561  assert( rc2==SQLITE_OK );
68562  }
68563 
68564  if( rc==SQLITE_IOERR_NOMEM ){
68565  rc = SQLITE_NOMEM_BKPT;
68566  }
68567  p->rc = rc;
68568  }
68569  if( p->pDestDb ){
68570  sqlite3_mutex_leave(p->pDestDb->mutex);
68571  }
68572  sqlite3BtreeLeave(p->pSrc);
68573  sqlite3_mutex_leave(p->pSrcDb->mutex);
68574  return rc;
68575 }
68576 
68577 /*
68578 ** Release all resources associated with an sqlite3_backup* handle.
68579 */
68580 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
68581  sqlite3_backup **pp; /* Ptr to head of pagers backup list */
68582  sqlite3 *pSrcDb; /* Source database connection */
68583  int rc; /* Value to return */
68584 
68585  /* Enter the mutexes */
68586  if( p==0 ) return SQLITE_OK;
68587  pSrcDb = p->pSrcDb;
68588  sqlite3_mutex_enter(pSrcDb->mutex);
68589  sqlite3BtreeEnter(p->pSrc);
68590  if( p->pDestDb ){
68591  sqlite3_mutex_enter(p->pDestDb->mutex);
68592  }
68593 
68594  /* Detach this backup from the source pager. */
68595  if( p->pDestDb ){
68596  p->pSrc->nBackup--;
68597  }
68598  if( p->isAttached ){
68599  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
68600  while( *pp!=p ){
68601  pp = &(*pp)->pNext;
68602  }
68603  *pp = p->pNext;
68604  }
68605 
68606  /* If a transaction is still open on the Btree, roll it back. */
68607  sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
68608 
68609  /* Set the error code of the destination database handle. */
68610  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
68611  if( p->pDestDb ){
68612  sqlite3Error(p->pDestDb, rc);
68613 
68614  /* Exit the mutexes and free the backup context structure. */
68615  sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
68616  }
68617  sqlite3BtreeLeave(p->pSrc);
68618  if( p->pDestDb ){
68619  /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68620  ** call to sqlite3_backup_init() and is destroyed by a call to
68621  ** sqlite3_backup_finish(). */
68622  sqlite3_free(p);
68623  }
68624  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
68625  return rc;
68626 }
68627 
68628 /*
68629 ** Return the number of pages still to be backed up as of the most recent
68630 ** call to sqlite3_backup_step().
68631 */
68632 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
68633 #ifdef SQLITE_ENABLE_API_ARMOR
68634  if( p==0 ){
68635  (void)SQLITE_MISUSE_BKPT;
68636  return 0;
68637  }
68638 #endif
68639  return p->nRemaining;
68640 }
68641 
68642 /*
68643 ** Return the total number of pages in the source database as of the most
68644 ** recent call to sqlite3_backup_step().
68645 */
68646 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
68647 #ifdef SQLITE_ENABLE_API_ARMOR
68648  if( p==0 ){
68649  (void)SQLITE_MISUSE_BKPT;
68650  return 0;
68651  }
68652 #endif
68653  return p->nPagecount;
68654 }
68655 
68656 /*
68657 ** This function is called after the contents of page iPage of the
68658 ** source database have been modified. If page iPage has already been
68659 ** copied into the destination database, then the data written to the
68660 ** destination is now invalidated. The destination copy of iPage needs
68661 ** to be updated with the new data before the backup operation is
68662 ** complete.
68663 **
68664 ** It is assumed that the mutex associated with the BtShared object
68665 ** corresponding to the source database is held when this function is
68666 ** called.
68667 */
68668 static SQLITE_NOINLINE void backupUpdate(
68669  sqlite3_backup *p,
68670  Pgno iPage,
68671  const u8 *aData
68672 ){
68673  assert( p!=0 );
68674  do{
68675  assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68676  if( !isFatalError(p->rc) && iPage<p->iNext ){
68677  /* The backup process p has already copied page iPage. But now it
68678  ** has been modified by a transaction on the source pager. Copy
68679  ** the new data into the backup.
68680  */
68681  int rc;
68682  assert( p->pDestDb );
68683  sqlite3_mutex_enter(p->pDestDb->mutex);
68684  rc = backupOnePage(p, iPage, aData, 1);
68685  sqlite3_mutex_leave(p->pDestDb->mutex);
68686  assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
68687  if( rc!=SQLITE_OK ){
68688  p->rc = rc;
68689  }
68690  }
68691  }while( (p = p->pNext)!=0 );
68692 }
68693 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
68694  if( pBackup ) backupUpdate(pBackup, iPage, aData);
68695 }
68696 
68697 /*
68698 ** Restart the backup process. This is called when the pager layer
68699 ** detects that the database has been modified by an external database
68700 ** connection. In this case there is no way of knowing which of the
68701 ** pages that have been copied into the destination database are still
68702 ** valid and which are not, so the entire process needs to be restarted.
68703 **
68704 ** It is assumed that the mutex associated with the BtShared object
68705 ** corresponding to the source database is held when this function is
68706 ** called.
68707 */
68708 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
68709  sqlite3_backup *p; /* Iterator variable */
68710  for(p=pBackup; p; p=p->pNext){
68711  assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68712  p->iNext = 1;
68713  }
68714 }
68715 
68716 #ifndef SQLITE_OMIT_VACUUM
68717 /*
68718 ** Copy the complete content of pBtFrom into pBtTo. A transaction
68719 ** must be active for both files.
68720 **
68721 ** The size of file pTo may be reduced by this operation. If anything
68722 ** goes wrong, the transaction on pTo is rolled back. If successful, the
68723 ** transaction is committed before returning.
68724 */
68725 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
68726  int rc;
68727  sqlite3_file *pFd; /* File descriptor for database pTo */
68728  sqlite3_backup b;
68729  sqlite3BtreeEnter(pTo);
68730  sqlite3BtreeEnter(pFrom);
68731 
68732  assert( sqlite3BtreeIsInTrans(pTo) );
68733  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
68734  if( pFd->pMethods ){
68735  i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
68736  rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
68737  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
68738  if( rc ) goto copy_finished;
68739  }
68740 
68741  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
68742  ** to 0. This is used by the implementations of sqlite3_backup_step()
68743  ** and sqlite3_backup_finish() to detect that they are being called
68744  ** from this function, not directly by the user.
68745  */
68746  memset(&b, 0, sizeof(b));
68747  b.pSrcDb = pFrom->db;
68748  b.pSrc = pFrom;
68749  b.pDest = pTo;
68750  b.iNext = 1;
68751 
68752 #ifdef SQLITE_HAS_CODEC
68753  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
68754 #endif
68755 
68756  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
68757  ** file. By passing this as the number of pages to copy to
68758  ** sqlite3_backup_step(), we can guarantee that the copy finishes
68759  ** within a single call (unless an error occurs). The assert() statement
68760  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
68761  ** or an error code. */
68762  sqlite3_backup_step(&b, 0x7FFFFFFF);
68763  assert( b.rc!=SQLITE_OK );
68764 
68765  rc = sqlite3_backup_finish(&b);
68766  if( rc==SQLITE_OK ){
68767  pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
68768  }else{
68769  sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
68770  }
68771 
68772  assert( sqlite3BtreeIsInTrans(pTo)==0 );
68773 copy_finished:
68774  sqlite3BtreeLeave(pFrom);
68775  sqlite3BtreeLeave(pTo);
68776  return rc;
68777 }
68778 #endif /* SQLITE_OMIT_VACUUM */
68779 
68780 /************** End of backup.c **********************************************/
68781 /************** Begin file vdbemem.c *****************************************/
68782 /*
68783 ** 2004 May 26
68784 **
68785 ** The author disclaims copyright to this source code. In place of
68786 ** a legal notice, here is a blessing:
68787 **
68788 ** May you do good and not evil.
68789 ** May you find forgiveness for yourself and forgive others.
68790 ** May you share freely, never taking more than you give.
68791 **
68792 *************************************************************************
68793 **
68794 ** This file contains code use to manipulate "Mem" structure. A "Mem"
68795 ** stores a single value in the VDBE. Mem is an opaque structure visible
68796 ** only within the VDBE. Interface routines refer to a Mem using the
68797 ** name sqlite_value
68798 */
68799 /* #include "sqliteInt.h" */
68800 /* #include "vdbeInt.h" */
68801 
68802 #ifdef SQLITE_DEBUG
68803 /*
68804 ** Check invariants on a Mem object.
68805 **
68806 ** This routine is intended for use inside of assert() statements, like
68807 ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
68808 */
68809 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
68810  /* If MEM_Dyn is set then Mem.xDel!=0.
68811  ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
68812  */
68813  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
68814 
68815  /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
68816  ** ensure that if Mem.szMalloc>0 then it is safe to do
68817  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
68818  ** That saves a few cycles in inner loops. */
68819  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
68820 
68821  /* Cannot be both MEM_Int and MEM_Real at the same time */
68822  assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
68823 
68824  /* The szMalloc field holds the correct memory allocation size */
68825  assert( p->szMalloc==0
68826  || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
68827 
68828  /* If p holds a string or blob, the Mem.z must point to exactly
68829  ** one of the following:
68830  **
68831  ** (1) Memory in Mem.zMalloc and managed by the Mem object
68832  ** (2) Memory to be freed using Mem.xDel
68833  ** (3) An ephemeral string or blob
68834  ** (4) A static string or blob
68835  */
68836  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
68837  assert(
68838  ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
68839  ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
68840  ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
68841  ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
68842  );
68843  }
68844  return 1;
68845 }
68846 #endif
68847 
68848 
68849 /*
68850 ** If pMem is an object with a valid string representation, this routine
68851 ** ensures the internal encoding for the string representation is
68852 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
68853 **
68854 ** If pMem is not a string object, or the encoding of the string
68855 ** representation is already stored using the requested encoding, then this
68856 ** routine is a no-op.
68857 **
68858 ** SQLITE_OK is returned if the conversion is successful (or not required).
68859 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
68860 ** between formats.
68861 */
68862 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
68863 #ifndef SQLITE_OMIT_UTF16
68864  int rc;
68865 #endif
68866  assert( (pMem->flags&MEM_RowSet)==0 );
68867  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
68868  || desiredEnc==SQLITE_UTF16BE );
68869  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
68870  return SQLITE_OK;
68871  }
68872  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68873 #ifdef SQLITE_OMIT_UTF16
68874  return SQLITE_ERROR;
68875 #else
68876 
68877  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
68878  ** then the encoding of the value may not have changed.
68879  */
68880  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
68881  assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
68882  assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
68883  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
68884  return rc;
68885 #endif
68886 }
68887 
68888 /*
68889 ** Make sure pMem->z points to a writable allocation of at least
68890 ** min(n,32) bytes.
68891 **
68892 ** If the bPreserve argument is true, then copy of the content of
68893 ** pMem->z into the new allocation. pMem must be either a string or
68894 ** blob if bPreserve is true. If bPreserve is false, any prior content
68895 ** in pMem->z is discarded.
68896 */
68897 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
68898  assert( sqlite3VdbeCheckMemInvariants(pMem) );
68899  assert( (pMem->flags&MEM_RowSet)==0 );
68900  testcase( pMem->db==0 );
68901 
68902  /* If the bPreserve flag is set to true, then the memory cell must already
68903  ** contain a valid string or blob value. */
68904  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
68905  testcase( bPreserve && pMem->z==0 );
68906 
68907  assert( pMem->szMalloc==0
68908  || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
68909  if( pMem->szMalloc<n ){
68910  if( n<32 ) n = 32;
68911  if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
68912  pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
68913  bPreserve = 0;
68914  }else{
68915  if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68916  pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
68917  }
68918  if( pMem->zMalloc==0 ){
68919  sqlite3VdbeMemSetNull(pMem);
68920  pMem->z = 0;
68921  pMem->szMalloc = 0;
68922  return SQLITE_NOMEM_BKPT;
68923  }else{
68924  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
68925  }
68926  }
68927 
68928  if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
68929  memcpy(pMem->zMalloc, pMem->z, pMem->n);
68930  }
68931  if( (pMem->flags&MEM_Dyn)!=0 ){
68932  assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
68933  pMem->xDel((void *)(pMem->z));
68934  }
68935 
68936  pMem->z = pMem->zMalloc;
68937  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
68938  return SQLITE_OK;
68939 }
68940 
68941 /*
68942 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
68943 ** If pMem->zMalloc already meets or exceeds the requested size, this
68944 ** routine is a no-op.
68945 **
68946 ** Any prior string or blob content in the pMem object may be discarded.
68947 ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
68948 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
68949 ** values are preserved.
68950 **
68951 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
68952 ** if unable to complete the resizing.
68953 */
68954 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
68955  assert( szNew>0 );
68956  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
68957  if( pMem->szMalloc<szNew ){
68958  return sqlite3VdbeMemGrow(pMem, szNew, 0);
68959  }
68960  assert( (pMem->flags & MEM_Dyn)==0 );
68961  pMem->z = pMem->zMalloc;
68962  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
68963  return SQLITE_OK;
68964 }
68965 
68966 /*
68967 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
68968 ** MEM.zMalloc, where it can be safely written.
68969 **
68970 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
68971 */
68972 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
68973  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68974  assert( (pMem->flags&MEM_RowSet)==0 );
68975  if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
68976  if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
68977  if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
68978  if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
68979  return SQLITE_NOMEM_BKPT;
68980  }
68981  pMem->z[pMem->n] = 0;
68982  pMem->z[pMem->n+1] = 0;
68983  pMem->flags |= MEM_Term;
68984  }
68985  }
68986  pMem->flags &= ~MEM_Ephem;
68987 #ifdef SQLITE_DEBUG
68988  pMem->pScopyFrom = 0;
68989 #endif
68990 
68991  return SQLITE_OK;
68992 }
68993 
68994 /*
68995 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
68996 ** blob stored in dynamically allocated space.
68997 */
68998 #ifndef SQLITE_OMIT_INCRBLOB
68999 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
69000  int nByte;
69001  assert( pMem->flags & MEM_Zero );
69002  assert( pMem->flags&MEM_Blob );
69003  assert( (pMem->flags&MEM_RowSet)==0 );
69004  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69005 
69006  /* Set nByte to the number of bytes required to store the expanded blob. */
69007  nByte = pMem->n + pMem->u.nZero;
69008  if( nByte<=0 ){
69009  nByte = 1;
69010  }
69011  if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
69012  return SQLITE_NOMEM_BKPT;
69013  }
69014 
69015  memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
69016  pMem->n += pMem->u.nZero;
69017  pMem->flags &= ~(MEM_Zero|MEM_Term);
69018  return SQLITE_OK;
69019 }
69020 #endif
69021 
69022 /*
69023 ** It is already known that pMem contains an unterminated string.
69024 ** Add the zero terminator.
69025 */
69026 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
69027  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
69028  return SQLITE_NOMEM_BKPT;
69029  }
69030  pMem->z[pMem->n] = 0;
69031  pMem->z[pMem->n+1] = 0;
69032  pMem->flags |= MEM_Term;
69033  return SQLITE_OK;
69034 }
69035 
69036 /*
69037 ** Make sure the given Mem is \u0000 terminated.
69038 */
69039 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
69040  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69041  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
69042  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
69043  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
69044  return SQLITE_OK; /* Nothing to do */
69045  }else{
69046  return vdbeMemAddTerminator(pMem);
69047  }
69048 }
69049 
69050 /*
69051 ** Add MEM_Str to the set of representations for the given Mem. Numbers
69052 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
69053 ** is a no-op.
69054 **
69055 ** Existing representations MEM_Int and MEM_Real are invalidated if
69056 ** bForce is true but are retained if bForce is false.
69057 **
69058 ** A MEM_Null value will never be passed to this function. This function is
69059 ** used for converting values to text for returning to the user (i.e. via
69060 ** sqlite3_value_text()), or for ensuring that values to be used as btree
69061 ** keys are strings. In the former case a NULL pointer is returned the
69062 ** user and the latter is an internal programming error.
69063 */
69064 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
69065  int fg = pMem->flags;
69066  const int nByte = 32;
69067 
69068  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69069  assert( !(fg&MEM_Zero) );
69070  assert( !(fg&(MEM_Str|MEM_Blob)) );
69071  assert( fg&(MEM_Int|MEM_Real) );
69072  assert( (pMem->flags&MEM_RowSet)==0 );
69073  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69074 
69075 
69076  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
69077  pMem->enc = 0;
69078  return SQLITE_NOMEM_BKPT;
69079  }
69080 
69081  /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
69082  ** string representation of the value. Then, if the required encoding
69083  ** is UTF-16le or UTF-16be do a translation.
69084  **
69085  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
69086  */
69087  if( fg & MEM_Int ){
69088  sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
69089  }else{
69090  assert( fg & MEM_Real );
69091  sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
69092  }
69093  pMem->n = sqlite3Strlen30(pMem->z);
69094  pMem->enc = SQLITE_UTF8;
69095  pMem->flags |= MEM_Str|MEM_Term;
69096  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
69097  sqlite3VdbeChangeEncoding(pMem, enc);
69098  return SQLITE_OK;
69099 }
69100 
69101 /*
69102 ** Memory cell pMem contains the context of an aggregate function.
69103 ** This routine calls the finalize method for that function. The
69104 ** result of the aggregate is stored back into pMem.
69105 **
69106 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
69107 ** otherwise.
69108 */
69109 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
69110  int rc = SQLITE_OK;
69111  if( ALWAYS(pFunc && pFunc->xFinalize) ){
69112  sqlite3_context ctx;
69113  Mem t;
69114  assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
69115  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69116  memset(&ctx, 0, sizeof(ctx));
69117  memset(&t, 0, sizeof(t));
69118  t.flags = MEM_Null;
69119  t.db = pMem->db;
69120  ctx.pOut = &t;
69121  ctx.pMem = pMem;
69122  ctx.pFunc = pFunc;
69123  pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
69124  assert( (pMem->flags & MEM_Dyn)==0 );
69125  if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
69126  memcpy(pMem, &t, sizeof(t));
69127  rc = ctx.isError;
69128  }
69129  return rc;
69130 }
69131 
69132 /*
69133 ** If the memory cell contains a value that must be freed by
69134 ** invoking the external callback in Mem.xDel, then this routine
69135 ** will free that value. It also sets Mem.flags to MEM_Null.
69136 **
69137 ** This is a helper routine for sqlite3VdbeMemSetNull() and
69138 ** for sqlite3VdbeMemRelease(). Use those other routines as the
69139 ** entry point for releasing Mem resources.
69140 */
69141 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
69142  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
69143  assert( VdbeMemDynamic(p) );
69144  if( p->flags&MEM_Agg ){
69145  sqlite3VdbeMemFinalize(p, p->u.pDef);
69146  assert( (p->flags & MEM_Agg)==0 );
69147  testcase( p->flags & MEM_Dyn );
69148  }
69149  if( p->flags&MEM_Dyn ){
69150  assert( (p->flags&MEM_RowSet)==0 );
69151  assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
69152  p->xDel((void *)p->z);
69153  }else if( p->flags&MEM_RowSet ){
69154  sqlite3RowSetClear(p->u.pRowSet);
69155  }else if( p->flags&MEM_Frame ){
69156  VdbeFrame *pFrame = p->u.pFrame;
69157  pFrame->pParent = pFrame->v->pDelFrame;
69158  pFrame->v->pDelFrame = pFrame;
69159  }
69160  p->flags = MEM_Null;
69161 }
69162 
69163 /*
69164 ** Release memory held by the Mem p, both external memory cleared
69165 ** by p->xDel and memory in p->zMalloc.
69166 **
69167 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
69168 ** the unusual case where there really is memory in p that needs
69169 ** to be freed.
69170 */
69171 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
69172  if( VdbeMemDynamic(p) ){
69173  vdbeMemClearExternAndSetNull(p);
69174  }
69175  if( p->szMalloc ){
69176  sqlite3DbFree(p->db, p->zMalloc);
69177  p->szMalloc = 0;
69178  }
69179  p->z = 0;
69180 }
69181 
69182 /*
69183 ** Release any memory resources held by the Mem. Both the memory that is
69184 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
69185 **
69186 ** Use this routine prior to clean up prior to abandoning a Mem, or to
69187 ** reset a Mem back to its minimum memory utilization.
69188 **
69189 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
69190 ** prior to inserting new content into the Mem.
69191 */
69192 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
69193  assert( sqlite3VdbeCheckMemInvariants(p) );
69194  if( VdbeMemDynamic(p) || p->szMalloc ){
69195  vdbeMemClear(p);
69196  }
69197 }
69198 
69199 /*
69200 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
69201 ** If the double is out of range of a 64-bit signed integer then
69202 ** return the closest available 64-bit signed integer.
69203 */
69204 static i64 doubleToInt64(double r){
69205 #ifdef SQLITE_OMIT_FLOATING_POINT
69206  /* When floating-point is omitted, double and int64 are the same thing */
69207  return r;
69208 #else
69209  /*
69210  ** Many compilers we encounter do not define constants for the
69211  ** minimum and maximum 64-bit integers, or they define them
69212  ** inconsistently. And many do not understand the "LL" notation.
69213  ** So we define our own static constants here using nothing
69214  ** larger than a 32-bit integer constant.
69215  */
69216  static const i64 maxInt = LARGEST_INT64;
69217  static const i64 minInt = SMALLEST_INT64;
69218 
69219  if( r<=(double)minInt ){
69220  return minInt;
69221  }else if( r>=(double)maxInt ){
69222  return maxInt;
69223  }else{
69224  return (i64)r;
69225  }
69226 #endif
69227 }
69228 
69229 /*
69230 ** Return some kind of integer value which is the best we can do
69231 ** at representing the value that *pMem describes as an integer.
69232 ** If pMem is an integer, then the value is exact. If pMem is
69233 ** a floating-point then the value returned is the integer part.
69234 ** If pMem is a string or blob, then we make an attempt to convert
69235 ** it into an integer and return that. If pMem represents an
69236 ** an SQL-NULL value, return 0.
69237 **
69238 ** If pMem represents a string value, its encoding might be changed.
69239 */
69240 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
69241  int flags;
69242  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69243  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69244  flags = pMem->flags;
69245  if( flags & MEM_Int ){
69246  return pMem->u.i;
69247  }else if( flags & MEM_Real ){
69248  return doubleToInt64(pMem->u.r);
69249  }else if( flags & (MEM_Str|MEM_Blob) ){
69250  i64 value = 0;
69251  assert( pMem->z || pMem->n==0 );
69252  sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
69253  return value;
69254  }else{
69255  return 0;
69256  }
69257 }
69258 
69259 /*
69260 ** Return the best representation of pMem that we can get into a
69261 ** double. If pMem is already a double or an integer, return its
69262 ** value. If it is a string or blob, try to convert it to a double.
69263 ** If it is a NULL, return 0.0.
69264 */
69265 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
69266  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69267  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69268  if( pMem->flags & MEM_Real ){
69269  return pMem->u.r;
69270  }else if( pMem->flags & MEM_Int ){
69271  return (double)pMem->u.i;
69272  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
69273  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69274  double val = (double)0;
69275  sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
69276  return val;
69277  }else{
69278  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69279  return (double)0;
69280  }
69281 }
69282 
69283 /*
69284 ** The MEM structure is already a MEM_Real. Try to also make it a
69285 ** MEM_Int if we can.
69286 */
69287 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
69288  i64 ix;
69289  assert( pMem->flags & MEM_Real );
69290  assert( (pMem->flags & MEM_RowSet)==0 );
69291  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69292  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69293 
69294  ix = doubleToInt64(pMem->u.r);
69295 
69296  /* Only mark the value as an integer if
69297  **
69298  ** (1) the round-trip conversion real->int->real is a no-op, and
69299  ** (2) The integer is neither the largest nor the smallest
69300  ** possible integer (ticket #3922)
69301  **
69302  ** The second and third terms in the following conditional enforces
69303  ** the second condition under the assumption that addition overflow causes
69304  ** values to wrap around.
69305  */
69306  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
69307  pMem->u.i = ix;
69308  MemSetTypeFlag(pMem, MEM_Int);
69309  }
69310 }
69311 
69312 /*
69313 ** Convert pMem to type integer. Invalidate any prior representations.
69314 */
69315 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
69316  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69317  assert( (pMem->flags & MEM_RowSet)==0 );
69318  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69319 
69320  pMem->u.i = sqlite3VdbeIntValue(pMem);
69321  MemSetTypeFlag(pMem, MEM_Int);
69322  return SQLITE_OK;
69323 }
69324 
69325 /*
69326 ** Convert pMem so that it is of type MEM_Real.
69327 ** Invalidate any prior representations.
69328 */
69329 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
69330  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69331  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69332 
69333  pMem->u.r = sqlite3VdbeRealValue(pMem);
69334  MemSetTypeFlag(pMem, MEM_Real);
69335  return SQLITE_OK;
69336 }
69337 
69338 /*
69339 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
69340 ** Invalidate any prior representations.
69341 **
69342 ** Every effort is made to force the conversion, even if the input
69343 ** is a string that does not look completely like a number. Convert
69344 ** as much of the string as we can and ignore the rest.
69345 */
69346 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
69347  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
69348  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
69349  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69350  if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
69351  MemSetTypeFlag(pMem, MEM_Int);
69352  }else{
69353  pMem->u.r = sqlite3VdbeRealValue(pMem);
69354  MemSetTypeFlag(pMem, MEM_Real);
69355  sqlite3VdbeIntegerAffinity(pMem);
69356  }
69357  }
69358  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
69359  pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
69360  return SQLITE_OK;
69361 }
69362 
69363 /*
69364 ** Cast the datatype of the value in pMem according to the affinity
69365 ** "aff". Casting is different from applying affinity in that a cast
69366 ** is forced. In other words, the value is converted into the desired
69367 ** affinity even if that results in loss of data. This routine is
69368 ** used (for example) to implement the SQL "cast()" operator.
69369 */
69370 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
69371  if( pMem->flags & MEM_Null ) return;
69372  switch( aff ){
69373  case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
69374  if( (pMem->flags & MEM_Blob)==0 ){
69375  sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69376  assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69377  if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
69378  }else{
69379  pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
69380  }
69381  break;
69382  }
69383  case SQLITE_AFF_NUMERIC: {
69384  sqlite3VdbeMemNumerify(pMem);
69385  break;
69386  }
69387  case SQLITE_AFF_INTEGER: {
69388  sqlite3VdbeMemIntegerify(pMem);
69389  break;
69390  }
69391  case SQLITE_AFF_REAL: {
69392  sqlite3VdbeMemRealify(pMem);
69393  break;
69394  }
69395  default: {
69396  assert( aff==SQLITE_AFF_TEXT );
69397  assert( MEM_Str==(MEM_Blob>>3) );
69398  pMem->flags |= (pMem->flags&MEM_Blob)>>3;
69399  sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69400  assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69401  pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
69402  break;
69403  }
69404  }
69405 }
69406 
69407 /*
69408 ** Initialize bulk memory to be a consistent Mem object.
69409 **
69410 ** The minimum amount of initialization feasible is performed.
69411 */
69412 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
69413  assert( (flags & ~MEM_TypeMask)==0 );
69414  pMem->flags = flags;
69415  pMem->db = db;
69416  pMem->szMalloc = 0;
69417 }
69418 
69419 
69420 /*
69421 ** Delete any previous value and set the value stored in *pMem to NULL.
69422 **
69423 ** This routine calls the Mem.xDel destructor to dispose of values that
69424 ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
69425 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
69426 ** routine to invoke the destructor and deallocates Mem.zMalloc.
69427 **
69428 ** Use this routine to reset the Mem prior to insert a new value.
69429 **
69430 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
69431 */
69432 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
69433  if( VdbeMemDynamic(pMem) ){
69434  vdbeMemClearExternAndSetNull(pMem);
69435  }else{
69436  pMem->flags = MEM_Null;
69437  }
69438 }
69439 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
69440  sqlite3VdbeMemSetNull((Mem*)p);
69441 }
69442 
69443 /*
69444 ** Delete any previous value and set the value to be a BLOB of length
69445 ** n containing all zeros.
69446 */
69447 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
69448  sqlite3VdbeMemRelease(pMem);
69449  pMem->flags = MEM_Blob|MEM_Zero;
69450  pMem->n = 0;
69451  if( n<0 ) n = 0;
69452  pMem->u.nZero = n;
69453  pMem->enc = SQLITE_UTF8;
69454  pMem->z = 0;
69455 }
69456 
69457 /*
69458 ** The pMem is known to contain content that needs to be destroyed prior
69459 ** to a value change. So invoke the destructor, then set the value to
69460 ** a 64-bit integer.
69461 */
69462 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
69463  sqlite3VdbeMemSetNull(pMem);
69464  pMem->u.i = val;
69465  pMem->flags = MEM_Int;
69466 }
69467 
69468 /*
69469 ** Delete any previous value and set the value stored in *pMem to val,
69470 ** manifest type INTEGER.
69471 */
69472 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
69473  if( VdbeMemDynamic(pMem) ){
69474  vdbeReleaseAndSetInt64(pMem, val);
69475  }else{
69476  pMem->u.i = val;
69477  pMem->flags = MEM_Int;
69478  }
69479 }
69480 
69481 #ifndef SQLITE_OMIT_FLOATING_POINT
69482 /*
69483 ** Delete any previous value and set the value stored in *pMem to val,
69484 ** manifest type REAL.
69485 */
69486 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
69487  sqlite3VdbeMemSetNull(pMem);
69488  if( !sqlite3IsNaN(val) ){
69489  pMem->u.r = val;
69490  pMem->flags = MEM_Real;
69491  }
69492 }
69493 #endif
69494 
69495 /*
69496 ** Delete any previous value and set the value of pMem to be an
69497 ** empty boolean index.
69498 */
69499 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
69500  sqlite3 *db = pMem->db;
69501  assert( db!=0 );
69502  assert( (pMem->flags & MEM_RowSet)==0 );
69503  sqlite3VdbeMemRelease(pMem);
69504  pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
69505  if( db->mallocFailed ){
69506  pMem->flags = MEM_Null;
69507  pMem->szMalloc = 0;
69508  }else{
69509  assert( pMem->zMalloc );
69510  pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
69511  pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
69512  assert( pMem->u.pRowSet!=0 );
69513  pMem->flags = MEM_RowSet;
69514  }
69515 }
69516 
69517 /*
69518 ** Return true if the Mem object contains a TEXT or BLOB that is
69519 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
69520 */
69521 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
69522  assert( p->db!=0 );
69523  if( p->flags & (MEM_Str|MEM_Blob) ){
69524  int n = p->n;
69525  if( p->flags & MEM_Zero ){
69526  n += p->u.nZero;
69527  }
69528  return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
69529  }
69530  return 0;
69531 }
69532 
69533 #ifdef SQLITE_DEBUG
69534 /*
69535 ** This routine prepares a memory cell for modification by breaking
69536 ** its link to a shallow copy and by marking any current shallow
69537 ** copies of this cell as invalid.
69538 **
69539 ** This is used for testing and debugging only - to make sure shallow
69540 ** copies are not misused.
69541 */
69542 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
69543  int i;
69544  Mem *pX;
69545  for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
69546  if( pX->pScopyFrom==pMem ){
69547  pX->flags |= MEM_Undefined;
69548  pX->pScopyFrom = 0;
69549  }
69550  }
69551  pMem->pScopyFrom = 0;
69552 }
69553 #endif /* SQLITE_DEBUG */
69554 
69555 
69556 /*
69557 ** Make an shallow copy of pFrom into pTo. Prior contents of
69558 ** pTo are freed. The pFrom->z field is not duplicated. If
69559 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
69560 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
69561 */
69562 static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
69563  vdbeMemClearExternAndSetNull(pTo);
69564  assert( !VdbeMemDynamic(pTo) );
69565  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
69566 }
69567 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
69568  assert( (pFrom->flags & MEM_RowSet)==0 );
69569  assert( pTo->db==pFrom->db );
69570  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
69571  memcpy(pTo, pFrom, MEMCELLSIZE);
69572  if( (pFrom->flags&MEM_Static)==0 ){
69573  pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
69574  assert( srcType==MEM_Ephem || srcType==MEM_Static );
69575  pTo->flags |= srcType;
69576  }
69577 }
69578 
69579 /*
69580 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
69581 ** freed before the copy is made.
69582 */
69583 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
69584  int rc = SQLITE_OK;
69585 
69586  assert( (pFrom->flags & MEM_RowSet)==0 );
69587  if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
69588  memcpy(pTo, pFrom, MEMCELLSIZE);
69589  pTo->flags &= ~MEM_Dyn;
69590  if( pTo->flags&(MEM_Str|MEM_Blob) ){
69591  if( 0==(pFrom->flags&MEM_Static) ){
69592  pTo->flags |= MEM_Ephem;
69593  rc = sqlite3VdbeMemMakeWriteable(pTo);
69594  }
69595  }
69596 
69597  return rc;
69598 }
69599 
69600 /*
69601 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
69602 ** freed. If pFrom contains ephemeral data, a copy is made.
69603 **
69604 ** pFrom contains an SQL NULL when this routine returns.
69605 */
69606 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
69607  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
69608  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
69609  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
69610 
69611  sqlite3VdbeMemRelease(pTo);
69612  memcpy(pTo, pFrom, sizeof(Mem));
69613  pFrom->flags = MEM_Null;
69614  pFrom->szMalloc = 0;
69615 }
69616 
69617 /*
69618 ** Change the value of a Mem to be a string or a BLOB.
69619 **
69620 ** The memory management strategy depends on the value of the xDel
69621 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
69622 ** string is copied into a (possibly existing) buffer managed by the
69623 ** Mem structure. Otherwise, any existing buffer is freed and the
69624 ** pointer copied.
69625 **
69626 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
69627 ** size limit) then no memory allocation occurs. If the string can be
69628 ** stored without allocating memory, then it is. If a memory allocation
69629 ** is required to store the string, then value of pMem is unchanged. In
69630 ** either case, SQLITE_TOOBIG is returned.
69631 */
69632 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
69633  Mem *pMem, /* Memory cell to set to string value */
69634  const char *z, /* String pointer */
69635  int n, /* Bytes in string, or negative */
69636  u8 enc, /* Encoding of z. 0 for BLOBs */
69637  void (*xDel)(void*) /* Destructor function */
69638 ){
69639  int nByte = n; /* New value for pMem->n */
69640  int iLimit; /* Maximum allowed string or blob size */
69641  u16 flags = 0; /* New value for pMem->flags */
69642 
69643  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69644  assert( (pMem->flags & MEM_RowSet)==0 );
69645 
69646  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
69647  if( !z ){
69648  sqlite3VdbeMemSetNull(pMem);
69649  return SQLITE_OK;
69650  }
69651 
69652  if( pMem->db ){
69653  iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
69654  }else{
69655  iLimit = SQLITE_MAX_LENGTH;
69656  }
69657  flags = (enc==0?MEM_Blob:MEM_Str);
69658  if( nByte<0 ){
69659  assert( enc!=0 );
69660  if( enc==SQLITE_UTF8 ){
69661  nByte = sqlite3Strlen30(z);
69662  if( nByte>iLimit ) nByte = iLimit+1;
69663  }else{
69664  for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
69665  }
69666  flags |= MEM_Term;
69667  }
69668 
69669  /* The following block sets the new values of Mem.z and Mem.xDel. It
69670  ** also sets a flag in local variable "flags" to indicate the memory
69671  ** management (one of MEM_Dyn or MEM_Static).
69672  */
69673  if( xDel==SQLITE_TRANSIENT ){
69674  int nAlloc = nByte;
69675  if( flags&MEM_Term ){
69676  nAlloc += (enc==SQLITE_UTF8?1:2);
69677  }
69678  if( nByte>iLimit ){
69679  return SQLITE_TOOBIG;
69680  }
69681  testcase( nAlloc==0 );
69682  testcase( nAlloc==31 );
69683  testcase( nAlloc==32 );
69684  if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
69685  return SQLITE_NOMEM_BKPT;
69686  }
69687  memcpy(pMem->z, z, nAlloc);
69688  }else if( xDel==SQLITE_DYNAMIC ){
69689  sqlite3VdbeMemRelease(pMem);
69690  pMem->zMalloc = pMem->z = (char *)z;
69691  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
69692  }else{
69693  sqlite3VdbeMemRelease(pMem);
69694  pMem->z = (char *)z;
69695  pMem->xDel = xDel;
69696  flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
69697  }
69698 
69699  pMem->n = nByte;
69700  pMem->flags = flags;
69701  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
69702 
69703 #ifndef SQLITE_OMIT_UTF16
69704  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
69705  return SQLITE_NOMEM_BKPT;
69706  }
69707 #endif
69708 
69709  if( nByte>iLimit ){
69710  return SQLITE_TOOBIG;
69711  }
69712 
69713  return SQLITE_OK;
69714 }
69715 
69716 /*
69717 ** Move data out of a btree key or data field and into a Mem structure.
69718 ** The data or key is taken from the entry that pCur is currently pointing
69719 ** to. offset and amt determine what portion of the data or key to retrieve.
69720 ** key is true to get the key or false to get data. The result is written
69721 ** into the pMem element.
69722 **
69723 ** The pMem object must have been initialized. This routine will use
69724 ** pMem->zMalloc to hold the content from the btree, if possible. New
69725 ** pMem->zMalloc space will be allocated if necessary. The calling routine
69726 ** is responsible for making sure that the pMem object is eventually
69727 ** destroyed.
69728 **
69729 ** If this routine fails for any reason (malloc returns NULL or unable
69730 ** to read from the disk) then the pMem is left in an inconsistent state.
69731 */
69732 static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
69733  BtCursor *pCur, /* Cursor pointing at record to retrieve. */
69734  u32 offset, /* Offset from the start of data to return bytes from. */
69735  u32 amt, /* Number of bytes to return. */
69736  int key, /* If true, retrieve from the btree key, not data. */
69737  Mem *pMem /* OUT: Return data in this Mem structure. */
69738 ){
69739  int rc;
69740  pMem->flags = MEM_Null;
69741  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
69742  if( key ){
69743  rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
69744  }else{
69745  rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
69746  }
69747  if( rc==SQLITE_OK ){
69748  pMem->z[amt] = 0;
69749  pMem->z[amt+1] = 0;
69750  pMem->flags = MEM_Blob|MEM_Term;
69751  pMem->n = (int)amt;
69752  }else{
69753  sqlite3VdbeMemRelease(pMem);
69754  }
69755  }
69756  return rc;
69757 }
69758 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
69759  BtCursor *pCur, /* Cursor pointing at record to retrieve. */
69760  u32 offset, /* Offset from the start of data to return bytes from. */
69761  u32 amt, /* Number of bytes to return. */
69762  int key, /* If true, retrieve from the btree key, not data. */
69763  Mem *pMem /* OUT: Return data in this Mem structure. */
69764 ){
69765  char *zData; /* Data from the btree layer */
69766  u32 available = 0; /* Number of bytes available on the local btree page */
69767  int rc = SQLITE_OK; /* Return code */
69768 
69769  assert( sqlite3BtreeCursorIsValid(pCur) );
69770  assert( !VdbeMemDynamic(pMem) );
69771 
69772  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
69773  ** that both the BtShared and database handle mutexes are held. */
69774  assert( (pMem->flags & MEM_RowSet)==0 );
69775  zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
69776  assert( zData!=0 );
69777 
69778  if( offset+amt<=available ){
69779  pMem->z = &zData[offset];
69780  pMem->flags = MEM_Blob|MEM_Ephem;
69781  pMem->n = (int)amt;
69782  }else{
69783  rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
69784  }
69785 
69786  return rc;
69787 }
69788 
69789 /*
69790 ** The pVal argument is known to be a value other than NULL.
69791 ** Convert it into a string with encoding enc and return a pointer
69792 ** to a zero-terminated version of that string.
69793 */
69794 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
69795  assert( pVal!=0 );
69796  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69797  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69798  assert( (pVal->flags & MEM_RowSet)==0 );
69799  assert( (pVal->flags & (MEM_Null))==0 );
69800  if( pVal->flags & (MEM_Blob|MEM_Str) ){
69801  pVal->flags |= MEM_Str;
69802  if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
69803  sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
69804  }
69805  if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
69806  assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
69807  if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
69808  return 0;
69809  }
69810  }
69811  sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
69812  }else{
69813  sqlite3VdbeMemStringify(pVal, enc, 0);
69814  assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
69815  }
69816  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
69817  || pVal->db->mallocFailed );
69818  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
69819  return pVal->z;
69820  }else{
69821  return 0;
69822  }
69823 }
69824 
69825 /* This function is only available internally, it is not part of the
69826 ** external API. It works in a similar way to sqlite3_value_text(),
69827 ** except the data returned is in the encoding specified by the second
69828 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
69829 ** SQLITE_UTF8.
69830 **
69831 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
69832 ** If that is the case, then the result must be aligned on an even byte
69833 ** boundary.
69834 */
69835 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
69836  if( !pVal ) return 0;
69837  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69838  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69839  assert( (pVal->flags & MEM_RowSet)==0 );
69840  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
69841  return pVal->z;
69842  }
69843  if( pVal->flags&MEM_Null ){
69844  return 0;
69845  }
69846  return valueToText(pVal, enc);
69847 }
69848 
69849 /*
69850 ** Create a new sqlite3_value object.
69851 */
69852 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
69853  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
69854  if( p ){
69855  p->flags = MEM_Null;
69856  p->db = db;
69857  }
69858  return p;
69859 }
69860 
69861 /*
69862 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
69863 ** valueNew(). See comments above valueNew() for details.
69864 */
69866  Parse *pParse;
69867  Index *pIdx;
69868  UnpackedRecord **ppRec;
69869  int iVal;
69870 };
69871 
69872 /*
69873 ** Allocate and return a pointer to a new sqlite3_value object. If
69874 ** the second argument to this function is NULL, the object is allocated
69875 ** by calling sqlite3ValueNew().
69876 **
69877 ** Otherwise, if the second argument is non-zero, then this function is
69878 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
69879 ** already been allocated, allocate the UnpackedRecord structure that
69880 ** that function will return to its caller here. Then return a pointer to
69881 ** an sqlite3_value within the UnpackedRecord.a[] array.
69882 */
69883 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
69884 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69885  if( p ){
69886  UnpackedRecord *pRec = p->ppRec[0];
69887 
69888  if( pRec==0 ){
69889  Index *pIdx = p->pIdx; /* Index being probed */
69890  int nByte; /* Bytes of space to allocate */
69891  int i; /* Counter variable */
69892  int nCol = pIdx->nColumn; /* Number of index columns including rowid */
69893 
69894  nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
69895  pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
69896  if( pRec ){
69897  pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
69898  if( pRec->pKeyInfo ){
69899  assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
69900  assert( pRec->pKeyInfo->enc==ENC(db) );
69901  pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
69902  for(i=0; i<nCol; i++){
69903  pRec->aMem[i].flags = MEM_Null;
69904  pRec->aMem[i].db = db;
69905  }
69906  }else{
69907  sqlite3DbFree(db, pRec);
69908  pRec = 0;
69909  }
69910  }
69911  if( pRec==0 ) return 0;
69912  p->ppRec[0] = pRec;
69913  }
69914 
69915  pRec->nField = p->iVal+1;
69916  return &pRec->aMem[p->iVal];
69917  }
69918 #else
69919  UNUSED_PARAMETER(p);
69920 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69921  return sqlite3ValueNew(db);
69922 }
69923 
69924 /*
69925 ** The expression object indicated by the second argument is guaranteed
69926 ** to be a scalar SQL function. If
69927 **
69928 ** * all function arguments are SQL literals,
69929 ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
69930 ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
69931 **
69932 ** then this routine attempts to invoke the SQL function. Assuming no
69933 ** error occurs, output parameter (*ppVal) is set to point to a value
69934 ** object containing the result before returning SQLITE_OK.
69935 **
69936 ** Affinity aff is applied to the result of the function before returning.
69937 ** If the result is a text value, the sqlite3_value object uses encoding
69938 ** enc.
69939 **
69940 ** If the conditions above are not met, this function returns SQLITE_OK
69941 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
69942 ** NULL and an SQLite error code returned.
69943 */
69944 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69945 static int valueFromFunction(
69946  sqlite3 *db, /* The database connection */
69947  Expr *p, /* The expression to evaluate */
69948  u8 enc, /* Encoding to use */
69949  u8 aff, /* Affinity to use */
69950  sqlite3_value **ppVal, /* Write the new value here */
69951  struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
69952 ){
69953  sqlite3_context ctx; /* Context object for function invocation */
69954  sqlite3_value **apVal = 0; /* Function arguments */
69955  int nVal = 0; /* Size of apVal[] array */
69956  FuncDef *pFunc = 0; /* Function definition */
69957  sqlite3_value *pVal = 0; /* New value */
69958  int rc = SQLITE_OK; /* Return code */
69959  ExprList *pList = 0; /* Function arguments */
69960  int i; /* Iterator variable */
69961 
69962  assert( pCtx!=0 );
69963  assert( (p->flags & EP_TokenOnly)==0 );
69964  pList = p->x.pList;
69965  if( pList ) nVal = pList->nExpr;
69966  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
69967  assert( pFunc );
69968  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
69969  || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
69970  ){
69971  return SQLITE_OK;
69972  }
69973 
69974  if( pList ){
69975  apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
69976  if( apVal==0 ){
69977  rc = SQLITE_NOMEM_BKPT;
69978  goto value_from_function_out;
69979  }
69980  for(i=0; i<nVal; i++){
69981  rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
69982  if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
69983  }
69984  }
69985 
69986  pVal = valueNew(db, pCtx);
69987  if( pVal==0 ){
69988  rc = SQLITE_NOMEM_BKPT;
69989  goto value_from_function_out;
69990  }
69991 
69992  assert( pCtx->pParse->rc==SQLITE_OK );
69993  memset(&ctx, 0, sizeof(ctx));
69994  ctx.pOut = pVal;
69995  ctx.pFunc = pFunc;
69996  pFunc->xSFunc(&ctx, nVal, apVal);
69997  if( ctx.isError ){
69998  rc = ctx.isError;
69999  sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
70000  }else{
70001  sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
70002  assert( rc==SQLITE_OK );
70003  rc = sqlite3VdbeChangeEncoding(pVal, enc);
70004  if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
70005  rc = SQLITE_TOOBIG;
70006  pCtx->pParse->nErr++;
70007  }
70008  }
70009  pCtx->pParse->rc = rc;
70010 
70011  value_from_function_out:
70012  if( rc!=SQLITE_OK ){
70013  pVal = 0;
70014  }
70015  if( apVal ){
70016  for(i=0; i<nVal; i++){
70017  sqlite3ValueFree(apVal[i]);
70018  }
70019  sqlite3DbFree(db, apVal);
70020  }
70021 
70022  *ppVal = pVal;
70023  return rc;
70024 }
70025 #else
70026 # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
70027 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
70028 
70029 /*
70030 ** Extract a value from the supplied expression in the manner described
70031 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
70032 ** using valueNew().
70033 **
70034 ** If pCtx is NULL and an error occurs after the sqlite3_value object
70035 ** has been allocated, it is freed before returning. Or, if pCtx is not
70036 ** NULL, it is assumed that the caller will free any allocated object
70037 ** in all cases.
70038 */
70039 static int valueFromExpr(
70040  sqlite3 *db, /* The database connection */
70041  Expr *pExpr, /* The expression to evaluate */
70042  u8 enc, /* Encoding to use */
70043  u8 affinity, /* Affinity to use */
70044  sqlite3_value **ppVal, /* Write the new value here */
70045  struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
70046 ){
70047  int op;
70048  char *zVal = 0;
70049  sqlite3_value *pVal = 0;
70050  int negInt = 1;
70051  const char *zNeg = "";
70052  int rc = SQLITE_OK;
70053 
70054  assert( pExpr!=0 );
70055  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
70056  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
70057 
70058  /* Compressed expressions only appear when parsing the DEFAULT clause
70059  ** on a table column definition, and hence only when pCtx==0. This
70060  ** check ensures that an EP_TokenOnly expression is never passed down
70061  ** into valueFromFunction(). */
70062  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
70063 
70064  if( op==TK_CAST ){
70065  u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
70066  rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
70067  testcase( rc!=SQLITE_OK );
70068  if( *ppVal ){
70069  sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
70070  sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
70071  }
70072  return rc;
70073  }
70074 
70075  /* Handle negative integers in a single step. This is needed in the
70076  ** case when the value is -9223372036854775808.
70077  */
70078  if( op==TK_UMINUS
70079  && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
70080  pExpr = pExpr->pLeft;
70081  op = pExpr->op;
70082  negInt = -1;
70083  zNeg = "-";
70084  }
70085 
70086  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
70087  pVal = valueNew(db, pCtx);
70088  if( pVal==0 ) goto no_mem;
70089  if( ExprHasProperty(pExpr, EP_IntValue) ){
70090  sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
70091  }else{
70092  zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
70093  if( zVal==0 ) goto no_mem;
70094  sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
70095  }
70096  if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
70097  sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
70098  }else{
70099  sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
70100  }
70101  if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
70102  if( enc!=SQLITE_UTF8 ){
70103  rc = sqlite3VdbeChangeEncoding(pVal, enc);
70104  }
70105  }else if( op==TK_UMINUS ) {
70106  /* This branch happens for multiple negative signs. Ex: -(-5) */
70107  if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
70108  && pVal!=0
70109  ){
70110  sqlite3VdbeMemNumerify(pVal);
70111  if( pVal->flags & MEM_Real ){
70112  pVal->u.r = -pVal->u.r;
70113  }else if( pVal->u.i==SMALLEST_INT64 ){
70114  pVal->u.r = -(double)SMALLEST_INT64;
70115  MemSetTypeFlag(pVal, MEM_Real);
70116  }else{
70117  pVal->u.i = -pVal->u.i;
70118  }
70119  sqlite3ValueApplyAffinity(pVal, affinity, enc);
70120  }
70121  }else if( op==TK_NULL ){
70122  pVal = valueNew(db, pCtx);
70123  if( pVal==0 ) goto no_mem;
70124  }
70125 #ifndef SQLITE_OMIT_BLOB_LITERAL
70126  else if( op==TK_BLOB ){
70127  int nVal;
70128  assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
70129  assert( pExpr->u.zToken[1]=='\'' );
70130  pVal = valueNew(db, pCtx);
70131  if( !pVal ) goto no_mem;
70132  zVal = &pExpr->u.zToken[2];
70133  nVal = sqlite3Strlen30(zVal)-1;
70134  assert( zVal[nVal]=='\'' );
70135  sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
70136  0, SQLITE_DYNAMIC);
70137  }
70138 #endif
70139 
70140 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70141  else if( op==TK_FUNCTION && pCtx!=0 ){
70142  rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
70143  }
70144 #endif
70145 
70146  *ppVal = pVal;
70147  return rc;
70148 
70149 no_mem:
70150  sqlite3OomFault(db);
70151  sqlite3DbFree(db, zVal);
70152  assert( *ppVal==0 );
70153 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70154  if( pCtx==0 ) sqlite3ValueFree(pVal);
70155 #else
70156  assert( pCtx==0 ); sqlite3ValueFree(pVal);
70157 #endif
70158  return SQLITE_NOMEM_BKPT;
70159 }
70160 
70161 /*
70162 ** Create a new sqlite3_value object, containing the value of pExpr.
70163 **
70164 ** This only works for very simple expressions that consist of one constant
70165 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
70166 ** be converted directly into a value, then the value is allocated and
70167 ** a pointer written to *ppVal. The caller is responsible for deallocating
70168 ** the value by passing it to sqlite3ValueFree() later on. If the expression
70169 ** cannot be converted to a value, then *ppVal is set to NULL.
70170 */
70171 SQLITE_PRIVATE int sqlite3ValueFromExpr(
70172  sqlite3 *db, /* The database connection */
70173  Expr *pExpr, /* The expression to evaluate */
70174  u8 enc, /* Encoding to use */
70175  u8 affinity, /* Affinity to use */
70176  sqlite3_value **ppVal /* Write the new value here */
70177 ){
70178  return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
70179 }
70180 
70181 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70182 /*
70183 ** The implementation of the sqlite_record() function. This function accepts
70184 ** a single argument of any type. The return value is a formatted database
70185 ** record (a blob) containing the argument value.
70186 **
70187 ** This is used to convert the value stored in the 'sample' column of the
70188 ** sqlite_stat3 table to the record format SQLite uses internally.
70189 */
70190 static void recordFunc(
70191  sqlite3_context *context,
70192  int argc,
70193  sqlite3_value **argv
70194 ){
70195  const int file_format = 1;
70196  u32 iSerial; /* Serial type */
70197  int nSerial; /* Bytes of space for iSerial as varint */
70198  u32 nVal; /* Bytes of space required for argv[0] */
70199  int nRet;
70200  sqlite3 *db;
70201  u8 *aRet;
70202 
70203  UNUSED_PARAMETER( argc );
70204  iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
70205  nSerial = sqlite3VarintLen(iSerial);
70206  db = sqlite3_context_db_handle(context);
70207 
70208  nRet = 1 + nSerial + nVal;
70209  aRet = sqlite3DbMallocRawNN(db, nRet);
70210  if( aRet==0 ){
70211  sqlite3_result_error_nomem(context);
70212  }else{
70213  aRet[0] = nSerial+1;
70214  putVarint32(&aRet[1], iSerial);
70215  sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
70216  sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
70217  sqlite3DbFree(db, aRet);
70218  }
70219 }
70220 
70221 /*
70222 ** Register built-in functions used to help read ANALYZE data.
70223 */
70224 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
70225  static FuncDef aAnalyzeTableFuncs[] = {
70226  FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
70227  };
70228  sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
70229 }
70230 
70231 /*
70232 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
70233 **
70234 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
70235 ** pAlloc if one does not exist and the new value is added to the
70236 ** UnpackedRecord object.
70237 **
70238 ** A value is extracted in the following cases:
70239 **
70240 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70241 **
70242 ** * The expression is a bound variable, and this is a reprepare, or
70243 **
70244 ** * The expression is a literal value.
70245 **
70246 ** On success, *ppVal is made to point to the extracted value. The caller
70247 ** is responsible for ensuring that the value is eventually freed.
70248 */
70249 static int stat4ValueFromExpr(
70250  Parse *pParse, /* Parse context */
70251  Expr *pExpr, /* The expression to extract a value from */
70252  u8 affinity, /* Affinity to use */
70253  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
70254  sqlite3_value **ppVal /* OUT: New value object (or NULL) */
70255 ){
70256  int rc = SQLITE_OK;
70257  sqlite3_value *pVal = 0;
70258  sqlite3 *db = pParse->db;
70259 
70260  /* Skip over any TK_COLLATE nodes */
70261  pExpr = sqlite3ExprSkipCollate(pExpr);
70262 
70263  if( !pExpr ){
70264  pVal = valueNew(db, pAlloc);
70265  if( pVal ){
70266  sqlite3VdbeMemSetNull((Mem*)pVal);
70267  }
70268  }else if( pExpr->op==TK_VARIABLE
70269  || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
70270  ){
70271  Vdbe *v;
70272  int iBindVar = pExpr->iColumn;
70273  sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
70274  if( (v = pParse->pReprepare)!=0 ){
70275  pVal = valueNew(db, pAlloc);
70276  if( pVal ){
70277  rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
70278  if( rc==SQLITE_OK ){
70279  sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
70280  }
70281  pVal->db = pParse->db;
70282  }
70283  }
70284  }else{
70285  rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
70286  }
70287 
70288  assert( pVal==0 || pVal->db==db );
70289  *ppVal = pVal;
70290  return rc;
70291 }
70292 
70293 /*
70294 ** This function is used to allocate and populate UnpackedRecord
70295 ** structures intended to be compared against sample index keys stored
70296 ** in the sqlite_stat4 table.
70297 **
70298 ** A single call to this function populates zero or more fields of the
70299 ** record starting with field iVal (fields are numbered from left to
70300 ** right starting with 0). A single field is populated if:
70301 **
70302 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70303 **
70304 ** * The expression is a bound variable, and this is a reprepare, or
70305 **
70306 ** * The sqlite3ValueFromExpr() function is able to extract a value
70307 ** from the expression (i.e. the expression is a literal value).
70308 **
70309 ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
70310 ** vector components that match either of the two latter criteria listed
70311 ** above.
70312 **
70313 ** Before any value is appended to the record, the affinity of the
70314 ** corresponding column within index pIdx is applied to it. Before
70315 ** this function returns, output parameter *pnExtract is set to the
70316 ** number of values appended to the record.
70317 **
70318 ** When this function is called, *ppRec must either point to an object
70319 ** allocated by an earlier call to this function, or must be NULL. If it
70320 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
70321 ** is allocated (and *ppRec set to point to it) before returning.
70322 **
70323 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
70324 ** error if a value cannot be extracted from pExpr. If an error does
70325 ** occur, an SQLite error code is returned.
70326 */
70327 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
70328  Parse *pParse, /* Parse context */
70329  Index *pIdx, /* Index being probed */
70330  UnpackedRecord **ppRec, /* IN/OUT: Probe record */
70331  Expr *pExpr, /* The expression to extract a value from */
70332  int nElem, /* Maximum number of values to append */
70333  int iVal, /* Array element to populate */
70334  int *pnExtract /* OUT: Values appended to the record */
70335 ){
70336  int rc = SQLITE_OK;
70337  int nExtract = 0;
70338 
70339  if( pExpr==0 || pExpr->op!=TK_SELECT ){
70340  int i;
70341  struct ValueNewStat4Ctx alloc;
70342 
70343  alloc.pParse = pParse;
70344  alloc.pIdx = pIdx;
70345  alloc.ppRec = ppRec;
70346 
70347  for(i=0; i<nElem; i++){
70348  sqlite3_value *pVal = 0;
70349  Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
70350  u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
70351  alloc.iVal = iVal+i;
70352  rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
70353  if( !pVal ) break;
70354  nExtract++;
70355  }
70356  }
70357 
70358  *pnExtract = nExtract;
70359  return rc;
70360 }
70361 
70362 /*
70363 ** Attempt to extract a value from expression pExpr using the methods
70364 ** as described for sqlite3Stat4ProbeSetValue() above.
70365 **
70366 ** If successful, set *ppVal to point to a new value object and return
70367 ** SQLITE_OK. If no value can be extracted, but no other error occurs
70368 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
70369 ** does occur, return an SQLite error code. The final value of *ppVal
70370 ** is undefined in this case.
70371 */
70372 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
70373  Parse *pParse, /* Parse context */
70374  Expr *pExpr, /* The expression to extract a value from */
70375  u8 affinity, /* Affinity to use */
70376  sqlite3_value **ppVal /* OUT: New value object (or NULL) */
70377 ){
70378  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
70379 }
70380 
70381 /*
70382 ** Extract the iCol-th column from the nRec-byte record in pRec. Write
70383 ** the column value into *ppVal. If *ppVal is initially NULL then a new
70384 ** sqlite3_value object is allocated.
70385 **
70386 ** If *ppVal is initially NULL then the caller is responsible for
70387 ** ensuring that the value written into *ppVal is eventually freed.
70388 */
70389 SQLITE_PRIVATE int sqlite3Stat4Column(
70390  sqlite3 *db, /* Database handle */
70391  const void *pRec, /* Pointer to buffer containing record */
70392  int nRec, /* Size of buffer pRec in bytes */
70393  int iCol, /* Column to extract */
70394  sqlite3_value **ppVal /* OUT: Extracted value */
70395 ){
70396  u32 t; /* a column type code */
70397  int nHdr; /* Size of the header in the record */
70398  int iHdr; /* Next unread header byte */
70399  int iField; /* Next unread data byte */
70400  int szField; /* Size of the current data field */
70401  int i; /* Column index */
70402  u8 *a = (u8*)pRec; /* Typecast byte array */
70403  Mem *pMem = *ppVal; /* Write result into this Mem object */
70404 
70405  assert( iCol>0 );
70406  iHdr = getVarint32(a, nHdr);
70407  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
70408  iField = nHdr;
70409  for(i=0; i<=iCol; i++){
70410  iHdr += getVarint32(&a[iHdr], t);
70411  testcase( iHdr==nHdr );
70412  testcase( iHdr==nHdr+1 );
70413  if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
70414  szField = sqlite3VdbeSerialTypeLen(t);
70415  iField += szField;
70416  }
70417  testcase( iField==nRec );
70418  testcase( iField==nRec+1 );
70419  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
70420  if( pMem==0 ){
70421  pMem = *ppVal = sqlite3ValueNew(db);
70422  if( pMem==0 ) return SQLITE_NOMEM_BKPT;
70423  }
70424  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
70425  pMem->enc = ENC(db);
70426  return SQLITE_OK;
70427 }
70428 
70429 /*
70430 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
70431 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
70432 ** the object.
70433 */
70434 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
70435  if( pRec ){
70436  int i;
70437  int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
70438  Mem *aMem = pRec->aMem;
70439  sqlite3 *db = aMem[0].db;
70440  for(i=0; i<nCol; i++){
70441  sqlite3VdbeMemRelease(&aMem[i]);
70442  }
70443  sqlite3KeyInfoUnref(pRec->pKeyInfo);
70444  sqlite3DbFree(db, pRec);
70445  }
70446 }
70447 #endif /* ifdef SQLITE_ENABLE_STAT4 */
70448 
70449 /*
70450 ** Change the string value of an sqlite3_value object
70451 */
70452 SQLITE_PRIVATE void sqlite3ValueSetStr(
70453  sqlite3_value *v, /* Value to be set */
70454  int n, /* Length of string z */
70455  const void *z, /* Text of the new string */
70456  u8 enc, /* Encoding to use */
70457  void (*xDel)(void*) /* Destructor for the string */
70458 ){
70459  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
70460 }
70461 
70462 /*
70463 ** Free an sqlite3_value object
70464 */
70465 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
70466  if( !v ) return;
70467  sqlite3VdbeMemRelease((Mem *)v);
70468  sqlite3DbFree(((Mem*)v)->db, v);
70469 }
70470 
70471 /*
70472 ** The sqlite3ValueBytes() routine returns the number of bytes in the
70473 ** sqlite3_value object assuming that it uses the encoding "enc".
70474 ** The valueBytes() routine is a helper function.
70475 */
70476 static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
70477  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
70478 }
70479 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
70480  Mem *p = (Mem*)pVal;
70481  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
70482  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
70483  return p->n;
70484  }
70485  if( (p->flags & MEM_Blob)!=0 ){
70486  if( p->flags & MEM_Zero ){
70487  return p->n + p->u.nZero;
70488  }else{
70489  return p->n;
70490  }
70491  }
70492  if( p->flags & MEM_Null ) return 0;
70493  return valueBytes(pVal, enc);
70494 }
70495 
70496 /************** End of vdbemem.c *********************************************/
70497 /************** Begin file vdbeaux.c *****************************************/
70498 /*
70499 ** 2003 September 6
70500 **
70501 ** The author disclaims copyright to this source code. In place of
70502 ** a legal notice, here is a blessing:
70503 **
70504 ** May you do good and not evil.
70505 ** May you find forgiveness for yourself and forgive others.
70506 ** May you share freely, never taking more than you give.
70507 **
70508 *************************************************************************
70509 ** This file contains code used for creating, destroying, and populating
70510 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
70511 */
70512 /* #include "sqliteInt.h" */
70513 /* #include "vdbeInt.h" */
70514 
70515 /*
70516 ** Create a new virtual database engine.
70517 */
70518 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
70519  sqlite3 *db = pParse->db;
70520  Vdbe *p;
70521  p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
70522  if( p==0 ) return 0;
70523  memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
70524  p->db = db;
70525  if( db->pVdbe ){
70526  db->pVdbe->pPrev = p;
70527  }
70528  p->pNext = db->pVdbe;
70529  p->pPrev = 0;
70530  db->pVdbe = p;
70531  p->magic = VDBE_MAGIC_INIT;
70532  p->pParse = pParse;
70533  assert( pParse->aLabel==0 );
70534  assert( pParse->nLabel==0 );
70535  assert( pParse->nOpAlloc==0 );
70536  assert( pParse->szOpAlloc==0 );
70537  return p;
70538 }
70539 
70540 /*
70541 ** Change the error string stored in Vdbe.zErrMsg
70542 */
70543 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
70544  va_list ap;
70545  sqlite3DbFree(p->db, p->zErrMsg);
70546  va_start(ap, zFormat);
70547  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
70548  va_end(ap);
70549 }
70550 
70551 /*
70552 ** Remember the SQL string for a prepared statement.
70553 */
70554 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
70555  assert( isPrepareV2==1 || isPrepareV2==0 );
70556  if( p==0 ) return;
70557 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
70558  if( !isPrepareV2 ) return;
70559 #endif
70560  assert( p->zSql==0 );
70561  p->zSql = sqlite3DbStrNDup(p->db, z, n);
70562  p->isPrepareV2 = (u8)isPrepareV2;
70563 }
70564 
70565 /*
70566 ** Swap all content between two VDBE structures.
70567 */
70568 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
70569  Vdbe tmp, *pTmp;
70570  char *zTmp;
70571  assert( pA->db==pB->db );
70572  tmp = *pA;
70573  *pA = *pB;
70574  *pB = tmp;
70575  pTmp = pA->pNext;
70576  pA->pNext = pB->pNext;
70577  pB->pNext = pTmp;
70578  pTmp = pA->pPrev;
70579  pA->pPrev = pB->pPrev;
70580  pB->pPrev = pTmp;
70581  zTmp = pA->zSql;
70582  pA->zSql = pB->zSql;
70583  pB->zSql = zTmp;
70584  pB->isPrepareV2 = pA->isPrepareV2;
70585 }
70586 
70587 /*
70588 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
70589 ** than its current size. nOp is guaranteed to be less than or equal
70590 ** to 1024/sizeof(Op).
70591 **
70592 ** If an out-of-memory error occurs while resizing the array, return
70593 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
70594 ** unchanged (this is so that any opcodes already allocated can be
70595 ** correctly deallocated along with the rest of the Vdbe).
70596 */
70597 static int growOpArray(Vdbe *v, int nOp){
70598  VdbeOp *pNew;
70599  Parse *p = v->pParse;
70600 
70601  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
70602  ** more frequent reallocs and hence provide more opportunities for
70603  ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
70604  ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
70605  ** by the minimum* amount required until the size reaches 512. Normal
70606  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
70607  ** size of the op array or add 1KB of space, whichever is smaller. */
70608 #ifdef SQLITE_TEST_REALLOC_STRESS
70609  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
70610 #else
70611  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
70612  UNUSED_PARAMETER(nOp);
70613 #endif
70614 
70615  assert( nOp<=(1024/sizeof(Op)) );
70616  assert( nNew>=(p->nOpAlloc+nOp) );
70617  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
70618  if( pNew ){
70619  p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
70620  p->nOpAlloc = p->szOpAlloc/sizeof(Op);
70621  v->aOp = pNew;
70622  }
70623  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
70624 }
70625 
70626 #ifdef SQLITE_DEBUG
70627 /* This routine is just a convenient place to set a breakpoint that will
70628 ** fire after each opcode is inserted and displayed using
70629 ** "PRAGMA vdbe_addoptrace=on".
70630 */
70631 static void test_addop_breakpoint(void){
70632  static int n = 0;
70633  n++;
70634 }
70635 #endif
70636 
70637 /*
70638 ** Add a new instruction to the list of instructions current in the
70639 ** VDBE. Return the address of the new instruction.
70640 **
70641 ** Parameters:
70642 **
70643 ** p Pointer to the VDBE
70644 **
70645 ** op The opcode for this instruction
70646 **
70647 ** p1, p2, p3 Operands
70648 **
70649 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
70650 ** the sqlite3VdbeChangeP4() function to change the value of the P4
70651 ** operand.
70652 */
70653 static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
70654  assert( p->pParse->nOpAlloc<=p->nOp );
70655  if( growOpArray(p, 1) ) return 1;
70656  assert( p->pParse->nOpAlloc>p->nOp );
70657  return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70658 }
70659 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
70660  int i;
70661  VdbeOp *pOp;
70662 
70663  i = p->nOp;
70664  assert( p->magic==VDBE_MAGIC_INIT );
70665  assert( op>=0 && op<0xff );
70666  if( p->pParse->nOpAlloc<=i ){
70667  return growOp3(p, op, p1, p2, p3);
70668  }
70669  p->nOp++;
70670  pOp = &p->aOp[i];
70671  pOp->opcode = (u8)op;
70672  pOp->p5 = 0;
70673  pOp->p1 = p1;
70674  pOp->p2 = p2;
70675  pOp->p3 = p3;
70676  pOp->p4.p = 0;
70677  pOp->p4type = P4_NOTUSED;
70678 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
70679  pOp->zComment = 0;
70680 #endif
70681 #ifdef SQLITE_DEBUG
70682  if( p->db->flags & SQLITE_VdbeAddopTrace ){
70683  int jj, kk;
70684  Parse *pParse = p->pParse;
70685  for(jj=kk=0; jj<pParse->nColCache; jj++){
70686  struct yColCache *x = pParse->aColCache + jj;
70687  printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
70688  kk++;
70689  }
70690  if( kk ) printf("\n");
70691  sqlite3VdbePrintOp(0, i, &p->aOp[i]);
70692  test_addop_breakpoint();
70693  }
70694 #endif
70695 #ifdef VDBE_PROFILE
70696  pOp->cycles = 0;
70697  pOp->cnt = 0;
70698 #endif
70699 #ifdef SQLITE_VDBE_COVERAGE
70700  pOp->iSrcLine = 0;
70701 #endif
70702  return i;
70703 }
70704 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
70705  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
70706 }
70707 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
70708  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
70709 }
70710 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
70711  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
70712 }
70713 
70714 /* Generate code for an unconditional jump to instruction iDest
70715 */
70716 SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
70717  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
70718 }
70719 
70720 /* Generate code to cause the string zStr to be loaded into
70721 ** register iDest
70722 */
70723 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
70724  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
70725 }
70726 
70727 /*
70728 ** Generate code that initializes multiple registers to string or integer
70729 ** constants. The registers begin with iDest and increase consecutively.
70730 ** One register is initialized for each characgter in zTypes[]. For each
70731 ** "s" character in zTypes[], the register is a string if the argument is
70732 ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
70733 ** in zTypes[], the register is initialized to an integer.
70734 */
70735 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
70736  va_list ap;
70737  int i;
70738  char c;
70739  va_start(ap, zTypes);
70740  for(i=0; (c = zTypes[i])!=0; i++){
70741  if( c=='s' ){
70742  const char *z = va_arg(ap, const char*);
70743  sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
70744  }else{
70745  assert( c=='i' );
70746  sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
70747  }
70748  }
70749  va_end(ap);
70750 }
70751 
70752 /*
70753 ** Add an opcode that includes the p4 value as a pointer.
70754 */
70755 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
70756  Vdbe *p, /* Add the opcode to this VM */
70757  int op, /* The new opcode */
70758  int p1, /* The P1 operand */
70759  int p2, /* The P2 operand */
70760  int p3, /* The P3 operand */
70761  const char *zP4, /* The P4 operand */
70762  int p4type /* P4 operand type */
70763 ){
70764  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70765  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
70766  return addr;
70767 }
70768 
70769 /*
70770 ** Add an opcode that includes the p4 value with a P4_INT64 or
70771 ** P4_REAL type.
70772 */
70773 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
70774  Vdbe *p, /* Add the opcode to this VM */
70775  int op, /* The new opcode */
70776  int p1, /* The P1 operand */
70777  int p2, /* The P2 operand */
70778  int p3, /* The P3 operand */
70779  const u8 *zP4, /* The P4 operand */
70780  int p4type /* P4 operand type */
70781 ){
70782  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
70783  if( p4copy ) memcpy(p4copy, zP4, 8);
70784  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
70785 }
70786 
70787 /*
70788 ** Add an OP_ParseSchema opcode. This routine is broken out from
70789 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
70790 ** as having been used.
70791 **
70792 ** The zWhere string must have been obtained from sqlite3_malloc().
70793 ** This routine will take ownership of the allocated memory.
70794 */
70795 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
70796  int j;
70797  sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
70798  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
70799 }
70800 
70801 /*
70802 ** Add an opcode that includes the p4 value as an integer.
70803 */
70804 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
70805  Vdbe *p, /* Add the opcode to this VM */
70806  int op, /* The new opcode */
70807  int p1, /* The P1 operand */
70808  int p2, /* The P2 operand */
70809  int p3, /* The P3 operand */
70810  int p4 /* The P4 operand as an integer */
70811 ){
70812  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70813  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
70814  return addr;
70815 }
70816 
70817 /* Insert the end of a co-routine
70818 */
70819 SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
70820  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
70821 
70822  /* Clear the temporary register cache, thereby ensuring that each
70823  ** co-routine has its own independent set of registers, because co-routines
70824  ** might expect their registers to be preserved across an OP_Yield, and
70825  ** that could cause problems if two or more co-routines are using the same
70826  ** temporary register.
70827  */
70828  v->pParse->nTempReg = 0;
70829  v->pParse->nRangeReg = 0;
70830 }
70831 
70832 /*
70833 ** Create a new symbolic label for an instruction that has yet to be
70834 ** coded. The symbolic label is really just a negative number. The
70835 ** label can be used as the P2 value of an operation. Later, when
70836 ** the label is resolved to a specific address, the VDBE will scan
70837 ** through its operation list and change all values of P2 which match
70838 ** the label into the resolved address.
70839 **
70840 ** The VDBE knows that a P2 value is a label because labels are
70841 ** always negative and P2 values are suppose to be non-negative.
70842 ** Hence, a negative P2 value is a label that has yet to be resolved.
70843 **
70844 ** Zero is returned if a malloc() fails.
70845 */
70846 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
70847  Parse *p = v->pParse;
70848  int i = p->nLabel++;
70849  assert( v->magic==VDBE_MAGIC_INIT );
70850  if( (i & (i-1))==0 ){
70851  p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
70852  (i*2+1)*sizeof(p->aLabel[0]));
70853  }
70854  if( p->aLabel ){
70855  p->aLabel[i] = -1;
70856  }
70857  return ADDR(i);
70858 }
70859 
70860 /*
70861 ** Resolve label "x" to be the address of the next instruction to
70862 ** be inserted. The parameter "x" must have been obtained from
70863 ** a prior call to sqlite3VdbeMakeLabel().
70864 */
70865 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
70866  Parse *p = v->pParse;
70867  int j = ADDR(x);
70868  assert( v->magic==VDBE_MAGIC_INIT );
70869  assert( j<p->nLabel );
70870  assert( j>=0 );
70871  if( p->aLabel ){
70872  p->aLabel[j] = v->nOp;
70873  }
70874 }
70875 
70876 /*
70877 ** Mark the VDBE as one that can only be run one time.
70878 */
70879 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
70880  p->runOnlyOnce = 1;
70881 }
70882 
70883 /*
70884 ** Mark the VDBE as one that can only be run multiple times.
70885 */
70886 SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
70887  p->runOnlyOnce = 0;
70888 }
70889 
70890 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
70891 
70892 /*
70893 ** The following type and function are used to iterate through all opcodes
70894 ** in a Vdbe main program and each of the sub-programs (triggers) it may
70895 ** invoke directly or indirectly. It should be used as follows:
70896 **
70897 ** Op *pOp;
70898 ** VdbeOpIter sIter;
70899 **
70900 ** memset(&sIter, 0, sizeof(sIter));
70901 ** sIter.v = v; // v is of type Vdbe*
70902 ** while( (pOp = opIterNext(&sIter)) ){
70903 ** // Do something with pOp
70904 ** }
70905 ** sqlite3DbFree(v->db, sIter.apSub);
70906 **
70907 */
70908 typedef struct VdbeOpIter VdbeOpIter;
70909 struct VdbeOpIter {
70910  Vdbe *v; /* Vdbe to iterate through the opcodes of */
70911  SubProgram **apSub; /* Array of subprograms */
70912  int nSub; /* Number of entries in apSub */
70913  int iAddr; /* Address of next instruction to return */
70914  int iSub; /* 0 = main program, 1 = first sub-program etc. */
70915 };
70916 static Op *opIterNext(VdbeOpIter *p){
70917  Vdbe *v = p->v;
70918  Op *pRet = 0;
70919  Op *aOp;
70920  int nOp;
70921 
70922  if( p->iSub<=p->nSub ){
70923 
70924  if( p->iSub==0 ){
70925  aOp = v->aOp;
70926  nOp = v->nOp;
70927  }else{
70928  aOp = p->apSub[p->iSub-1]->aOp;
70929  nOp = p->apSub[p->iSub-1]->nOp;
70930  }
70931  assert( p->iAddr<nOp );
70932 
70933  pRet = &aOp[p->iAddr];
70934  p->iAddr++;
70935  if( p->iAddr==nOp ){
70936  p->iSub++;
70937  p->iAddr = 0;
70938  }
70939 
70940  if( pRet->p4type==P4_SUBPROGRAM ){
70941  int nByte = (p->nSub+1)*sizeof(SubProgram*);
70942  int j;
70943  for(j=0; j<p->nSub; j++){
70944  if( p->apSub[j]==pRet->p4.pProgram ) break;
70945  }
70946  if( j==p->nSub ){
70947  p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
70948  if( !p->apSub ){
70949  pRet = 0;
70950  }else{
70951  p->apSub[p->nSub++] = pRet->p4.pProgram;
70952  }
70953  }
70954  }
70955  }
70956 
70957  return pRet;
70958 }
70959 
70960 /*
70961 ** Check if the program stored in the VM associated with pParse may
70962 ** throw an ABORT exception (causing the statement, but not entire transaction
70963 ** to be rolled back). This condition is true if the main program or any
70964 ** sub-programs contains any of the following:
70965 **
70966 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70967 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70968 ** * OP_Destroy
70969 ** * OP_VUpdate
70970 ** * OP_VRename
70971 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
70972 ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
70973 **
70974 ** Then check that the value of Parse.mayAbort is true if an
70975 ** ABORT may be thrown, or false otherwise. Return true if it does
70976 ** match, or false otherwise. This function is intended to be used as
70977 ** part of an assert statement in the compiler. Similar to:
70978 **
70979 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
70980 */
70981 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
70982  int hasAbort = 0;
70983  int hasFkCounter = 0;
70984  int hasCreateTable = 0;
70985  int hasInitCoroutine = 0;
70986  Op *pOp;
70987  VdbeOpIter sIter;
70988  memset(&sIter, 0, sizeof(sIter));
70989  sIter.v = v;
70990 
70991  while( (pOp = opIterNext(&sIter))!=0 ){
70992  int opcode = pOp->opcode;
70993  if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
70994  || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
70995  && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
70996  ){
70997  hasAbort = 1;
70998  break;
70999  }
71000  if( opcode==OP_CreateTable ) hasCreateTable = 1;
71001  if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
71002 #ifndef SQLITE_OMIT_FOREIGN_KEY
71003  if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
71004  hasFkCounter = 1;
71005  }
71006 #endif
71007  }
71008  sqlite3DbFree(v->db, sIter.apSub);
71009 
71010  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
71011  ** If malloc failed, then the while() loop above may not have iterated
71012  ** through all opcodes and hasAbort may be set incorrectly. Return
71013  ** true for this case to prevent the assert() in the callers frame
71014  ** from failing. */
71015  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
71016  || (hasCreateTable && hasInitCoroutine) );
71017 }
71018 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
71019 
71020 /*
71021 ** This routine is called after all opcodes have been inserted. It loops
71022 ** through all the opcodes and fixes up some details.
71023 **
71024 ** (1) For each jump instruction with a negative P2 value (a label)
71025 ** resolve the P2 value to an actual address.
71026 **
71027 ** (2) Compute the maximum number of arguments used by any SQL function
71028 ** and store that value in *pMaxFuncArgs.
71029 **
71030 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
71031 ** indicate what the prepared statement actually does.
71032 **
71033 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
71034 **
71035 ** (5) Reclaim the memory allocated for storing labels.
71036 **
71037 ** This routine will only function correctly if the mkopcodeh.tcl generator
71038 ** script numbers the opcodes correctly. Changes to this routine must be
71039 ** coordinated with changes to mkopcodeh.tcl.
71040 */
71041 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
71042  int nMaxArgs = *pMaxFuncArgs;
71043  Op *pOp;
71044  Parse *pParse = p->pParse;
71045  int *aLabel = pParse->aLabel;
71046  p->readOnly = 1;
71047  p->bIsReader = 0;
71048  pOp = &p->aOp[p->nOp-1];
71049  while(1){
71050 
71051  /* Only JUMP opcodes and the short list of special opcodes in the switch
71052  ** below need to be considered. The mkopcodeh.tcl generator script groups
71053  ** all these opcodes together near the front of the opcode list. Skip
71054  ** any opcode that does not need processing by virtual of the fact that
71055  ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
71056  */
71057  if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
71058  /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
71059  ** cases from this switch! */
71060  switch( pOp->opcode ){
71061  case OP_Transaction: {
71062  if( pOp->p2!=0 ) p->readOnly = 0;
71063  /* fall thru */
71064  }
71065  case OP_AutoCommit:
71066  case OP_Savepoint: {
71067  p->bIsReader = 1;
71068  break;
71069  }
71070 #ifndef SQLITE_OMIT_WAL
71071  case OP_Checkpoint:
71072 #endif
71073  case OP_Vacuum:
71074  case OP_JournalMode: {
71075  p->readOnly = 0;
71076  p->bIsReader = 1;
71077  break;
71078  }
71079 #ifndef SQLITE_OMIT_VIRTUALTABLE
71080  case OP_VUpdate: {
71081  if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
71082  break;
71083  }
71084  case OP_VFilter: {
71085  int n;
71086  assert( (pOp - p->aOp) >= 3 );
71087  assert( pOp[-1].opcode==OP_Integer );
71088  n = pOp[-1].p1;
71089  if( n>nMaxArgs ) nMaxArgs = n;
71090  break;
71091  }
71092 #endif
71093  case OP_Next:
71094  case OP_NextIfOpen:
71095  case OP_SorterNext: {
71096  pOp->p4.xAdvance = sqlite3BtreeNext;
71097  pOp->p4type = P4_ADVANCE;
71098  break;
71099  }
71100  case OP_Prev:
71101  case OP_PrevIfOpen: {
71102  pOp->p4.xAdvance = sqlite3BtreePrevious;
71103  pOp->p4type = P4_ADVANCE;
71104  break;
71105  }
71106  }
71107  if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
71108  assert( ADDR(pOp->p2)<pParse->nLabel );
71109  pOp->p2 = aLabel[ADDR(pOp->p2)];
71110  }
71111  }
71112  if( pOp==p->aOp ) break;
71113  pOp--;
71114  }
71115  sqlite3DbFree(p->db, pParse->aLabel);
71116  pParse->aLabel = 0;
71117  pParse->nLabel = 0;
71118  *pMaxFuncArgs = nMaxArgs;
71119  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
71120 }
71121 
71122 /*
71123 ** Return the address of the next instruction to be inserted.
71124 */
71125 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
71126  assert( p->magic==VDBE_MAGIC_INIT );
71127  return p->nOp;
71128 }
71129 
71130 /*
71131 ** Verify that at least N opcode slots are available in p without
71132 ** having to malloc for more space (except when compiled using
71133 ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
71134 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
71135 ** fail due to a OOM fault and hence that the return value from
71136 ** sqlite3VdbeAddOpList() will always be non-NULL.
71137 */
71138 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
71139 SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
71140  assert( p->nOp + N <= p->pParse->nOpAlloc );
71141 }
71142 #endif
71143 
71144 /*
71145 ** This function returns a pointer to the array of opcodes associated with
71146 ** the Vdbe passed as the first argument. It is the callers responsibility
71147 ** to arrange for the returned array to be eventually freed using the
71148 ** vdbeFreeOpArray() function.
71149 **
71150 ** Before returning, *pnOp is set to the number of entries in the returned
71151 ** array. Also, *pnMaxArg is set to the larger of its current value and
71152 ** the number of entries in the Vdbe.apArg[] array required to execute the
71153 ** returned program.
71154 */
71155 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
71156  VdbeOp *aOp = p->aOp;
71157  assert( aOp && !p->db->mallocFailed );
71158 
71159  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
71160  assert( DbMaskAllZero(p->btreeMask) );
71161 
71162  resolveP2Values(p, pnMaxArg);
71163  *pnOp = p->nOp;
71164  p->aOp = 0;
71165  return aOp;
71166 }
71167 
71168 /*
71169 ** Add a whole list of operations to the operation stack. Return a
71170 ** pointer to the first operation inserted.
71171 **
71172 ** Non-zero P2 arguments to jump instructions are automatically adjusted
71173 ** so that the jump target is relative to the first operation inserted.
71174 */
71175 SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
71176  Vdbe *p, /* Add opcodes to the prepared statement */
71177  int nOp, /* Number of opcodes to add */
71178  VdbeOpList const *aOp, /* The opcodes to be added */
71179  int iLineno /* Source-file line number of first opcode */
71180 ){
71181  int i;
71182  VdbeOp *pOut, *pFirst;
71183  assert( nOp>0 );
71184  assert( p->magic==VDBE_MAGIC_INIT );
71185  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
71186  return 0;
71187  }
71188  pFirst = pOut = &p->aOp[p->nOp];
71189  for(i=0; i<nOp; i++, aOp++, pOut++){
71190  pOut->opcode = aOp->opcode;
71191  pOut->p1 = aOp->p1;
71192  pOut->p2 = aOp->p2;
71193  assert( aOp->p2>=0 );
71194  if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
71195  pOut->p2 += p->nOp;
71196  }
71197  pOut->p3 = aOp->p3;
71198  pOut->p4type = P4_NOTUSED;
71199  pOut->p4.p = 0;
71200  pOut->p5 = 0;
71201 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71202  pOut->zComment = 0;
71203 #endif
71204 #ifdef SQLITE_VDBE_COVERAGE
71205  pOut->iSrcLine = iLineno+i;
71206 #else
71207  (void)iLineno;
71208 #endif
71209 #ifdef SQLITE_DEBUG
71210  if( p->db->flags & SQLITE_VdbeAddopTrace ){
71211  sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
71212  }
71213 #endif
71214  }
71215  p->nOp += nOp;
71216  return pFirst;
71217 }
71218 
71219 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
71220 /*
71221 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
71222 */
71223 SQLITE_PRIVATE void sqlite3VdbeScanStatus(
71224  Vdbe *p, /* VM to add scanstatus() to */
71225  int addrExplain, /* Address of OP_Explain (or 0) */
71226  int addrLoop, /* Address of loop counter */
71227  int addrVisit, /* Address of rows visited counter */
71228  LogEst nEst, /* Estimated number of output rows */
71229  const char *zName /* Name of table or index being scanned */
71230 ){
71231  int nByte = (p->nScan+1) * sizeof(ScanStatus);
71232  ScanStatus *aNew;
71233  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
71234  if( aNew ){
71235  ScanStatus *pNew = &aNew[p->nScan++];
71236  pNew->addrExplain = addrExplain;
71237  pNew->addrLoop = addrLoop;
71238  pNew->addrVisit = addrVisit;
71239  pNew->nEst = nEst;
71240  pNew->zName = sqlite3DbStrDup(p->db, zName);
71241  p->aScan = aNew;
71242  }
71243 }
71244 #endif
71245 
71246 
71247 /*
71248 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
71249 ** for a specific instruction.
71250 */
71251 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
71252  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
71253 }
71254 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
71255  sqlite3VdbeGetOp(p,addr)->p1 = val;
71256 }
71257 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
71258  sqlite3VdbeGetOp(p,addr)->p2 = val;
71259 }
71260 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
71261  sqlite3VdbeGetOp(p,addr)->p3 = val;
71262 }
71263 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
71264  assert( p->nOp>0 || p->db->mallocFailed );
71265  if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
71266 }
71267 
71268 /*
71269 ** Change the P2 operand of instruction addr so that it points to
71270 ** the address of the next instruction to be coded.
71271 */
71272 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
71273  sqlite3VdbeChangeP2(p, addr, p->nOp);
71274 }
71275 
71276 
71277 /*
71278 ** If the input FuncDef structure is ephemeral, then free it. If
71279 ** the FuncDef is not ephermal, then do nothing.
71280 */
71281 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
71282  if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
71283  sqlite3DbFree(db, pDef);
71284  }
71285 }
71286 
71287 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
71288 
71289 /*
71290 ** Delete a P4 value if necessary.
71291 */
71292 static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
71293  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71294  sqlite3DbFree(db, p);
71295 }
71296 static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
71297  freeEphemeralFunction(db, p->pFunc);
71298  sqlite3DbFree(db, p);
71299 }
71300 static void freeP4(sqlite3 *db, int p4type, void *p4){
71301  assert( db );
71302  switch( p4type ){
71303  case P4_FUNCCTX: {
71304  freeP4FuncCtx(db, (sqlite3_context*)p4);
71305  break;
71306  }
71307  case P4_REAL:
71308  case P4_INT64:
71309  case P4_DYNAMIC:
71310  case P4_INTARRAY: {
71311  sqlite3DbFree(db, p4);
71312  break;
71313  }
71314  case P4_KEYINFO: {
71315  if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
71316  break;
71317  }
71318 #ifdef SQLITE_ENABLE_CURSOR_HINTS
71319  case P4_EXPR: {
71320  sqlite3ExprDelete(db, (Expr*)p4);
71321  break;
71322  }
71323 #endif
71324  case P4_MPRINTF: {
71325  if( db->pnBytesFreed==0 ) sqlite3_free(p4);
71326  break;
71327  }
71328  case P4_FUNCDEF: {
71329  freeEphemeralFunction(db, (FuncDef*)p4);
71330  break;
71331  }
71332  case P4_MEM: {
71333  if( db->pnBytesFreed==0 ){
71334  sqlite3ValueFree((sqlite3_value*)p4);
71335  }else{
71336  freeP4Mem(db, (Mem*)p4);
71337  }
71338  break;
71339  }
71340  case P4_VTAB : {
71341  if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
71342  break;
71343  }
71344  }
71345 }
71346 
71347 /*
71348 ** Free the space allocated for aOp and any p4 values allocated for the
71349 ** opcodes contained within. If aOp is not NULL it is assumed to contain
71350 ** nOp entries.
71351 */
71352 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
71353  if( aOp ){
71354  Op *pOp;
71355  for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
71356  if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
71357 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71358  sqlite3DbFree(db, pOp->zComment);
71359 #endif
71360  }
71361  }
71362  sqlite3DbFree(db, aOp);
71363 }
71364 
71365 /*
71366 ** Link the SubProgram object passed as the second argument into the linked
71367 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
71368 ** objects when the VM is no longer required.
71369 */
71370 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
71371  p->pNext = pVdbe->pProgram;
71372  pVdbe->pProgram = p;
71373 }
71374 
71375 /*
71376 ** Change the opcode at addr into OP_Noop
71377 */
71378 SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
71379  VdbeOp *pOp;
71380  if( p->db->mallocFailed ) return 0;
71381  assert( addr>=0 && addr<p->nOp );
71382  pOp = &p->aOp[addr];
71383  freeP4(p->db, pOp->p4type, pOp->p4.p);
71384  pOp->p4type = P4_NOTUSED;
71385  pOp->p4.z = 0;
71386  pOp->opcode = OP_Noop;
71387  return 1;
71388 }
71389 
71390 /*
71391 ** If the last opcode is "op" and it is not a jump destination,
71392 ** then remove it. Return true if and only if an opcode was removed.
71393 */
71394 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
71395  if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
71396  return sqlite3VdbeChangeToNoop(p, p->nOp-1);
71397  }else{
71398  return 0;
71399  }
71400 }
71401 
71402 /*
71403 ** Change the value of the P4 operand for a specific instruction.
71404 ** This routine is useful when a large program is loaded from a
71405 ** static array using sqlite3VdbeAddOpList but we want to make a
71406 ** few minor changes to the program.
71407 **
71408 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
71409 ** the string is made into memory obtained from sqlite3_malloc().
71410 ** A value of n==0 means copy bytes of zP4 up to and including the
71411 ** first null byte. If n>0 then copy n+1 bytes of zP4.
71412 **
71413 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
71414 ** to a string or structure that is guaranteed to exist for the lifetime of
71415 ** the Vdbe. In these cases we can just copy the pointer.
71416 **
71417 ** If addr<0 then change P4 on the most recently inserted instruction.
71418 */
71419 static void SQLITE_NOINLINE vdbeChangeP4Full(
71420  Vdbe *p,
71421  Op *pOp,
71422  const char *zP4,
71423  int n
71424 ){
71425  if( pOp->p4type ){
71426  freeP4(p->db, pOp->p4type, pOp->p4.p);
71427  pOp->p4type = 0;
71428  pOp->p4.p = 0;
71429  }
71430  if( n<0 ){
71431  sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
71432  }else{
71433  if( n==0 ) n = sqlite3Strlen30(zP4);
71434  pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
71435  pOp->p4type = P4_DYNAMIC;
71436  }
71437 }
71438 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
71439  Op *pOp;
71440  sqlite3 *db;
71441  assert( p!=0 );
71442  db = p->db;
71443  assert( p->magic==VDBE_MAGIC_INIT );
71444  assert( p->aOp!=0 || db->mallocFailed );
71445  if( db->mallocFailed ){
71446  if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
71447  return;
71448  }
71449  assert( p->nOp>0 );
71450  assert( addr<p->nOp );
71451  if( addr<0 ){
71452  addr = p->nOp - 1;
71453  }
71454  pOp = &p->aOp[addr];
71455  if( n>=0 || pOp->p4type ){
71456  vdbeChangeP4Full(p, pOp, zP4, n);
71457  return;
71458  }
71459  if( n==P4_INT32 ){
71460  /* Note: this cast is safe, because the origin data point was an int
71461  ** that was cast to a (const char *). */
71462  pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
71463  pOp->p4type = P4_INT32;
71464  }else if( zP4!=0 ){
71465  assert( n<0 );
71466  pOp->p4.p = (void*)zP4;
71467  pOp->p4type = (signed char)n;
71468  if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
71469  }
71470 }
71471 
71472 /*
71473 ** Set the P4 on the most recently added opcode to the KeyInfo for the
71474 ** index given.
71475 */
71476 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
71477  Vdbe *v = pParse->pVdbe;
71478  assert( v!=0 );
71479  assert( pIdx!=0 );
71480  sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
71481  P4_KEYINFO);
71482 }
71483 
71484 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71485 /*
71486 ** Change the comment on the most recently coded instruction. Or
71487 ** insert a No-op and add the comment to that new instruction. This
71488 ** makes the code easier to read during debugging. None of this happens
71489 ** in a production build.
71490 */
71491 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
71492  assert( p->nOp>0 || p->aOp==0 );
71493  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
71494  if( p->nOp ){
71495  assert( p->aOp );
71496  sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
71497  p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
71498  }
71499 }
71500 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
71501  va_list ap;
71502  if( p ){
71503  va_start(ap, zFormat);
71504  vdbeVComment(p, zFormat, ap);
71505  va_end(ap);
71506  }
71507 }
71508 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
71509  va_list ap;
71510  if( p ){
71511  sqlite3VdbeAddOp0(p, OP_Noop);
71512  va_start(ap, zFormat);
71513  vdbeVComment(p, zFormat, ap);
71514  va_end(ap);
71515  }
71516 }
71517 #endif /* NDEBUG */
71518 
71519 #ifdef SQLITE_VDBE_COVERAGE
71520 /*
71521 ** Set the value if the iSrcLine field for the previously coded instruction.
71522 */
71523 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
71524  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
71525 }
71526 #endif /* SQLITE_VDBE_COVERAGE */
71527 
71528 /*
71529 ** Return the opcode for a given address. If the address is -1, then
71530 ** return the most recently inserted opcode.
71531 **
71532 ** If a memory allocation error has occurred prior to the calling of this
71533 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
71534 ** is readable but not writable, though it is cast to a writable value.
71535 ** The return of a dummy opcode allows the call to continue functioning
71536 ** after an OOM fault without having to check to see if the return from
71537 ** this routine is a valid pointer. But because the dummy.opcode is 0,
71538 ** dummy will never be written to. This is verified by code inspection and
71539 ** by running with Valgrind.
71540 */
71541 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
71542  /* C89 specifies that the constant "dummy" will be initialized to all
71543  ** zeros, which is correct. MSVC generates a warning, nevertheless. */
71544  static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
71545  assert( p->magic==VDBE_MAGIC_INIT );
71546  if( addr<0 ){
71547  addr = p->nOp - 1;
71548  }
71549  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
71550  if( p->db->mallocFailed ){
71551  return (VdbeOp*)&dummy;
71552  }else{
71553  return &p->aOp[addr];
71554  }
71555 }
71556 
71557 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
71558 /*
71559 ** Return an integer value for one of the parameters to the opcode pOp
71560 ** determined by character c.
71561 */
71562 static int translateP(char c, const Op *pOp){
71563  if( c=='1' ) return pOp->p1;
71564  if( c=='2' ) return pOp->p2;
71565  if( c=='3' ) return pOp->p3;
71566  if( c=='4' ) return pOp->p4.i;
71567  return pOp->p5;
71568 }
71569 
71570 /*
71571 ** Compute a string for the "comment" field of a VDBE opcode listing.
71572 **
71573 ** The Synopsis: field in comments in the vdbe.c source file gets converted
71574 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
71575 ** absence of other comments, this synopsis becomes the comment on the opcode.
71576 ** Some translation occurs:
71577 **
71578 ** "PX" -> "r[X]"
71579 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
71580 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
71581 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
71582 */
71583 static int displayComment(
71584  const Op *pOp, /* The opcode to be commented */
71585  const char *zP4, /* Previously obtained value for P4 */
71586  char *zTemp, /* Write result here */
71587  int nTemp /* Space available in zTemp[] */
71588 ){
71589  const char *zOpName;
71590  const char *zSynopsis;
71591  int nOpName;
71592  int ii, jj;
71593  char zAlt[50];
71594  zOpName = sqlite3OpcodeName(pOp->opcode);
71595  nOpName = sqlite3Strlen30(zOpName);
71596  if( zOpName[nOpName+1] ){
71597  int seenCom = 0;
71598  char c;
71599  zSynopsis = zOpName += nOpName + 1;
71600  if( strncmp(zSynopsis,"IF ",3)==0 ){
71601  if( pOp->p5 & SQLITE_STOREP2 ){
71602  sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
71603  }else{
71604  sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
71605  }
71606  zSynopsis = zAlt;
71607  }
71608  for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
71609  if( c=='P' ){
71610  c = zSynopsis[++ii];
71611  if( c=='4' ){
71612  sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
71613  }else if( c=='X' ){
71614  sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
71615  seenCom = 1;
71616  }else{
71617  int v1 = translateP(c, pOp);
71618  int v2;
71619  sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
71620  if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
71621  ii += 3;
71622  jj += sqlite3Strlen30(zTemp+jj);
71623  v2 = translateP(zSynopsis[ii], pOp);
71624  if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
71625  ii += 2;
71626  v2++;
71627  }
71628  if( v2>1 ){
71629  sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
71630  }
71631  }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
71632  ii += 4;
71633  }
71634  }
71635  jj += sqlite3Strlen30(zTemp+jj);
71636  }else{
71637  zTemp[jj++] = c;
71638  }
71639  }
71640  if( !seenCom && jj<nTemp-5 && pOp->zComment ){
71641  sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
71642  jj += sqlite3Strlen30(zTemp+jj);
71643  }
71644  if( jj<nTemp ) zTemp[jj] = 0;
71645  }else if( pOp->zComment ){
71646  sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
71647  jj = sqlite3Strlen30(zTemp);
71648  }else{
71649  zTemp[0] = 0;
71650  jj = 0;
71651  }
71652  return jj;
71653 }
71654 #endif /* SQLITE_DEBUG */
71655 
71656 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
71657 /*
71658 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
71659 ** that can be displayed in the P4 column of EXPLAIN output.
71660 */
71661 static void displayP4Expr(StrAccum *p, Expr *pExpr){
71662  const char *zOp = 0;
71663  switch( pExpr->op ){
71664  case TK_STRING:
71665  sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
71666  break;
71667  case TK_INTEGER:
71668  sqlite3XPrintf(p, "%d", pExpr->u.iValue);
71669  break;
71670  case TK_NULL:
71671  sqlite3XPrintf(p, "NULL");
71672  break;
71673  case TK_REGISTER: {
71674  sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
71675  break;
71676  }
71677  case TK_COLUMN: {
71678  if( pExpr->iColumn<0 ){
71679  sqlite3XPrintf(p, "rowid");
71680  }else{
71681  sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
71682  }
71683  break;
71684  }
71685  case TK_LT: zOp = "LT"; break;
71686  case TK_LE: zOp = "LE"; break;
71687  case TK_GT: zOp = "GT"; break;
71688  case TK_GE: zOp = "GE"; break;
71689  case TK_NE: zOp = "NE"; break;
71690  case TK_EQ: zOp = "EQ"; break;
71691  case TK_IS: zOp = "IS"; break;
71692  case TK_ISNOT: zOp = "ISNOT"; break;
71693  case TK_AND: zOp = "AND"; break;
71694  case TK_OR: zOp = "OR"; break;
71695  case TK_PLUS: zOp = "ADD"; break;
71696  case TK_STAR: zOp = "MUL"; break;
71697  case TK_MINUS: zOp = "SUB"; break;
71698  case TK_REM: zOp = "REM"; break;
71699  case TK_BITAND: zOp = "BITAND"; break;
71700  case TK_BITOR: zOp = "BITOR"; break;
71701  case TK_SLASH: zOp = "DIV"; break;
71702  case TK_LSHIFT: zOp = "LSHIFT"; break;
71703  case TK_RSHIFT: zOp = "RSHIFT"; break;
71704  case TK_CONCAT: zOp = "CONCAT"; break;
71705  case TK_UMINUS: zOp = "MINUS"; break;
71706  case TK_UPLUS: zOp = "PLUS"; break;
71707  case TK_BITNOT: zOp = "BITNOT"; break;
71708  case TK_NOT: zOp = "NOT"; break;
71709  case TK_ISNULL: zOp = "ISNULL"; break;
71710  case TK_NOTNULL: zOp = "NOTNULL"; break;
71711 
71712  default:
71713  sqlite3XPrintf(p, "%s", "expr");
71714  break;
71715  }
71716 
71717  if( zOp ){
71718  sqlite3XPrintf(p, "%s(", zOp);
71719  displayP4Expr(p, pExpr->pLeft);
71720  if( pExpr->pRight ){
71721  sqlite3StrAccumAppend(p, ",", 1);
71722  displayP4Expr(p, pExpr->pRight);
71723  }
71724  sqlite3StrAccumAppend(p, ")", 1);
71725  }
71726 }
71727 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
71728 
71729 
71730 #if VDBE_DISPLAY_P4
71731 /*
71732 ** Compute a string that describes the P4 parameter for an opcode.
71733 ** Use zTemp for any required temporary buffer space.
71734 */
71735 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
71736  char *zP4 = zTemp;
71737  StrAccum x;
71738  assert( nTemp>=20 );
71739  sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
71740  switch( pOp->p4type ){
71741  case P4_KEYINFO: {
71742  int j;
71743  KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
71744  assert( pKeyInfo->aSortOrder!=0 );
71745  sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
71746  for(j=0; j<pKeyInfo->nField; j++){
71747  CollSeq *pColl = pKeyInfo->aColl[j];
71748  const char *zColl = pColl ? pColl->zName : "";
71749  if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
71750  sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
71751  }
71752  sqlite3StrAccumAppend(&x, ")", 1);
71753  break;
71754  }
71755 #ifdef SQLITE_ENABLE_CURSOR_HINTS
71756  case P4_EXPR: {
71757  displayP4Expr(&x, pOp->p4.pExpr);
71758  break;
71759  }
71760 #endif
71761  case P4_COLLSEQ: {
71762  CollSeq *pColl = pOp->p4.pColl;
71763  sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
71764  break;
71765  }
71766  case P4_FUNCDEF: {
71767  FuncDef *pDef = pOp->p4.pFunc;
71768  sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71769  break;
71770  }
71771 #ifdef SQLITE_DEBUG
71772  case P4_FUNCCTX: {
71773  FuncDef *pDef = pOp->p4.pCtx->pFunc;
71774  sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71775  break;
71776  }
71777 #endif
71778  case P4_INT64: {
71779  sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
71780  break;
71781  }
71782  case P4_INT32: {
71783  sqlite3XPrintf(&x, "%d", pOp->p4.i);
71784  break;
71785  }
71786  case P4_REAL: {
71787  sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
71788  break;
71789  }
71790  case P4_MEM: {
71791  Mem *pMem = pOp->p4.pMem;
71792  if( pMem->flags & MEM_Str ){
71793  zP4 = pMem->z;
71794  }else if( pMem->flags & MEM_Int ){
71795  sqlite3XPrintf(&x, "%lld", pMem->u.i);
71796  }else if( pMem->flags & MEM_Real ){
71797  sqlite3XPrintf(&x, "%.16g", pMem->u.r);
71798  }else if( pMem->flags & MEM_Null ){
71799  zP4 = "NULL";
71800  }else{
71801  assert( pMem->flags & MEM_Blob );
71802  zP4 = "(blob)";
71803  }
71804  break;
71805  }
71806 #ifndef SQLITE_OMIT_VIRTUALTABLE
71807  case P4_VTAB: {
71808  sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
71809  sqlite3XPrintf(&x, "vtab:%p", pVtab);
71810  break;
71811  }
71812 #endif
71813  case P4_INTARRAY: {
71814  int i;
71815  int *ai = pOp->p4.ai;
71816  int n = ai[0]; /* The first element of an INTARRAY is always the
71817  ** count of the number of elements to follow */
71818  for(i=1; i<n; i++){
71819  sqlite3XPrintf(&x, ",%d", ai[i]);
71820  }
71821  zTemp[0] = '[';
71822  sqlite3StrAccumAppend(&x, "]", 1);
71823  break;
71824  }
71825  case P4_SUBPROGRAM: {
71826  sqlite3XPrintf(&x, "program");
71827  break;
71828  }
71829  case P4_ADVANCE: {
71830  zTemp[0] = 0;
71831  break;
71832  }
71833  case P4_TABLE: {
71834  sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
71835  break;
71836  }
71837  default: {
71838  zP4 = pOp->p4.z;
71839  if( zP4==0 ){
71840  zP4 = zTemp;
71841  zTemp[0] = 0;
71842  }
71843  }
71844  }
71845  sqlite3StrAccumFinish(&x);
71846  assert( zP4!=0 );
71847  return zP4;
71848 }
71849 #endif /* VDBE_DISPLAY_P4 */
71850 
71851 /*
71852 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
71853 **
71854 ** The prepared statements need to know in advance the complete set of
71855 ** attached databases that will be use. A mask of these databases
71856 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
71857 ** p->btreeMask of databases that will require a lock.
71858 */
71859 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
71860  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
71861  assert( i<(int)sizeof(p->btreeMask)*8 );
71862  DbMaskSet(p->btreeMask, i);
71863  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
71864  DbMaskSet(p->lockMask, i);
71865  }
71866 }
71867 
71868 #if !defined(SQLITE_OMIT_SHARED_CACHE)
71869 /*
71870 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
71871 ** this routine obtains the mutex associated with each BtShared structure
71872 ** that may be accessed by the VM passed as an argument. In doing so it also
71873 ** sets the BtShared.db member of each of the BtShared structures, ensuring
71874 ** that the correct busy-handler callback is invoked if required.
71875 **
71876 ** If SQLite is not threadsafe but does support shared-cache mode, then
71877 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
71878 ** of all of BtShared structures accessible via the database handle
71879 ** associated with the VM.
71880 **
71881 ** If SQLite is not threadsafe and does not support shared-cache mode, this
71882 ** function is a no-op.
71883 **
71884 ** The p->btreeMask field is a bitmask of all btrees that the prepared
71885 ** statement p will ever use. Let N be the number of bits in p->btreeMask
71886 ** corresponding to btrees that use shared cache. Then the runtime of
71887 ** this routine is N*N. But as N is rarely more than 1, this should not
71888 ** be a problem.
71889 */
71890 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
71891  int i;
71892  sqlite3 *db;
71893  Db *aDb;
71894  int nDb;
71895  if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
71896  db = p->db;
71897  aDb = db->aDb;
71898  nDb = db->nDb;
71899  for(i=0; i<nDb; i++){
71900  if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71901  sqlite3BtreeEnter(aDb[i].pBt);
71902  }
71903  }
71904 }
71905 #endif
71906 
71907 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
71908 /*
71909 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
71910 */
71911 static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
71912  int i;
71913  sqlite3 *db;
71914  Db *aDb;
71915  int nDb;
71916  db = p->db;
71917  aDb = db->aDb;
71918  nDb = db->nDb;
71919  for(i=0; i<nDb; i++){
71920  if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71921  sqlite3BtreeLeave(aDb[i].pBt);
71922  }
71923  }
71924 }
71925 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
71926  if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
71927  vdbeLeave(p);
71928 }
71929 #endif
71930 
71931 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
71932 /*
71933 ** Print a single opcode. This routine is used for debugging only.
71934 */
71935 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
71936  char *zP4;
71937  char zPtr[50];
71938  char zCom[100];
71939  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
71940  if( pOut==0 ) pOut = stdout;
71941  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
71942 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71943  displayComment(pOp, zP4, zCom, sizeof(zCom));
71944 #else
71945  zCom[0] = 0;
71946 #endif
71947  /* NB: The sqlite3OpcodeName() function is implemented by code created
71948  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
71949  ** information from the vdbe.c source text */
71950  fprintf(pOut, zFormat1, pc,
71951  sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
71952  zCom
71953  );
71954  fflush(pOut);
71955 }
71956 #endif
71957 
71958 /*
71959 ** Initialize an array of N Mem element.
71960 */
71961 static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
71962  while( (N--)>0 ){
71963  p->db = db;
71964  p->flags = flags;
71965  p->szMalloc = 0;
71966 #ifdef SQLITE_DEBUG
71967  p->pScopyFrom = 0;
71968 #endif
71969  p++;
71970  }
71971 }
71972 
71973 /*
71974 ** Release an array of N Mem elements
71975 */
71976 static void releaseMemArray(Mem *p, int N){
71977  if( p && N ){
71978  Mem *pEnd = &p[N];
71979  sqlite3 *db = p->db;
71980  if( db->pnBytesFreed ){
71981  do{
71982  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71983  }while( (++p)<pEnd );
71984  return;
71985  }
71986  do{
71987  assert( (&p[1])==pEnd || p[0].db==p[1].db );
71988  assert( sqlite3VdbeCheckMemInvariants(p) );
71989 
71990  /* This block is really an inlined version of sqlite3VdbeMemRelease()
71991  ** that takes advantage of the fact that the memory cell value is
71992  ** being set to NULL after releasing any dynamic resources.
71993  **
71994  ** The justification for duplicating code is that according to
71995  ** callgrind, this causes a certain test case to hit the CPU 4.7
71996  ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
71997  ** sqlite3MemRelease() were called from here. With -O2, this jumps
71998  ** to 6.6 percent. The test case is inserting 1000 rows into a table
71999  ** with no indexes using a single prepared INSERT statement, bind()
72000  ** and reset(). Inserts are grouped into a transaction.
72001  */
72002  testcase( p->flags & MEM_Agg );
72003  testcase( p->flags & MEM_Dyn );
72004  testcase( p->flags & MEM_Frame );
72005  testcase( p->flags & MEM_RowSet );
72006  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
72007  sqlite3VdbeMemRelease(p);
72008  }else if( p->szMalloc ){
72009  sqlite3DbFree(db, p->zMalloc);
72010  p->szMalloc = 0;
72011  }
72012 
72013  p->flags = MEM_Undefined;
72014  }while( (++p)<pEnd );
72015  }
72016 }
72017 
72018 /*
72019 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
72020 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
72021 */
72022 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
72023  int i;
72024  Mem *aMem = VdbeFrameMem(p);
72025  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
72026  for(i=0; i<p->nChildCsr; i++){
72027  sqlite3VdbeFreeCursor(p->v, apCsr[i]);
72028  }
72029  releaseMemArray(aMem, p->nChildMem);
72030  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
72031  sqlite3DbFree(p->v->db, p);
72032 }
72033 
72034 #ifndef SQLITE_OMIT_EXPLAIN
72035 /*
72036 ** Give a listing of the program in the virtual machine.
72037 **
72038 ** The interface is the same as sqlite3VdbeExec(). But instead of
72039 ** running the code, it invokes the callback once for each instruction.
72040 ** This feature is used to implement "EXPLAIN".
72041 **
72042 ** When p->explain==1, each instruction is listed. When
72043 ** p->explain==2, only OP_Explain instructions are listed and these
72044 ** are shown in a different format. p->explain==2 is used to implement
72045 ** EXPLAIN QUERY PLAN.
72046 **
72047 ** When p->explain==1, first the main program is listed, then each of
72048 ** the trigger subprograms are listed one by one.
72049 */
72050 SQLITE_PRIVATE int sqlite3VdbeList(
72051  Vdbe *p /* The VDBE */
72052 ){
72053  int nRow; /* Stop when row count reaches this */
72054  int nSub = 0; /* Number of sub-vdbes seen so far */
72055  SubProgram **apSub = 0; /* Array of sub-vdbes */
72056  Mem *pSub = 0; /* Memory cell hold array of subprogs */
72057  sqlite3 *db = p->db; /* The database connection */
72058  int i; /* Loop counter */
72059  int rc = SQLITE_OK; /* Return code */
72060  Mem *pMem = &p->aMem[1]; /* First Mem of result set */
72061 
72062  assert( p->explain );
72063  assert( p->magic==VDBE_MAGIC_RUN );
72064  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
72065 
72066  /* Even though this opcode does not use dynamic strings for
72067  ** the result, result columns may become dynamic if the user calls
72068  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
72069  */
72070  releaseMemArray(pMem, 8);
72071  p->pResultSet = 0;
72072 
72073  if( p->rc==SQLITE_NOMEM_BKPT ){
72074  /* This happens if a malloc() inside a call to sqlite3_column_text() or
72075  ** sqlite3_column_text16() failed. */
72076  sqlite3OomFault(db);
72077  return SQLITE_ERROR;
72078  }
72079 
72080  /* When the number of output rows reaches nRow, that means the
72081  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
72082  ** nRow is the sum of the number of rows in the main program, plus
72083  ** the sum of the number of rows in all trigger subprograms encountered
72084  ** so far. The nRow value will increase as new trigger subprograms are
72085  ** encountered, but p->pc will eventually catch up to nRow.
72086  */
72087  nRow = p->nOp;
72088  if( p->explain==1 ){
72089  /* The first 8 memory cells are used for the result set. So we will
72090  ** commandeer the 9th cell to use as storage for an array of pointers
72091  ** to trigger subprograms. The VDBE is guaranteed to have at least 9
72092  ** cells. */
72093  assert( p->nMem>9 );
72094  pSub = &p->aMem[9];
72095  if( pSub->flags&MEM_Blob ){
72096  /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
72097  ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
72098  nSub = pSub->n/sizeof(Vdbe*);
72099  apSub = (SubProgram **)pSub->z;
72100  }
72101  for(i=0; i<nSub; i++){
72102  nRow += apSub[i]->nOp;
72103  }
72104  }
72105 
72106  do{
72107  i = p->pc++;
72108  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
72109  if( i>=nRow ){
72110  p->rc = SQLITE_OK;
72111  rc = SQLITE_DONE;
72112  }else if( db->u1.isInterrupted ){
72113  p->rc = SQLITE_INTERRUPT;
72114  rc = SQLITE_ERROR;
72115  sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
72116  }else{
72117  char *zP4;
72118  Op *pOp;
72119  if( i<p->nOp ){
72120  /* The output line number is small enough that we are still in the
72121  ** main program. */
72122  pOp = &p->aOp[i];
72123  }else{
72124  /* We are currently listing subprograms. Figure out which one and
72125  ** pick up the appropriate opcode. */
72126  int j;
72127  i -= p->nOp;
72128  for(j=0; i>=apSub[j]->nOp; j++){
72129  i -= apSub[j]->nOp;
72130  }
72131  pOp = &apSub[j]->aOp[i];
72132  }
72133  if( p->explain==1 ){
72134  pMem->flags = MEM_Int;
72135  pMem->u.i = i; /* Program counter */
72136  pMem++;
72137 
72138  pMem->flags = MEM_Static|MEM_Str|MEM_Term;
72139  pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
72140  assert( pMem->z!=0 );
72141  pMem->n = sqlite3Strlen30(pMem->z);
72142  pMem->enc = SQLITE_UTF8;
72143  pMem++;
72144 
72145  /* When an OP_Program opcode is encounter (the only opcode that has
72146  ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
72147  ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
72148  ** has not already been seen.
72149  */
72150  if( pOp->p4type==P4_SUBPROGRAM ){
72151  int nByte = (nSub+1)*sizeof(SubProgram*);
72152  int j;
72153  for(j=0; j<nSub; j++){
72154  if( apSub[j]==pOp->p4.pProgram ) break;
72155  }
72156  if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
72157  apSub = (SubProgram **)pSub->z;
72158  apSub[nSub++] = pOp->p4.pProgram;
72159  pSub->flags |= MEM_Blob;
72160  pSub->n = nSub*sizeof(SubProgram*);
72161  }
72162  }
72163  }
72164 
72165  pMem->flags = MEM_Int;
72166  pMem->u.i = pOp->p1; /* P1 */
72167  pMem++;
72168 
72169  pMem->flags = MEM_Int;
72170  pMem->u.i = pOp->p2; /* P2 */
72171  pMem++;
72172 
72173  pMem->flags = MEM_Int;
72174  pMem->u.i = pOp->p3; /* P3 */
72175  pMem++;
72176 
72177  if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
72178  assert( p->db->mallocFailed );
72179  return SQLITE_ERROR;
72180  }
72181  pMem->flags = MEM_Str|MEM_Term;
72182  zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
72183  if( zP4!=pMem->z ){
72184  pMem->n = 0;
72185  sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
72186  }else{
72187  assert( pMem->z!=0 );
72188  pMem->n = sqlite3Strlen30(pMem->z);
72189  pMem->enc = SQLITE_UTF8;
72190  }
72191  pMem++;
72192 
72193  if( p->explain==1 ){
72194  if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
72195  assert( p->db->mallocFailed );
72196  return SQLITE_ERROR;
72197  }
72198  pMem->flags = MEM_Str|MEM_Term;
72199  pMem->n = 2;
72200  sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
72201  pMem->enc = SQLITE_UTF8;
72202  pMem++;
72203 
72204 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72205  if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
72206  assert( p->db->mallocFailed );
72207  return SQLITE_ERROR;
72208  }
72209  pMem->flags = MEM_Str|MEM_Term;
72210  pMem->n = displayComment(pOp, zP4, pMem->z, 500);
72211  pMem->enc = SQLITE_UTF8;
72212 #else
72213  pMem->flags = MEM_Null; /* Comment */
72214 #endif
72215  }
72216 
72217  p->nResColumn = 8 - 4*(p->explain-1);
72218  p->pResultSet = &p->aMem[1];
72219  p->rc = SQLITE_OK;
72220  rc = SQLITE_ROW;
72221  }
72222  return rc;
72223 }
72224 #endif /* SQLITE_OMIT_EXPLAIN */
72225 
72226 #ifdef SQLITE_DEBUG
72227 /*
72228 ** Print the SQL that was used to generate a VDBE program.
72229 */
72230 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
72231  const char *z = 0;
72232  if( p->zSql ){
72233  z = p->zSql;
72234  }else if( p->nOp>=1 ){
72235  const VdbeOp *pOp = &p->aOp[0];
72236  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72237  z = pOp->p4.z;
72238  while( sqlite3Isspace(*z) ) z++;
72239  }
72240  }
72241  if( z ) printf("SQL: [%s]\n", z);
72242 }
72243 #endif
72244 
72245 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
72246 /*
72247 ** Print an IOTRACE message showing SQL content.
72248 */
72249 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
72250  int nOp = p->nOp;
72251  VdbeOp *pOp;
72252  if( sqlite3IoTrace==0 ) return;
72253  if( nOp<1 ) return;
72254  pOp = &p->aOp[0];
72255  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72256  int i, j;
72257  char z[1000];
72258  sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
72259  for(i=0; sqlite3Isspace(z[i]); i++){}
72260  for(j=0; z[i]; i++){
72261  if( sqlite3Isspace(z[i]) ){
72262  if( z[i-1]!=' ' ){
72263  z[j++] = ' ';
72264  }
72265  }else{
72266  z[j++] = z[i];
72267  }
72268  }
72269  z[j] = 0;
72270  sqlite3IoTrace("SQL %s\n", z);
72271  }
72272 }
72273 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
72274 
72275 /* An instance of this object describes bulk memory available for use
72276 ** by subcomponents of a prepared statement. Space is allocated out
72277 ** of a ReusableSpace object by the allocSpace() routine below.
72278 */
72280  u8 *pSpace; /* Available memory */
72281  int nFree; /* Bytes of available memory */
72282  int nNeeded; /* Total bytes that could not be allocated */
72283 };
72284 
72285 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
72286 ** from the ReusableSpace object. Return a pointer to the allocated
72287 ** memory on success. If insufficient memory is available in the
72288 ** ReusableSpace object, increase the ReusableSpace.nNeeded
72289 ** value by the amount needed and return NULL.
72290 **
72291 ** If pBuf is not initially NULL, that means that the memory has already
72292 ** been allocated by a prior call to this routine, so just return a copy
72293 ** of pBuf and leave ReusableSpace unchanged.
72294 **
72295 ** This allocator is employed to repurpose unused slots at the end of the
72296 ** opcode array of prepared state for other memory needs of the prepared
72297 ** statement.
72298 */
72299 static void *allocSpace(
72300  struct ReusableSpace *p, /* Bulk memory available for allocation */
72301  void *pBuf, /* Pointer to a prior allocation */
72302  int nByte /* Bytes of memory needed */
72303 ){
72304  assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
72305  if( pBuf==0 ){
72306  nByte = ROUND8(nByte);
72307  if( nByte <= p->nFree ){
72308  p->nFree -= nByte;
72309  pBuf = &p->pSpace[p->nFree];
72310  }else{
72311  p->nNeeded += nByte;
72312  }
72313  }
72314  assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
72315  return pBuf;
72316 }
72317 
72318 /*
72319 ** Rewind the VDBE back to the beginning in preparation for
72320 ** running it.
72321 */
72322 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
72323 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
72324  int i;
72325 #endif
72326  assert( p!=0 );
72327  assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
72328 
72329  /* There should be at least one opcode.
72330  */
72331  assert( p->nOp>0 );
72332 
72333  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
72334  p->magic = VDBE_MAGIC_RUN;
72335 
72336 #ifdef SQLITE_DEBUG
72337  for(i=0; i<p->nMem; i++){
72338  assert( p->aMem[i].db==p->db );
72339  }
72340 #endif
72341  p->pc = -1;
72342  p->rc = SQLITE_OK;
72343  p->errorAction = OE_Abort;
72344  p->nChange = 0;
72345  p->cacheCtr = 1;
72346  p->minWriteFileFormat = 255;
72347  p->iStatement = 0;
72348  p->nFkConstraint = 0;
72349 #ifdef VDBE_PROFILE
72350  for(i=0; i<p->nOp; i++){
72351  p->aOp[i].cnt = 0;
72352  p->aOp[i].cycles = 0;
72353  }
72354 #endif
72355 }
72356 
72357 /*
72358 ** Prepare a virtual machine for execution for the first time after
72359 ** creating the virtual machine. This involves things such
72360 ** as allocating registers and initializing the program counter.
72361 ** After the VDBE has be prepped, it can be executed by one or more
72362 ** calls to sqlite3VdbeExec().
72363 **
72364 ** This function may be called exactly once on each virtual machine.
72365 ** After this routine is called the VM has been "packaged" and is ready
72366 ** to run. After this routine is called, further calls to
72367 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
72368 ** the Vdbe from the Parse object that helped generate it so that the
72369 ** the Vdbe becomes an independent entity and the Parse object can be
72370 ** destroyed.
72371 **
72372 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
72373 ** to its initial state after it has been run.
72374 */
72375 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
72376  Vdbe *p, /* The VDBE */
72377  Parse *pParse /* Parsing context */
72378 ){
72379  sqlite3 *db; /* The database connection */
72380  int nVar; /* Number of parameters */
72381  int nMem; /* Number of VM memory registers */
72382  int nCursor; /* Number of cursors required */
72383  int nArg; /* Number of arguments in subprograms */
72384  int n; /* Loop counter */
72385  struct ReusableSpace x; /* Reusable bulk memory */
72386 
72387  assert( p!=0 );
72388  assert( p->nOp>0 );
72389  assert( pParse!=0 );
72390  assert( p->magic==VDBE_MAGIC_INIT );
72391  assert( pParse==p->pParse );
72392  db = p->db;
72393  assert( db->mallocFailed==0 );
72394  nVar = pParse->nVar;
72395  nMem = pParse->nMem;
72396  nCursor = pParse->nTab;
72397  nArg = pParse->nMaxArg;
72398 
72399  /* Each cursor uses a memory cell. The first cursor (cursor 0) can
72400  ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
72401  ** space at the end of aMem[] for cursors 1 and greater.
72402  ** See also: allocateCursor().
72403  */
72404  nMem += nCursor;
72405  if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
72406 
72407  /* Figure out how much reusable memory is available at the end of the
72408  ** opcode array. This extra memory will be reallocated for other elements
72409  ** of the prepared statement.
72410  */
72411  n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
72412  x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
72413  assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
72414  x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
72415  assert( x.nFree>=0 );
72416  assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
72417 
72418  resolveP2Values(p, &nArg);
72419  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
72420  if( pParse->explain && nMem<10 ){
72421  nMem = 10;
72422  }
72423  p->expired = 0;
72424 
72425  /* Memory for registers, parameters, cursor, etc, is allocated in one or two
72426  ** passes. On the first pass, we try to reuse unused memory at the
72427  ** end of the opcode array. If we are unable to satisfy all memory
72428  ** requirements by reusing the opcode array tail, then the second
72429  ** pass will fill in the remainder using a fresh memory allocation.
72430  **
72431  ** This two-pass approach that reuses as much memory as possible from
72432  ** the leftover memory at the end of the opcode array. This can significantly
72433  ** reduce the amount of memory held by a prepared statement.
72434  */
72435  do {
72436  x.nNeeded = 0;
72437  p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
72438  p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
72439  p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
72440  p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
72441 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72442  p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
72443 #endif
72444  if( x.nNeeded==0 ) break;
72445  x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
72446  x.nFree = x.nNeeded;
72447  }while( !db->mallocFailed );
72448 
72449  p->nzVar = pParse->nzVar;
72450  p->azVar = pParse->azVar;
72451  pParse->nzVar = 0;
72452  pParse->azVar = 0;
72453  p->explain = pParse->explain;
72454  if( db->mallocFailed ){
72455  p->nVar = 0;
72456  p->nCursor = 0;
72457  p->nMem = 0;
72458  }else{
72459  p->nCursor = nCursor;
72460  p->nVar = (ynVar)nVar;
72461  initMemArray(p->aVar, nVar, db, MEM_Null);
72462  p->nMem = nMem;
72463  initMemArray(p->aMem, nMem, db, MEM_Undefined);
72464  memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
72465 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72466  memset(p->anExec, 0, p->nOp*sizeof(i64));
72467 #endif
72468  }
72469  sqlite3VdbeRewind(p);
72470 }
72471 
72472 /*
72473 ** Close a VDBE cursor and release all the resources that cursor
72474 ** happens to hold.
72475 */
72476 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
72477  if( pCx==0 ){
72478  return;
72479  }
72480  assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE );
72481  switch( pCx->eCurType ){
72482  case CURTYPE_SORTER: {
72483  sqlite3VdbeSorterClose(p->db, pCx);
72484  break;
72485  }
72486  case CURTYPE_BTREE: {
72487  if( pCx->pBt ){
72488  sqlite3BtreeClose(pCx->pBt);
72489  /* The pCx->pCursor will be close automatically, if it exists, by
72490  ** the call above. */
72491  }else{
72492  assert( pCx->uc.pCursor!=0 );
72493  sqlite3BtreeCloseCursor(pCx->uc.pCursor);
72494  }
72495  break;
72496  }
72497 #ifndef SQLITE_OMIT_VIRTUALTABLE
72498  case CURTYPE_VTAB: {
72499  sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
72500  const sqlite3_module *pModule = pVCur->pVtab->pModule;
72501  assert( pVCur->pVtab->nRef>0 );
72502  pVCur->pVtab->nRef--;
72503  pModule->xClose(pVCur);
72504  break;
72505  }
72506 #endif
72507  }
72508 }
72509 
72510 /*
72511 ** Close all cursors in the current frame.
72512 */
72513 static void closeCursorsInFrame(Vdbe *p){
72514  if( p->apCsr ){
72515  int i;
72516  for(i=0; i<p->nCursor; i++){
72517  VdbeCursor *pC = p->apCsr[i];
72518  if( pC ){
72519  sqlite3VdbeFreeCursor(p, pC);
72520  p->apCsr[i] = 0;
72521  }
72522  }
72523  }
72524 }
72525 
72526 /*
72527 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
72528 ** is used, for example, when a trigger sub-program is halted to restore
72529 ** control to the main program.
72530 */
72531 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
72532  Vdbe *v = pFrame->v;
72533  closeCursorsInFrame(v);
72534 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72535  v->anExec = pFrame->anExec;
72536 #endif
72537  v->aOp = pFrame->aOp;
72538  v->nOp = pFrame->nOp;
72539  v->aMem = pFrame->aMem;
72540  v->nMem = pFrame->nMem;
72541  v->apCsr = pFrame->apCsr;
72542  v->nCursor = pFrame->nCursor;
72543  v->db->lastRowid = pFrame->lastRowid;
72544  v->nChange = pFrame->nChange;
72545  v->db->nChange = pFrame->nDbChange;
72546  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
72547  v->pAuxData = pFrame->pAuxData;
72548  pFrame->pAuxData = 0;
72549  return pFrame->pc;
72550 }
72551 
72552 /*
72553 ** Close all cursors.
72554 **
72555 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
72556 ** cell array. This is necessary as the memory cell array may contain
72557 ** pointers to VdbeFrame objects, which may in turn contain pointers to
72558 ** open cursors.
72559 */
72560 static void closeAllCursors(Vdbe *p){
72561  if( p->pFrame ){
72562  VdbeFrame *pFrame;
72563  for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
72564  sqlite3VdbeFrameRestore(pFrame);
72565  p->pFrame = 0;
72566  p->nFrame = 0;
72567  }
72568  assert( p->nFrame==0 );
72569  closeCursorsInFrame(p);
72570  if( p->aMem ){
72571  releaseMemArray(p->aMem, p->nMem);
72572  }
72573  while( p->pDelFrame ){
72574  VdbeFrame *pDel = p->pDelFrame;
72575  p->pDelFrame = pDel->pParent;
72576  sqlite3VdbeFrameDelete(pDel);
72577  }
72578 
72579  /* Delete any auxdata allocations made by the VM */
72580  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
72581  assert( p->pAuxData==0 );
72582 }
72583 
72584 /*
72585 ** Clean up the VM after a single run.
72586 */
72587 static void Cleanup(Vdbe *p){
72588  sqlite3 *db = p->db;
72589 
72590 #ifdef SQLITE_DEBUG
72591  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
72592  ** Vdbe.aMem[] arrays have already been cleaned up. */
72593  int i;
72594  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
72595  if( p->aMem ){
72596  for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
72597  }
72598 #endif
72599 
72600  sqlite3DbFree(db, p->zErrMsg);
72601  p->zErrMsg = 0;
72602  p->pResultSet = 0;
72603 }
72604 
72605 /*
72606 ** Set the number of result columns that will be returned by this SQL
72607 ** statement. This is now set at compile time, rather than during
72608 ** execution of the vdbe program so that sqlite3_column_count() can
72609 ** be called on an SQL statement before sqlite3_step().
72610 */
72611 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
72612  Mem *pColName;
72613  int n;
72614  sqlite3 *db = p->db;
72615 
72616  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
72617  sqlite3DbFree(db, p->aColName);
72618  n = nResColumn*COLNAME_N;
72619  p->nResColumn = (u16)nResColumn;
72620  p->aColName = pColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
72621  if( p->aColName==0 ) return;
72622  initMemArray(p->aColName, n, p->db, MEM_Null);
72623 }
72624 
72625 /*
72626 ** Set the name of the idx'th column to be returned by the SQL statement.
72627 ** zName must be a pointer to a nul terminated string.
72628 **
72629 ** This call must be made after a call to sqlite3VdbeSetNumCols().
72630 **
72631 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
72632 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
72633 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
72634 */
72635 SQLITE_PRIVATE int sqlite3VdbeSetColName(
72636  Vdbe *p, /* Vdbe being configured */
72637  int idx, /* Index of column zName applies to */
72638  int var, /* One of the COLNAME_* constants */
72639  const char *zName, /* Pointer to buffer containing name */
72640  void (*xDel)(void*) /* Memory management strategy for zName */
72641 ){
72642  int rc;
72643  Mem *pColName;
72644  assert( idx<p->nResColumn );
72645  assert( var<COLNAME_N );
72646  if( p->db->mallocFailed ){
72647  assert( !zName || xDel!=SQLITE_DYNAMIC );
72648  return SQLITE_NOMEM_BKPT;
72649  }
72650  assert( p->aColName!=0 );
72651  pColName = &(p->aColName[idx+var*p->nResColumn]);
72652  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
72653  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
72654  return rc;
72655 }
72656 
72657 /*
72658 ** A read or write transaction may or may not be active on database handle
72659 ** db. If a transaction is active, commit it. If there is a
72660 ** write-transaction spanning more than one database file, this routine
72661 ** takes care of the master journal trickery.
72662 */
72663 static int vdbeCommit(sqlite3 *db, Vdbe *p){
72664  int i;
72665  int nTrans = 0; /* Number of databases with an active write-transaction
72666  ** that are candidates for a two-phase commit using a
72667  ** master-journal */
72668  int rc = SQLITE_OK;
72669  int needXcommit = 0;
72670 
72671 #ifdef SQLITE_OMIT_VIRTUALTABLE
72672  /* With this option, sqlite3VtabSync() is defined to be simply
72673  ** SQLITE_OK so p is not used.
72674  */
72675  UNUSED_PARAMETER(p);
72676 #endif
72677 
72678  /* Before doing anything else, call the xSync() callback for any
72679  ** virtual module tables written in this transaction. This has to
72680  ** be done before determining whether a master journal file is
72681  ** required, as an xSync() callback may add an attached database
72682  ** to the transaction.
72683  */
72684  rc = sqlite3VtabSync(db, p);
72685 
72686  /* This loop determines (a) if the commit hook should be invoked and
72687  ** (b) how many database files have open write transactions, not
72688  ** including the temp database. (b) is important because if more than
72689  ** one database file has an open write transaction, a master journal
72690  ** file is required for an atomic commit.
72691  */
72692  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72693  Btree *pBt = db->aDb[i].pBt;
72694  if( sqlite3BtreeIsInTrans(pBt) ){
72695  /* Whether or not a database might need a master journal depends upon
72696  ** its journal mode (among other things). This matrix determines which
72697  ** journal modes use a master journal and which do not */
72698  static const u8 aMJNeeded[] = {
72699  /* DELETE */ 1,
72700  /* PERSIST */ 1,
72701  /* OFF */ 0,
72702  /* TRUNCATE */ 1,
72703  /* MEMORY */ 0,
72704  /* WAL */ 0
72705  };
72706  Pager *pPager; /* Pager associated with pBt */
72707  needXcommit = 1;
72708  sqlite3BtreeEnter(pBt);
72709  pPager = sqlite3BtreePager(pBt);
72710  if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
72711  && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
72712  ){
72713  assert( i!=1 );
72714  nTrans++;
72715  }
72716  rc = sqlite3PagerExclusiveLock(pPager);
72717  sqlite3BtreeLeave(pBt);
72718  }
72719  }
72720  if( rc!=SQLITE_OK ){
72721  return rc;
72722  }
72723 
72724  /* If there are any write-transactions at all, invoke the commit hook */
72725  if( needXcommit && db->xCommitCallback ){
72726  rc = db->xCommitCallback(db->pCommitArg);
72727  if( rc ){
72728  return SQLITE_CONSTRAINT_COMMITHOOK;
72729  }
72730  }
72731 
72732  /* The simple case - no more than one database file (not counting the
72733  ** TEMP database) has a transaction active. There is no need for the
72734  ** master-journal.
72735  **
72736  ** If the return value of sqlite3BtreeGetFilename() is a zero length
72737  ** string, it means the main database is :memory: or a temp file. In
72738  ** that case we do not support atomic multi-file commits, so use the
72739  ** simple case then too.
72740  */
72741  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
72742  || nTrans<=1
72743  ){
72744  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72745  Btree *pBt = db->aDb[i].pBt;
72746  if( pBt ){
72747  rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
72748  }
72749  }
72750 
72751  /* Do the commit only if all databases successfully complete phase 1.
72752  ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
72753  ** IO error while deleting or truncating a journal file. It is unlikely,
72754  ** but could happen. In this case abandon processing and return the error.
72755  */
72756  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72757  Btree *pBt = db->aDb[i].pBt;
72758  if( pBt ){
72759  rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
72760  }
72761  }
72762  if( rc==SQLITE_OK ){
72763  sqlite3VtabCommit(db);
72764  }
72765  }
72766 
72767  /* The complex case - There is a multi-file write-transaction active.
72768  ** This requires a master journal file to ensure the transaction is
72769  ** committed atomically.
72770  */
72771 #ifndef SQLITE_OMIT_DISKIO
72772  else{
72773  sqlite3_vfs *pVfs = db->pVfs;
72774  char *zMaster = 0; /* File-name for the master journal */
72775  char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
72776  sqlite3_file *pMaster = 0;
72777  i64 offset = 0;
72778  int res;
72779  int retryCount = 0;
72780  int nMainFile;
72781 
72782  /* Select a master journal file name */
72783  nMainFile = sqlite3Strlen30(zMainFile);
72784  zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
72785  if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
72786  do {
72787  u32 iRandom;
72788  if( retryCount ){
72789  if( retryCount>100 ){
72790  sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
72791  sqlite3OsDelete(pVfs, zMaster, 0);
72792  break;
72793  }else if( retryCount==1 ){
72794  sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
72795  }
72796  }
72797  retryCount++;
72798  sqlite3_randomness(sizeof(iRandom), &iRandom);
72799  sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
72800  (iRandom>>8)&0xffffff, iRandom&0xff);
72801  /* The antipenultimate character of the master journal name must
72802  ** be "9" to avoid name collisions when using 8+3 filenames. */
72803  assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
72804  sqlite3FileSuffix3(zMainFile, zMaster);
72805  rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
72806  }while( rc==SQLITE_OK && res );
72807  if( rc==SQLITE_OK ){
72808  /* Open the master journal. */
72809  rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
72810  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
72811  SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
72812  );
72813  }
72814  if( rc!=SQLITE_OK ){
72815  sqlite3DbFree(db, zMaster);
72816  return rc;
72817  }
72818 
72819  /* Write the name of each database file in the transaction into the new
72820  ** master journal file. If an error occurs at this point close
72821  ** and delete the master journal file. All the individual journal files
72822  ** still have 'null' as the master journal pointer, so they will roll
72823  ** back independently if a failure occurs.
72824  */
72825  for(i=0; i<db->nDb; i++){
72826  Btree *pBt = db->aDb[i].pBt;
72827  if( sqlite3BtreeIsInTrans(pBt) ){
72828  char const *zFile = sqlite3BtreeGetJournalname(pBt);
72829  if( zFile==0 ){
72830  continue; /* Ignore TEMP and :memory: databases */
72831  }
72832  assert( zFile[0]!=0 );
72833  rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
72834  offset += sqlite3Strlen30(zFile)+1;
72835  if( rc!=SQLITE_OK ){
72836  sqlite3OsCloseFree(pMaster);
72837  sqlite3OsDelete(pVfs, zMaster, 0);
72838  sqlite3DbFree(db, zMaster);
72839  return rc;
72840  }
72841  }
72842  }
72843 
72844  /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
72845  ** flag is set this is not required.
72846  */
72847  if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
72848  && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
72849  ){
72850  sqlite3OsCloseFree(pMaster);
72851  sqlite3OsDelete(pVfs, zMaster, 0);
72852  sqlite3DbFree(db, zMaster);
72853  return rc;
72854  }
72855 
72856  /* Sync all the db files involved in the transaction. The same call
72857  ** sets the master journal pointer in each individual journal. If
72858  ** an error occurs here, do not delete the master journal file.
72859  **
72860  ** If the error occurs during the first call to
72861  ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
72862  ** master journal file will be orphaned. But we cannot delete it,
72863  ** in case the master journal file name was written into the journal
72864  ** file before the failure occurred.
72865  */
72866  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72867  Btree *pBt = db->aDb[i].pBt;
72868  if( pBt ){
72869  rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
72870  }
72871  }
72872  sqlite3OsCloseFree(pMaster);
72873  assert( rc!=SQLITE_BUSY );
72874  if( rc!=SQLITE_OK ){
72875  sqlite3DbFree(db, zMaster);
72876  return rc;
72877  }
72878 
72879  /* Delete the master journal file. This commits the transaction. After
72880  ** doing this the directory is synced again before any individual
72881  ** transaction files are deleted.
72882  */
72883  rc = sqlite3OsDelete(pVfs, zMaster, 1);
72884  sqlite3DbFree(db, zMaster);
72885  zMaster = 0;
72886  if( rc ){
72887  return rc;
72888  }
72889 
72890  /* All files and directories have already been synced, so the following
72891  ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
72892  ** deleting or truncating journals. If something goes wrong while
72893  ** this is happening we don't really care. The integrity of the
72894  ** transaction is already guaranteed, but some stray 'cold' journals
72895  ** may be lying around. Returning an error code won't help matters.
72896  */
72897  disable_simulated_io_errors();
72898  sqlite3BeginBenignMalloc();
72899  for(i=0; i<db->nDb; i++){
72900  Btree *pBt = db->aDb[i].pBt;
72901  if( pBt ){
72902  sqlite3BtreeCommitPhaseTwo(pBt, 1);
72903  }
72904  }
72905  sqlite3EndBenignMalloc();
72906  enable_simulated_io_errors();
72907 
72908  sqlite3VtabCommit(db);
72909  }
72910 #endif
72911 
72912  return rc;
72913 }
72914 
72915 /*
72916 ** This routine checks that the sqlite3.nVdbeActive count variable
72917 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
72918 ** currently active. An assertion fails if the two counts do not match.
72919 ** This is an internal self-check only - it is not an essential processing
72920 ** step.
72921 **
72922 ** This is a no-op if NDEBUG is defined.
72923 */
72924 #ifndef NDEBUG
72925 static void checkActiveVdbeCnt(sqlite3 *db){
72926  Vdbe *p;
72927  int cnt = 0;
72928  int nWrite = 0;
72929  int nRead = 0;
72930  p = db->pVdbe;
72931  while( p ){
72932  if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
72933  cnt++;
72934  if( p->readOnly==0 ) nWrite++;
72935  if( p->bIsReader ) nRead++;
72936  }
72937  p = p->pNext;
72938  }
72939  assert( cnt==db->nVdbeActive );
72940  assert( nWrite==db->nVdbeWrite );
72941  assert( nRead==db->nVdbeRead );
72942 }
72943 #else
72944 #define checkActiveVdbeCnt(x)
72945 #endif
72946 
72947 /*
72948 ** If the Vdbe passed as the first argument opened a statement-transaction,
72949 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
72950 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
72951 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
72952 ** statement transaction is committed.
72953 **
72954 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
72955 ** Otherwise SQLITE_OK.
72956 */
72957 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
72958  sqlite3 *const db = p->db;
72959  int rc = SQLITE_OK;
72960 
72961  /* If p->iStatement is greater than zero, then this Vdbe opened a
72962  ** statement transaction that should be closed here. The only exception
72963  ** is that an IO error may have occurred, causing an emergency rollback.
72964  ** In this case (db->nStatement==0), and there is nothing to do.
72965  */
72966  if( db->nStatement && p->iStatement ){
72967  int i;
72968  const int iSavepoint = p->iStatement-1;
72969 
72970  assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
72971  assert( db->nStatement>0 );
72972  assert( p->iStatement==(db->nStatement+db->nSavepoint) );
72973 
72974  for(i=0; i<db->nDb; i++){
72975  int rc2 = SQLITE_OK;
72976  Btree *pBt = db->aDb[i].pBt;
72977  if( pBt ){
72978  if( eOp==SAVEPOINT_ROLLBACK ){
72979  rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
72980  }
72981  if( rc2==SQLITE_OK ){
72982  rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
72983  }
72984  if( rc==SQLITE_OK ){
72985  rc = rc2;
72986  }
72987  }
72988  }
72989  db->nStatement--;
72990  p->iStatement = 0;
72991 
72992  if( rc==SQLITE_OK ){
72993  if( eOp==SAVEPOINT_ROLLBACK ){
72994  rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
72995  }
72996  if( rc==SQLITE_OK ){
72997  rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
72998  }
72999  }
73000 
73001  /* If the statement transaction is being rolled back, also restore the
73002  ** database handles deferred constraint counter to the value it had when
73003  ** the statement transaction was opened. */
73004  if( eOp==SAVEPOINT_ROLLBACK ){
73005  db->nDeferredCons = p->nStmtDefCons;
73006  db->nDeferredImmCons = p->nStmtDefImmCons;
73007  }
73008  }
73009  return rc;
73010 }
73011 
73012 /*
73013 ** This function is called when a transaction opened by the database
73014 ** handle associated with the VM passed as an argument is about to be
73015 ** committed. If there are outstanding deferred foreign key constraint
73016 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
73017 **
73018 ** If there are outstanding FK violations and this function returns
73019 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
73020 ** and write an error message to it. Then return SQLITE_ERROR.
73021 */
73022 #ifndef SQLITE_OMIT_FOREIGN_KEY
73023 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
73024  sqlite3 *db = p->db;
73025  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
73026  || (!deferred && p->nFkConstraint>0)
73027  ){
73028  p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
73029  p->errorAction = OE_Abort;
73030  sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
73031  return SQLITE_ERROR;
73032  }
73033  return SQLITE_OK;
73034 }
73035 #endif
73036 
73037 /*
73038 ** This routine is called the when a VDBE tries to halt. If the VDBE
73039 ** has made changes and is in autocommit mode, then commit those
73040 ** changes. If a rollback is needed, then do the rollback.
73041 **
73042 ** This routine is the only way to move the state of a VM from
73043 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
73044 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
73045 **
73046 ** Return an error code. If the commit could not complete because of
73047 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
73048 ** means the close did not happen and needs to be repeated.
73049 */
73050 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
73051  int rc; /* Used to store transient return codes */
73052  sqlite3 *db = p->db;
73053 
73054  /* This function contains the logic that determines if a statement or
73055  ** transaction will be committed or rolled back as a result of the
73056  ** execution of this virtual machine.
73057  **
73058  ** If any of the following errors occur:
73059  **
73060  ** SQLITE_NOMEM
73061  ** SQLITE_IOERR
73062  ** SQLITE_FULL
73063  ** SQLITE_INTERRUPT
73064  **
73065  ** Then the internal cache might have been left in an inconsistent
73066  ** state. We need to rollback the statement transaction, if there is
73067  ** one, or the complete transaction if there is no statement transaction.
73068  */
73069 
73070  if( db->mallocFailed ){
73071  p->rc = SQLITE_NOMEM_BKPT;
73072  }
73073  closeAllCursors(p);
73074  if( p->magic!=VDBE_MAGIC_RUN ){
73075  return SQLITE_OK;
73076  }
73077  checkActiveVdbeCnt(db);
73078 
73079  /* No commit or rollback needed if the program never started or if the
73080  ** SQL statement does not read or write a database file. */
73081  if( p->pc>=0 && p->bIsReader ){
73082  int mrc; /* Primary error code from p->rc */
73083  int eStatementOp = 0;
73084  int isSpecialError; /* Set to true if a 'special' error */
73085 
73086  /* Lock all btrees used by the statement */
73087  sqlite3VdbeEnter(p);
73088 
73089  /* Check for one of the special errors */
73090  mrc = p->rc & 0xff;
73091  isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
73092  || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
73093  if( isSpecialError ){
73094  /* If the query was read-only and the error code is SQLITE_INTERRUPT,
73095  ** no rollback is necessary. Otherwise, at least a savepoint
73096  ** transaction must be rolled back to restore the database to a
73097  ** consistent state.
73098  **
73099  ** Even if the statement is read-only, it is important to perform
73100  ** a statement or transaction rollback operation. If the error
73101  ** occurred while writing to the journal, sub-journal or database
73102  ** file as part of an effort to free up cache space (see function
73103  ** pagerStress() in pager.c), the rollback is required to restore
73104  ** the pager to a consistent state.
73105  */
73106  if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
73107  if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
73108  eStatementOp = SAVEPOINT_ROLLBACK;
73109  }else{
73110  /* We are forced to roll back the active transaction. Before doing
73111  ** so, abort any other statements this handle currently has active.
73112  */
73113  sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73114  sqlite3CloseSavepoints(db);
73115  db->autoCommit = 1;
73116  p->nChange = 0;
73117  }
73118  }
73119  }
73120 
73121  /* Check for immediate foreign key violations. */
73122  if( p->rc==SQLITE_OK ){
73123  sqlite3VdbeCheckFk(p, 0);
73124  }
73125 
73126  /* If the auto-commit flag is set and this is the only active writer
73127  ** VM, then we do either a commit or rollback of the current transaction.
73128  **
73129  ** Note: This block also runs if one of the special errors handled
73130  ** above has occurred.
73131  */
73132  if( !sqlite3VtabInSync(db)
73133  && db->autoCommit
73134  && db->nVdbeWrite==(p->readOnly==0)
73135  ){
73136  if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
73137  rc = sqlite3VdbeCheckFk(p, 1);
73138  if( rc!=SQLITE_OK ){
73139  if( NEVER(p->readOnly) ){
73140  sqlite3VdbeLeave(p);
73141  return SQLITE_ERROR;
73142  }
73143  rc = SQLITE_CONSTRAINT_FOREIGNKEY;
73144  }else{
73145  /* The auto-commit flag is true, the vdbe program was successful
73146  ** or hit an 'OR FAIL' constraint and there are no deferred foreign
73147  ** key constraints to hold up the transaction. This means a commit
73148  ** is required. */
73149  rc = vdbeCommit(db, p);
73150  }
73151  if( rc==SQLITE_BUSY && p->readOnly ){
73152  sqlite3VdbeLeave(p);
73153  return SQLITE_BUSY;
73154  }else if( rc!=SQLITE_OK ){
73155  p->rc = rc;
73156  sqlite3RollbackAll(db, SQLITE_OK);
73157  p->nChange = 0;
73158  }else{
73159  db->nDeferredCons = 0;
73160  db->nDeferredImmCons = 0;
73161  db->flags &= ~SQLITE_DeferFKs;
73162  sqlite3CommitInternalChanges(db);
73163  }
73164  }else{
73165  sqlite3RollbackAll(db, SQLITE_OK);
73166  p->nChange = 0;
73167  }
73168  db->nStatement = 0;
73169  }else if( eStatementOp==0 ){
73170  if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
73171  eStatementOp = SAVEPOINT_RELEASE;
73172  }else if( p->errorAction==OE_Abort ){
73173  eStatementOp = SAVEPOINT_ROLLBACK;
73174  }else{
73175  sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73176  sqlite3CloseSavepoints(db);
73177  db->autoCommit = 1;
73178  p->nChange = 0;
73179  }
73180  }
73181 
73182  /* If eStatementOp is non-zero, then a statement transaction needs to
73183  ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
73184  ** do so. If this operation returns an error, and the current statement
73185  ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
73186  ** current statement error code.
73187  */
73188  if( eStatementOp ){
73189  rc = sqlite3VdbeCloseStatement(p, eStatementOp);
73190  if( rc ){
73191  if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
73192  p->rc = rc;
73193  sqlite3DbFree(db, p->zErrMsg);
73194  p->zErrMsg = 0;
73195  }
73196  sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73197  sqlite3CloseSavepoints(db);
73198  db->autoCommit = 1;
73199  p->nChange = 0;
73200  }
73201  }
73202 
73203  /* If this was an INSERT, UPDATE or DELETE and no statement transaction
73204  ** has been rolled back, update the database connection change-counter.
73205  */
73206  if( p->changeCntOn ){
73207  if( eStatementOp!=SAVEPOINT_ROLLBACK ){
73208  sqlite3VdbeSetChanges(db, p->nChange);
73209  }else{
73210  sqlite3VdbeSetChanges(db, 0);
73211  }
73212  p->nChange = 0;
73213  }
73214 
73215  /* Release the locks */
73216  sqlite3VdbeLeave(p);
73217  }
73218 
73219  /* We have successfully halted and closed the VM. Record this fact. */
73220  if( p->pc>=0 ){
73221  db->nVdbeActive--;
73222  if( !p->readOnly ) db->nVdbeWrite--;
73223  if( p->bIsReader ) db->nVdbeRead--;
73224  assert( db->nVdbeActive>=db->nVdbeRead );
73225  assert( db->nVdbeRead>=db->nVdbeWrite );
73226  assert( db->nVdbeWrite>=0 );
73227  }
73228  p->magic = VDBE_MAGIC_HALT;
73229  checkActiveVdbeCnt(db);
73230  if( db->mallocFailed ){
73231  p->rc = SQLITE_NOMEM_BKPT;
73232  }
73233 
73234  /* If the auto-commit flag is set to true, then any locks that were held
73235  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
73236  ** to invoke any required unlock-notify callbacks.
73237  */
73238  if( db->autoCommit ){
73239  sqlite3ConnectionUnlocked(db);
73240  }
73241 
73242  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
73243  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
73244 }
73245 
73246 
73247 /*
73248 ** Each VDBE holds the result of the most recent sqlite3_step() call
73249 ** in p->rc. This routine sets that result back to SQLITE_OK.
73250 */
73251 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
73252  p->rc = SQLITE_OK;
73253 }
73254 
73255 /*
73256 ** Copy the error code and error message belonging to the VDBE passed
73257 ** as the first argument to its database handle (so that they will be
73258 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
73259 **
73260 ** This function does not clear the VDBE error code or message, just
73261 ** copies them to the database handle.
73262 */
73263 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
73264  sqlite3 *db = p->db;
73265  int rc = p->rc;
73266  if( p->zErrMsg ){
73267  db->bBenignMalloc++;
73268  sqlite3BeginBenignMalloc();
73269  if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
73270  sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
73271  sqlite3EndBenignMalloc();
73272  db->bBenignMalloc--;
73273  db->errCode = rc;
73274  }else{
73275  sqlite3Error(db, rc);
73276  }
73277  return rc;
73278 }
73279 
73280 #ifdef SQLITE_ENABLE_SQLLOG
73281 /*
73282 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
73283 ** invoke it.
73284 */
73285 static void vdbeInvokeSqllog(Vdbe *v){
73286  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
73287  char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
73288  assert( v->db->init.busy==0 );
73289  if( zExpanded ){
73290  sqlite3GlobalConfig.xSqllog(
73291  sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
73292  );
73293  sqlite3DbFree(v->db, zExpanded);
73294  }
73295  }
73296 }
73297 #else
73298 # define vdbeInvokeSqllog(x)
73299 #endif
73300 
73301 /*
73302 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
73303 ** Write any error messages into *pzErrMsg. Return the result code.
73304 **
73305 ** After this routine is run, the VDBE should be ready to be executed
73306 ** again.
73307 **
73308 ** To look at it another way, this routine resets the state of the
73309 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
73310 ** VDBE_MAGIC_INIT.
73311 */
73312 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
73313  sqlite3 *db;
73314  db = p->db;
73315 
73316  /* If the VM did not run to completion or if it encountered an
73317  ** error, then it might not have been halted properly. So halt
73318  ** it now.
73319  */
73320  sqlite3VdbeHalt(p);
73321 
73322  /* If the VDBE has be run even partially, then transfer the error code
73323  ** and error message from the VDBE into the main database structure. But
73324  ** if the VDBE has just been set to run but has not actually executed any
73325  ** instructions yet, leave the main database error information unchanged.
73326  */
73327  if( p->pc>=0 ){
73328  vdbeInvokeSqllog(p);
73329  sqlite3VdbeTransferError(p);
73330  sqlite3DbFree(db, p->zErrMsg);
73331  p->zErrMsg = 0;
73332  if( p->runOnlyOnce ) p->expired = 1;
73333  }else if( p->rc && p->expired ){
73334  /* The expired flag was set on the VDBE before the first call
73335  ** to sqlite3_step(). For consistency (since sqlite3_step() was
73336  ** called), set the database error in this case as well.
73337  */
73338  sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
73339  sqlite3DbFree(db, p->zErrMsg);
73340  p->zErrMsg = 0;
73341  }
73342 
73343  /* Reclaim all memory used by the VDBE
73344  */
73345  Cleanup(p);
73346 
73347  /* Save profiling information from this VDBE run.
73348  */
73349 #ifdef VDBE_PROFILE
73350  {
73351  FILE *out = fopen("vdbe_profile.out", "a");
73352  if( out ){
73353  int i;
73354  fprintf(out, "---- ");
73355  for(i=0; i<p->nOp; i++){
73356  fprintf(out, "%02x", p->aOp[i].opcode);
73357  }
73358  fprintf(out, "\n");
73359  if( p->zSql ){
73360  char c, pc = 0;
73361  fprintf(out, "-- ");
73362  for(i=0; (c = p->zSql[i])!=0; i++){
73363  if( pc=='\n' ) fprintf(out, "-- ");
73364  putc(c, out);
73365  pc = c;
73366  }
73367  if( pc!='\n' ) fprintf(out, "\n");
73368  }
73369  for(i=0; i<p->nOp; i++){
73370  char zHdr[100];
73371  sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
73372  p->aOp[i].cnt,
73373  p->aOp[i].cycles,
73374  p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
73375  );
73376  fprintf(out, "%s", zHdr);
73377  sqlite3VdbePrintOp(out, i, &p->aOp[i]);
73378  }
73379  fclose(out);
73380  }
73381  }
73382 #endif
73383  p->iCurrentTime = 0;
73384  p->magic = VDBE_MAGIC_RESET;
73385  return p->rc & db->errMask;
73386 }
73387 
73388 /*
73389 ** Clean up and delete a VDBE after execution. Return an integer which is
73390 ** the result code. Write any error message text into *pzErrMsg.
73391 */
73392 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
73393  int rc = SQLITE_OK;
73394  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
73395  rc = sqlite3VdbeReset(p);
73396  assert( (rc & p->db->errMask)==rc );
73397  }
73398  sqlite3VdbeDelete(p);
73399  return rc;
73400 }
73401 
73402 /*
73403 ** If parameter iOp is less than zero, then invoke the destructor for
73404 ** all auxiliary data pointers currently cached by the VM passed as
73405 ** the first argument.
73406 **
73407 ** Or, if iOp is greater than or equal to zero, then the destructor is
73408 ** only invoked for those auxiliary data pointers created by the user
73409 ** function invoked by the OP_Function opcode at instruction iOp of
73410 ** VM pVdbe, and only then if:
73411 **
73412 ** * the associated function parameter is the 32nd or later (counting
73413 ** from left to right), or
73414 **
73415 ** * the corresponding bit in argument mask is clear (where the first
73416 ** function parameter corresponds to bit 0 etc.).
73417 */
73418 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
73419  while( *pp ){
73420  AuxData *pAux = *pp;
73421  if( (iOp<0)
73422  || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
73423  ){
73424  testcase( pAux->iArg==31 );
73425  if( pAux->xDelete ){
73426  pAux->xDelete(pAux->pAux);
73427  }
73428  *pp = pAux->pNext;
73429  sqlite3DbFree(db, pAux);
73430  }else{
73431  pp= &pAux->pNext;
73432  }
73433  }
73434 }
73435 
73436 /*
73437 ** Free all memory associated with the Vdbe passed as the second argument,
73438 ** except for object itself, which is preserved.
73439 **
73440 ** The difference between this function and sqlite3VdbeDelete() is that
73441 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
73442 ** the database connection and frees the object itself.
73443 */
73444 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
73445  SubProgram *pSub, *pNext;
73446  int i;
73447  assert( p->db==0 || p->db==db );
73448  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
73449  for(pSub=p->pProgram; pSub; pSub=pNext){
73450  pNext = pSub->pNext;
73451  vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
73452  sqlite3DbFree(db, pSub);
73453  }
73454  if( p->magic!=VDBE_MAGIC_INIT ){
73455  releaseMemArray(p->aVar, p->nVar);
73456  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
73457  sqlite3DbFree(db, p->azVar);
73458  sqlite3DbFree(db, p->pFree);
73459  }
73460  vdbeFreeOpArray(db, p->aOp, p->nOp);
73461  sqlite3DbFree(db, p->aColName);
73462  sqlite3DbFree(db, p->zSql);
73463 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73464  for(i=0; i<p->nScan; i++){
73465  sqlite3DbFree(db, p->aScan[i].zName);
73466  }
73467  sqlite3DbFree(db, p->aScan);
73468 #endif
73469 }
73470 
73471 /*
73472 ** Delete an entire VDBE.
73473 */
73474 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
73475  sqlite3 *db;
73476 
73477  if( NEVER(p==0) ) return;
73478  db = p->db;
73479  assert( sqlite3_mutex_held(db->mutex) );
73480  sqlite3VdbeClearObject(db, p);
73481  if( p->pPrev ){
73482  p->pPrev->pNext = p->pNext;
73483  }else{
73484  assert( db->pVdbe==p );
73485  db->pVdbe = p->pNext;
73486  }
73487  if( p->pNext ){
73488  p->pNext->pPrev = p->pPrev;
73489  }
73490  p->magic = VDBE_MAGIC_DEAD;
73491  p->db = 0;
73492  sqlite3DbFree(db, p);
73493 }
73494 
73495 /*
73496 ** The cursor "p" has a pending seek operation that has not yet been
73497 ** carried out. Seek the cursor now. If an error occurs, return
73498 ** the appropriate error code.
73499 */
73500 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
73501  int res, rc;
73502 #ifdef SQLITE_TEST
73503  extern int sqlite3_search_count;
73504 #endif
73505  assert( p->deferredMoveto );
73506  assert( p->isTable );
73507  assert( p->eCurType==CURTYPE_BTREE );
73508  rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
73509  if( rc ) return rc;
73510  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
73511 #ifdef SQLITE_TEST
73512  sqlite3_search_count++;
73513 #endif
73514  p->deferredMoveto = 0;
73515  p->cacheStatus = CACHE_STALE;
73516  return SQLITE_OK;
73517 }
73518 
73519 /*
73520 ** Something has moved cursor "p" out of place. Maybe the row it was
73521 ** pointed to was deleted out from under it. Or maybe the btree was
73522 ** rebalanced. Whatever the cause, try to restore "p" to the place it
73523 ** is supposed to be pointing. If the row was deleted out from under the
73524 ** cursor, set the cursor to point to a NULL row.
73525 */
73526 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
73527  int isDifferentRow, rc;
73528  assert( p->eCurType==CURTYPE_BTREE );
73529  assert( p->uc.pCursor!=0 );
73530  assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
73531  rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
73532  p->cacheStatus = CACHE_STALE;
73533  if( isDifferentRow ) p->nullRow = 1;
73534  return rc;
73535 }
73536 
73537 /*
73538 ** Check to ensure that the cursor is valid. Restore the cursor
73539 ** if need be. Return any I/O error from the restore operation.
73540 */
73541 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
73542  assert( p->eCurType==CURTYPE_BTREE );
73543  if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
73544  return handleMovedCursor(p);
73545  }
73546  return SQLITE_OK;
73547 }
73548 
73549 /*
73550 ** Make sure the cursor p is ready to read or write the row to which it
73551 ** was last positioned. Return an error code if an OOM fault or I/O error
73552 ** prevents us from positioning the cursor to its correct position.
73553 **
73554 ** If a MoveTo operation is pending on the given cursor, then do that
73555 ** MoveTo now. If no move is pending, check to see if the row has been
73556 ** deleted out from under the cursor and if it has, mark the row as
73557 ** a NULL row.
73558 **
73559 ** If the cursor is already pointing to the correct row and that row has
73560 ** not been deleted out from under the cursor, then this routine is a no-op.
73561 */
73562 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
73563  VdbeCursor *p = *pp;
73564  if( p->eCurType==CURTYPE_BTREE ){
73565  if( p->deferredMoveto ){
73566  int iMap;
73567  if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
73568  *pp = p->pAltCursor;
73569  *piCol = iMap - 1;
73570  return SQLITE_OK;
73571  }
73572  return handleDeferredMoveto(p);
73573  }
73574  if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
73575  return handleMovedCursor(p);
73576  }
73577  }
73578  return SQLITE_OK;
73579 }
73580 
73581 /*
73582 ** The following functions:
73583 **
73584 ** sqlite3VdbeSerialType()
73585 ** sqlite3VdbeSerialTypeLen()
73586 ** sqlite3VdbeSerialLen()
73587 ** sqlite3VdbeSerialPut()
73588 ** sqlite3VdbeSerialGet()
73589 **
73590 ** encapsulate the code that serializes values for storage in SQLite
73591 ** data and index records. Each serialized value consists of a
73592 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
73593 ** integer, stored as a varint.
73594 **
73595 ** In an SQLite index record, the serial type is stored directly before
73596 ** the blob of data that it corresponds to. In a table record, all serial
73597 ** types are stored at the start of the record, and the blobs of data at
73598 ** the end. Hence these functions allow the caller to handle the
73599 ** serial-type and data blob separately.
73600 **
73601 ** The following table describes the various storage classes for data:
73602 **
73603 ** serial type bytes of data type
73604 ** -------------- --------------- ---------------
73605 ** 0 0 NULL
73606 ** 1 1 signed integer
73607 ** 2 2 signed integer
73608 ** 3 3 signed integer
73609 ** 4 4 signed integer
73610 ** 5 6 signed integer
73611 ** 6 8 signed integer
73612 ** 7 8 IEEE float
73613 ** 8 0 Integer constant 0
73614 ** 9 0 Integer constant 1
73615 ** 10,11 reserved for expansion
73616 ** N>=12 and even (N-12)/2 BLOB
73617 ** N>=13 and odd (N-13)/2 text
73618 **
73619 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
73620 ** of SQLite will not understand those serial types.
73621 */
73622 
73623 /*
73624 ** Return the serial-type for the value stored in pMem.
73625 */
73626 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
73627  int flags = pMem->flags;
73628  u32 n;
73629 
73630  assert( pLen!=0 );
73631  if( flags&MEM_Null ){
73632  *pLen = 0;
73633  return 0;
73634  }
73635  if( flags&MEM_Int ){
73636  /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
73637 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
73638  i64 i = pMem->u.i;
73639  u64 u;
73640  if( i<0 ){
73641  u = ~i;
73642  }else{
73643  u = i;
73644  }
73645  if( u<=127 ){
73646  if( (i&1)==i && file_format>=4 ){
73647  *pLen = 0;
73648  return 8+(u32)u;
73649  }else{
73650  *pLen = 1;
73651  return 1;
73652  }
73653  }
73654  if( u<=32767 ){ *pLen = 2; return 2; }
73655  if( u<=8388607 ){ *pLen = 3; return 3; }
73656  if( u<=2147483647 ){ *pLen = 4; return 4; }
73657  if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
73658  *pLen = 8;
73659  return 6;
73660  }
73661  if( flags&MEM_Real ){
73662  *pLen = 8;
73663  return 7;
73664  }
73665  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
73666  assert( pMem->n>=0 );
73667  n = (u32)pMem->n;
73668  if( flags & MEM_Zero ){
73669  n += pMem->u.nZero;
73670  }
73671  *pLen = n;
73672  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
73673 }
73674 
73675 /*
73676 ** The sizes for serial types less than 128
73677 */
73678 static const u8 sqlite3SmallTypeSizes[] = {
73679  /* 0 1 2 3 4 5 6 7 8 9 */
73680 /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
73681 /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
73682 /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
73683 /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
73684 /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
73685 /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
73686 /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
73687 /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
73688 /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
73689 /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
73690 /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
73691 /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
73692 /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
73693 };
73694 
73695 /*
73696 ** Return the length of the data corresponding to the supplied serial-type.
73697 */
73698 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
73699  if( serial_type>=128 ){
73700  return (serial_type-12)/2;
73701  }else{
73702  assert( serial_type<12
73703  || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
73704  return sqlite3SmallTypeSizes[serial_type];
73705  }
73706 }
73707 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
73708  assert( serial_type<128 );
73709  return sqlite3SmallTypeSizes[serial_type];
73710 }
73711 
73712 /*
73713 ** If we are on an architecture with mixed-endian floating
73714 ** points (ex: ARM7) then swap the lower 4 bytes with the
73715 ** upper 4 bytes. Return the result.
73716 **
73717 ** For most architectures, this is a no-op.
73718 **
73719 ** (later): It is reported to me that the mixed-endian problem
73720 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
73721 ** that early versions of GCC stored the two words of a 64-bit
73722 ** float in the wrong order. And that error has been propagated
73723 ** ever since. The blame is not necessarily with GCC, though.
73724 ** GCC might have just copying the problem from a prior compiler.
73725 ** I am also told that newer versions of GCC that follow a different
73726 ** ABI get the byte order right.
73727 **
73728 ** Developers using SQLite on an ARM7 should compile and run their
73729 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
73730 ** enabled, some asserts below will ensure that the byte order of
73731 ** floating point values is correct.
73732 **
73733 ** (2007-08-30) Frank van Vugt has studied this problem closely
73734 ** and has send his findings to the SQLite developers. Frank
73735 ** writes that some Linux kernels offer floating point hardware
73736 ** emulation that uses only 32-bit mantissas instead of a full
73737 ** 48-bits as required by the IEEE standard. (This is the
73738 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
73739 ** byte swapping becomes very complicated. To avoid problems,
73740 ** the necessary byte swapping is carried out using a 64-bit integer
73741 ** rather than a 64-bit float. Frank assures us that the code here
73742 ** works for him. We, the developers, have no way to independently
73743 ** verify this, but Frank seems to know what he is talking about
73744 ** so we trust him.
73745 */
73746 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
73747 static u64 floatSwap(u64 in){
73748  union {
73749  u64 r;
73750  u32 i[2];
73751  } u;
73752  u32 t;
73753 
73754  u.r = in;
73755  t = u.i[0];
73756  u.i[0] = u.i[1];
73757  u.i[1] = t;
73758  return u.r;
73759 }
73760 # define swapMixedEndianFloat(X) X = floatSwap(X)
73761 #else
73762 # define swapMixedEndianFloat(X)
73763 #endif
73764 
73765 /*
73766 ** Write the serialized data blob for the value stored in pMem into
73767 ** buf. It is assumed that the caller has allocated sufficient space.
73768 ** Return the number of bytes written.
73769 **
73770 ** nBuf is the amount of space left in buf[]. The caller is responsible
73771 ** for allocating enough space to buf[] to hold the entire field, exclusive
73772 ** of the pMem->u.nZero bytes for a MEM_Zero value.
73773 **
73774 ** Return the number of bytes actually written into buf[]. The number
73775 ** of bytes in the zero-filled tail is included in the return value only
73776 ** if those bytes were zeroed in buf[].
73777 */
73778 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
73779  u32 len;
73780 
73781  /* Integer and Real */
73782  if( serial_type<=7 && serial_type>0 ){
73783  u64 v;
73784  u32 i;
73785  if( serial_type==7 ){
73786  assert( sizeof(v)==sizeof(pMem->u.r) );
73787  memcpy(&v, &pMem->u.r, sizeof(v));
73788  swapMixedEndianFloat(v);
73789  }else{
73790  v = pMem->u.i;
73791  }
73792  len = i = sqlite3SmallTypeSizes[serial_type];
73793  assert( i>0 );
73794  do{
73795  buf[--i] = (u8)(v&0xFF);
73796  v >>= 8;
73797  }while( i );
73798  return len;
73799  }
73800 
73801  /* String or blob */
73802  if( serial_type>=12 ){
73803  assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
73804  == (int)sqlite3VdbeSerialTypeLen(serial_type) );
73805  len = pMem->n;
73806  if( len>0 ) memcpy(buf, pMem->z, len);
73807  return len;
73808  }
73809 
73810  /* NULL or constants 0 or 1 */
73811  return 0;
73812 }
73813 
73814 /* Input "x" is a sequence of unsigned characters that represent a
73815 ** big-endian integer. Return the equivalent native integer
73816 */
73817 #define ONE_BYTE_INT(x) ((i8)(x)[0])
73818 #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
73819 #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
73820 #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73821 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73822 
73823 /*
73824 ** Deserialize the data blob pointed to by buf as serial type serial_type
73825 ** and store the result in pMem. Return the number of bytes read.
73826 **
73827 ** This function is implemented as two separate routines for performance.
73828 ** The few cases that require local variables are broken out into a separate
73829 ** routine so that in most cases the overhead of moving the stack pointer
73830 ** is avoided.
73831 */
73832 static u32 SQLITE_NOINLINE serialGet(
73833  const unsigned char *buf, /* Buffer to deserialize from */
73834  u32 serial_type, /* Serial type to deserialize */
73835  Mem *pMem /* Memory cell to write value into */
73836 ){
73837  u64 x = FOUR_BYTE_UINT(buf);
73838  u32 y = FOUR_BYTE_UINT(buf+4);
73839  x = (x<<32) + y;
73840  if( serial_type==6 ){
73841  /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
73842  ** twos-complement integer. */
73843  pMem->u.i = *(i64*)&x;
73844  pMem->flags = MEM_Int;
73845  testcase( pMem->u.i<0 );
73846  }else{
73847  /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
73848  ** floating point number. */
73849 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
73850  /* Verify that integers and floating point values use the same
73851  ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
73852  ** defined that 64-bit floating point values really are mixed
73853  ** endian.
73854  */
73855  static const u64 t1 = ((u64)0x3ff00000)<<32;
73856  static const double r1 = 1.0;
73857  u64 t2 = t1;
73858  swapMixedEndianFloat(t2);
73859  assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
73860 #endif
73861  assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
73862  swapMixedEndianFloat(x);
73863  memcpy(&pMem->u.r, &x, sizeof(x));
73864  pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
73865  }
73866  return 8;
73867 }
73868 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
73869  const unsigned char *buf, /* Buffer to deserialize from */
73870  u32 serial_type, /* Serial type to deserialize */
73871  Mem *pMem /* Memory cell to write value into */
73872 ){
73873  switch( serial_type ){
73874  case 10: /* Reserved for future use */
73875  case 11: /* Reserved for future use */
73876  case 0: { /* Null */
73877  /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
73878  pMem->flags = MEM_Null;
73879  break;
73880  }
73881  case 1: {
73882  /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
73883  ** integer. */
73884  pMem->u.i = ONE_BYTE_INT(buf);
73885  pMem->flags = MEM_Int;
73886  testcase( pMem->u.i<0 );
73887  return 1;
73888  }
73889  case 2: { /* 2-byte signed integer */
73890  /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
73891  ** twos-complement integer. */
73892  pMem->u.i = TWO_BYTE_INT(buf);
73893  pMem->flags = MEM_Int;
73894  testcase( pMem->u.i<0 );
73895  return 2;
73896  }
73897  case 3: { /* 3-byte signed integer */
73898  /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
73899  ** twos-complement integer. */
73900  pMem->u.i = THREE_BYTE_INT(buf);
73901  pMem->flags = MEM_Int;
73902  testcase( pMem->u.i<0 );
73903  return 3;
73904  }
73905  case 4: { /* 4-byte signed integer */
73906  /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
73907  ** twos-complement integer. */
73908  pMem->u.i = FOUR_BYTE_INT(buf);
73909 #ifdef __HP_cc
73910  /* Work around a sign-extension bug in the HP compiler for HP/UX */
73911  if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
73912 #endif
73913  pMem->flags = MEM_Int;
73914  testcase( pMem->u.i<0 );
73915  return 4;
73916  }
73917  case 5: { /* 6-byte signed integer */
73918  /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
73919  ** twos-complement integer. */
73920  pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
73921  pMem->flags = MEM_Int;
73922  testcase( pMem->u.i<0 );
73923  return 6;
73924  }
73925  case 6: /* 8-byte signed integer */
73926  case 7: { /* IEEE floating point */
73927  /* These use local variables, so do them in a separate routine
73928  ** to avoid having to move the frame pointer in the common case */
73929  return serialGet(buf,serial_type,pMem);
73930  }
73931  case 8: /* Integer 0 */
73932  case 9: { /* Integer 1 */
73933  /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
73934  /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
73935  pMem->u.i = serial_type-8;
73936  pMem->flags = MEM_Int;
73937  return 0;
73938  }
73939  default: {
73940  /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
73941  ** length.
73942  ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
73943  ** (N-13)/2 bytes in length. */
73944  static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
73945  pMem->z = (char *)buf;
73946  pMem->n = (serial_type-12)/2;
73947  pMem->flags = aFlag[serial_type&1];
73948  return pMem->n;
73949  }
73950  }
73951  return 0;
73952 }
73953 /*
73954 ** This routine is used to allocate sufficient space for an UnpackedRecord
73955 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
73956 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
73957 **
73958 ** The space is either allocated using sqlite3DbMallocRaw() or from within
73959 ** the unaligned buffer passed via the second and third arguments (presumably
73960 ** stack space). If the former, then *ppFree is set to a pointer that should
73961 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
73962 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
73963 ** before returning.
73964 **
73965 ** If an OOM error occurs, NULL is returned.
73966 */
73967 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
73968  KeyInfo *pKeyInfo, /* Description of the record */
73969  char *pSpace, /* Unaligned space available */
73970  int szSpace, /* Size of pSpace[] in bytes */
73971  char **ppFree /* OUT: Caller should free this pointer */
73972 ){
73973  UnpackedRecord *p; /* Unpacked record to return */
73974  int nOff; /* Increment pSpace by nOff to align it */
73975  int nByte; /* Number of bytes required for *p */
73976 
73977  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
73978  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
73979  ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
73980  */
73981  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
73982  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
73983  if( nByte>szSpace+nOff ){
73984  p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
73985  *ppFree = (char *)p;
73986  if( !p ) return 0;
73987  }else{
73988  p = (UnpackedRecord*)&pSpace[nOff];
73989  *ppFree = 0;
73990  }
73991 
73992  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
73993  assert( pKeyInfo->aSortOrder!=0 );
73994  p->pKeyInfo = pKeyInfo;
73995  p->nField = pKeyInfo->nField + 1;
73996  return p;
73997 }
73998 
73999 /*
74000 ** Given the nKey-byte encoding of a record in pKey[], populate the
74001 ** UnpackedRecord structure indicated by the fourth argument with the
74002 ** contents of the decoded record.
74003 */
74004 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
74005  KeyInfo *pKeyInfo, /* Information about the record format */
74006  int nKey, /* Size of the binary record */
74007  const void *pKey, /* The binary record */
74008  UnpackedRecord *p /* Populate this structure before returning. */
74009 ){
74010  const unsigned char *aKey = (const unsigned char *)pKey;
74011  int d;
74012  u32 idx; /* Offset in aKey[] to read from */
74013  u16 u; /* Unsigned loop counter */
74014  u32 szHdr;
74015  Mem *pMem = p->aMem;
74016 
74017  p->default_rc = 0;
74018  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
74019  idx = getVarint32(aKey, szHdr);
74020  d = szHdr;
74021  u = 0;
74022  while( idx<szHdr && d<=nKey ){
74023  u32 serial_type;
74024 
74025  idx += getVarint32(&aKey[idx], serial_type);
74026  pMem->enc = pKeyInfo->enc;
74027  pMem->db = pKeyInfo->db;
74028  /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
74029  pMem->szMalloc = 0;
74030  pMem->z = 0;
74031  d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
74032  pMem++;
74033  if( (++u)>=p->nField ) break;
74034  }
74035  assert( u<=pKeyInfo->nField + 1 );
74036  p->nField = u;
74037 }
74038 
74039 #if SQLITE_DEBUG
74040 /*
74041 ** This function compares two index or table record keys in the same way
74042 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
74043 ** this function deserializes and compares values using the
74044 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
74045 ** in assert() statements to ensure that the optimized code in
74046 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
74047 **
74048 ** Return true if the result of comparison is equivalent to desiredResult.
74049 ** Return false if there is a disagreement.
74050 */
74051 static int vdbeRecordCompareDebug(
74052  int nKey1, const void *pKey1, /* Left key */
74053  const UnpackedRecord *pPKey2, /* Right key */
74054  int desiredResult /* Correct answer */
74055 ){
74056  u32 d1; /* Offset into aKey[] of next data element */
74057  u32 idx1; /* Offset into aKey[] of next header element */
74058  u32 szHdr1; /* Number of bytes in header */
74059  int i = 0;
74060  int rc = 0;
74061  const unsigned char *aKey1 = (const unsigned char *)pKey1;
74062  KeyInfo *pKeyInfo;
74063  Mem mem1;
74064 
74065  pKeyInfo = pPKey2->pKeyInfo;
74066  if( pKeyInfo->db==0 ) return 1;
74067  mem1.enc = pKeyInfo->enc;
74068  mem1.db = pKeyInfo->db;
74069  /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
74070  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
74071 
74072  /* Compilers may complain that mem1.u.i is potentially uninitialized.
74073  ** We could initialize it, as shown here, to silence those complaints.
74074  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
74075  ** the unnecessary initialization has a measurable negative performance
74076  ** impact, since this routine is a very high runner. And so, we choose
74077  ** to ignore the compiler warnings and leave this variable uninitialized.
74078  */
74079  /* mem1.u.i = 0; // not needed, here to silence compiler warning */
74080 
74081  idx1 = getVarint32(aKey1, szHdr1);
74082  if( szHdr1>98307 ) return SQLITE_CORRUPT;
74083  d1 = szHdr1;
74084  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
74085  assert( pKeyInfo->aSortOrder!=0 );
74086  assert( pKeyInfo->nField>0 );
74087  assert( idx1<=szHdr1 || CORRUPT_DB );
74088  do{
74089  u32 serial_type1;
74090 
74091  /* Read the serial types for the next element in each key. */
74092  idx1 += getVarint32( aKey1+idx1, serial_type1 );
74093 
74094  /* Verify that there is enough key space remaining to avoid
74095  ** a buffer overread. The "d1+serial_type1+2" subexpression will
74096  ** always be greater than or equal to the amount of required key space.
74097  ** Use that approximation to avoid the more expensive call to
74098  ** sqlite3VdbeSerialTypeLen() in the common case.
74099  */
74100  if( d1+serial_type1+2>(u32)nKey1
74101  && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
74102  ){
74103  break;
74104  }
74105 
74106  /* Extract the values to be compared.
74107  */
74108  d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
74109 
74110  /* Do the comparison
74111  */
74112  rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
74113  if( rc!=0 ){
74114  assert( mem1.szMalloc==0 ); /* See comment below */
74115  if( pKeyInfo->aSortOrder[i] ){
74116  rc = -rc; /* Invert the result for DESC sort order. */
74117  }
74118  goto debugCompareEnd;
74119  }
74120  i++;
74121  }while( idx1<szHdr1 && i<pPKey2->nField );
74122 
74123  /* No memory allocation is ever used on mem1. Prove this using
74124  ** the following assert(). If the assert() fails, it indicates a
74125  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
74126  */
74127  assert( mem1.szMalloc==0 );
74128 
74129  /* rc==0 here means that one of the keys ran out of fields and
74130  ** all the fields up to that point were equal. Return the default_rc
74131  ** value. */
74132  rc = pPKey2->default_rc;
74133 
74134 debugCompareEnd:
74135  if( desiredResult==0 && rc==0 ) return 1;
74136  if( desiredResult<0 && rc<0 ) return 1;
74137  if( desiredResult>0 && rc>0 ) return 1;
74138  if( CORRUPT_DB ) return 1;
74139  if( pKeyInfo->db->mallocFailed ) return 1;
74140  return 0;
74141 }
74142 #endif
74143 
74144 #if SQLITE_DEBUG
74145 /*
74146 ** Count the number of fields (a.k.a. columns) in the record given by
74147 ** pKey,nKey. The verify that this count is less than or equal to the
74148 ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
74149 **
74150 ** If this constraint is not satisfied, it means that the high-speed
74151 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
74152 ** not work correctly. If this assert() ever fires, it probably means
74153 ** that the KeyInfo.nField or KeyInfo.nXField values were computed
74154 ** incorrectly.
74155 */
74156 static void vdbeAssertFieldCountWithinLimits(
74157  int nKey, const void *pKey, /* The record to verify */
74158  const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
74159 ){
74160  int nField = 0;
74161  u32 szHdr;
74162  u32 idx;
74163  u32 notUsed;
74164  const unsigned char *aKey = (const unsigned char*)pKey;
74165 
74166  if( CORRUPT_DB ) return;
74167  idx = getVarint32(aKey, szHdr);
74168  assert( nKey>=0 );
74169  assert( szHdr<=(u32)nKey );
74170  while( idx<szHdr ){
74171  idx += getVarint32(aKey+idx, notUsed);
74172  nField++;
74173  }
74174  assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
74175 }
74176 #else
74177 # define vdbeAssertFieldCountWithinLimits(A,B,C)
74178 #endif
74179 
74180 /*
74181 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
74182 ** using the collation sequence pColl. As usual, return a negative , zero
74183 ** or positive value if *pMem1 is less than, equal to or greater than
74184 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
74185 */
74186 static int vdbeCompareMemString(
74187  const Mem *pMem1,
74188  const Mem *pMem2,
74189  const CollSeq *pColl,
74190  u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
74191 ){
74192  if( pMem1->enc==pColl->enc ){
74193  /* The strings are already in the correct encoding. Call the
74194  ** comparison function directly */
74195  return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
74196  }else{
74197  int rc;
74198  const void *v1, *v2;
74199  int n1, n2;
74200  Mem c1;
74201  Mem c2;
74202  sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
74203  sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
74204  sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
74205  sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
74206  v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
74207  n1 = v1==0 ? 0 : c1.n;
74208  v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
74209  n2 = v2==0 ? 0 : c2.n;
74210  rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
74211  if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
74212  sqlite3VdbeMemRelease(&c1);
74213  sqlite3VdbeMemRelease(&c2);
74214  return rc;
74215  }
74216 }
74217 
74218 /*
74219 ** The input pBlob is guaranteed to be a Blob that is not marked
74220 ** with MEM_Zero. Return true if it could be a zero-blob.
74221 */
74222 static int isAllZero(const char *z, int n){
74223  int i;
74224  for(i=0; i<n; i++){
74225  if( z[i] ) return 0;
74226  }
74227  return 1;
74228 }
74229 
74230 /*
74231 ** Compare two blobs. Return negative, zero, or positive if the first
74232 ** is less than, equal to, or greater than the second, respectively.
74233 ** If one blob is a prefix of the other, then the shorter is the lessor.
74234 */
74235 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
74236  int c;
74237  int n1 = pB1->n;
74238  int n2 = pB2->n;
74239 
74240  /* It is possible to have a Blob value that has some non-zero content
74241  ** followed by zero content. But that only comes up for Blobs formed
74242  ** by the OP_MakeRecord opcode, and such Blobs never get passed into
74243  ** sqlite3MemCompare(). */
74244  assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
74245  assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
74246 
74247  if( (pB1->flags|pB2->flags) & MEM_Zero ){
74248  if( pB1->flags & pB2->flags & MEM_Zero ){
74249  return pB1->u.nZero - pB2->u.nZero;
74250  }else if( pB1->flags & MEM_Zero ){
74251  if( !isAllZero(pB2->z, pB2->n) ) return -1;
74252  return pB1->u.nZero - n2;
74253  }else{
74254  if( !isAllZero(pB1->z, pB1->n) ) return +1;
74255  return n1 - pB2->u.nZero;
74256  }
74257  }
74258  c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
74259  if( c ) return c;
74260  return n1 - n2;
74261 }
74262 
74263 /*
74264 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
74265 ** number. Return negative, zero, or positive if the first (i64) is less than,
74266 ** equal to, or greater than the second (double).
74267 */
74268 static int sqlite3IntFloatCompare(i64 i, double r){
74269  if( sizeof(LONGDOUBLE_TYPE)>8 ){
74270  LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
74271  if( x<r ) return -1;
74272  if( x>r ) return +1;
74273  return 0;
74274  }else{
74275  i64 y;
74276  double s;
74277  if( r<-9223372036854775808.0 ) return +1;
74278  if( r>9223372036854775807.0 ) return -1;
74279  y = (i64)r;
74280  if( i<y ) return -1;
74281  if( i>y ){
74282  if( y==SMALLEST_INT64 && r>0.0 ) return -1;
74283  return +1;
74284  }
74285  s = (double)i;
74286  if( s<r ) return -1;
74287  if( s>r ) return +1;
74288  return 0;
74289  }
74290 }
74291 
74292 /*
74293 ** Compare the values contained by the two memory cells, returning
74294 ** negative, zero or positive if pMem1 is less than, equal to, or greater
74295 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
74296 ** and reals) sorted numerically, followed by text ordered by the collating
74297 ** sequence pColl and finally blob's ordered by memcmp().
74298 **
74299 ** Two NULL values are considered equal by this function.
74300 */
74301 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
74302  int f1, f2;
74303  int combined_flags;
74304 
74305  f1 = pMem1->flags;
74306  f2 = pMem2->flags;
74307  combined_flags = f1|f2;
74308  assert( (combined_flags & MEM_RowSet)==0 );
74309 
74310  /* If one value is NULL, it is less than the other. If both values
74311  ** are NULL, return 0.
74312  */
74313  if( combined_flags&MEM_Null ){
74314  return (f2&MEM_Null) - (f1&MEM_Null);
74315  }
74316 
74317  /* At least one of the two values is a number
74318  */
74319  if( combined_flags&(MEM_Int|MEM_Real) ){
74320  if( (f1 & f2 & MEM_Int)!=0 ){
74321  if( pMem1->u.i < pMem2->u.i ) return -1;
74322  if( pMem1->u.i > pMem2->u.i ) return +1;
74323  return 0;
74324  }
74325  if( (f1 & f2 & MEM_Real)!=0 ){
74326  if( pMem1->u.r < pMem2->u.r ) return -1;
74327  if( pMem1->u.r > pMem2->u.r ) return +1;
74328  return 0;
74329  }
74330  if( (f1&MEM_Int)!=0 ){
74331  if( (f2&MEM_Real)!=0 ){
74332  return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
74333  }else{
74334  return -1;
74335  }
74336  }
74337  if( (f1&MEM_Real)!=0 ){
74338  if( (f2&MEM_Int)!=0 ){
74339  return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
74340  }else{
74341  return -1;
74342  }
74343  }
74344  return +1;
74345  }
74346 
74347  /* If one value is a string and the other is a blob, the string is less.
74348  ** If both are strings, compare using the collating functions.
74349  */
74350  if( combined_flags&MEM_Str ){
74351  if( (f1 & MEM_Str)==0 ){
74352  return 1;
74353  }
74354  if( (f2 & MEM_Str)==0 ){
74355  return -1;
74356  }
74357 
74358  assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
74359  assert( pMem1->enc==SQLITE_UTF8 ||
74360  pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
74361 
74362  /* The collation sequence must be defined at this point, even if
74363  ** the user deletes the collation sequence after the vdbe program is
74364  ** compiled (this was not always the case).
74365  */
74366  assert( !pColl || pColl->xCmp );
74367 
74368  if( pColl ){
74369  return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
74370  }
74371  /* If a NULL pointer was passed as the collate function, fall through
74372  ** to the blob case and use memcmp(). */
74373  }
74374 
74375  /* Both values must be blobs. Compare using memcmp(). */
74376  return sqlite3BlobCompare(pMem1, pMem2);
74377 }
74378 
74379 
74380 /*
74381 ** The first argument passed to this function is a serial-type that
74382 ** corresponds to an integer - all values between 1 and 9 inclusive
74383 ** except 7. The second points to a buffer containing an integer value
74384 ** serialized according to serial_type. This function deserializes
74385 ** and returns the value.
74386 */
74387 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
74388  u32 y;
74389  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
74390  switch( serial_type ){
74391  case 0:
74392  case 1:
74393  testcase( aKey[0]&0x80 );
74394  return ONE_BYTE_INT(aKey);
74395  case 2:
74396  testcase( aKey[0]&0x80 );
74397  return TWO_BYTE_INT(aKey);
74398  case 3:
74399  testcase( aKey[0]&0x80 );
74400  return THREE_BYTE_INT(aKey);
74401  case 4: {
74402  testcase( aKey[0]&0x80 );
74403  y = FOUR_BYTE_UINT(aKey);
74404  return (i64)*(int*)&y;
74405  }
74406  case 5: {
74407  testcase( aKey[0]&0x80 );
74408  return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74409  }
74410  case 6: {
74411  u64 x = FOUR_BYTE_UINT(aKey);
74412  testcase( aKey[0]&0x80 );
74413  x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74414  return (i64)*(i64*)&x;
74415  }
74416  }
74417 
74418  return (serial_type - 8);
74419 }
74420 
74421 /*
74422 ** This function compares the two table rows or index records
74423 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
74424 ** or positive integer if key1 is less than, equal to or
74425 ** greater than key2. The {nKey1, pKey1} key must be a blob
74426 ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
74427 ** key must be a parsed key such as obtained from
74428 ** sqlite3VdbeParseRecord.
74429 **
74430 ** If argument bSkip is non-zero, it is assumed that the caller has already
74431 ** determined that the first fields of the keys are equal.
74432 **
74433 ** Key1 and Key2 do not have to contain the same number of fields. If all
74434 ** fields that appear in both keys are equal, then pPKey2->default_rc is
74435 ** returned.
74436 **
74437 ** If database corruption is discovered, set pPKey2->errCode to
74438 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
74439 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
74440 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
74441 */
74442 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
74443  int nKey1, const void *pKey1, /* Left key */
74444  UnpackedRecord *pPKey2, /* Right key */
74445  int bSkip /* If true, skip the first field */
74446 ){
74447  u32 d1; /* Offset into aKey[] of next data element */
74448  int i; /* Index of next field to compare */
74449  u32 szHdr1; /* Size of record header in bytes */
74450  u32 idx1; /* Offset of first type in header */
74451  int rc = 0; /* Return value */
74452  Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
74453  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
74454  const unsigned char *aKey1 = (const unsigned char *)pKey1;
74455  Mem mem1;
74456 
74457  /* If bSkip is true, then the caller has already determined that the first
74458  ** two elements in the keys are equal. Fix the various stack variables so
74459  ** that this routine begins comparing at the second field. */
74460  if( bSkip ){
74461  u32 s1;
74462  idx1 = 1 + getVarint32(&aKey1[1], s1);
74463  szHdr1 = aKey1[0];
74464  d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
74465  i = 1;
74466  pRhs++;
74467  }else{
74468  idx1 = getVarint32(aKey1, szHdr1);
74469  d1 = szHdr1;
74470  if( d1>(unsigned)nKey1 ){
74471  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74472  return 0; /* Corruption */
74473  }
74474  i = 0;
74475  }
74476 
74477  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
74478  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
74479  || CORRUPT_DB );
74480  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
74481  assert( pPKey2->pKeyInfo->nField>0 );
74482  assert( idx1<=szHdr1 || CORRUPT_DB );
74483  do{
74484  u32 serial_type;
74485 
74486  /* RHS is an integer */
74487  if( pRhs->flags & MEM_Int ){
74488  serial_type = aKey1[idx1];
74489  testcase( serial_type==12 );
74490  if( serial_type>=10 ){
74491  rc = +1;
74492  }else if( serial_type==0 ){
74493  rc = -1;
74494  }else if( serial_type==7 ){
74495  sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74496  rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
74497  }else{
74498  i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
74499  i64 rhs = pRhs->u.i;
74500  if( lhs<rhs ){
74501  rc = -1;
74502  }else if( lhs>rhs ){
74503  rc = +1;
74504  }
74505  }
74506  }
74507 
74508  /* RHS is real */
74509  else if( pRhs->flags & MEM_Real ){
74510  serial_type = aKey1[idx1];
74511  if( serial_type>=10 ){
74512  /* Serial types 12 or greater are strings and blobs (greater than
74513  ** numbers). Types 10 and 11 are currently "reserved for future
74514  ** use", so it doesn't really matter what the results of comparing
74515  ** them to numberic values are. */
74516  rc = +1;
74517  }else if( serial_type==0 ){
74518  rc = -1;
74519  }else{
74520  sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74521  if( serial_type==7 ){
74522  if( mem1.u.r<pRhs->u.r ){
74523  rc = -1;
74524  }else if( mem1.u.r>pRhs->u.r ){
74525  rc = +1;
74526  }
74527  }else{
74528  rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
74529  }
74530  }
74531  }
74532 
74533  /* RHS is a string */
74534  else if( pRhs->flags & MEM_Str ){
74535  getVarint32(&aKey1[idx1], serial_type);
74536  testcase( serial_type==12 );
74537  if( serial_type<12 ){
74538  rc = -1;
74539  }else if( !(serial_type & 0x01) ){
74540  rc = +1;
74541  }else{
74542  mem1.n = (serial_type - 12) / 2;
74543  testcase( (d1+mem1.n)==(unsigned)nKey1 );
74544  testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
74545  if( (d1+mem1.n) > (unsigned)nKey1 ){
74546  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74547  return 0; /* Corruption */
74548  }else if( pKeyInfo->aColl[i] ){
74549  mem1.enc = pKeyInfo->enc;
74550  mem1.db = pKeyInfo->db;
74551  mem1.flags = MEM_Str;
74552  mem1.z = (char*)&aKey1[d1];
74553  rc = vdbeCompareMemString(
74554  &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
74555  );
74556  }else{
74557  int nCmp = MIN(mem1.n, pRhs->n);
74558  rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74559  if( rc==0 ) rc = mem1.n - pRhs->n;
74560  }
74561  }
74562  }
74563 
74564  /* RHS is a blob */
74565  else if( pRhs->flags & MEM_Blob ){
74566  assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
74567  getVarint32(&aKey1[idx1], serial_type);
74568  testcase( serial_type==12 );
74569  if( serial_type<12 || (serial_type & 0x01) ){
74570  rc = -1;
74571  }else{
74572  int nStr = (serial_type - 12) / 2;
74573  testcase( (d1+nStr)==(unsigned)nKey1 );
74574  testcase( (d1+nStr+1)==(unsigned)nKey1 );
74575  if( (d1+nStr) > (unsigned)nKey1 ){
74576  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74577  return 0; /* Corruption */
74578  }else if( pRhs->flags & MEM_Zero ){
74579  if( !isAllZero((const char*)&aKey1[d1],nStr) ){
74580  rc = 1;
74581  }else{
74582  rc = nStr - pRhs->u.nZero;
74583  }
74584  }else{
74585  int nCmp = MIN(nStr, pRhs->n);
74586  rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74587  if( rc==0 ) rc = nStr - pRhs->n;
74588  }
74589  }
74590  }
74591 
74592  /* RHS is null */
74593  else{
74594  serial_type = aKey1[idx1];
74595  rc = (serial_type!=0);
74596  }
74597 
74598  if( rc!=0 ){
74599  if( pKeyInfo->aSortOrder[i] ){
74600  rc = -rc;
74601  }
74602  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
74603  assert( mem1.szMalloc==0 ); /* See comment below */
74604  return rc;
74605  }
74606 
74607  i++;
74608  pRhs++;
74609  d1 += sqlite3VdbeSerialTypeLen(serial_type);
74610  idx1 += sqlite3VarintLen(serial_type);
74611  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
74612 
74613  /* No memory allocation is ever used on mem1. Prove this using
74614  ** the following assert(). If the assert() fails, it indicates a
74615  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
74616  assert( mem1.szMalloc==0 );
74617 
74618  /* rc==0 here means that one or both of the keys ran out of fields and
74619  ** all the fields up to that point were equal. Return the default_rc
74620  ** value. */
74621  assert( CORRUPT_DB
74622  || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
74623  || pKeyInfo->db->mallocFailed
74624  );
74625  pPKey2->eqSeen = 1;
74626  return pPKey2->default_rc;
74627 }
74628 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
74629  int nKey1, const void *pKey1, /* Left key */
74630  UnpackedRecord *pPKey2 /* Right key */
74631 ){
74632  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
74633 }
74634 
74635 
74636 /*
74637 ** This function is an optimized version of sqlite3VdbeRecordCompare()
74638 ** that (a) the first field of pPKey2 is an integer, and (b) the
74639 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
74640 ** byte (i.e. is less than 128).
74641 **
74642 ** To avoid concerns about buffer overreads, this routine is only used
74643 ** on schemas where the maximum valid header size is 63 bytes or less.
74644 */
74645 static int vdbeRecordCompareInt(
74646  int nKey1, const void *pKey1, /* Left key */
74647  UnpackedRecord *pPKey2 /* Right key */
74648 ){
74649  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
74650  int serial_type = ((const u8*)pKey1)[1];
74651  int res;
74652  u32 y;
74653  u64 x;
74654  i64 v;
74655  i64 lhs;
74656 
74657  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74658  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
74659  switch( serial_type ){
74660  case 1: { /* 1-byte signed integer */
74661  lhs = ONE_BYTE_INT(aKey);
74662  testcase( lhs<0 );
74663  break;
74664  }
74665  case 2: { /* 2-byte signed integer */
74666  lhs = TWO_BYTE_INT(aKey);
74667  testcase( lhs<0 );
74668  break;
74669  }
74670  case 3: { /* 3-byte signed integer */
74671  lhs = THREE_BYTE_INT(aKey);
74672  testcase( lhs<0 );
74673  break;
74674  }
74675  case 4: { /* 4-byte signed integer */
74676  y = FOUR_BYTE_UINT(aKey);
74677  lhs = (i64)*(int*)&y;
74678  testcase( lhs<0 );
74679  break;
74680  }
74681  case 5: { /* 6-byte signed integer */
74682  lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74683  testcase( lhs<0 );
74684  break;
74685  }
74686  case 6: { /* 8-byte signed integer */
74687  x = FOUR_BYTE_UINT(aKey);
74688  x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74689  lhs = *(i64*)&x;
74690  testcase( lhs<0 );
74691  break;
74692  }
74693  case 8:
74694  lhs = 0;
74695  break;
74696  case 9:
74697  lhs = 1;
74698  break;
74699 
74700  /* This case could be removed without changing the results of running
74701  ** this code. Including it causes gcc to generate a faster switch
74702  ** statement (since the range of switch targets now starts at zero and
74703  ** is contiguous) but does not cause any duplicate code to be generated
74704  ** (as gcc is clever enough to combine the two like cases). Other
74705  ** compilers might be similar. */
74706  case 0: case 7:
74707  return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74708 
74709  default:
74710  return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74711  }
74712 
74713  v = pPKey2->aMem[0].u.i;
74714  if( v>lhs ){
74715  res = pPKey2->r1;
74716  }else if( v<lhs ){
74717  res = pPKey2->r2;
74718  }else if( pPKey2->nField>1 ){
74719  /* The first fields of the two keys are equal. Compare the trailing
74720  ** fields. */
74721  res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74722  }else{
74723  /* The first fields of the two keys are equal and there are no trailing
74724  ** fields. Return pPKey2->default_rc in this case. */
74725  res = pPKey2->default_rc;
74726  pPKey2->eqSeen = 1;
74727  }
74728 
74729  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
74730  return res;
74731 }
74732 
74733 /*
74734 ** This function is an optimized version of sqlite3VdbeRecordCompare()
74735 ** that (a) the first field of pPKey2 is a string, that (b) the first field
74736 ** uses the collation sequence BINARY and (c) that the size-of-header varint
74737 ** at the start of (pKey1/nKey1) fits in a single byte.
74738 */
74739 static int vdbeRecordCompareString(
74740  int nKey1, const void *pKey1, /* Left key */
74741  UnpackedRecord *pPKey2 /* Right key */
74742 ){
74743  const u8 *aKey1 = (const u8*)pKey1;
74744  int serial_type;
74745  int res;
74746 
74747  assert( pPKey2->aMem[0].flags & MEM_Str );
74748  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74749  getVarint32(&aKey1[1], serial_type);
74750  if( serial_type<12 ){
74751  res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
74752  }else if( !(serial_type & 0x01) ){
74753  res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
74754  }else{
74755  int nCmp;
74756  int nStr;
74757  int szHdr = aKey1[0];
74758 
74759  nStr = (serial_type-12) / 2;
74760  if( (szHdr + nStr) > nKey1 ){
74761  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74762  return 0; /* Corruption */
74763  }
74764  nCmp = MIN( pPKey2->aMem[0].n, nStr );
74765  res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
74766 
74767  if( res==0 ){
74768  res = nStr - pPKey2->aMem[0].n;
74769  if( res==0 ){
74770  if( pPKey2->nField>1 ){
74771  res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74772  }else{
74773  res = pPKey2->default_rc;
74774  pPKey2->eqSeen = 1;
74775  }
74776  }else if( res>0 ){
74777  res = pPKey2->r2;
74778  }else{
74779  res = pPKey2->r1;
74780  }
74781  }else if( res>0 ){
74782  res = pPKey2->r2;
74783  }else{
74784  res = pPKey2->r1;
74785  }
74786  }
74787 
74788  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
74789  || CORRUPT_DB
74790  || pPKey2->pKeyInfo->db->mallocFailed
74791  );
74792  return res;
74793 }
74794 
74795 /*
74796 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
74797 ** suitable for comparing serialized records to the unpacked record passed
74798 ** as the only argument.
74799 */
74800 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
74801  /* varintRecordCompareInt() and varintRecordCompareString() both assume
74802  ** that the size-of-header varint that occurs at the start of each record
74803  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
74804  ** also assumes that it is safe to overread a buffer by at least the
74805  ** maximum possible legal header size plus 8 bytes. Because there is
74806  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
74807  ** buffer passed to varintRecordCompareInt() this makes it convenient to
74808  ** limit the size of the header to 64 bytes in cases where the first field
74809  ** is an integer.
74810  **
74811  ** The easiest way to enforce this limit is to consider only records with
74812  ** 13 fields or less. If the first field is an integer, the maximum legal
74813  ** header size is (12*5 + 1 + 1) bytes. */
74814  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
74815  int flags = p->aMem[0].flags;
74816  if( p->pKeyInfo->aSortOrder[0] ){
74817  p->r1 = 1;
74818  p->r2 = -1;
74819  }else{
74820  p->r1 = -1;
74821  p->r2 = 1;
74822  }
74823  if( (flags & MEM_Int) ){
74824  return vdbeRecordCompareInt;
74825  }
74826  testcase( flags & MEM_Real );
74827  testcase( flags & MEM_Null );
74828  testcase( flags & MEM_Blob );
74829  if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
74830  assert( flags & MEM_Str );
74831  return vdbeRecordCompareString;
74832  }
74833  }
74834 
74835  return sqlite3VdbeRecordCompare;
74836 }
74837 
74838 /*
74839 ** pCur points at an index entry created using the OP_MakeRecord opcode.
74840 ** Read the rowid (the last field in the record) and store it in *rowid.
74841 ** Return SQLITE_OK if everything works, or an error code otherwise.
74842 **
74843 ** pCur might be pointing to text obtained from a corrupt database file.
74844 ** So the content cannot be trusted. Do appropriate checks on the content.
74845 */
74846 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
74847  i64 nCellKey = 0;
74848  int rc;
74849  u32 szHdr; /* Size of the header */
74850  u32 typeRowid; /* Serial type of the rowid */
74851  u32 lenRowid; /* Size of the rowid */
74852  Mem m, v;
74853 
74854  /* Get the size of the index entry. Only indices entries of less
74855  ** than 2GiB are support - anything large must be database corruption.
74856  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
74857  ** this code can safely assume that nCellKey is 32-bits
74858  */
74859  assert( sqlite3BtreeCursorIsValid(pCur) );
74860  nCellKey = sqlite3BtreePayloadSize(pCur);
74861  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
74862 
74863  /* Read in the complete content of the index entry */
74864  sqlite3VdbeMemInit(&m, db, 0);
74865  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74866  if( rc ){
74867  return rc;
74868  }
74869 
74870  /* The index entry must begin with a header size */
74871  (void)getVarint32((u8*)m.z, szHdr);
74872  testcase( szHdr==3 );
74873  testcase( szHdr==m.n );
74874  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
74875  goto idx_rowid_corruption;
74876  }
74877 
74878  /* The last field of the index should be an integer - the ROWID.
74879  ** Verify that the last entry really is an integer. */
74880  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
74881  testcase( typeRowid==1 );
74882  testcase( typeRowid==2 );
74883  testcase( typeRowid==3 );
74884  testcase( typeRowid==4 );
74885  testcase( typeRowid==5 );
74886  testcase( typeRowid==6 );
74887  testcase( typeRowid==8 );
74888  testcase( typeRowid==9 );
74889  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
74890  goto idx_rowid_corruption;
74891  }
74892  lenRowid = sqlite3SmallTypeSizes[typeRowid];
74893  testcase( (u32)m.n==szHdr+lenRowid );
74894  if( unlikely((u32)m.n<szHdr+lenRowid) ){
74895  goto idx_rowid_corruption;
74896  }
74897 
74898  /* Fetch the integer off the end of the index record */
74899  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
74900  *rowid = v.u.i;
74901  sqlite3VdbeMemRelease(&m);
74902  return SQLITE_OK;
74903 
74904  /* Jump here if database corruption is detected after m has been
74905  ** allocated. Free the m object and return SQLITE_CORRUPT. */
74906 idx_rowid_corruption:
74907  testcase( m.szMalloc!=0 );
74908  sqlite3VdbeMemRelease(&m);
74909  return SQLITE_CORRUPT_BKPT;
74910 }
74911 
74912 /*
74913 ** Compare the key of the index entry that cursor pC is pointing to against
74914 ** the key string in pUnpacked. Write into *pRes a number
74915 ** that is negative, zero, or positive if pC is less than, equal to,
74916 ** or greater than pUnpacked. Return SQLITE_OK on success.
74917 **
74918 ** pUnpacked is either created without a rowid or is truncated so that it
74919 ** omits the rowid at the end. The rowid at the end of the index entry
74920 ** is ignored as well. Hence, this routine only compares the prefixes
74921 ** of the keys prior to the final rowid, not the entire key.
74922 */
74923 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
74924  sqlite3 *db, /* Database connection */
74925  VdbeCursor *pC, /* The cursor to compare against */
74926  UnpackedRecord *pUnpacked, /* Unpacked version of key */
74927  int *res /* Write the comparison result here */
74928 ){
74929  i64 nCellKey = 0;
74930  int rc;
74931  BtCursor *pCur;
74932  Mem m;
74933 
74934  assert( pC->eCurType==CURTYPE_BTREE );
74935  pCur = pC->uc.pCursor;
74936  assert( sqlite3BtreeCursorIsValid(pCur) );
74937  nCellKey = sqlite3BtreePayloadSize(pCur);
74938  /* nCellKey will always be between 0 and 0xffffffff because of the way
74939  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
74940  if( nCellKey<=0 || nCellKey>0x7fffffff ){
74941  *res = 0;
74942  return SQLITE_CORRUPT_BKPT;
74943  }
74944  sqlite3VdbeMemInit(&m, db, 0);
74945  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74946  if( rc ){
74947  return rc;
74948  }
74949  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
74950  sqlite3VdbeMemRelease(&m);
74951  return SQLITE_OK;
74952 }
74953 
74954 /*
74955 ** This routine sets the value to be returned by subsequent calls to
74956 ** sqlite3_changes() on the database handle 'db'.
74957 */
74958 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
74959  assert( sqlite3_mutex_held(db->mutex) );
74960  db->nChange = nChange;
74961  db->nTotalChange += nChange;
74962 }
74963 
74964 /*
74965 ** Set a flag in the vdbe to update the change counter when it is finalised
74966 ** or reset.
74967 */
74968 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
74969  v->changeCntOn = 1;
74970 }
74971 
74972 /*
74973 ** Mark every prepared statement associated with a database connection
74974 ** as expired.
74975 **
74976 ** An expired statement means that recompilation of the statement is
74977 ** recommend. Statements expire when things happen that make their
74978 ** programs obsolete. Removing user-defined functions or collating
74979 ** sequences, or changing an authorization function are the types of
74980 ** things that make prepared statements obsolete.
74981 */
74982 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
74983  Vdbe *p;
74984  for(p = db->pVdbe; p; p=p->pNext){
74985  p->expired = 1;
74986  }
74987 }
74988 
74989 /*
74990 ** Return the database associated with the Vdbe.
74991 */
74992 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
74993  return v->db;
74994 }
74995 
74996 /*
74997 ** Return a pointer to an sqlite3_value structure containing the value bound
74998 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
74999 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
75000 ** constants) to the value before returning it.
75001 **
75002 ** The returned value must be freed by the caller using sqlite3ValueFree().
75003 */
75004 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
75005  assert( iVar>0 );
75006  if( v ){
75007  Mem *pMem = &v->aVar[iVar-1];
75008  if( 0==(pMem->flags & MEM_Null) ){
75009  sqlite3_value *pRet = sqlite3ValueNew(v->db);
75010  if( pRet ){
75011  sqlite3VdbeMemCopy((Mem *)pRet, pMem);
75012  sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
75013  }
75014  return pRet;
75015  }
75016  }
75017  return 0;
75018 }
75019 
75020 /*
75021 ** Configure SQL variable iVar so that binding a new value to it signals
75022 ** to sqlite3_reoptimize() that re-preparing the statement may result
75023 ** in a better query plan.
75024 */
75025 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
75026  assert( iVar>0 );
75027  if( iVar>32 ){
75028  v->expmask = 0xffffffff;
75029  }else{
75030  v->expmask |= ((u32)1 << (iVar-1));
75031  }
75032 }
75033 
75034 #ifndef SQLITE_OMIT_VIRTUALTABLE
75035 /*
75036 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
75037 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
75038 ** in memory obtained from sqlite3DbMalloc).
75039 */
75040 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
75041  if( pVtab->zErrMsg ){
75042  sqlite3 *db = p->db;
75043  sqlite3DbFree(db, p->zErrMsg);
75044  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
75045  sqlite3_free(pVtab->zErrMsg);
75046  pVtab->zErrMsg = 0;
75047  }
75048 }
75049 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75050 
75051 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
75052 
75053 /*
75054 ** If the second argument is not NULL, release any allocations associated
75055 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
75056 ** structure itself, using sqlite3DbFree().
75057 **
75058 ** This function is used to free UnpackedRecord structures allocated by
75059 ** the vdbeUnpackRecord() function found in vdbeapi.c.
75060 */
75061 static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){
75062  if( p ){
75063  int i;
75064  for(i=0; i<p->nField; i++){
75065  Mem *pMem = &p->aMem[i];
75066  if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
75067  }
75068  sqlite3DbFree(db, p);
75069  }
75070 }
75071 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
75072 
75073 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
75074 /*
75075 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
75076 ** then cursor passed as the second argument should point to the row about
75077 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
75078 ** the required value will be read from the row the cursor points to.
75079 */
75080 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
75081  Vdbe *v, /* Vdbe pre-update hook is invoked by */
75082  VdbeCursor *pCsr, /* Cursor to grab old.* values from */
75083  int op, /* SQLITE_INSERT, UPDATE or DELETE */
75084  const char *zDb, /* Database name */
75085  Table *pTab, /* Modified table */
75086  i64 iKey1, /* Initial key value */
75087  int iReg /* Register for new.* record */
75088 ){
75089  sqlite3 *db = v->db;
75090  i64 iKey2;
75091  PreUpdate preupdate;
75092  const char *zTbl = pTab->zName;
75093  static const u8 fakeSortOrder = 0;
75094 
75095  assert( db->pPreUpdate==0 );
75096  memset(&preupdate, 0, sizeof(PreUpdate));
75097  if( op==SQLITE_UPDATE ){
75098  iKey2 = v->aMem[iReg].u.i;
75099  }else{
75100  iKey2 = iKey1;
75101  }
75102 
75103  assert( pCsr->nField==pTab->nCol
75104  || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
75105  );
75106 
75107  preupdate.v = v;
75108  preupdate.pCsr = pCsr;
75109  preupdate.op = op;
75110  preupdate.iNewReg = iReg;
75111  preupdate.keyinfo.db = db;
75112  preupdate.keyinfo.enc = ENC(db);
75113  preupdate.keyinfo.nField = pTab->nCol;
75114  preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
75115  preupdate.iKey1 = iKey1;
75116  preupdate.iKey2 = iKey2;
75117  preupdate.pTab = pTab;
75118 
75119  db->pPreUpdate = &preupdate;
75120  db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
75121  db->pPreUpdate = 0;
75122  sqlite3DbFree(db, preupdate.aRecord);
75123  vdbeFreeUnpacked(db, preupdate.pUnpacked);
75124  vdbeFreeUnpacked(db, preupdate.pNewUnpacked);
75125  if( preupdate.aNew ){
75126  int i;
75127  for(i=0; i<pCsr->nField; i++){
75128  sqlite3VdbeMemRelease(&preupdate.aNew[i]);
75129  }
75130  sqlite3DbFree(db, preupdate.aNew);
75131  }
75132 }
75133 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
75134 
75135 /************** End of vdbeaux.c *********************************************/
75136 /************** Begin file vdbeapi.c *****************************************/
75137 /*
75138 ** 2004 May 26
75139 **
75140 ** The author disclaims copyright to this source code. In place of
75141 ** a legal notice, here is a blessing:
75142 **
75143 ** May you do good and not evil.
75144 ** May you find forgiveness for yourself and forgive others.
75145 ** May you share freely, never taking more than you give.
75146 **
75147 *************************************************************************
75148 **
75149 ** This file contains code use to implement APIs that are part of the
75150 ** VDBE.
75151 */
75152 /* #include "sqliteInt.h" */
75153 /* #include "vdbeInt.h" */
75154 
75155 #ifndef SQLITE_OMIT_DEPRECATED
75156 /*
75157 ** Return TRUE (non-zero) of the statement supplied as an argument needs
75158 ** to be recompiled. A statement needs to be recompiled whenever the
75159 ** execution environment changes in a way that would alter the program
75160 ** that sqlite3_prepare() generates. For example, if new functions or
75161 ** collating sequences are registered or if an authorizer function is
75162 ** added or changed.
75163 */
75164 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
75165  Vdbe *p = (Vdbe*)pStmt;
75166  return p==0 || p->expired;
75167 }
75168 #endif
75169 
75170 /*
75171 ** Check on a Vdbe to make sure it has not been finalized. Log
75172 ** an error and return true if it has been finalized (or is otherwise
75173 ** invalid). Return false if it is ok.
75174 */
75175 static int vdbeSafety(Vdbe *p){
75176  if( p->db==0 ){
75177  sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
75178  return 1;
75179  }else{
75180  return 0;
75181  }
75182 }
75183 static int vdbeSafetyNotNull(Vdbe *p){
75184  if( p==0 ){
75185  sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
75186  return 1;
75187  }else{
75188  return vdbeSafety(p);
75189  }
75190 }
75191 
75192 #ifndef SQLITE_OMIT_TRACE
75193 /*
75194 ** Invoke the profile callback. This routine is only called if we already
75195 ** know that the profile callback is defined and needs to be invoked.
75196 */
75197 static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
75198  sqlite3_int64 iNow;
75199  sqlite3_int64 iElapse;
75200  assert( p->startTime>0 );
75201  assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
75202  assert( db->init.busy==0 );
75203  assert( p->zSql!=0 );
75204  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
75205  iElapse = (iNow - p->startTime)*1000000;
75206  if( db->xProfile ){
75207  db->xProfile(db->pProfileArg, p->zSql, iElapse);
75208  }
75209  if( db->mTrace & SQLITE_TRACE_PROFILE ){
75210  db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
75211  }
75212  p->startTime = 0;
75213 }
75214 /*
75215 ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
75216 ** is needed, and it invokes the callback if it is needed.
75217 */
75218 # define checkProfileCallback(DB,P) \
75219  if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
75220 #else
75221 # define checkProfileCallback(DB,P) /*no-op*/
75222 #endif
75223 
75224 /*
75225 ** The following routine destroys a virtual machine that is created by
75226 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
75227 ** success/failure code that describes the result of executing the virtual
75228 ** machine.
75229 **
75230 ** This routine sets the error code and string returned by
75231 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75232 */
75233 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
75234  int rc;
75235  if( pStmt==0 ){
75236  /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
75237  ** pointer is a harmless no-op. */
75238  rc = SQLITE_OK;
75239  }else{
75240  Vdbe *v = (Vdbe*)pStmt;
75241  sqlite3 *db = v->db;
75242  if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
75243  sqlite3_mutex_enter(db->mutex);
75244  checkProfileCallback(db, v);
75245  rc = sqlite3VdbeFinalize(v);
75246  rc = sqlite3ApiExit(db, rc);
75247  sqlite3LeaveMutexAndCloseZombie(db);
75248  }
75249  return rc;
75250 }
75251 
75252 /*
75253 ** Terminate the current execution of an SQL statement and reset it
75254 ** back to its starting state so that it can be reused. A success code from
75255 ** the prior execution is returned.
75256 **
75257 ** This routine sets the error code and string returned by
75258 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75259 */
75260 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
75261  int rc;
75262  if( pStmt==0 ){
75263  rc = SQLITE_OK;
75264  }else{
75265  Vdbe *v = (Vdbe*)pStmt;
75266  sqlite3 *db = v->db;
75267  sqlite3_mutex_enter(db->mutex);
75268  checkProfileCallback(db, v);
75269  rc = sqlite3VdbeReset(v);
75270  sqlite3VdbeRewind(v);
75271  assert( (rc & (db->errMask))==rc );
75272  rc = sqlite3ApiExit(db, rc);
75273  sqlite3_mutex_leave(db->mutex);
75274  }
75275  return rc;
75276 }
75277 
75278 /*
75279 ** Set all the parameters in the compiled SQL statement to NULL.
75280 */
75281 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
75282  int i;
75283  int rc = SQLITE_OK;
75284  Vdbe *p = (Vdbe*)pStmt;
75285 #if SQLITE_THREADSAFE
75286  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
75287 #endif
75288  sqlite3_mutex_enter(mutex);
75289  for(i=0; i<p->nVar; i++){
75290  sqlite3VdbeMemRelease(&p->aVar[i]);
75291  p->aVar[i].flags = MEM_Null;
75292  }
75293  if( p->isPrepareV2 && p->expmask ){
75294  p->expired = 1;
75295  }
75296  sqlite3_mutex_leave(mutex);
75297  return rc;
75298 }
75299 
75300 
75301 /**************************** sqlite3_value_ *******************************
75302 ** The following routines extract information from a Mem or sqlite3_value
75303 ** structure.
75304 */
75305 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
75306  Mem *p = (Mem*)pVal;
75307  if( p->flags & (MEM_Blob|MEM_Str) ){
75308  if( ExpandBlob(p)!=SQLITE_OK ){
75309  assert( p->flags==MEM_Null && p->z==0 );
75310  return 0;
75311  }
75312  p->flags |= MEM_Blob;
75313  return p->n ? p->z : 0;
75314  }else{
75315  return sqlite3_value_text(pVal);
75316  }
75317 }
75318 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
75319  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
75320 }
75321 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
75322  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
75323 }
75324 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
75325  return sqlite3VdbeRealValue((Mem*)pVal);
75326 }
75327 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
75328  return (int)sqlite3VdbeIntValue((Mem*)pVal);
75329 }
75330 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
75331  return sqlite3VdbeIntValue((Mem*)pVal);
75332 }
75333 SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
75334  Mem *pMem = (Mem*)pVal;
75335  return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
75336 }
75337 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
75338  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
75339 }
75340 #ifndef SQLITE_OMIT_UTF16
75341 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
75342  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
75343 }
75344 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
75345  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
75346 }
75347 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
75348  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
75349 }
75350 #endif /* SQLITE_OMIT_UTF16 */
75351 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
75352 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
75353 ** point number string BLOB NULL
75354 */
75355 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
75356  static const u8 aType[] = {
75357  SQLITE_BLOB, /* 0x00 */
75358  SQLITE_NULL, /* 0x01 */
75359  SQLITE_TEXT, /* 0x02 */
75360  SQLITE_NULL, /* 0x03 */
75361  SQLITE_INTEGER, /* 0x04 */
75362  SQLITE_NULL, /* 0x05 */
75363  SQLITE_INTEGER, /* 0x06 */
75364  SQLITE_NULL, /* 0x07 */
75365  SQLITE_FLOAT, /* 0x08 */
75366  SQLITE_NULL, /* 0x09 */
75367  SQLITE_FLOAT, /* 0x0a */
75368  SQLITE_NULL, /* 0x0b */
75369  SQLITE_INTEGER, /* 0x0c */
75370  SQLITE_NULL, /* 0x0d */
75371  SQLITE_INTEGER, /* 0x0e */
75372  SQLITE_NULL, /* 0x0f */
75373  SQLITE_BLOB, /* 0x10 */
75374  SQLITE_NULL, /* 0x11 */
75375  SQLITE_TEXT, /* 0x12 */
75376  SQLITE_NULL, /* 0x13 */
75377  SQLITE_INTEGER, /* 0x14 */
75378  SQLITE_NULL, /* 0x15 */
75379  SQLITE_INTEGER, /* 0x16 */
75380  SQLITE_NULL, /* 0x17 */
75381  SQLITE_FLOAT, /* 0x18 */
75382  SQLITE_NULL, /* 0x19 */
75383  SQLITE_FLOAT, /* 0x1a */
75384  SQLITE_NULL, /* 0x1b */
75385  SQLITE_INTEGER, /* 0x1c */
75386  SQLITE_NULL, /* 0x1d */
75387  SQLITE_INTEGER, /* 0x1e */
75388  SQLITE_NULL, /* 0x1f */
75389  };
75390  return aType[pVal->flags&MEM_AffMask];
75391 }
75392 
75393 /* Make a copy of an sqlite3_value object
75394 */
75395 SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
75396  sqlite3_value *pNew;
75397  if( pOrig==0 ) return 0;
75398  pNew = sqlite3_malloc( sizeof(*pNew) );
75399  if( pNew==0 ) return 0;
75400  memset(pNew, 0, sizeof(*pNew));
75401  memcpy(pNew, pOrig, MEMCELLSIZE);
75402  pNew->flags &= ~MEM_Dyn;
75403  pNew->db = 0;
75404  if( pNew->flags&(MEM_Str|MEM_Blob) ){
75405  pNew->flags &= ~(MEM_Static|MEM_Dyn);
75406  pNew->flags |= MEM_Ephem;
75407  if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
75408  sqlite3ValueFree(pNew);
75409  pNew = 0;
75410  }
75411  }
75412  return pNew;
75413 }
75414 
75415 /* Destroy an sqlite3_value object previously obtained from
75416 ** sqlite3_value_dup().
75417 */
75418 SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
75419  sqlite3ValueFree(pOld);
75420 }
75421 
75422 
75423 /**************************** sqlite3_result_ *******************************
75424 ** The following routines are used by user-defined functions to specify
75425 ** the function result.
75426 **
75427 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
75428 ** result as a string or blob but if the string or blob is too large, it
75429 ** then sets the error code to SQLITE_TOOBIG
75430 **
75431 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
75432 ** on value P is not going to be used and need to be destroyed.
75433 */
75434 static void setResultStrOrError(
75435  sqlite3_context *pCtx, /* Function context */
75436  const char *z, /* String pointer */
75437  int n, /* Bytes in string, or negative */
75438  u8 enc, /* Encoding of z. 0 for BLOBs */
75439  void (*xDel)(void*) /* Destructor function */
75440 ){
75441  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
75442  sqlite3_result_error_toobig(pCtx);
75443  }
75444 }
75445 static int invokeValueDestructor(
75446  const void *p, /* Value to destroy */
75447  void (*xDel)(void*), /* The destructor */
75448  sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
75449 ){
75450  assert( xDel!=SQLITE_DYNAMIC );
75451  if( xDel==0 ){
75452  /* noop */
75453  }else if( xDel==SQLITE_TRANSIENT ){
75454  /* noop */
75455  }else{
75456  xDel((void*)p);
75457  }
75458  if( pCtx ) sqlite3_result_error_toobig(pCtx);
75459  return SQLITE_TOOBIG;
75460 }
75461 SQLITE_API void sqlite3_result_blob(
75462  sqlite3_context *pCtx,
75463  const void *z,
75464  int n,
75465  void (*xDel)(void *)
75466 ){
75467  assert( n>=0 );
75468  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75469  setResultStrOrError(pCtx, z, n, 0, xDel);
75470 }
75471 SQLITE_API void sqlite3_result_blob64(
75472  sqlite3_context *pCtx,
75473  const void *z,
75474  sqlite3_uint64 n,
75475  void (*xDel)(void *)
75476 ){
75477  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75478  assert( xDel!=SQLITE_DYNAMIC );
75479  if( n>0x7fffffff ){
75480  (void)invokeValueDestructor(z, xDel, pCtx);
75481  }else{
75482  setResultStrOrError(pCtx, z, (int)n, 0, xDel);
75483  }
75484 }
75485 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
75486  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75487  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
75488 }
75489 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
75490  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75491  pCtx->isError = SQLITE_ERROR;
75492  pCtx->fErrorOrAux = 1;
75493  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
75494 }
75495 #ifndef SQLITE_OMIT_UTF16
75496 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
75497  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75498  pCtx->isError = SQLITE_ERROR;
75499  pCtx->fErrorOrAux = 1;
75500  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
75501 }
75502 #endif
75503 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
75504  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75505  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
75506 }
75507 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
75508  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75509  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
75510 }
75511 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
75512  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75513  sqlite3VdbeMemSetNull(pCtx->pOut);
75514 }
75515 SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
75516  Mem *pOut = pCtx->pOut;
75517  assert( sqlite3_mutex_held(pOut->db->mutex) );
75518  pOut->eSubtype = eSubtype & 0xff;
75519  pOut->flags |= MEM_Subtype;
75520 }
75521 SQLITE_API void sqlite3_result_text(
75522  sqlite3_context *pCtx,
75523  const char *z,
75524  int n,
75525  void (*xDel)(void *)
75526 ){
75527  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75528  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
75529 }
75530 SQLITE_API void sqlite3_result_text64(
75531  sqlite3_context *pCtx,
75532  const char *z,
75533  sqlite3_uint64 n,
75534  void (*xDel)(void *),
75535  unsigned char enc
75536 ){
75537  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75538  assert( xDel!=SQLITE_DYNAMIC );
75539  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
75540  if( n>0x7fffffff ){
75541  (void)invokeValueDestructor(z, xDel, pCtx);
75542  }else{
75543  setResultStrOrError(pCtx, z, (int)n, enc, xDel);
75544  }
75545 }
75546 #ifndef SQLITE_OMIT_UTF16
75547 SQLITE_API void sqlite3_result_text16(
75548  sqlite3_context *pCtx,
75549  const void *z,
75550  int n,
75551  void (*xDel)(void *)
75552 ){
75553  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75554  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
75555 }
75556 SQLITE_API void sqlite3_result_text16be(
75557  sqlite3_context *pCtx,
75558  const void *z,
75559  int n,
75560  void (*xDel)(void *)
75561 ){
75562  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75563  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
75564 }
75565 SQLITE_API void sqlite3_result_text16le(
75566  sqlite3_context *pCtx,
75567  const void *z,
75568  int n,
75569  void (*xDel)(void *)
75570 ){
75571  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75572  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
75573 }
75574 #endif /* SQLITE_OMIT_UTF16 */
75575 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
75576  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75577  sqlite3VdbeMemCopy(pCtx->pOut, pValue);
75578 }
75579 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
75580  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75581  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
75582 }
75583 SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
75584  Mem *pOut = pCtx->pOut;
75585  assert( sqlite3_mutex_held(pOut->db->mutex) );
75586  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
75587  return SQLITE_TOOBIG;
75588  }
75589  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
75590  return SQLITE_OK;
75591 }
75592 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
75593  pCtx->isError = errCode;
75594  pCtx->fErrorOrAux = 1;
75595 #ifdef SQLITE_DEBUG
75596  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
75597 #endif
75598  if( pCtx->pOut->flags & MEM_Null ){
75599  sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
75600  SQLITE_UTF8, SQLITE_STATIC);
75601  }
75602 }
75603 
75604 /* Force an SQLITE_TOOBIG error. */
75605 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
75606  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75607  pCtx->isError = SQLITE_TOOBIG;
75608  pCtx->fErrorOrAux = 1;
75609  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
75610  SQLITE_UTF8, SQLITE_STATIC);
75611 }
75612 
75613 /* An SQLITE_NOMEM error. */
75614 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
75615  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75616  sqlite3VdbeMemSetNull(pCtx->pOut);
75617  pCtx->isError = SQLITE_NOMEM_BKPT;
75618  pCtx->fErrorOrAux = 1;
75619  sqlite3OomFault(pCtx->pOut->db);
75620 }
75621 
75622 /*
75623 ** This function is called after a transaction has been committed. It
75624 ** invokes callbacks registered with sqlite3_wal_hook() as required.
75625 */
75626 static int doWalCallbacks(sqlite3 *db){
75627  int rc = SQLITE_OK;
75628 #ifndef SQLITE_OMIT_WAL
75629  int i;
75630  for(i=0; i<db->nDb; i++){
75631  Btree *pBt = db->aDb[i].pBt;
75632  if( pBt ){
75633  int nEntry;
75634  sqlite3BtreeEnter(pBt);
75635  nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
75636  sqlite3BtreeLeave(pBt);
75637  if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
75638  rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
75639  }
75640  }
75641  }
75642 #endif
75643  return rc;
75644 }
75645 
75646 
75647 /*
75648 ** Execute the statement pStmt, either until a row of data is ready, the
75649 ** statement is completely executed or an error occurs.
75650 **
75651 ** This routine implements the bulk of the logic behind the sqlite_step()
75652 ** API. The only thing omitted is the automatic recompile if a
75653 ** schema change has occurred. That detail is handled by the
75654 ** outer sqlite3_step() wrapper procedure.
75655 */
75656 static int sqlite3Step(Vdbe *p){
75657  sqlite3 *db;
75658  int rc;
75659 
75660  assert(p);
75661  if( p->magic!=VDBE_MAGIC_RUN ){
75662  /* We used to require that sqlite3_reset() be called before retrying
75663  ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
75664  ** with version 3.7.0, we changed this so that sqlite3_reset() would
75665  ** be called automatically instead of throwing the SQLITE_MISUSE error.
75666  ** This "automatic-reset" change is not technically an incompatibility,
75667  ** since any application that receives an SQLITE_MISUSE is broken by
75668  ** definition.
75669  **
75670  ** Nevertheless, some published applications that were originally written
75671  ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
75672  ** returns, and those were broken by the automatic-reset change. As a
75673  ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
75674  ** legacy behavior of returning SQLITE_MISUSE for cases where the
75675  ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
75676  ** or SQLITE_BUSY error.
75677  */
75678 #ifdef SQLITE_OMIT_AUTORESET
75679  if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
75680  sqlite3_reset((sqlite3_stmt*)p);
75681  }else{
75682  return SQLITE_MISUSE_BKPT;
75683  }
75684 #else
75685  sqlite3_reset((sqlite3_stmt*)p);
75686 #endif
75687  }
75688 
75689  /* Check that malloc() has not failed. If it has, return early. */
75690  db = p->db;
75691  if( db->mallocFailed ){
75692  p->rc = SQLITE_NOMEM;
75693  return SQLITE_NOMEM_BKPT;
75694  }
75695 
75696  if( p->pc<=0 && p->expired ){
75697  p->rc = SQLITE_SCHEMA;
75698  rc = SQLITE_ERROR;
75699  goto end_of_step;
75700  }
75701  if( p->pc<0 ){
75702  /* If there are no other statements currently running, then
75703  ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
75704  ** from interrupting a statement that has not yet started.
75705  */
75706  if( db->nVdbeActive==0 ){
75707  db->u1.isInterrupted = 0;
75708  }
75709 
75710  assert( db->nVdbeWrite>0 || db->autoCommit==0
75711  || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
75712  );
75713 
75714 #ifndef SQLITE_OMIT_TRACE
75715  if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
75716  && !db->init.busy && p->zSql ){
75717  sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
75718  }else{
75719  assert( p->startTime==0 );
75720  }
75721 #endif
75722 
75723  db->nVdbeActive++;
75724  if( p->readOnly==0 ) db->nVdbeWrite++;
75725  if( p->bIsReader ) db->nVdbeRead++;
75726  p->pc = 0;
75727  }
75728 #ifdef SQLITE_DEBUG
75729  p->rcApp = SQLITE_OK;
75730 #endif
75731 #ifndef SQLITE_OMIT_EXPLAIN
75732  if( p->explain ){
75733  rc = sqlite3VdbeList(p);
75734  }else
75735 #endif /* SQLITE_OMIT_EXPLAIN */
75736  {
75737  db->nVdbeExec++;
75738  rc = sqlite3VdbeExec(p);
75739  db->nVdbeExec--;
75740  }
75741 
75742 #ifndef SQLITE_OMIT_TRACE
75743  /* If the statement completed successfully, invoke the profile callback */
75744  if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
75745 #endif
75746 
75747  if( rc==SQLITE_DONE ){
75748  assert( p->rc==SQLITE_OK );
75749  p->rc = doWalCallbacks(db);
75750  if( p->rc!=SQLITE_OK ){
75751  rc = SQLITE_ERROR;
75752  }
75753  }
75754 
75755  db->errCode = rc;
75756  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
75757  p->rc = SQLITE_NOMEM_BKPT;
75758  }
75759 end_of_step:
75760  /* At this point local variable rc holds the value that should be
75761  ** returned if this statement was compiled using the legacy
75762  ** sqlite3_prepare() interface. According to the docs, this can only
75763  ** be one of the values in the first assert() below. Variable p->rc
75764  ** contains the value that would be returned if sqlite3_finalize()
75765  ** were called on statement p.
75766  */
75767  assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
75768  || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
75769  );
75770  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
75771  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
75772  /* If this statement was prepared using sqlite3_prepare_v2(), and an
75773  ** error has occurred, then return the error code in p->rc to the
75774  ** caller. Set the error code in the database handle to the same value.
75775  */
75776  rc = sqlite3VdbeTransferError(p);
75777  }
75778  return (rc&db->errMask);
75779 }
75780 
75781 /*
75782 ** This is the top-level implementation of sqlite3_step(). Call
75783 ** sqlite3Step() to do most of the work. If a schema error occurs,
75784 ** call sqlite3Reprepare() and try again.
75785 */
75786 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
75787  int rc = SQLITE_OK; /* Result from sqlite3Step() */
75788  int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
75789  Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
75790  int cnt = 0; /* Counter to prevent infinite loop of reprepares */
75791  sqlite3 *db; /* The database connection */
75792 
75793  if( vdbeSafetyNotNull(v) ){
75794  return SQLITE_MISUSE_BKPT;
75795  }
75796  db = v->db;
75797  sqlite3_mutex_enter(db->mutex);
75798  v->doingRerun = 0;
75799  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
75800  && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
75801  int savedPc = v->pc;
75802  rc2 = rc = sqlite3Reprepare(v);
75803  if( rc!=SQLITE_OK) break;
75804  sqlite3_reset(pStmt);
75805  if( savedPc>=0 ) v->doingRerun = 1;
75806  assert( v->expired==0 );
75807  }
75808  if( rc2!=SQLITE_OK ){
75809  /* This case occurs after failing to recompile an sql statement.
75810  ** The error message from the SQL compiler has already been loaded
75811  ** into the database handle. This block copies the error message
75812  ** from the database handle into the statement and sets the statement
75813  ** program counter to 0 to ensure that when the statement is
75814  ** finalized or reset the parser error message is available via
75815  ** sqlite3_errmsg() and sqlite3_errcode().
75816  */
75817  const char *zErr = (const char *)sqlite3_value_text(db->pErr);
75818  sqlite3DbFree(db, v->zErrMsg);
75819  if( !db->mallocFailed ){
75820  v->zErrMsg = sqlite3DbStrDup(db, zErr);
75821  v->rc = rc2;
75822  } else {
75823  v->zErrMsg = 0;
75824  v->rc = rc = SQLITE_NOMEM_BKPT;
75825  }
75826  }
75827  rc = sqlite3ApiExit(db, rc);
75828  sqlite3_mutex_leave(db->mutex);
75829  return rc;
75830 }
75831 
75832 
75833 /*
75834 ** Extract the user data from a sqlite3_context structure and return a
75835 ** pointer to it.
75836 */
75837 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
75838  assert( p && p->pFunc );
75839  return p->pFunc->pUserData;
75840 }
75841 
75842 /*
75843 ** Extract the user data from a sqlite3_context structure and return a
75844 ** pointer to it.
75845 **
75846 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
75847 ** returns a copy of the pointer to the database connection (the 1st
75848 ** parameter) of the sqlite3_create_function() and
75849 ** sqlite3_create_function16() routines that originally registered the
75850 ** application defined function.
75851 */
75852 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
75853  assert( p && p->pOut );
75854  return p->pOut->db;
75855 }
75856 
75857 /*
75858 ** Return the current time for a statement. If the current time
75859 ** is requested more than once within the same run of a single prepared
75860 ** statement, the exact same time is returned for each invocation regardless
75861 ** of the amount of time that elapses between invocations. In other words,
75862 ** the time returned is always the time of the first call.
75863 */
75864 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
75865  int rc;
75866 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
75867  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
75868  assert( p->pVdbe!=0 );
75869 #else
75870  sqlite3_int64 iTime = 0;
75871  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
75872 #endif
75873  if( *piTime==0 ){
75874  rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
75875  if( rc ) *piTime = 0;
75876  }
75877  return *piTime;
75878 }
75879 
75880 /*
75881 ** The following is the implementation of an SQL function that always
75882 ** fails with an error message stating that the function is used in the
75883 ** wrong context. The sqlite3_overload_function() API might construct
75884 ** SQL function that use this routine so that the functions will exist
75885 ** for name resolution but are actually overloaded by the xFindFunction
75886 ** method of virtual tables.
75887 */
75888 SQLITE_PRIVATE void sqlite3InvalidFunction(
75889  sqlite3_context *context, /* The function calling context */
75890  int NotUsed, /* Number of arguments to the function */
75891  sqlite3_value **NotUsed2 /* Value of each argument */
75892 ){
75893  const char *zName = context->pFunc->zName;
75894  char *zErr;
75895  UNUSED_PARAMETER2(NotUsed, NotUsed2);
75896  zErr = sqlite3_mprintf(
75897  "unable to use function %s in the requested context", zName);
75898  sqlite3_result_error(context, zErr, -1);
75899  sqlite3_free(zErr);
75900 }
75901 
75902 /*
75903 ** Create a new aggregate context for p and return a pointer to
75904 ** its pMem->z element.
75905 */
75906 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
75907  Mem *pMem = p->pMem;
75908  assert( (pMem->flags & MEM_Agg)==0 );
75909  if( nByte<=0 ){
75910  sqlite3VdbeMemSetNull(pMem);
75911  pMem->z = 0;
75912  }else{
75913  sqlite3VdbeMemClearAndResize(pMem, nByte);
75914  pMem->flags = MEM_Agg;
75915  pMem->u.pDef = p->pFunc;
75916  if( pMem->z ){
75917  memset(pMem->z, 0, nByte);
75918  }
75919  }
75920  return (void*)pMem->z;
75921 }
75922 
75923 /*
75924 ** Allocate or return the aggregate context for a user function. A new
75925 ** context is allocated on the first call. Subsequent calls return the
75926 ** same context that was returned on prior calls.
75927 */
75928 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
75929  assert( p && p->pFunc && p->pFunc->xFinalize );
75930  assert( sqlite3_mutex_held(p->pOut->db->mutex) );
75931  testcase( nByte<0 );
75932  if( (p->pMem->flags & MEM_Agg)==0 ){
75933  return createAggContext(p, nByte);
75934  }else{
75935  return (void*)p->pMem->z;
75936  }
75937 }
75938 
75939 /*
75940 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
75941 ** the user-function defined by pCtx.
75942 */
75943 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
75944  AuxData *pAuxData;
75945 
75946  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75947 #if SQLITE_ENABLE_STAT3_OR_STAT4
75948  if( pCtx->pVdbe==0 ) return 0;
75949 #else
75950  assert( pCtx->pVdbe!=0 );
75951 #endif
75952  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75953  if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75954  }
75955 
75956  return (pAuxData ? pAuxData->pAux : 0);
75957 }
75958 
75959 /*
75960 ** Set the auxiliary data pointer and delete function, for the iArg'th
75961 ** argument to the user-function defined by pCtx. Any previous value is
75962 ** deleted by calling the delete function specified when it was set.
75963 */
75964 SQLITE_API void sqlite3_set_auxdata(
75965  sqlite3_context *pCtx,
75966  int iArg,
75967  void *pAux,
75968  void (*xDelete)(void*)
75969 ){
75970  AuxData *pAuxData;
75971  Vdbe *pVdbe = pCtx->pVdbe;
75972 
75973  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75974  if( iArg<0 ) goto failed;
75975 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
75976  if( pVdbe==0 ) goto failed;
75977 #else
75978  assert( pVdbe!=0 );
75979 #endif
75980 
75981  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75982  if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75983  }
75984  if( pAuxData==0 ){
75985  pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
75986  if( !pAuxData ) goto failed;
75987  pAuxData->iOp = pCtx->iOp;
75988  pAuxData->iArg = iArg;
75989  pAuxData->pNext = pVdbe->pAuxData;
75990  pVdbe->pAuxData = pAuxData;
75991  if( pCtx->fErrorOrAux==0 ){
75992  pCtx->isError = 0;
75993  pCtx->fErrorOrAux = 1;
75994  }
75995  }else if( pAuxData->xDelete ){
75996  pAuxData->xDelete(pAuxData->pAux);
75997  }
75998 
75999  pAuxData->pAux = pAux;
76000  pAuxData->xDelete = xDelete;
76001  return;
76002 
76003 failed:
76004  if( xDelete ){
76005  xDelete(pAux);
76006  }
76007 }
76008 
76009 #ifndef SQLITE_OMIT_DEPRECATED
76010 /*
76011 ** Return the number of times the Step function of an aggregate has been
76012 ** called.
76013 **
76014 ** This function is deprecated. Do not use it for new code. It is
76015 ** provide only to avoid breaking legacy code. New aggregate function
76016 ** implementations should keep their own counts within their aggregate
76017 ** context.
76018 */
76019 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
76020  assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
76021  return p->pMem->n;
76022 }
76023 #endif
76024 
76025 /*
76026 ** Return the number of columns in the result set for the statement pStmt.
76027 */
76028 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
76029  Vdbe *pVm = (Vdbe *)pStmt;
76030  return pVm ? pVm->nResColumn : 0;
76031 }
76032 
76033 /*
76034 ** Return the number of values available from the current row of the
76035 ** currently executing statement pStmt.
76036 */
76037 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
76038  Vdbe *pVm = (Vdbe *)pStmt;
76039  if( pVm==0 || pVm->pResultSet==0 ) return 0;
76040  return pVm->nResColumn;
76041 }
76042 
76043 /*
76044 ** Return a pointer to static memory containing an SQL NULL value.
76045 */
76046 static const Mem *columnNullValue(void){
76047  /* Even though the Mem structure contains an element
76048  ** of type i64, on certain architectures (x86) with certain compiler
76049  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
76050  ** instead of an 8-byte one. This all works fine, except that when
76051  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
76052  ** that a Mem structure is located on an 8-byte boundary. To prevent
76053  ** these assert()s from failing, when building with SQLITE_DEBUG defined
76054  ** using gcc, we force nullMem to be 8-byte aligned using the magical
76055  ** __attribute__((aligned(8))) macro. */
76056  static const Mem nullMem
76057 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
76058  __attribute__((aligned(8)))
76059 #endif
76060  = {
76061  /* .u = */ {0},
76062  /* .flags = */ (u16)MEM_Null,
76063  /* .enc = */ (u8)0,
76064  /* .eSubtype = */ (u8)0,
76065  /* .n = */ (int)0,
76066  /* .z = */ (char*)0,
76067  /* .zMalloc = */ (char*)0,
76068  /* .szMalloc = */ (int)0,
76069  /* .uTemp = */ (u32)0,
76070  /* .db = */ (sqlite3*)0,
76071  /* .xDel = */ (void(*)(void*))0,
76072 #ifdef SQLITE_DEBUG
76073  /* .pScopyFrom = */ (Mem*)0,
76074  /* .pFiller = */ (void*)0,
76075 #endif
76076  };
76077  return &nullMem;
76078 }
76079 
76080 /*
76081 ** Check to see if column iCol of the given statement is valid. If
76082 ** it is, return a pointer to the Mem for the value of that column.
76083 ** If iCol is not valid, return a pointer to a Mem which has a value
76084 ** of NULL.
76085 */
76086 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
76087  Vdbe *pVm;
76088  Mem *pOut;
76089 
76090  pVm = (Vdbe *)pStmt;
76091  if( pVm==0 ) return (Mem*)columnNullValue();
76092  assert( pVm->db );
76093  sqlite3_mutex_enter(pVm->db->mutex);
76094  if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
76095  pOut = &pVm->pResultSet[i];
76096  }else{
76097  sqlite3Error(pVm->db, SQLITE_RANGE);
76098  pOut = (Mem*)columnNullValue();
76099  }
76100  return pOut;
76101 }
76102 
76103 /*
76104 ** This function is called after invoking an sqlite3_value_XXX function on a
76105 ** column value (i.e. a value returned by evaluating an SQL expression in the
76106 ** select list of a SELECT statement) that may cause a malloc() failure. If
76107 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
76108 ** code of statement pStmt set to SQLITE_NOMEM.
76109 **
76110 ** Specifically, this is called from within:
76111 **
76112 ** sqlite3_column_int()
76113 ** sqlite3_column_int64()
76114 ** sqlite3_column_text()
76115 ** sqlite3_column_text16()
76116 ** sqlite3_column_real()
76117 ** sqlite3_column_bytes()
76118 ** sqlite3_column_bytes16()
76119 ** sqiite3_column_blob()
76120 */
76121 static void columnMallocFailure(sqlite3_stmt *pStmt)
76122 {
76123  /* If malloc() failed during an encoding conversion within an
76124  ** sqlite3_column_XXX API, then set the return code of the statement to
76125  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
76126  ** and _finalize() will return NOMEM.
76127  */
76128  Vdbe *p = (Vdbe *)pStmt;
76129  if( p ){
76130  assert( p->db!=0 );
76131  assert( sqlite3_mutex_held(p->db->mutex) );
76132  p->rc = sqlite3ApiExit(p->db, p->rc);
76133  sqlite3_mutex_leave(p->db->mutex);
76134  }
76135 }
76136 
76137 /**************************** sqlite3_column_ *******************************
76138 ** The following routines are used to access elements of the current row
76139 ** in the result set.
76140 */
76141 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
76142  const void *val;
76143  val = sqlite3_value_blob( columnMem(pStmt,i) );
76144  /* Even though there is no encoding conversion, value_blob() might
76145  ** need to call malloc() to expand the result of a zeroblob()
76146  ** expression.
76147  */
76148  columnMallocFailure(pStmt);
76149  return val;
76150 }
76151 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
76152  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
76153  columnMallocFailure(pStmt);
76154  return val;
76155 }
76156 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
76157  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
76158  columnMallocFailure(pStmt);
76159  return val;
76160 }
76161 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
76162  double val = sqlite3_value_double( columnMem(pStmt,i) );
76163  columnMallocFailure(pStmt);
76164  return val;
76165 }
76166 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
76167  int val = sqlite3_value_int( columnMem(pStmt,i) );
76168  columnMallocFailure(pStmt);
76169  return val;
76170 }
76171 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
76172  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
76173  columnMallocFailure(pStmt);
76174  return val;
76175 }
76176 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
76177  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
76178  columnMallocFailure(pStmt);
76179  return val;
76180 }
76181 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
76182  Mem *pOut = columnMem(pStmt, i);
76183  if( pOut->flags&MEM_Static ){
76184  pOut->flags &= ~MEM_Static;
76185  pOut->flags |= MEM_Ephem;
76186  }
76187  columnMallocFailure(pStmt);
76188  return (sqlite3_value *)pOut;
76189 }
76190 #ifndef SQLITE_OMIT_UTF16
76191 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
76192  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
76193  columnMallocFailure(pStmt);
76194  return val;
76195 }
76196 #endif /* SQLITE_OMIT_UTF16 */
76197 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
76198  int iType = sqlite3_value_type( columnMem(pStmt,i) );
76199  columnMallocFailure(pStmt);
76200  return iType;
76201 }
76202 
76203 /*
76204 ** Convert the N-th element of pStmt->pColName[] into a string using
76205 ** xFunc() then return that string. If N is out of range, return 0.
76206 **
76207 ** There are up to 5 names for each column. useType determines which
76208 ** name is returned. Here are the names:
76209 **
76210 ** 0 The column name as it should be displayed for output
76211 ** 1 The datatype name for the column
76212 ** 2 The name of the database that the column derives from
76213 ** 3 The name of the table that the column derives from
76214 ** 4 The name of the table column that the result column derives from
76215 **
76216 ** If the result is not a simple column reference (if it is an expression
76217 ** or a constant) then useTypes 2, 3, and 4 return NULL.
76218 */
76219 static const void *columnName(
76220  sqlite3_stmt *pStmt,
76221  int N,
76222  const void *(*xFunc)(Mem*),
76223  int useType
76224 ){
76225  const void *ret;
76226  Vdbe *p;
76227  int n;
76228  sqlite3 *db;
76229 #ifdef SQLITE_ENABLE_API_ARMOR
76230  if( pStmt==0 ){
76231  (void)SQLITE_MISUSE_BKPT;
76232  return 0;
76233  }
76234 #endif
76235  ret = 0;
76236  p = (Vdbe *)pStmt;
76237  db = p->db;
76238  assert( db!=0 );
76239  n = sqlite3_column_count(pStmt);
76240  if( N<n && N>=0 ){
76241  N += useType*n;
76242  sqlite3_mutex_enter(db->mutex);
76243  assert( db->mallocFailed==0 );
76244  ret = xFunc(&p->aColName[N]);
76245  /* A malloc may have failed inside of the xFunc() call. If this
76246  ** is the case, clear the mallocFailed flag and return NULL.
76247  */
76248  if( db->mallocFailed ){
76249  sqlite3OomClear(db);
76250  ret = 0;
76251  }
76252  sqlite3_mutex_leave(db->mutex);
76253  }
76254  return ret;
76255 }
76256 
76257 /*
76258 ** Return the name of the Nth column of the result set returned by SQL
76259 ** statement pStmt.
76260 */
76261 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
76262  return columnName(
76263  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
76264 }
76265 #ifndef SQLITE_OMIT_UTF16
76266 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
76267  return columnName(
76268  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
76269 }
76270 #endif
76271 
76272 /*
76273 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
76274 ** not define OMIT_DECLTYPE.
76275 */
76276 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
76277 # error "Must not define both SQLITE_OMIT_DECLTYPE \
76278  and SQLITE_ENABLE_COLUMN_METADATA"
76279 #endif
76280 
76281 #ifndef SQLITE_OMIT_DECLTYPE
76282 /*
76283 ** Return the column declaration type (if applicable) of the 'i'th column
76284 ** of the result set of SQL statement pStmt.
76285 */
76286 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
76287  return columnName(
76288  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
76289 }
76290 #ifndef SQLITE_OMIT_UTF16
76291 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
76292  return columnName(
76293  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
76294 }
76295 #endif /* SQLITE_OMIT_UTF16 */
76296 #endif /* SQLITE_OMIT_DECLTYPE */
76297 
76298 #ifdef SQLITE_ENABLE_COLUMN_METADATA
76299 /*
76300 ** Return the name of the database from which a result column derives.
76301 ** NULL is returned if the result column is an expression or constant or
76302 ** anything else which is not an unambiguous reference to a database column.
76303 */
76304 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
76305  return columnName(
76306  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
76307 }
76308 #ifndef SQLITE_OMIT_UTF16
76309 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
76310  return columnName(
76311  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
76312 }
76313 #endif /* SQLITE_OMIT_UTF16 */
76314 
76315 /*
76316 ** Return the name of the table from which a result column derives.
76317 ** NULL is returned if the result column is an expression or constant or
76318 ** anything else which is not an unambiguous reference to a database column.
76319 */
76320 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
76321  return columnName(
76322  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
76323 }
76324 #ifndef SQLITE_OMIT_UTF16
76325 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
76326  return columnName(
76327  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
76328 }
76329 #endif /* SQLITE_OMIT_UTF16 */
76330 
76331 /*
76332 ** Return the name of the table column from which a result column derives.
76333 ** NULL is returned if the result column is an expression or constant or
76334 ** anything else which is not an unambiguous reference to a database column.
76335 */
76336 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
76337  return columnName(
76338  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
76339 }
76340 #ifndef SQLITE_OMIT_UTF16
76341 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
76342  return columnName(
76343  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
76344 }
76345 #endif /* SQLITE_OMIT_UTF16 */
76346 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
76347 
76348 
76349 /******************************* sqlite3_bind_ ***************************
76350 **
76351 ** Routines used to attach values to wildcards in a compiled SQL statement.
76352 */
76353 /*
76354 ** Unbind the value bound to variable i in virtual machine p. This is the
76355 ** the same as binding a NULL value to the column. If the "i" parameter is
76356 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
76357 **
76358 ** A successful evaluation of this routine acquires the mutex on p.
76359 ** the mutex is released if any kind of error occurs.
76360 **
76361 ** The error code stored in database p->db is overwritten with the return
76362 ** value in any case.
76363 */
76364 static int vdbeUnbind(Vdbe *p, int i){
76365  Mem *pVar;
76366  if( vdbeSafetyNotNull(p) ){
76367  return SQLITE_MISUSE_BKPT;
76368  }
76369  sqlite3_mutex_enter(p->db->mutex);
76370  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
76371  sqlite3Error(p->db, SQLITE_MISUSE);
76372  sqlite3_mutex_leave(p->db->mutex);
76373  sqlite3_log(SQLITE_MISUSE,
76374  "bind on a busy prepared statement: [%s]", p->zSql);
76375  return SQLITE_MISUSE_BKPT;
76376  }
76377  if( i<1 || i>p->nVar ){
76378  sqlite3Error(p->db, SQLITE_RANGE);
76379  sqlite3_mutex_leave(p->db->mutex);
76380  return SQLITE_RANGE;
76381  }
76382  i--;
76383  pVar = &p->aVar[i];
76384  sqlite3VdbeMemRelease(pVar);
76385  pVar->flags = MEM_Null;
76386  sqlite3Error(p->db, SQLITE_OK);
76387 
76388  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
76389  ** binding a new value to this variable invalidates the current query plan.
76390  **
76391  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
76392  ** parameter in the WHERE clause might influence the choice of query plan
76393  ** for a statement, then the statement will be automatically recompiled,
76394  ** as if there had been a schema change, on the first sqlite3_step() call
76395  ** following any change to the bindings of that parameter.
76396  */
76397  if( p->isPrepareV2 &&
76398  ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
76399  ){
76400  p->expired = 1;
76401  }
76402  return SQLITE_OK;
76403 }
76404 
76405 /*
76406 ** Bind a text or BLOB value.
76407 */
76408 static int bindText(
76409  sqlite3_stmt *pStmt, /* The statement to bind against */
76410  int i, /* Index of the parameter to bind */
76411  const void *zData, /* Pointer to the data to be bound */
76412  int nData, /* Number of bytes of data to be bound */
76413  void (*xDel)(void*), /* Destructor for the data */
76414  u8 encoding /* Encoding for the data */
76415 ){
76416  Vdbe *p = (Vdbe *)pStmt;
76417  Mem *pVar;
76418  int rc;
76419 
76420  rc = vdbeUnbind(p, i);
76421  if( rc==SQLITE_OK ){
76422  if( zData!=0 ){
76423  pVar = &p->aVar[i-1];
76424  rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
76425  if( rc==SQLITE_OK && encoding!=0 ){
76426  rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
76427  }
76428  sqlite3Error(p->db, rc);
76429  rc = sqlite3ApiExit(p->db, rc);
76430  }
76431  sqlite3_mutex_leave(p->db->mutex);
76432  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
76433  xDel((void*)zData);
76434  }
76435  return rc;
76436 }
76437 
76438 
76439 /*
76440 ** Bind a blob value to an SQL statement variable.
76441 */
76442 SQLITE_API int sqlite3_bind_blob(
76443  sqlite3_stmt *pStmt,
76444  int i,
76445  const void *zData,
76446  int nData,
76447  void (*xDel)(void*)
76448 ){
76449 #ifdef SQLITE_ENABLE_API_ARMOR
76450  if( nData<0 ) return SQLITE_MISUSE_BKPT;
76451 #endif
76452  return bindText(pStmt, i, zData, nData, xDel, 0);
76453 }
76454 SQLITE_API int sqlite3_bind_blob64(
76455  sqlite3_stmt *pStmt,
76456  int i,
76457  const void *zData,
76458  sqlite3_uint64 nData,
76459  void (*xDel)(void*)
76460 ){
76461  assert( xDel!=SQLITE_DYNAMIC );
76462  if( nData>0x7fffffff ){
76463  return invokeValueDestructor(zData, xDel, 0);
76464  }else{
76465  return bindText(pStmt, i, zData, (int)nData, xDel, 0);
76466  }
76467 }
76468 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
76469  int rc;
76470  Vdbe *p = (Vdbe *)pStmt;
76471  rc = vdbeUnbind(p, i);
76472  if( rc==SQLITE_OK ){
76473  sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
76474  sqlite3_mutex_leave(p->db->mutex);
76475  }
76476  return rc;
76477 }
76478 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
76479  return sqlite3_bind_int64(p, i, (i64)iValue);
76480 }
76481 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
76482  int rc;
76483  Vdbe *p = (Vdbe *)pStmt;
76484  rc = vdbeUnbind(p, i);
76485  if( rc==SQLITE_OK ){
76486  sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
76487  sqlite3_mutex_leave(p->db->mutex);
76488  }
76489  return rc;
76490 }
76491 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
76492  int rc;
76493  Vdbe *p = (Vdbe*)pStmt;
76494  rc = vdbeUnbind(p, i);
76495  if( rc==SQLITE_OK ){
76496  sqlite3_mutex_leave(p->db->mutex);
76497  }
76498  return rc;
76499 }
76500 SQLITE_API int sqlite3_bind_text(
76501  sqlite3_stmt *pStmt,
76502  int i,
76503  const char *zData,
76504  int nData,
76505  void (*xDel)(void*)
76506 ){
76507  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
76508 }
76509 SQLITE_API int sqlite3_bind_text64(
76510  sqlite3_stmt *pStmt,
76511  int i,
76512  const char *zData,
76513  sqlite3_uint64 nData,
76514  void (*xDel)(void*),
76515  unsigned char enc
76516 ){
76517  assert( xDel!=SQLITE_DYNAMIC );
76518  if( nData>0x7fffffff ){
76519  return invokeValueDestructor(zData, xDel, 0);
76520  }else{
76521  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
76522  return bindText(pStmt, i, zData, (int)nData, xDel, enc);
76523  }
76524 }
76525 #ifndef SQLITE_OMIT_UTF16
76526 SQLITE_API int sqlite3_bind_text16(
76527  sqlite3_stmt *pStmt,
76528  int i,
76529  const void *zData,
76530  int nData,
76531  void (*xDel)(void*)
76532 ){
76533  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
76534 }
76535 #endif /* SQLITE_OMIT_UTF16 */
76536 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
76537  int rc;
76538  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
76539  case SQLITE_INTEGER: {
76540  rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
76541  break;
76542  }
76543  case SQLITE_FLOAT: {
76544  rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
76545  break;
76546  }
76547  case SQLITE_BLOB: {
76548  if( pValue->flags & MEM_Zero ){
76549  rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
76550  }else{
76551  rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
76552  }
76553  break;
76554  }
76555  case SQLITE_TEXT: {
76556  rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
76557  pValue->enc);
76558  break;
76559  }
76560  default: {
76561  rc = sqlite3_bind_null(pStmt, i);
76562  break;
76563  }
76564  }
76565  return rc;
76566 }
76567 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
76568  int rc;
76569  Vdbe *p = (Vdbe *)pStmt;
76570  rc = vdbeUnbind(p, i);
76571  if( rc==SQLITE_OK ){
76572  sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
76573  sqlite3_mutex_leave(p->db->mutex);
76574  }
76575  return rc;
76576 }
76577 SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
76578  int rc;
76579  Vdbe *p = (Vdbe *)pStmt;
76580  sqlite3_mutex_enter(p->db->mutex);
76581  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
76582  rc = SQLITE_TOOBIG;
76583  }else{
76584  assert( (n & 0x7FFFFFFF)==n );
76585  rc = sqlite3_bind_zeroblob(pStmt, i, n);
76586  }
76587  rc = sqlite3ApiExit(p->db, rc);
76588  sqlite3_mutex_leave(p->db->mutex);
76589  return rc;
76590 }
76591 
76592 /*
76593 ** Return the number of wildcards that can be potentially bound to.
76594 ** This routine is added to support DBD::SQLite.
76595 */
76596 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
76597  Vdbe *p = (Vdbe*)pStmt;
76598  return p ? p->nVar : 0;
76599 }
76600 
76601 /*
76602 ** Return the name of a wildcard parameter. Return NULL if the index
76603 ** is out of range or if the wildcard is unnamed.
76604 **
76605 ** The result is always UTF-8.
76606 */
76607 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
76608  Vdbe *p = (Vdbe*)pStmt;
76609  if( p==0 || i<1 || i>p->nzVar ){
76610  return 0;
76611  }
76612  return p->azVar[i-1];
76613 }
76614 
76615 /*
76616 ** Given a wildcard parameter name, return the index of the variable
76617 ** with that name. If there is no variable with the given name,
76618 ** return 0.
76619 */
76620 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
76621  int i;
76622  if( p==0 ){
76623  return 0;
76624  }
76625  if( zName ){
76626  for(i=0; i<p->nzVar; i++){
76627  const char *z = p->azVar[i];
76628  if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
76629  return i+1;
76630  }
76631  }
76632  }
76633  return 0;
76634 }
76635 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
76636  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
76637 }
76638 
76639 /*
76640 ** Transfer all bindings from the first statement over to the second.
76641 */
76642 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
76643  Vdbe *pFrom = (Vdbe*)pFromStmt;
76644  Vdbe *pTo = (Vdbe*)pToStmt;
76645  int i;
76646  assert( pTo->db==pFrom->db );
76647  assert( pTo->nVar==pFrom->nVar );
76648  sqlite3_mutex_enter(pTo->db->mutex);
76649  for(i=0; i<pFrom->nVar; i++){
76650  sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
76651  }
76652  sqlite3_mutex_leave(pTo->db->mutex);
76653  return SQLITE_OK;
76654 }
76655 
76656 #ifndef SQLITE_OMIT_DEPRECATED
76657 /*
76658 ** Deprecated external interface. Internal/core SQLite code
76659 ** should call sqlite3TransferBindings.
76660 **
76661 ** It is misuse to call this routine with statements from different
76662 ** database connections. But as this is a deprecated interface, we
76663 ** will not bother to check for that condition.
76664 **
76665 ** If the two statements contain a different number of bindings, then
76666 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
76667 ** SQLITE_OK is returned.
76668 */
76669 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
76670  Vdbe *pFrom = (Vdbe*)pFromStmt;
76671  Vdbe *pTo = (Vdbe*)pToStmt;
76672  if( pFrom->nVar!=pTo->nVar ){
76673  return SQLITE_ERROR;
76674  }
76675  if( pTo->isPrepareV2 && pTo->expmask ){
76676  pTo->expired = 1;
76677  }
76678  if( pFrom->isPrepareV2 && pFrom->expmask ){
76679  pFrom->expired = 1;
76680  }
76681  return sqlite3TransferBindings(pFromStmt, pToStmt);
76682 }
76683 #endif
76684 
76685 /*
76686 ** Return the sqlite3* database handle to which the prepared statement given
76687 ** in the argument belongs. This is the same database handle that was
76688 ** the first argument to the sqlite3_prepare() that was used to create
76689 ** the statement in the first place.
76690 */
76691 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
76692  return pStmt ? ((Vdbe*)pStmt)->db : 0;
76693 }
76694 
76695 /*
76696 ** Return true if the prepared statement is guaranteed to not modify the
76697 ** database.
76698 */
76699 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
76700  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
76701 }
76702 
76703 /*
76704 ** Return true if the prepared statement is in need of being reset.
76705 */
76706 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
76707  Vdbe *v = (Vdbe*)pStmt;
76708  return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
76709 }
76710 
76711 /*
76712 ** Return a pointer to the next prepared statement after pStmt associated
76713 ** with database connection pDb. If pStmt is NULL, return the first
76714 ** prepared statement for the database connection. Return NULL if there
76715 ** are no more.
76716 */
76717 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
76718  sqlite3_stmt *pNext;
76719 #ifdef SQLITE_ENABLE_API_ARMOR
76720  if( !sqlite3SafetyCheckOk(pDb) ){
76721  (void)SQLITE_MISUSE_BKPT;
76722  return 0;
76723  }
76724 #endif
76725  sqlite3_mutex_enter(pDb->mutex);
76726  if( pStmt==0 ){
76727  pNext = (sqlite3_stmt*)pDb->pVdbe;
76728  }else{
76729  pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
76730  }
76731  sqlite3_mutex_leave(pDb->mutex);
76732  return pNext;
76733 }
76734 
76735 /*
76736 ** Return the value of a status counter for a prepared statement
76737 */
76738 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
76739  Vdbe *pVdbe = (Vdbe*)pStmt;
76740  u32 v;
76741 #ifdef SQLITE_ENABLE_API_ARMOR
76742  if( !pStmt ){
76743  (void)SQLITE_MISUSE_BKPT;
76744  return 0;
76745  }
76746 #endif
76747  v = pVdbe->aCounter[op];
76748  if( resetFlag ) pVdbe->aCounter[op] = 0;
76749  return (int)v;
76750 }
76751 
76752 /*
76753 ** Return the SQL associated with a prepared statement
76754 */
76755 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
76756  Vdbe *p = (Vdbe *)pStmt;
76757  return p ? p->zSql : 0;
76758 }
76759 
76760 /*
76761 ** Return the SQL associated with a prepared statement with
76762 ** bound parameters expanded. Space to hold the returned string is
76763 ** obtained from sqlite3_malloc(). The caller is responsible for
76764 ** freeing the returned string by passing it to sqlite3_free().
76765 **
76766 ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
76767 ** expanded bound parameters.
76768 */
76769 SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
76770 #ifdef SQLITE_OMIT_TRACE
76771  return 0;
76772 #else
76773  char *z = 0;
76774  const char *zSql = sqlite3_sql(pStmt);
76775  if( zSql ){
76776  Vdbe *p = (Vdbe *)pStmt;
76777  sqlite3_mutex_enter(p->db->mutex);
76778  z = sqlite3VdbeExpandSql(p, zSql);
76779  sqlite3_mutex_leave(p->db->mutex);
76780  }
76781  return z;
76782 #endif
76783 }
76784 
76785 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76786 /*
76787 ** Allocate and populate an UnpackedRecord structure based on the serialized
76788 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
76789 ** if successful, or a NULL pointer if an OOM error is encountered.
76790 */
76791 static UnpackedRecord *vdbeUnpackRecord(
76792  KeyInfo *pKeyInfo,
76793  int nKey,
76794  const void *pKey
76795 ){
76796  char *dummy; /* Dummy argument for AllocUnpackedRecord() */
76797  UnpackedRecord *pRet; /* Return value */
76798 
76799  pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy);
76800  if( pRet ){
76801  memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
76802  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
76803  }
76804  return pRet;
76805 }
76806 
76807 /*
76808 ** This function is called from within a pre-update callback to retrieve
76809 ** a field of the row currently being updated or deleted.
76810 */
76811 SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76812  PreUpdate *p = db->pPreUpdate;
76813  int rc = SQLITE_OK;
76814 
76815  /* Test that this call is being made from within an SQLITE_DELETE or
76816  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
76817  if( !p || p->op==SQLITE_INSERT ){
76818  rc = SQLITE_MISUSE_BKPT;
76819  goto preupdate_old_out;
76820  }
76821  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76822  rc = SQLITE_RANGE;
76823  goto preupdate_old_out;
76824  }
76825 
76826  /* If the old.* record has not yet been loaded into memory, do so now. */
76827  if( p->pUnpacked==0 ){
76828  u32 nRec;
76829  u8 *aRec;
76830 
76831  nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
76832  aRec = sqlite3DbMallocRaw(db, nRec);
76833  if( !aRec ) goto preupdate_old_out;
76834  rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec);
76835  if( rc==SQLITE_OK ){
76836  p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
76837  if( !p->pUnpacked ) rc = SQLITE_NOMEM;
76838  }
76839  if( rc!=SQLITE_OK ){
76840  sqlite3DbFree(db, aRec);
76841  goto preupdate_old_out;
76842  }
76843  p->aRecord = aRec;
76844  }
76845 
76846  if( iIdx>=p->pUnpacked->nField ){
76847  *ppValue = (sqlite3_value *)columnNullValue();
76848  }else{
76849  Mem *pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
76850  *ppValue = &p->pUnpacked->aMem[iIdx];
76851  if( iIdx==p->pTab->iPKey ){
76852  sqlite3VdbeMemSetInt64(pMem, p->iKey1);
76853  }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
76854  if( pMem->flags & MEM_Int ){
76855  sqlite3VdbeMemRealify(pMem);
76856  }
76857  }
76858  }
76859 
76860  preupdate_old_out:
76861  sqlite3Error(db, rc);
76862  return sqlite3ApiExit(db, rc);
76863 }
76864 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76865 
76866 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76867 /*
76868 ** This function is called from within a pre-update callback to retrieve
76869 ** the number of columns in the row being updated, deleted or inserted.
76870 */
76871 SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
76872  PreUpdate *p = db->pPreUpdate;
76873  return (p ? p->keyinfo.nField : 0);
76874 }
76875 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76876 
76877 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76878 /*
76879 ** This function is designed to be called from within a pre-update callback
76880 ** only. It returns zero if the change that caused the callback was made
76881 ** immediately by a user SQL statement. Or, if the change was made by a
76882 ** trigger program, it returns the number of trigger programs currently
76883 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
76884 ** top-level trigger etc.).
76885 **
76886 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
76887 ** or SET DEFAULT action is considered a trigger.
76888 */
76889 SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
76890  PreUpdate *p = db->pPreUpdate;
76891  return (p ? p->v->nFrame : 0);
76892 }
76893 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76894 
76895 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76896 /*
76897 ** This function is called from within a pre-update callback to retrieve
76898 ** a field of the row currently being updated or inserted.
76899 */
76900 SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76901  PreUpdate *p = db->pPreUpdate;
76902  int rc = SQLITE_OK;
76903  Mem *pMem;
76904 
76905  if( !p || p->op==SQLITE_DELETE ){
76906  rc = SQLITE_MISUSE_BKPT;
76907  goto preupdate_new_out;
76908  }
76909  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76910  rc = SQLITE_RANGE;
76911  goto preupdate_new_out;
76912  }
76913 
76914  if( p->op==SQLITE_INSERT ){
76915  /* For an INSERT, memory cell p->iNewReg contains the serialized record
76916  ** that is being inserted. Deserialize it. */
76917  UnpackedRecord *pUnpack = p->pNewUnpacked;
76918  if( !pUnpack ){
76919  Mem *pData = &p->v->aMem[p->iNewReg];
76920  rc = ExpandBlob(pData);
76921  if( rc!=SQLITE_OK ) goto preupdate_new_out;
76922  pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
76923  if( !pUnpack ){
76924  rc = SQLITE_NOMEM;
76925  goto preupdate_new_out;
76926  }
76927  p->pNewUnpacked = pUnpack;
76928  }
76929  if( iIdx>=pUnpack->nField ){
76930  pMem = (sqlite3_value *)columnNullValue();
76931  }else{
76932  pMem = &pUnpack->aMem[iIdx];
76933  if( iIdx==p->pTab->iPKey ){
76934  sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76935  }
76936  }
76937  }else{
76938  /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
76939  ** value. Make a copy of the cell contents and return a pointer to it.
76940  ** It is not safe to return a pointer to the memory cell itself as the
76941  ** caller may modify the value text encoding.
76942  */
76943  assert( p->op==SQLITE_UPDATE );
76944  if( !p->aNew ){
76945  p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
76946  if( !p->aNew ){
76947  rc = SQLITE_NOMEM;
76948  goto preupdate_new_out;
76949  }
76950  }
76951  assert( iIdx>=0 && iIdx<p->pCsr->nField );
76952  pMem = &p->aNew[iIdx];
76953  if( pMem->flags==0 ){
76954  if( iIdx==p->pTab->iPKey ){
76955  sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76956  }else{
76957  rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
76958  if( rc!=SQLITE_OK ) goto preupdate_new_out;
76959  }
76960  }
76961  }
76962  *ppValue = pMem;
76963 
76964  preupdate_new_out:
76965  sqlite3Error(db, rc);
76966  return sqlite3ApiExit(db, rc);
76967 }
76968 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76969 
76970 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76971 /*
76972 ** Return status data for a single loop within query pStmt.
76973 */
76974 SQLITE_API int sqlite3_stmt_scanstatus(
76975  sqlite3_stmt *pStmt, /* Prepared statement being queried */
76976  int idx, /* Index of loop to report on */
76977  int iScanStatusOp, /* Which metric to return */
76978  void *pOut /* OUT: Write the answer here */
76979 ){
76980  Vdbe *p = (Vdbe*)pStmt;
76981  ScanStatus *pScan;
76982  if( idx<0 || idx>=p->nScan ) return 1;
76983  pScan = &p->aScan[idx];
76984  switch( iScanStatusOp ){
76985  case SQLITE_SCANSTAT_NLOOP: {
76986  *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
76987  break;
76988  }
76989  case SQLITE_SCANSTAT_NVISIT: {
76990  *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
76991  break;
76992  }
76993  case SQLITE_SCANSTAT_EST: {
76994  double r = 1.0;
76995  LogEst x = pScan->nEst;
76996  while( x<100 ){
76997  x += 10;
76998  r *= 0.5;
76999  }
77000  *(double*)pOut = r*sqlite3LogEstToInt(x);
77001  break;
77002  }
77003  case SQLITE_SCANSTAT_NAME: {
77004  *(const char**)pOut = pScan->zName;
77005  break;
77006  }
77007  case SQLITE_SCANSTAT_EXPLAIN: {
77008  if( pScan->addrExplain ){
77009  *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
77010  }else{
77011  *(const char**)pOut = 0;
77012  }
77013  break;
77014  }
77015  case SQLITE_SCANSTAT_SELECTID: {
77016  if( pScan->addrExplain ){
77017  *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
77018  }else{
77019  *(int*)pOut = -1;
77020  }
77021  break;
77022  }
77023  default: {
77024  return 1;
77025  }
77026  }
77027  return 0;
77028 }
77029 
77030 /*
77031 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
77032 */
77033 SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
77034  Vdbe *p = (Vdbe*)pStmt;
77035  memset(p->anExec, 0, p->nOp * sizeof(i64));
77036 }
77037 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
77038 
77039 /************** End of vdbeapi.c *********************************************/
77040 /************** Begin file vdbetrace.c ***************************************/
77041 /*
77042 ** 2009 November 25
77043 **
77044 ** The author disclaims copyright to this source code. In place of
77045 ** a legal notice, here is a blessing:
77046 **
77047 ** May you do good and not evil.
77048 ** May you find forgiveness for yourself and forgive others.
77049 ** May you share freely, never taking more than you give.
77050 **
77051 *************************************************************************
77052 **
77053 ** This file contains code used to insert the values of host parameters
77054 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
77055 **
77056 ** The Vdbe parse-tree explainer is also found here.
77057 */
77058 /* #include "sqliteInt.h" */
77059 /* #include "vdbeInt.h" */
77060 
77061 #ifndef SQLITE_OMIT_TRACE
77062 
77063 /*
77064 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
77065 ** bytes in this text up to but excluding the first character in
77066 ** a host parameter. If the text contains no host parameters, return
77067 ** the total number of bytes in the text.
77068 */
77069 static int findNextHostParameter(const char *zSql, int *pnToken){
77070  int tokenType;
77071  int nTotal = 0;
77072  int n;
77073 
77074  *pnToken = 0;
77075  while( zSql[0] ){
77076  n = sqlite3GetToken((u8*)zSql, &tokenType);
77077  assert( n>0 && tokenType!=TK_ILLEGAL );
77078  if( tokenType==TK_VARIABLE ){
77079  *pnToken = n;
77080  break;
77081  }
77082  nTotal += n;
77083  zSql += n;
77084  }
77085  return nTotal;
77086 }
77087 
77088 /*
77089 ** This function returns a pointer to a nul-terminated string in memory
77090 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
77091 ** string contains a copy of zRawSql but with host parameters expanded to
77092 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
77093 ** then the returned string holds a copy of zRawSql with "-- " prepended
77094 ** to each line of text.
77095 **
77096 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
77097 ** then long strings and blobs are truncated to that many bytes. This
77098 ** can be used to prevent unreasonably large trace strings when dealing
77099 ** with large (multi-megabyte) strings and blobs.
77100 **
77101 ** The calling function is responsible for making sure the memory returned
77102 ** is eventually freed.
77103 **
77104 ** ALGORITHM: Scan the input string looking for host parameters in any of
77105 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
77106 ** string literals, quoted identifier names, and comments. For text forms,
77107 ** the host parameter index is found by scanning the prepared
77108 ** statement for the corresponding OP_Variable opcode. Once the host
77109 ** parameter index is known, locate the value in p->aVar[]. Then render
77110 ** the value as a literal in place of the host parameter name.
77111 */
77112 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
77113  Vdbe *p, /* The prepared statement being evaluated */
77114  const char *zRawSql /* Raw text of the SQL statement */
77115 ){
77116  sqlite3 *db; /* The database connection */
77117  int idx = 0; /* Index of a host parameter */
77118  int nextIndex = 1; /* Index of next ? host parameter */
77119  int n; /* Length of a token prefix */
77120  int nToken; /* Length of the parameter token */
77121  int i; /* Loop counter */
77122  Mem *pVar; /* Value of a host parameter */
77123  StrAccum out; /* Accumulate the output here */
77124 #ifndef SQLITE_OMIT_UTF16
77125  Mem utf8; /* Used to convert UTF16 parameters into UTF8 for display */
77126 #endif
77127  char zBase[100]; /* Initial working space */
77128 
77129  db = p->db;
77130  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
77131  db->aLimit[SQLITE_LIMIT_LENGTH]);
77132  if( db->nVdbeExec>1 ){
77133  while( *zRawSql ){
77134  const char *zStart = zRawSql;
77135  while( *(zRawSql++)!='\n' && *zRawSql );
77136  sqlite3StrAccumAppend(&out, "-- ", 3);
77137  assert( (zRawSql - zStart) > 0 );
77138  sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
77139  }
77140  }else if( p->nVar==0 ){
77141  sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
77142  }else{
77143  while( zRawSql[0] ){
77144  n = findNextHostParameter(zRawSql, &nToken);
77145  assert( n>0 );
77146  sqlite3StrAccumAppend(&out, zRawSql, n);
77147  zRawSql += n;
77148  assert( zRawSql[0] || nToken==0 );
77149  if( nToken==0 ) break;
77150  if( zRawSql[0]=='?' ){
77151  if( nToken>1 ){
77152  assert( sqlite3Isdigit(zRawSql[1]) );
77153  sqlite3GetInt32(&zRawSql[1], &idx);
77154  }else{
77155  idx = nextIndex;
77156  }
77157  }else{
77158  assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
77159  zRawSql[0]=='@' || zRawSql[0]=='#' );
77160  testcase( zRawSql[0]==':' );
77161  testcase( zRawSql[0]=='$' );
77162  testcase( zRawSql[0]=='@' );
77163  testcase( zRawSql[0]=='#' );
77164  idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
77165  assert( idx>0 );
77166  }
77167  zRawSql += nToken;
77168  nextIndex = idx + 1;
77169  assert( idx>0 && idx<=p->nVar );
77170  pVar = &p->aVar[idx-1];
77171  if( pVar->flags & MEM_Null ){
77172  sqlite3StrAccumAppend(&out, "NULL", 4);
77173  }else if( pVar->flags & MEM_Int ){
77174  sqlite3XPrintf(&out, "%lld", pVar->u.i);
77175  }else if( pVar->flags & MEM_Real ){
77176  sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
77177  }else if( pVar->flags & MEM_Str ){
77178  int nOut; /* Number of bytes of the string text to include in output */
77179 #ifndef SQLITE_OMIT_UTF16
77180  u8 enc = ENC(db);
77181  if( enc!=SQLITE_UTF8 ){
77182  memset(&utf8, 0, sizeof(utf8));
77183  utf8.db = db;
77184  sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
77185  if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
77186  out.accError = STRACCUM_NOMEM;
77187  out.nAlloc = 0;
77188  }
77189  pVar = &utf8;
77190  }
77191 #endif
77192  nOut = pVar->n;
77193 #ifdef SQLITE_TRACE_SIZE_LIMIT
77194  if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
77195  nOut = SQLITE_TRACE_SIZE_LIMIT;
77196  while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
77197  }
77198 #endif
77199  sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
77200 #ifdef SQLITE_TRACE_SIZE_LIMIT
77201  if( nOut<pVar->n ){
77202  sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
77203  }
77204 #endif
77205 #ifndef SQLITE_OMIT_UTF16
77206  if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
77207 #endif
77208  }else if( pVar->flags & MEM_Zero ){
77209  sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
77210  }else{
77211  int nOut; /* Number of bytes of the blob to include in output */
77212  assert( pVar->flags & MEM_Blob );
77213  sqlite3StrAccumAppend(&out, "x'", 2);
77214  nOut = pVar->n;
77215 #ifdef SQLITE_TRACE_SIZE_LIMIT
77216  if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
77217 #endif
77218  for(i=0; i<nOut; i++){
77219  sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
77220  }
77221  sqlite3StrAccumAppend(&out, "'", 1);
77222 #ifdef SQLITE_TRACE_SIZE_LIMIT
77223  if( nOut<pVar->n ){
77224  sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
77225  }
77226 #endif
77227  }
77228  }
77229  }
77230  if( out.accError ) sqlite3StrAccumReset(&out);
77231  return sqlite3StrAccumFinish(&out);
77232 }
77233 
77234 #endif /* #ifndef SQLITE_OMIT_TRACE */
77235 
77236 /************** End of vdbetrace.c *******************************************/
77237 /************** Begin file vdbe.c ********************************************/
77238 /*
77239 ** 2001 September 15
77240 **
77241 ** The author disclaims copyright to this source code. In place of
77242 ** a legal notice, here is a blessing:
77243 **
77244 ** May you do good and not evil.
77245 ** May you find forgiveness for yourself and forgive others.
77246 ** May you share freely, never taking more than you give.
77247 **
77248 *************************************************************************
77249 ** The code in this file implements the function that runs the
77250 ** bytecode of a prepared statement.
77251 **
77252 ** Various scripts scan this source file in order to generate HTML
77253 ** documentation, headers files, or other derived files. The formatting
77254 ** of the code in this file is, therefore, important. See other comments
77255 ** in this file for details. If in doubt, do not deviate from existing
77256 ** commenting and indentation practices when changing or adding code.
77257 */
77258 /* #include "sqliteInt.h" */
77259 /* #include "vdbeInt.h" */
77260 
77261 /*
77262 ** Invoke this macro on memory cells just prior to changing the
77263 ** value of the cell. This macro verifies that shallow copies are
77264 ** not misused. A shallow copy of a string or blob just copies a
77265 ** pointer to the string or blob, not the content. If the original
77266 ** is changed while the copy is still in use, the string or blob might
77267 ** be changed out from under the copy. This macro verifies that nothing
77268 ** like that ever happens.
77269 */
77270 #ifdef SQLITE_DEBUG
77271 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
77272 #else
77273 # define memAboutToChange(P,M)
77274 #endif
77275 
77276 /*
77277 ** The following global variable is incremented every time a cursor
77278 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
77279 ** procedures use this information to make sure that indices are
77280 ** working correctly. This variable has no function other than to
77281 ** help verify the correct operation of the library.
77282 */
77283 #ifdef SQLITE_TEST
77284 SQLITE_API int sqlite3_search_count = 0;
77285 #endif
77286 
77287 /*
77288 ** When this global variable is positive, it gets decremented once before
77289 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
77290 ** field of the sqlite3 structure is set in order to simulate an interrupt.
77291 **
77292 ** This facility is used for testing purposes only. It does not function
77293 ** in an ordinary build.
77294 */
77295 #ifdef SQLITE_TEST
77296 SQLITE_API int sqlite3_interrupt_count = 0;
77297 #endif
77298 
77299 /*
77300 ** The next global variable is incremented each type the OP_Sort opcode
77301 ** is executed. The test procedures use this information to make sure that
77302 ** sorting is occurring or not occurring at appropriate times. This variable
77303 ** has no function other than to help verify the correct operation of the
77304 ** library.
77305 */
77306 #ifdef SQLITE_TEST
77307 SQLITE_API int sqlite3_sort_count = 0;
77308 #endif
77309 
77310 /*
77311 ** The next global variable records the size of the largest MEM_Blob
77312 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
77313 ** use this information to make sure that the zero-blob functionality
77314 ** is working correctly. This variable has no function other than to
77315 ** help verify the correct operation of the library.
77316 */
77317 #ifdef SQLITE_TEST
77318 SQLITE_API int sqlite3_max_blobsize = 0;
77319 static void updateMaxBlobsize(Mem *p){
77320  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
77321  sqlite3_max_blobsize = p->n;
77322  }
77323 }
77324 #endif
77325 
77326 /*
77327 ** This macro evaluates to true if either the update hook or the preupdate
77328 ** hook are enabled for database connect DB.
77329 */
77330 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
77331 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
77332 #else
77333 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
77334 #endif
77335 
77336 /*
77337 ** The next global variable is incremented each time the OP_Found opcode
77338 ** is executed. This is used to test whether or not the foreign key
77339 ** operation implemented using OP_FkIsZero is working. This variable
77340 ** has no function other than to help verify the correct operation of the
77341 ** library.
77342 */
77343 #ifdef SQLITE_TEST
77344 SQLITE_API int sqlite3_found_count = 0;
77345 #endif
77346 
77347 /*
77348 ** Test a register to see if it exceeds the current maximum blob size.
77349 ** If it does, record the new maximum blob size.
77350 */
77351 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
77352 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
77353 #else
77354 # define UPDATE_MAX_BLOBSIZE(P)
77355 #endif
77356 
77357 /*
77358 ** Invoke the VDBE coverage callback, if that callback is defined. This
77359 ** feature is used for test suite validation only and does not appear an
77360 ** production builds.
77361 **
77362 ** M is an integer, 2 or 3, that indices how many different ways the
77363 ** branch can go. It is usually 2. "I" is the direction the branch
77364 ** goes. 0 means falls through. 1 means branch is taken. 2 means the
77365 ** second alternative branch is taken.
77366 **
77367 ** iSrcLine is the source code line (from the __LINE__ macro) that
77368 ** generated the VDBE instruction. This instrumentation assumes that all
77369 ** source code is in a single file (the amalgamation). Special values 1
77370 ** and 2 for the iSrcLine parameter mean that this particular branch is
77371 ** always taken or never taken, respectively.
77372 */
77373 #if !defined(SQLITE_VDBE_COVERAGE)
77374 # define VdbeBranchTaken(I,M)
77375 #else
77376 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
77377  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
77378  if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
77379  M = iSrcLine;
77380  /* Assert the truth of VdbeCoverageAlwaysTaken() and
77381  ** VdbeCoverageNeverTaken() */
77382  assert( (M & I)==I );
77383  }else{
77384  if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
77385  sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
77386  iSrcLine,I,M);
77387  }
77388  }
77389 #endif
77390 
77391 /*
77392 ** Convert the given register into a string if it isn't one
77393 ** already. Return non-zero if a malloc() fails.
77394 */
77395 #define Stringify(P, enc) \
77396  if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
77397  { goto no_mem; }
77398 
77399 /*
77400 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
77401 ** a pointer to a dynamically allocated string where some other entity
77402 ** is responsible for deallocating that string. Because the register
77403 ** does not control the string, it might be deleted without the register
77404 ** knowing it.
77405 **
77406 ** This routine converts an ephemeral string into a dynamically allocated
77407 ** string that the register itself controls. In other words, it
77408 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
77409 */
77410 #define Deephemeralize(P) \
77411  if( ((P)->flags&MEM_Ephem)!=0 \
77412  && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
77413 
77414 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
77415 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
77416 
77417 /*
77418 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
77419 ** if we run out of memory.
77420 */
77421 static VdbeCursor *allocateCursor(
77422  Vdbe *p, /* The virtual machine */
77423  int iCur, /* Index of the new VdbeCursor */
77424  int nField, /* Number of fields in the table or index */
77425  int iDb, /* Database the cursor belongs to, or -1 */
77426  u8 eCurType /* Type of the new cursor */
77427 ){
77428  /* Find the memory cell that will be used to store the blob of memory
77429  ** required for this VdbeCursor structure. It is convenient to use a
77430  ** vdbe memory cell to manage the memory allocation required for a
77431  ** VdbeCursor structure for the following reasons:
77432  **
77433  ** * Sometimes cursor numbers are used for a couple of different
77434  ** purposes in a vdbe program. The different uses might require
77435  ** different sized allocations. Memory cells provide growable
77436  ** allocations.
77437  **
77438  ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
77439  ** be freed lazily via the sqlite3_release_memory() API. This
77440  ** minimizes the number of malloc calls made by the system.
77441  **
77442  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
77443  ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
77444  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
77445  */
77446  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
77447 
77448  int nByte;
77449  VdbeCursor *pCx = 0;
77450  nByte =
77451  ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
77452  (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
77453 
77454  assert( iCur>=0 && iCur<p->nCursor );
77455  if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
77456  sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
77457  p->apCsr[iCur] = 0;
77458  }
77459  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
77460  p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
77461  memset(pCx, 0, sizeof(VdbeCursor));
77462  pCx->eCurType = eCurType;
77463  pCx->iDb = iDb;
77464  pCx->nField = nField;
77465  pCx->aOffset = &pCx->aType[nField];
77466  if( eCurType==CURTYPE_BTREE ){
77467  pCx->uc.pCursor = (BtCursor*)
77468  &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
77469  sqlite3BtreeCursorZero(pCx->uc.pCursor);
77470  }
77471  }
77472  return pCx;
77473 }
77474 
77475 /*
77476 ** Try to convert a value into a numeric representation if we can
77477 ** do so without loss of information. In other words, if the string
77478 ** looks like a number, convert it into a number. If it does not
77479 ** look like a number, leave it alone.
77480 **
77481 ** If the bTryForInt flag is true, then extra effort is made to give
77482 ** an integer representation. Strings that look like floating point
77483 ** values but which have no fractional component (example: '48.00')
77484 ** will have a MEM_Int representation when bTryForInt is true.
77485 **
77486 ** If bTryForInt is false, then if the input string contains a decimal
77487 ** point or exponential notation, the result is only MEM_Real, even
77488 ** if there is an exact integer representation of the quantity.
77489 */
77490 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
77491  double rValue;
77492  i64 iValue;
77493  u8 enc = pRec->enc;
77494  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
77495  if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
77496  if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
77497  pRec->u.i = iValue;
77498  pRec->flags |= MEM_Int;
77499  }else{
77500  pRec->u.r = rValue;
77501  pRec->flags |= MEM_Real;
77502  if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
77503  }
77504 }
77505 
77506 /*
77507 ** Processing is determine by the affinity parameter:
77508 **
77509 ** SQLITE_AFF_INTEGER:
77510 ** SQLITE_AFF_REAL:
77511 ** SQLITE_AFF_NUMERIC:
77512 ** Try to convert pRec to an integer representation or a
77513 ** floating-point representation if an integer representation
77514 ** is not possible. Note that the integer representation is
77515 ** always preferred, even if the affinity is REAL, because
77516 ** an integer representation is more space efficient on disk.
77517 **
77518 ** SQLITE_AFF_TEXT:
77519 ** Convert pRec to a text representation.
77520 **
77521 ** SQLITE_AFF_BLOB:
77522 ** No-op. pRec is unchanged.
77523 */
77524 static void applyAffinity(
77525  Mem *pRec, /* The value to apply affinity to */
77526  char affinity, /* The affinity to be applied */
77527  u8 enc /* Use this text encoding */
77528 ){
77529  if( affinity>=SQLITE_AFF_NUMERIC ){
77530  assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
77531  || affinity==SQLITE_AFF_NUMERIC );
77532  if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
77533  if( (pRec->flags & MEM_Real)==0 ){
77534  if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
77535  }else{
77536  sqlite3VdbeIntegerAffinity(pRec);
77537  }
77538  }
77539  }else if( affinity==SQLITE_AFF_TEXT ){
77540  /* Only attempt the conversion to TEXT if there is an integer or real
77541  ** representation (blob and NULL do not get converted) but no string
77542  ** representation. It would be harmless to repeat the conversion if
77543  ** there is already a string rep, but it is pointless to waste those
77544  ** CPU cycles. */
77545  if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
77546  if( (pRec->flags&(MEM_Real|MEM_Int)) ){
77547  sqlite3VdbeMemStringify(pRec, enc, 1);
77548  }
77549  }
77550  pRec->flags &= ~(MEM_Real|MEM_Int);
77551  }
77552 }
77553 
77554 /*
77555 ** Try to convert the type of a function argument or a result column
77556 ** into a numeric representation. Use either INTEGER or REAL whichever
77557 ** is appropriate. But only do the conversion if it is possible without
77558 ** loss of information and return the revised type of the argument.
77559 */
77560 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
77561  int eType = sqlite3_value_type(pVal);
77562  if( eType==SQLITE_TEXT ){
77563  Mem *pMem = (Mem*)pVal;
77564  applyNumericAffinity(pMem, 0);
77565  eType = sqlite3_value_type(pVal);
77566  }
77567  return eType;
77568 }
77569 
77570 /*
77571 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
77572 ** not the internal Mem* type.
77573 */
77574 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
77575  sqlite3_value *pVal,
77576  u8 affinity,
77577  u8 enc
77578 ){
77579  applyAffinity((Mem *)pVal, affinity, enc);
77580 }
77581 
77582 /*
77583 ** pMem currently only holds a string type (or maybe a BLOB that we can
77584 ** interpret as a string if we want to). Compute its corresponding
77585 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
77586 ** accordingly.
77587 */
77588 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
77589  assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
77590  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
77591  if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
77592  return 0;
77593  }
77594  if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
77595  return MEM_Int;
77596  }
77597  return MEM_Real;
77598 }
77599 
77600 /*
77601 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
77602 ** none.
77603 **
77604 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
77605 ** But it does set pMem->u.r and pMem->u.i appropriately.
77606 */
77607 static u16 numericType(Mem *pMem){
77608  if( pMem->flags & (MEM_Int|MEM_Real) ){
77609  return pMem->flags & (MEM_Int|MEM_Real);
77610  }
77611  if( pMem->flags & (MEM_Str|MEM_Blob) ){
77612  return computeNumericType(pMem);
77613  }
77614  return 0;
77615 }
77616 
77617 #ifdef SQLITE_DEBUG
77618 /*
77619 ** Write a nice string representation of the contents of cell pMem
77620 ** into buffer zBuf, length nBuf.
77621 */
77622 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
77623  char *zCsr = zBuf;
77624  int f = pMem->flags;
77625 
77626  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
77627 
77628  if( f&MEM_Blob ){
77629  int i;
77630  char c;
77631  if( f & MEM_Dyn ){
77632  c = 'z';
77633  assert( (f & (MEM_Static|MEM_Ephem))==0 );
77634  }else if( f & MEM_Static ){
77635  c = 't';
77636  assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77637  }else if( f & MEM_Ephem ){
77638  c = 'e';
77639  assert( (f & (MEM_Static|MEM_Dyn))==0 );
77640  }else{
77641  c = 's';
77642  }
77643 
77644  sqlite3_snprintf(100, zCsr, "%c", c);
77645  zCsr += sqlite3Strlen30(zCsr);
77646  sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
77647  zCsr += sqlite3Strlen30(zCsr);
77648  for(i=0; i<16 && i<pMem->n; i++){
77649  sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
77650  zCsr += sqlite3Strlen30(zCsr);
77651  }
77652  for(i=0; i<16 && i<pMem->n; i++){
77653  char z = pMem->z[i];
77654  if( z<32 || z>126 ) *zCsr++ = '.';
77655  else *zCsr++ = z;
77656  }
77657 
77658  sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
77659  zCsr += sqlite3Strlen30(zCsr);
77660  if( f & MEM_Zero ){
77661  sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
77662  zCsr += sqlite3Strlen30(zCsr);
77663  }
77664  *zCsr = '\0';
77665  }else if( f & MEM_Str ){
77666  int j, k;
77667  zBuf[0] = ' ';
77668  if( f & MEM_Dyn ){
77669  zBuf[1] = 'z';
77670  assert( (f & (MEM_Static|MEM_Ephem))==0 );
77671  }else if( f & MEM_Static ){
77672  zBuf[1] = 't';
77673  assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77674  }else if( f & MEM_Ephem ){
77675  zBuf[1] = 'e';
77676  assert( (f & (MEM_Static|MEM_Dyn))==0 );
77677  }else{
77678  zBuf[1] = 's';
77679  }
77680  k = 2;
77681  sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
77682  k += sqlite3Strlen30(&zBuf[k]);
77683  zBuf[k++] = '[';
77684  for(j=0; j<15 && j<pMem->n; j++){
77685  u8 c = pMem->z[j];
77686  if( c>=0x20 && c<0x7f ){
77687  zBuf[k++] = c;
77688  }else{
77689  zBuf[k++] = '.';
77690  }
77691  }
77692  zBuf[k++] = ']';
77693  sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
77694  k += sqlite3Strlen30(&zBuf[k]);
77695  zBuf[k++] = 0;
77696  }
77697 }
77698 #endif
77699 
77700 #ifdef SQLITE_DEBUG
77701 /*
77702 ** Print the value of a register for tracing purposes:
77703 */
77704 static void memTracePrint(Mem *p){
77705  if( p->flags & MEM_Undefined ){
77706  printf(" undefined");
77707  }else if( p->flags & MEM_Null ){
77708  printf(" NULL");
77709  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
77710  printf(" si:%lld", p->u.i);
77711  }else if( p->flags & MEM_Int ){
77712  printf(" i:%lld", p->u.i);
77713 #ifndef SQLITE_OMIT_FLOATING_POINT
77714  }else if( p->flags & MEM_Real ){
77715  printf(" r:%g", p->u.r);
77716 #endif
77717  }else if( p->flags & MEM_RowSet ){
77718  printf(" (rowset)");
77719  }else{
77720  char zBuf[200];
77721  sqlite3VdbeMemPrettyPrint(p, zBuf);
77722  printf(" %s", zBuf);
77723  }
77724  if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
77725 }
77726 static void registerTrace(int iReg, Mem *p){
77727  printf("REG[%d] = ", iReg);
77728  memTracePrint(p);
77729  printf("\n");
77730 }
77731 #endif
77732 
77733 #ifdef SQLITE_DEBUG
77734 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
77735 #else
77736 # define REGISTER_TRACE(R,M)
77737 #endif
77738 
77739 
77740 #ifdef VDBE_PROFILE
77741 
77742 /*
77743 ** hwtime.h contains inline assembler code for implementing
77744 ** high-performance timing routines.
77745 */
77746 /************** Include hwtime.h in the middle of vdbe.c *********************/
77747 /************** Begin file hwtime.h ******************************************/
77748 /*
77749 ** 2008 May 27
77750 **
77751 ** The author disclaims copyright to this source code. In place of
77752 ** a legal notice, here is a blessing:
77753 **
77754 ** May you do good and not evil.
77755 ** May you find forgiveness for yourself and forgive others.
77756 ** May you share freely, never taking more than you give.
77757 **
77758 ******************************************************************************
77759 **
77760 ** This file contains inline asm code for retrieving "high-performance"
77761 ** counters for x86 class CPUs.
77762 */
77763 #ifndef SQLITE_HWTIME_H
77764 #define SQLITE_HWTIME_H
77765 
77766 /*
77767 ** The following routine only works on pentium-class (or newer) processors.
77768 ** It uses the RDTSC opcode to read the cycle count value out of the
77769 ** processor and returns that value. This can be used for high-res
77770 ** profiling.
77771 */
77772 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
77773  (defined(i386) || defined(__i386__) || defined(_M_IX86))
77774 
77775  #if defined(__GNUC__)
77776 
77777  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77778  unsigned int lo, hi;
77779  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
77780  return (sqlite_uint64)hi << 32 | lo;
77781  }
77782 
77783  #elif defined(_MSC_VER)
77784 
77785  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
77786  __asm {
77787  rdtsc
77788  ret ; return value at EDX:EAX
77789  }
77790  }
77791 
77792  #endif
77793 
77794 #elif (defined(__GNUC__) && defined(__x86_64__))
77795 
77796  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77797  unsigned long val;
77798  __asm__ __volatile__ ("rdtsc" : "=A" (val));
77799  return val;
77800  }
77801 
77802 #elif (defined(__GNUC__) && defined(__ppc__))
77803 
77804  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77805  unsigned long long retval;
77806  unsigned long junk;
77807  __asm__ __volatile__ ("\n\
77808  1: mftbu %1\n\
77809  mftb %L0\n\
77810  mftbu %0\n\
77811  cmpw %0,%1\n\
77812  bne 1b"
77813  : "=r" (retval), "=r" (junk));
77814  return retval;
77815  }
77816 
77817 #else
77818 
77819  #error Need implementation of sqlite3Hwtime() for your platform.
77820 
77821  /*
77822  ** To compile without implementing sqlite3Hwtime() for your platform,
77823  ** you can remove the above #error and use the following
77824  ** stub function. You will lose timing support for many
77825  ** of the debugging and testing utilities, but it should at
77826  ** least compile and run.
77827  */
77828 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
77829 
77830 #endif
77831 
77832 #endif /* !defined(SQLITE_HWTIME_H) */
77833 
77834 /************** End of hwtime.h **********************************************/
77835 /************** Continuing where we left off in vdbe.c ***********************/
77836 
77837 #endif
77838 
77839 #ifndef NDEBUG
77840 /*
77841 ** This function is only called from within an assert() expression. It
77842 ** checks that the sqlite3.nTransaction variable is correctly set to
77843 ** the number of non-transaction savepoints currently in the
77844 ** linked list starting at sqlite3.pSavepoint.
77845 **
77846 ** Usage:
77847 **
77848 ** assert( checkSavepointCount(db) );
77849 */
77850 static int checkSavepointCount(sqlite3 *db){
77851  int n = 0;
77852  Savepoint *p;
77853  for(p=db->pSavepoint; p; p=p->pNext) n++;
77854  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
77855  return 1;
77856 }
77857 #endif
77858 
77859 /*
77860 ** Return the register of pOp->p2 after first preparing it to be
77861 ** overwritten with an integer value.
77862 */
77863 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
77864  sqlite3VdbeMemSetNull(pOut);
77865  pOut->flags = MEM_Int;
77866  return pOut;
77867 }
77868 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
77869  Mem *pOut;
77870  assert( pOp->p2>0 );
77871  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77872  pOut = &p->aMem[pOp->p2];
77873  memAboutToChange(p, pOut);
77874  if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
77875  return out2PrereleaseWithClear(pOut);
77876  }else{
77877  pOut->flags = MEM_Int;
77878  return pOut;
77879  }
77880 }
77881 
77882 
77883 /*
77884 ** Execute as much of a VDBE program as we can.
77885 ** This is the core of sqlite3_step().
77886 */
77887 SQLITE_PRIVATE int sqlite3VdbeExec(
77888  Vdbe *p /* The VDBE */
77889 ){
77890  Op *aOp = p->aOp; /* Copy of p->aOp */
77891  Op *pOp = aOp; /* Current operation */
77892 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77893  Op *pOrigOp; /* Value of pOp at the top of the loop */
77894 #endif
77895 #ifdef SQLITE_DEBUG
77896  int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
77897 #endif
77898  int rc = SQLITE_OK; /* Value to return */
77899  sqlite3 *db = p->db; /* The database */
77900  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
77901  u8 encoding = ENC(db); /* The database encoding */
77902  int iCompare = 0; /* Result of last comparison */
77903  unsigned nVmStep = 0; /* Number of virtual machine steps */
77904 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77905  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
77906 #endif
77907  Mem *aMem = p->aMem; /* Copy of p->aMem */
77908  Mem *pIn1 = 0; /* 1st input operand */
77909  Mem *pIn2 = 0; /* 2nd input operand */
77910  Mem *pIn3 = 0; /* 3rd input operand */
77911  Mem *pOut = 0; /* Output operand */
77912  int *aPermute = 0; /* Permutation of columns for OP_Compare */
77913  i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
77914 #ifdef VDBE_PROFILE
77915  u64 start; /* CPU clock count at start of opcode */
77916 #endif
77917  /*** INSERT STACK UNION HERE ***/
77918 
77919  assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
77920  sqlite3VdbeEnter(p);
77921  if( p->rc==SQLITE_NOMEM ){
77922  /* This happens if a malloc() inside a call to sqlite3_column_text() or
77923  ** sqlite3_column_text16() failed. */
77924  goto no_mem;
77925  }
77926  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
77927  assert( p->bIsReader || p->readOnly!=0 );
77928  p->rc = SQLITE_OK;
77929  p->iCurrentTime = 0;
77930  assert( p->explain==0 );
77931  p->pResultSet = 0;
77932  db->busyHandler.nBusy = 0;
77933  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77934  sqlite3VdbeIOTraceSql(p);
77935 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77936  if( db->xProgress ){
77937  u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
77938  assert( 0 < db->nProgressOps );
77939  nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
77940  }
77941 #endif
77942 #ifdef SQLITE_DEBUG
77943  sqlite3BeginBenignMalloc();
77944  if( p->pc==0
77945  && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
77946  ){
77947  int i;
77948  int once = 1;
77949  sqlite3VdbePrintSql(p);
77950  if( p->db->flags & SQLITE_VdbeListing ){
77951  printf("VDBE Program Listing:\n");
77952  for(i=0; i<p->nOp; i++){
77953  sqlite3VdbePrintOp(stdout, i, &aOp[i]);
77954  }
77955  }
77956  if( p->db->flags & SQLITE_VdbeEQP ){
77957  for(i=0; i<p->nOp; i++){
77958  if( aOp[i].opcode==OP_Explain ){
77959  if( once ) printf("VDBE Query Plan:\n");
77960  printf("%s\n", aOp[i].p4.z);
77961  once = 0;
77962  }
77963  }
77964  }
77965  if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
77966  }
77967  sqlite3EndBenignMalloc();
77968 #endif
77969  for(pOp=&aOp[p->pc]; 1; pOp++){
77970  /* Errors are detected by individual opcodes, with an immediate
77971  ** jumps to abort_due_to_error. */
77972  assert( rc==SQLITE_OK );
77973 
77974  assert( pOp>=aOp && pOp<&aOp[p->nOp]);
77975 #ifdef VDBE_PROFILE
77976  start = sqlite3Hwtime();
77977 #endif
77978  nVmStep++;
77979 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
77980  if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
77981 #endif
77982 
77983  /* Only allow tracing if SQLITE_DEBUG is defined.
77984  */
77985 #ifdef SQLITE_DEBUG
77986  if( db->flags & SQLITE_VdbeTrace ){
77987  sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
77988  }
77989 #endif
77990 
77991 
77992  /* Check to see if we need to simulate an interrupt. This only happens
77993  ** if we have a special test build.
77994  */
77995 #ifdef SQLITE_TEST
77996  if( sqlite3_interrupt_count>0 ){
77997  sqlite3_interrupt_count--;
77998  if( sqlite3_interrupt_count==0 ){
77999  sqlite3_interrupt(db);
78000  }
78001  }
78002 #endif
78003 
78004  /* Sanity checking on other operands */
78005 #ifdef SQLITE_DEBUG
78006  {
78007  u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
78008  if( (opProperty & OPFLG_IN1)!=0 ){
78009  assert( pOp->p1>0 );
78010  assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
78011  assert( memIsValid(&aMem[pOp->p1]) );
78012  assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
78013  REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
78014  }
78015  if( (opProperty & OPFLG_IN2)!=0 ){
78016  assert( pOp->p2>0 );
78017  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
78018  assert( memIsValid(&aMem[pOp->p2]) );
78019  assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
78020  REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
78021  }
78022  if( (opProperty & OPFLG_IN3)!=0 ){
78023  assert( pOp->p3>0 );
78024  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78025  assert( memIsValid(&aMem[pOp->p3]) );
78026  assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
78027  REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
78028  }
78029  if( (opProperty & OPFLG_OUT2)!=0 ){
78030  assert( pOp->p2>0 );
78031  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
78032  memAboutToChange(p, &aMem[pOp->p2]);
78033  }
78034  if( (opProperty & OPFLG_OUT3)!=0 ){
78035  assert( pOp->p3>0 );
78036  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78037  memAboutToChange(p, &aMem[pOp->p3]);
78038  }
78039  }
78040 #endif
78041 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
78042  pOrigOp = pOp;
78043 #endif
78044 
78045  switch( pOp->opcode ){
78046 
78047 /*****************************************************************************
78048 ** What follows is a massive switch statement where each case implements a
78049 ** separate instruction in the virtual machine. If we follow the usual
78050 ** indentation conventions, each case should be indented by 6 spaces. But
78051 ** that is a lot of wasted space on the left margin. So the code within
78052 ** the switch statement will break with convention and be flush-left. Another
78053 ** big comment (similar to this one) will mark the point in the code where
78054 ** we transition back to normal indentation.
78055 **
78056 ** The formatting of each case is important. The makefile for SQLite
78057 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
78058 ** file looking for lines that begin with "case OP_". The opcodes.h files
78059 ** will be filled with #defines that give unique integer values to each
78060 ** opcode and the opcodes.c file is filled with an array of strings where
78061 ** each string is the symbolic name for the corresponding opcode. If the
78062 ** case statement is followed by a comment of the form "/# same as ... #/"
78063 ** that comment is used to determine the particular value of the opcode.
78064 **
78065 ** Other keywords in the comment that follows each case are used to
78066 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
78067 ** Keywords include: in1, in2, in3, out2, out3. See
78068 ** the mkopcodeh.awk script for additional information.
78069 **
78070 ** Documentation about VDBE opcodes is generated by scanning this file
78071 ** for lines of that contain "Opcode:". That line and all subsequent
78072 ** comment lines are used in the generation of the opcode.html documentation
78073 ** file.
78074 **
78075 ** SUMMARY:
78076 **
78077 ** Formatting is important to scripts that scan this file.
78078 ** Do not deviate from the formatting style currently in use.
78079 **
78080 *****************************************************************************/
78081 
78082 /* Opcode: Goto * P2 * * *
78083 **
78084 ** An unconditional jump to address P2.
78085 ** The next instruction executed will be
78086 ** the one at index P2 from the beginning of
78087 ** the program.
78088 **
78089 ** The P1 parameter is not actually used by this opcode. However, it
78090 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
78091 ** that this Goto is the bottom of a loop and that the lines from P2 down
78092 ** to the current line should be indented for EXPLAIN output.
78093 */
78094 case OP_Goto: { /* jump */
78095 jump_to_p2_and_check_for_interrupt:
78096  pOp = &aOp[pOp->p2 - 1];
78097 
78098  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
78099  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
78100  ** completion. Check to see if sqlite3_interrupt() has been called
78101  ** or if the progress callback needs to be invoked.
78102  **
78103  ** This code uses unstructured "goto" statements and does not look clean.
78104  ** But that is not due to sloppy coding habits. The code is written this
78105  ** way for performance, to avoid having to run the interrupt and progress
78106  ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
78107  ** faster according to "valgrind --tool=cachegrind" */
78108 check_for_interrupt:
78109  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
78110 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78111  /* Call the progress callback if it is configured and the required number
78112  ** of VDBE ops have been executed (either since this invocation of
78113  ** sqlite3VdbeExec() or since last time the progress callback was called).
78114  ** If the progress callback returns non-zero, exit the virtual machine with
78115  ** a return code SQLITE_ABORT.
78116  */
78117  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
78118  assert( db->nProgressOps!=0 );
78119  nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
78120  if( db->xProgress(db->pProgressArg) ){
78121  rc = SQLITE_INTERRUPT;
78122  goto abort_due_to_error;
78123  }
78124  }
78125 #endif
78126 
78127  break;
78128 }
78129 
78130 /* Opcode: Gosub P1 P2 * * *
78131 **
78132 ** Write the current address onto register P1
78133 ** and then jump to address P2.
78134 */
78135 case OP_Gosub: { /* jump */
78136  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78137  pIn1 = &aMem[pOp->p1];
78138  assert( VdbeMemDynamic(pIn1)==0 );
78139  memAboutToChange(p, pIn1);
78140  pIn1->flags = MEM_Int;
78141  pIn1->u.i = (int)(pOp-aOp);
78142  REGISTER_TRACE(pOp->p1, pIn1);
78143 
78144  /* Most jump operations do a goto to this spot in order to update
78145  ** the pOp pointer. */
78146 jump_to_p2:
78147  pOp = &aOp[pOp->p2 - 1];
78148  break;
78149 }
78150 
78151 /* Opcode: Return P1 * * * *
78152 **
78153 ** Jump to the next instruction after the address in register P1. After
78154 ** the jump, register P1 becomes undefined.
78155 */
78156 case OP_Return: { /* in1 */
78157  pIn1 = &aMem[pOp->p1];
78158  assert( pIn1->flags==MEM_Int );
78159  pOp = &aOp[pIn1->u.i];
78160  pIn1->flags = MEM_Undefined;
78161  break;
78162 }
78163 
78164 /* Opcode: InitCoroutine P1 P2 P3 * *
78165 **
78166 ** Set up register P1 so that it will Yield to the coroutine
78167 ** located at address P3.
78168 **
78169 ** If P2!=0 then the coroutine implementation immediately follows
78170 ** this opcode. So jump over the coroutine implementation to
78171 ** address P2.
78172 **
78173 ** See also: EndCoroutine
78174 */
78175 case OP_InitCoroutine: { /* jump */
78176  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78177  assert( pOp->p2>=0 && pOp->p2<p->nOp );
78178  assert( pOp->p3>=0 && pOp->p3<p->nOp );
78179  pOut = &aMem[pOp->p1];
78180  assert( !VdbeMemDynamic(pOut) );
78181  pOut->u.i = pOp->p3 - 1;
78182  pOut->flags = MEM_Int;
78183  if( pOp->p2 ) goto jump_to_p2;
78184  break;
78185 }
78186 
78187 /* Opcode: EndCoroutine P1 * * * *
78188 **
78189 ** The instruction at the address in register P1 is a Yield.
78190 ** Jump to the P2 parameter of that Yield.
78191 ** After the jump, register P1 becomes undefined.
78192 **
78193 ** See also: InitCoroutine
78194 */
78195 case OP_EndCoroutine: { /* in1 */
78196  VdbeOp *pCaller;
78197  pIn1 = &aMem[pOp->p1];
78198  assert( pIn1->flags==MEM_Int );
78199  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
78200  pCaller = &aOp[pIn1->u.i];
78201  assert( pCaller->opcode==OP_Yield );
78202  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
78203  pOp = &aOp[pCaller->p2 - 1];
78204  pIn1->flags = MEM_Undefined;
78205  break;
78206 }
78207 
78208 /* Opcode: Yield P1 P2 * * *
78209 **
78210 ** Swap the program counter with the value in register P1. This
78211 ** has the effect of yielding to a coroutine.
78212 **
78213 ** If the coroutine that is launched by this instruction ends with
78214 ** Yield or Return then continue to the next instruction. But if
78215 ** the coroutine launched by this instruction ends with
78216 ** EndCoroutine, then jump to P2 rather than continuing with the
78217 ** next instruction.
78218 **
78219 ** See also: InitCoroutine
78220 */
78221 case OP_Yield: { /* in1, jump */
78222  int pcDest;
78223  pIn1 = &aMem[pOp->p1];
78224  assert( VdbeMemDynamic(pIn1)==0 );
78225  pIn1->flags = MEM_Int;
78226  pcDest = (int)pIn1->u.i;
78227  pIn1->u.i = (int)(pOp - aOp);
78228  REGISTER_TRACE(pOp->p1, pIn1);
78229  pOp = &aOp[pcDest];
78230  break;
78231 }
78232 
78233 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
78234 ** Synopsis: if r[P3]=null halt
78235 **
78236 ** Check the value in register P3. If it is NULL then Halt using
78237 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
78238 ** value in register P3 is not NULL, then this routine is a no-op.
78239 ** The P5 parameter should be 1.
78240 */
78241 case OP_HaltIfNull: { /* in3 */
78242  pIn3 = &aMem[pOp->p3];
78243  if( (pIn3->flags & MEM_Null)==0 ) break;
78244  /* Fall through into OP_Halt */
78245 }
78246 
78247 /* Opcode: Halt P1 P2 * P4 P5
78248 **
78249 ** Exit immediately. All open cursors, etc are closed
78250 ** automatically.
78251 **
78252 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
78253 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
78254 ** For errors, it can be some other value. If P1!=0 then P2 will determine
78255 ** whether or not to rollback the current transaction. Do not rollback
78256 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
78257 ** then back out all changes that have occurred during this execution of the
78258 ** VDBE, but do not rollback the transaction.
78259 **
78260 ** If P4 is not null then it is an error message string.
78261 **
78262 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
78263 **
78264 ** 0: (no change)
78265 ** 1: NOT NULL contraint failed: P4
78266 ** 2: UNIQUE constraint failed: P4
78267 ** 3: CHECK constraint failed: P4
78268 ** 4: FOREIGN KEY constraint failed: P4
78269 **
78270 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
78271 ** omitted.
78272 **
78273 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
78274 ** every program. So a jump past the last instruction of the program
78275 ** is the same as executing Halt.
78276 */
78277 case OP_Halt: {
78278  VdbeFrame *pFrame;
78279  int pcx;
78280 
78281  pcx = (int)(pOp - aOp);
78282  if( pOp->p1==SQLITE_OK && p->pFrame ){
78283  /* Halt the sub-program. Return control to the parent frame. */
78284  pFrame = p->pFrame;
78285  p->pFrame = pFrame->pParent;
78286  p->nFrame--;
78287  sqlite3VdbeSetChanges(db, p->nChange);
78288  pcx = sqlite3VdbeFrameRestore(pFrame);
78289  lastRowid = db->lastRowid;
78290  if( pOp->p2==OE_Ignore ){
78291  /* Instruction pcx is the OP_Program that invoked the sub-program
78292  ** currently being halted. If the p2 instruction of this OP_Halt
78293  ** instruction is set to OE_Ignore, then the sub-program is throwing
78294  ** an IGNORE exception. In this case jump to the address specified
78295  ** as the p2 of the calling OP_Program. */
78296  pcx = p->aOp[pcx].p2-1;
78297  }
78298  aOp = p->aOp;
78299  aMem = p->aMem;
78300  pOp = &aOp[pcx];
78301  break;
78302  }
78303  p->rc = pOp->p1;
78304  p->errorAction = (u8)pOp->p2;
78305  p->pc = pcx;
78306  assert( pOp->p5>=0 && pOp->p5<=4 );
78307  if( p->rc ){
78308  if( pOp->p5 ){
78309  static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
78310  "FOREIGN KEY" };
78311  testcase( pOp->p5==1 );
78312  testcase( pOp->p5==2 );
78313  testcase( pOp->p5==3 );
78314  testcase( pOp->p5==4 );
78315  sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
78316  if( pOp->p4.z ){
78317  p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
78318  }
78319  }else{
78320  sqlite3VdbeError(p, "%s", pOp->p4.z);
78321  }
78322  sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
78323  }
78324  rc = sqlite3VdbeHalt(p);
78325  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
78326  if( rc==SQLITE_BUSY ){
78327  p->rc = SQLITE_BUSY;
78328  }else{
78329  assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
78330  assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
78331  rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
78332  }
78333  goto vdbe_return;
78334 }
78335 
78336 /* Opcode: Integer P1 P2 * * *
78337 ** Synopsis: r[P2]=P1
78338 **
78339 ** The 32-bit integer value P1 is written into register P2.
78340 */
78341 case OP_Integer: { /* out2 */
78342  pOut = out2Prerelease(p, pOp);
78343  pOut->u.i = pOp->p1;
78344  break;
78345 }
78346 
78347 /* Opcode: Int64 * P2 * P4 *
78348 ** Synopsis: r[P2]=P4
78349 **
78350 ** P4 is a pointer to a 64-bit integer value.
78351 ** Write that value into register P2.
78352 */
78353 case OP_Int64: { /* out2 */
78354  pOut = out2Prerelease(p, pOp);
78355  assert( pOp->p4.pI64!=0 );
78356  pOut->u.i = *pOp->p4.pI64;
78357  break;
78358 }
78359 
78360 #ifndef SQLITE_OMIT_FLOATING_POINT
78361 /* Opcode: Real * P2 * P4 *
78362 ** Synopsis: r[P2]=P4
78363 **
78364 ** P4 is a pointer to a 64-bit floating point value.
78365 ** Write that value into register P2.
78366 */
78367 case OP_Real: { /* same as TK_FLOAT, out2 */
78368  pOut = out2Prerelease(p, pOp);
78369  pOut->flags = MEM_Real;
78370  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
78371  pOut->u.r = *pOp->p4.pReal;
78372  break;
78373 }
78374 #endif
78375 
78376 /* Opcode: String8 * P2 * P4 *
78377 ** Synopsis: r[P2]='P4'
78378 **
78379 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
78380 ** into a String opcode before it is executed for the first time. During
78381 ** this transformation, the length of string P4 is computed and stored
78382 ** as the P1 parameter.
78383 */
78384 case OP_String8: { /* same as TK_STRING, out2 */
78385  assert( pOp->p4.z!=0 );
78386  pOut = out2Prerelease(p, pOp);
78387  pOp->opcode = OP_String;
78388  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
78389 
78390 #ifndef SQLITE_OMIT_UTF16
78391  if( encoding!=SQLITE_UTF8 ){
78392  rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
78393  assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
78394  if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
78395  assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
78396  assert( VdbeMemDynamic(pOut)==0 );
78397  pOut->szMalloc = 0;
78398  pOut->flags |= MEM_Static;
78399  if( pOp->p4type==P4_DYNAMIC ){
78400  sqlite3DbFree(db, pOp->p4.z);
78401  }
78402  pOp->p4type = P4_DYNAMIC;
78403  pOp->p4.z = pOut->z;
78404  pOp->p1 = pOut->n;
78405  }
78406  testcase( rc==SQLITE_TOOBIG );
78407 #endif
78408  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78409  goto too_big;
78410  }
78411  assert( rc==SQLITE_OK );
78412  /* Fall through to the next case, OP_String */
78413 }
78414 
78415 /* Opcode: String P1 P2 P3 P4 P5
78416 ** Synopsis: r[P2]='P4' (len=P1)
78417 **
78418 ** The string value P4 of length P1 (bytes) is stored in register P2.
78419 **
78420 ** If P3 is not zero and the content of register P3 is equal to P5, then
78421 ** the datatype of the register P2 is converted to BLOB. The content is
78422 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
78423 ** of a string, as if it had been CAST. In other words:
78424 **
78425 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
78426 */
78427 case OP_String: { /* out2 */
78428  assert( pOp->p4.z!=0 );
78429  pOut = out2Prerelease(p, pOp);
78430  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
78431  pOut->z = pOp->p4.z;
78432  pOut->n = pOp->p1;
78433  pOut->enc = encoding;
78434  UPDATE_MAX_BLOBSIZE(pOut);
78435 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
78436  if( pOp->p3>0 ){
78437  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78438  pIn3 = &aMem[pOp->p3];
78439  assert( pIn3->flags & MEM_Int );
78440  if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
78441  }
78442 #endif
78443  break;
78444 }
78445 
78446 /* Opcode: Null P1 P2 P3 * *
78447 ** Synopsis: r[P2..P3]=NULL
78448 **
78449 ** Write a NULL into registers P2. If P3 greater than P2, then also write
78450 ** NULL into register P3 and every register in between P2 and P3. If P3
78451 ** is less than P2 (typically P3 is zero) then only register P2 is
78452 ** set to NULL.
78453 **
78454 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
78455 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
78456 ** OP_Ne or OP_Eq.
78457 */
78458 case OP_Null: { /* out2 */
78459  int cnt;
78460  u16 nullFlag;
78461  pOut = out2Prerelease(p, pOp);
78462  cnt = pOp->p3-pOp->p2;
78463  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78464  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
78465  pOut->n = 0;
78466  while( cnt>0 ){
78467  pOut++;
78468  memAboutToChange(p, pOut);
78469  sqlite3VdbeMemSetNull(pOut);
78470  pOut->flags = nullFlag;
78471  pOut->n = 0;
78472  cnt--;
78473  }
78474  break;
78475 }
78476 
78477 /* Opcode: SoftNull P1 * * * *
78478 ** Synopsis: r[P1]=NULL
78479 **
78480 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
78481 ** instruction, but do not free any string or blob memory associated with
78482 ** the register, so that if the value was a string or blob that was
78483 ** previously copied using OP_SCopy, the copies will continue to be valid.
78484 */
78485 case OP_SoftNull: {
78486  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78487  pOut = &aMem[pOp->p1];
78488  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
78489  break;
78490 }
78491 
78492 /* Opcode: Blob P1 P2 * P4 *
78493 ** Synopsis: r[P2]=P4 (len=P1)
78494 **
78495 ** P4 points to a blob of data P1 bytes long. Store this
78496 ** blob in register P2.
78497 */
78498 case OP_Blob: { /* out2 */
78499  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
78500  pOut = out2Prerelease(p, pOp);
78501  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
78502  pOut->enc = encoding;
78503  UPDATE_MAX_BLOBSIZE(pOut);
78504  break;
78505 }
78506 
78507 /* Opcode: Variable P1 P2 * P4 *
78508 ** Synopsis: r[P2]=parameter(P1,P4)
78509 **
78510 ** Transfer the values of bound parameter P1 into register P2
78511 **
78512 ** If the parameter is named, then its name appears in P4.
78513 ** The P4 value is used by sqlite3_bind_parameter_name().
78514 */
78515 case OP_Variable: { /* out2 */
78516  Mem *pVar; /* Value being transferred */
78517 
78518  assert( pOp->p1>0 && pOp->p1<=p->nVar );
78519  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
78520  pVar = &p->aVar[pOp->p1 - 1];
78521  if( sqlite3VdbeMemTooBig(pVar) ){
78522  goto too_big;
78523  }
78524  pOut = out2Prerelease(p, pOp);
78525  sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
78526  UPDATE_MAX_BLOBSIZE(pOut);
78527  break;
78528 }
78529 
78530 /* Opcode: Move P1 P2 P3 * *
78531 ** Synopsis: r[P2@P3]=r[P1@P3]
78532 **
78533 ** Move the P3 values in register P1..P1+P3-1 over into
78534 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
78535 ** left holding a NULL. It is an error for register ranges
78536 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
78537 ** for P3 to be less than 1.
78538 */
78539 case OP_Move: {
78540  int n; /* Number of registers left to copy */
78541  int p1; /* Register to copy from */
78542  int p2; /* Register to copy to */
78543 
78544  n = pOp->p3;
78545  p1 = pOp->p1;
78546  p2 = pOp->p2;
78547  assert( n>0 && p1>0 && p2>0 );
78548  assert( p1+n<=p2 || p2+n<=p1 );
78549 
78550  pIn1 = &aMem[p1];
78551  pOut = &aMem[p2];
78552  do{
78553  assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
78554  assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
78555  assert( memIsValid(pIn1) );
78556  memAboutToChange(p, pOut);
78557  sqlite3VdbeMemMove(pOut, pIn1);
78558 #ifdef SQLITE_DEBUG
78559  if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
78560  pOut->pScopyFrom += pOp->p2 - p1;
78561  }
78562 #endif
78563  Deephemeralize(pOut);
78564  REGISTER_TRACE(p2++, pOut);
78565  pIn1++;
78566  pOut++;
78567  }while( --n );
78568  break;
78569 }
78570 
78571 /* Opcode: Copy P1 P2 P3 * *
78572 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
78573 **
78574 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
78575 **
78576 ** This instruction makes a deep copy of the value. A duplicate
78577 ** is made of any string or blob constant. See also OP_SCopy.
78578 */
78579 case OP_Copy: {
78580  int n;
78581 
78582  n = pOp->p3;
78583  pIn1 = &aMem[pOp->p1];
78584  pOut = &aMem[pOp->p2];
78585  assert( pOut!=pIn1 );
78586  while( 1 ){
78587  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78588  Deephemeralize(pOut);
78589 #ifdef SQLITE_DEBUG
78590  pOut->pScopyFrom = 0;
78591 #endif
78592  REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
78593  if( (n--)==0 ) break;
78594  pOut++;
78595  pIn1++;
78596  }
78597  break;
78598 }
78599 
78600 /* Opcode: SCopy P1 P2 * * *
78601 ** Synopsis: r[P2]=r[P1]
78602 **
78603 ** Make a shallow copy of register P1 into register P2.
78604 **
78605 ** This instruction makes a shallow copy of the value. If the value
78606 ** is a string or blob, then the copy is only a pointer to the
78607 ** original and hence if the original changes so will the copy.
78608 ** Worse, if the original is deallocated, the copy becomes invalid.
78609 ** Thus the program must guarantee that the original will not change
78610 ** during the lifetime of the copy. Use OP_Copy to make a complete
78611 ** copy.
78612 */
78613 case OP_SCopy: { /* out2 */
78614  pIn1 = &aMem[pOp->p1];
78615  pOut = &aMem[pOp->p2];
78616  assert( pOut!=pIn1 );
78617  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78618 #ifdef SQLITE_DEBUG
78619  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
78620 #endif
78621  break;
78622 }
78623 
78624 /* Opcode: IntCopy P1 P2 * * *
78625 ** Synopsis: r[P2]=r[P1]
78626 **
78627 ** Transfer the integer value held in register P1 into register P2.
78628 **
78629 ** This is an optimized version of SCopy that works only for integer
78630 ** values.
78631 */
78632 case OP_IntCopy: { /* out2 */
78633  pIn1 = &aMem[pOp->p1];
78634  assert( (pIn1->flags & MEM_Int)!=0 );
78635  pOut = &aMem[pOp->p2];
78636  sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
78637  break;
78638 }
78639 
78640 /* Opcode: ResultRow P1 P2 * * *
78641 ** Synopsis: output=r[P1@P2]
78642 **
78643 ** The registers P1 through P1+P2-1 contain a single row of
78644 ** results. This opcode causes the sqlite3_step() call to terminate
78645 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
78646 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
78647 ** the result row.
78648 */
78649 case OP_ResultRow: {
78650  Mem *pMem;
78651  int i;
78652  assert( p->nResColumn==pOp->p2 );
78653  assert( pOp->p1>0 );
78654  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
78655 
78656 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78657  /* Run the progress counter just before returning.
78658  */
78659  if( db->xProgress!=0
78660  && nVmStep>=nProgressLimit
78661  && db->xProgress(db->pProgressArg)!=0
78662  ){
78663  rc = SQLITE_INTERRUPT;
78664  goto abort_due_to_error;
78665  }
78666 #endif
78667 
78668  /* If this statement has violated immediate foreign key constraints, do
78669  ** not return the number of rows modified. And do not RELEASE the statement
78670  ** transaction. It needs to be rolled back. */
78671  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
78672  assert( db->flags&SQLITE_CountRows );
78673  assert( p->usesStmtJournal );
78674  goto abort_due_to_error;
78675  }
78676 
78677  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
78678  ** DML statements invoke this opcode to return the number of rows
78679  ** modified to the user. This is the only way that a VM that
78680  ** opens a statement transaction may invoke this opcode.
78681  **
78682  ** In case this is such a statement, close any statement transaction
78683  ** opened by this VM before returning control to the user. This is to
78684  ** ensure that statement-transactions are always nested, not overlapping.
78685  ** If the open statement-transaction is not closed here, then the user
78686  ** may step another VM that opens its own statement transaction. This
78687  ** may lead to overlapping statement transactions.
78688  **
78689  ** The statement transaction is never a top-level transaction. Hence
78690  ** the RELEASE call below can never fail.
78691  */
78692  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
78693  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
78694  assert( rc==SQLITE_OK );
78695 
78696  /* Invalidate all ephemeral cursor row caches */
78697  p->cacheCtr = (p->cacheCtr + 2)|1;
78698 
78699  /* Make sure the results of the current row are \000 terminated
78700  ** and have an assigned type. The results are de-ephemeralized as
78701  ** a side effect.
78702  */
78703  pMem = p->pResultSet = &aMem[pOp->p1];
78704  for(i=0; i<pOp->p2; i++){
78705  assert( memIsValid(&pMem[i]) );
78706  Deephemeralize(&pMem[i]);
78707  assert( (pMem[i].flags & MEM_Ephem)==0
78708  || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
78709  sqlite3VdbeMemNulTerminate(&pMem[i]);
78710  REGISTER_TRACE(pOp->p1+i, &pMem[i]);
78711  }
78712  if( db->mallocFailed ) goto no_mem;
78713 
78714  if( db->mTrace & SQLITE_TRACE_ROW ){
78715  db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
78716  }
78717 
78718  /* Return SQLITE_ROW
78719  */
78720  p->pc = (int)(pOp - aOp) + 1;
78721  rc = SQLITE_ROW;
78722  goto vdbe_return;
78723 }
78724 
78725 /* Opcode: Concat P1 P2 P3 * *
78726 ** Synopsis: r[P3]=r[P2]+r[P1]
78727 **
78728 ** Add the text in register P1 onto the end of the text in
78729 ** register P2 and store the result in register P3.
78730 ** If either the P1 or P2 text are NULL then store NULL in P3.
78731 **
78732 ** P3 = P2 || P1
78733 **
78734 ** It is illegal for P1 and P3 to be the same register. Sometimes,
78735 ** if P3 is the same register as P2, the implementation is able
78736 ** to avoid a memcpy().
78737 */
78738 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
78739  i64 nByte;
78740 
78741  pIn1 = &aMem[pOp->p1];
78742  pIn2 = &aMem[pOp->p2];
78743  pOut = &aMem[pOp->p3];
78744  assert( pIn1!=pOut );
78745  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78746  sqlite3VdbeMemSetNull(pOut);
78747  break;
78748  }
78749  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
78750  Stringify(pIn1, encoding);
78751  Stringify(pIn2, encoding);
78752  nByte = pIn1->n + pIn2->n;
78753  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78754  goto too_big;
78755  }
78756  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
78757  goto no_mem;
78758  }
78759  MemSetTypeFlag(pOut, MEM_Str);
78760  if( pOut!=pIn2 ){
78761  memcpy(pOut->z, pIn2->z, pIn2->n);
78762  }
78763  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
78764  pOut->z[nByte]=0;
78765  pOut->z[nByte+1] = 0;
78766  pOut->flags |= MEM_Term;
78767  pOut->n = (int)nByte;
78768  pOut->enc = encoding;
78769  UPDATE_MAX_BLOBSIZE(pOut);
78770  break;
78771 }
78772 
78773 /* Opcode: Add P1 P2 P3 * *
78774 ** Synopsis: r[P3]=r[P1]+r[P2]
78775 **
78776 ** Add the value in register P1 to the value in register P2
78777 ** and store the result in register P3.
78778 ** If either input is NULL, the result is NULL.
78779 */
78780 /* Opcode: Multiply P1 P2 P3 * *
78781 ** Synopsis: r[P3]=r[P1]*r[P2]
78782 **
78783 **
78784 ** Multiply the value in register P1 by the value in register P2
78785 ** and store the result in register P3.
78786 ** If either input is NULL, the result is NULL.
78787 */
78788 /* Opcode: Subtract P1 P2 P3 * *
78789 ** Synopsis: r[P3]=r[P2]-r[P1]
78790 **
78791 ** Subtract the value in register P1 from the value in register P2
78792 ** and store the result in register P3.
78793 ** If either input is NULL, the result is NULL.
78794 */
78795 /* Opcode: Divide P1 P2 P3 * *
78796 ** Synopsis: r[P3]=r[P2]/r[P1]
78797 **
78798 ** Divide the value in register P1 by the value in register P2
78799 ** and store the result in register P3 (P3=P2/P1). If the value in
78800 ** register P1 is zero, then the result is NULL. If either input is
78801 ** NULL, the result is NULL.
78802 */
78803 /* Opcode: Remainder P1 P2 P3 * *
78804 ** Synopsis: r[P3]=r[P2]%r[P1]
78805 **
78806 ** Compute the remainder after integer register P2 is divided by
78807 ** register P1 and store the result in register P3.
78808 ** If the value in register P1 is zero the result is NULL.
78809 ** If either operand is NULL, the result is NULL.
78810 */
78811 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
78812 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
78813 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
78814 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
78815 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
78816  char bIntint; /* Started out as two integer operands */
78817  u16 flags; /* Combined MEM_* flags from both inputs */
78818  u16 type1; /* Numeric type of left operand */
78819  u16 type2; /* Numeric type of right operand */
78820  i64 iA; /* Integer value of left operand */
78821  i64 iB; /* Integer value of right operand */
78822  double rA; /* Real value of left operand */
78823  double rB; /* Real value of right operand */
78824 
78825  pIn1 = &aMem[pOp->p1];
78826  type1 = numericType(pIn1);
78827  pIn2 = &aMem[pOp->p2];
78828  type2 = numericType(pIn2);
78829  pOut = &aMem[pOp->p3];
78830  flags = pIn1->flags | pIn2->flags;
78831  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
78832  if( (type1 & type2 & MEM_Int)!=0 ){
78833  iA = pIn1->u.i;
78834  iB = pIn2->u.i;
78835  bIntint = 1;
78836  switch( pOp->opcode ){
78837  case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
78838  case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
78839  case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
78840  case OP_Divide: {
78841  if( iA==0 ) goto arithmetic_result_is_null;
78842  if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
78843  iB /= iA;
78844  break;
78845  }
78846  default: {
78847  if( iA==0 ) goto arithmetic_result_is_null;
78848  if( iA==-1 ) iA = 1;
78849  iB %= iA;
78850  break;
78851  }
78852  }
78853  pOut->u.i = iB;
78854  MemSetTypeFlag(pOut, MEM_Int);
78855  }else{
78856  bIntint = 0;
78857 fp_math:
78858  rA = sqlite3VdbeRealValue(pIn1);
78859  rB = sqlite3VdbeRealValue(pIn2);
78860  switch( pOp->opcode ){
78861  case OP_Add: rB += rA; break;
78862  case OP_Subtract: rB -= rA; break;
78863  case OP_Multiply: rB *= rA; break;
78864  case OP_Divide: {
78865  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
78866  if( rA==(double)0 ) goto arithmetic_result_is_null;
78867  rB /= rA;
78868  break;
78869  }
78870  default: {
78871  iA = (i64)rA;
78872  iB = (i64)rB;
78873  if( iA==0 ) goto arithmetic_result_is_null;
78874  if( iA==-1 ) iA = 1;
78875  rB = (double)(iB % iA);
78876  break;
78877  }
78878  }
78879 #ifdef SQLITE_OMIT_FLOATING_POINT
78880  pOut->u.i = rB;
78881  MemSetTypeFlag(pOut, MEM_Int);
78882 #else
78883  if( sqlite3IsNaN(rB) ){
78884  goto arithmetic_result_is_null;
78885  }
78886  pOut->u.r = rB;
78887  MemSetTypeFlag(pOut, MEM_Real);
78888  if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
78889  sqlite3VdbeIntegerAffinity(pOut);
78890  }
78891 #endif
78892  }
78893  break;
78894 
78895 arithmetic_result_is_null:
78896  sqlite3VdbeMemSetNull(pOut);
78897  break;
78898 }
78899 
78900 /* Opcode: CollSeq P1 * * P4
78901 **
78902 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
78903 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
78904 ** be returned. This is used by the built-in min(), max() and nullif()
78905 ** functions.
78906 **
78907 ** If P1 is not zero, then it is a register that a subsequent min() or
78908 ** max() aggregate will set to 1 if the current row is not the minimum or
78909 ** maximum. The P1 register is initialized to 0 by this instruction.
78910 **
78911 ** The interface used by the implementation of the aforementioned functions
78912 ** to retrieve the collation sequence set by this opcode is not available
78913 ** publicly. Only built-in functions have access to this feature.
78914 */
78915 case OP_CollSeq: {
78916  assert( pOp->p4type==P4_COLLSEQ );
78917  if( pOp->p1 ){
78918  sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
78919  }
78920  break;
78921 }
78922 
78923 /* Opcode: Function0 P1 P2 P3 P4 P5
78924 ** Synopsis: r[P3]=func(r[P2@P5])
78925 **
78926 ** Invoke a user function (P4 is a pointer to a FuncDef object that
78927 ** defines the function) with P5 arguments taken from register P2 and
78928 ** successors. The result of the function is stored in register P3.
78929 ** Register P3 must not be one of the function inputs.
78930 **
78931 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
78932 ** function was determined to be constant at compile time. If the first
78933 ** argument was constant then bit 0 of P1 is set. This is used to determine
78934 ** whether meta data associated with a user function argument using the
78935 ** sqlite3_set_auxdata() API may be safely retained until the next
78936 ** invocation of this opcode.
78937 **
78938 ** See also: Function, AggStep, AggFinal
78939 */
78940 /* Opcode: Function P1 P2 P3 P4 P5
78941 ** Synopsis: r[P3]=func(r[P2@P5])
78942 **
78943 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
78944 ** contains a pointer to the function to be run) with P5 arguments taken
78945 ** from register P2 and successors. The result of the function is stored
78946 ** in register P3. Register P3 must not be one of the function inputs.
78947 **
78948 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
78949 ** function was determined to be constant at compile time. If the first
78950 ** argument was constant then bit 0 of P1 is set. This is used to determine
78951 ** whether meta data associated with a user function argument using the
78952 ** sqlite3_set_auxdata() API may be safely retained until the next
78953 ** invocation of this opcode.
78954 **
78955 ** SQL functions are initially coded as OP_Function0 with P4 pointing
78956 ** to a FuncDef object. But on first evaluation, the P4 operand is
78957 ** automatically converted into an sqlite3_context object and the operation
78958 ** changed to this OP_Function opcode. In this way, the initialization of
78959 ** the sqlite3_context object occurs only once, rather than once for each
78960 ** evaluation of the function.
78961 **
78962 ** See also: Function0, AggStep, AggFinal
78963 */
78964 case OP_Function0: {
78965  int n;
78966  sqlite3_context *pCtx;
78967 
78968  assert( pOp->p4type==P4_FUNCDEF );
78969  n = pOp->p5;
78970  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
78971  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
78972  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
78973  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
78974  if( pCtx==0 ) goto no_mem;
78975  pCtx->pOut = 0;
78976  pCtx->pFunc = pOp->p4.pFunc;
78977  pCtx->iOp = (int)(pOp - aOp);
78978  pCtx->pVdbe = p;
78979  pCtx->argc = n;
78980  pOp->p4type = P4_FUNCCTX;
78981  pOp->p4.pCtx = pCtx;
78982  pOp->opcode = OP_Function;
78983  /* Fall through into OP_Function */
78984 }
78985 case OP_Function: {
78986  int i;
78987  sqlite3_context *pCtx;
78988 
78989  assert( pOp->p4type==P4_FUNCCTX );
78990  pCtx = pOp->p4.pCtx;
78991 
78992  /* If this function is inside of a trigger, the register array in aMem[]
78993  ** might change from one evaluation to the next. The next block of code
78994  ** checks to see if the register array has changed, and if so it
78995  ** reinitializes the relavant parts of the sqlite3_context object */
78996  pOut = &aMem[pOp->p3];
78997  if( pCtx->pOut != pOut ){
78998  pCtx->pOut = pOut;
78999  for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
79000  }
79001 
79002  memAboutToChange(p, pCtx->pOut);
79003 #ifdef SQLITE_DEBUG
79004  for(i=0; i<pCtx->argc; i++){
79005  assert( memIsValid(pCtx->argv[i]) );
79006  REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
79007  }
79008 #endif
79009  MemSetTypeFlag(pCtx->pOut, MEM_Null);
79010  pCtx->fErrorOrAux = 0;
79011  db->lastRowid = lastRowid;
79012  (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
79013  lastRowid = db->lastRowid; /* Remember rowid changes made by xSFunc */
79014 
79015  /* If the function returned an error, throw an exception */
79016  if( pCtx->fErrorOrAux ){
79017  if( pCtx->isError ){
79018  sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
79019  rc = pCtx->isError;
79020  }
79021  sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
79022  if( rc ) goto abort_due_to_error;
79023  }
79024 
79025  /* Copy the result of the function into register P3 */
79026  if( pOut->flags & (MEM_Str|MEM_Blob) ){
79027  sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
79028  if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
79029  }
79030 
79031  REGISTER_TRACE(pOp->p3, pCtx->pOut);
79032  UPDATE_MAX_BLOBSIZE(pCtx->pOut);
79033  break;
79034 }
79035 
79036 /* Opcode: BitAnd P1 P2 P3 * *
79037 ** Synopsis: r[P3]=r[P1]&r[P2]
79038 **
79039 ** Take the bit-wise AND of the values in register P1 and P2 and
79040 ** store the result in register P3.
79041 ** If either input is NULL, the result is NULL.
79042 */
79043 /* Opcode: BitOr P1 P2 P3 * *
79044 ** Synopsis: r[P3]=r[P1]|r[P2]
79045 **
79046 ** Take the bit-wise OR of the values in register P1 and P2 and
79047 ** store the result in register P3.
79048 ** If either input is NULL, the result is NULL.
79049 */
79050 /* Opcode: ShiftLeft P1 P2 P3 * *
79051 ** Synopsis: r[P3]=r[P2]<<r[P1]
79052 **
79053 ** Shift the integer value in register P2 to the left by the
79054 ** number of bits specified by the integer in register P1.
79055 ** Store the result in register P3.
79056 ** If either input is NULL, the result is NULL.
79057 */
79058 /* Opcode: ShiftRight P1 P2 P3 * *
79059 ** Synopsis: r[P3]=r[P2]>>r[P1]
79060 **
79061 ** Shift the integer value in register P2 to the right by the
79062 ** number of bits specified by the integer in register P1.
79063 ** Store the result in register P3.
79064 ** If either input is NULL, the result is NULL.
79065 */
79066 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
79067 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
79068 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
79069 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
79070  i64 iA;
79071  u64 uA;
79072  i64 iB;
79073  u8 op;
79074 
79075  pIn1 = &aMem[pOp->p1];
79076  pIn2 = &aMem[pOp->p2];
79077  pOut = &aMem[pOp->p3];
79078  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
79079  sqlite3VdbeMemSetNull(pOut);
79080  break;
79081  }
79082  iA = sqlite3VdbeIntValue(pIn2);
79083  iB = sqlite3VdbeIntValue(pIn1);
79084  op = pOp->opcode;
79085  if( op==OP_BitAnd ){
79086  iA &= iB;
79087  }else if( op==OP_BitOr ){
79088  iA |= iB;
79089  }else if( iB!=0 ){
79090  assert( op==OP_ShiftRight || op==OP_ShiftLeft );
79091 
79092  /* If shifting by a negative amount, shift in the other direction */
79093  if( iB<0 ){
79094  assert( OP_ShiftRight==OP_ShiftLeft+1 );
79095  op = 2*OP_ShiftLeft + 1 - op;
79096  iB = iB>(-64) ? -iB : 64;
79097  }
79098 
79099  if( iB>=64 ){
79100  iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
79101  }else{
79102  memcpy(&uA, &iA, sizeof(uA));
79103  if( op==OP_ShiftLeft ){
79104  uA <<= iB;
79105  }else{
79106  uA >>= iB;
79107  /* Sign-extend on a right shift of a negative number */
79108  if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
79109  }
79110  memcpy(&iA, &uA, sizeof(iA));
79111  }
79112  }
79113  pOut->u.i = iA;
79114  MemSetTypeFlag(pOut, MEM_Int);
79115  break;
79116 }
79117 
79118 /* Opcode: AddImm P1 P2 * * *
79119 ** Synopsis: r[P1]=r[P1]+P2
79120 **
79121 ** Add the constant P2 to the value in register P1.
79122 ** The result is always an integer.
79123 **
79124 ** To force any register to be an integer, just add 0.
79125 */
79126 case OP_AddImm: { /* in1 */
79127  pIn1 = &aMem[pOp->p1];
79128  memAboutToChange(p, pIn1);
79129  sqlite3VdbeMemIntegerify(pIn1);
79130  pIn1->u.i += pOp->p2;
79131  break;
79132 }
79133 
79134 /* Opcode: MustBeInt P1 P2 * * *
79135 **
79136 ** Force the value in register P1 to be an integer. If the value
79137 ** in P1 is not an integer and cannot be converted into an integer
79138 ** without data loss, then jump immediately to P2, or if P2==0
79139 ** raise an SQLITE_MISMATCH exception.
79140 */
79141 case OP_MustBeInt: { /* jump, in1 */
79142  pIn1 = &aMem[pOp->p1];
79143  if( (pIn1->flags & MEM_Int)==0 ){
79144  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
79145  VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
79146  if( (pIn1->flags & MEM_Int)==0 ){
79147  if( pOp->p2==0 ){
79148  rc = SQLITE_MISMATCH;
79149  goto abort_due_to_error;
79150  }else{
79151  goto jump_to_p2;
79152  }
79153  }
79154  }
79155  MemSetTypeFlag(pIn1, MEM_Int);
79156  break;
79157 }
79158 
79159 #ifndef SQLITE_OMIT_FLOATING_POINT
79160 /* Opcode: RealAffinity P1 * * * *
79161 **
79162 ** If register P1 holds an integer convert it to a real value.
79163 **
79164 ** This opcode is used when extracting information from a column that
79165 ** has REAL affinity. Such column values may still be stored as
79166 ** integers, for space efficiency, but after extraction we want them
79167 ** to have only a real value.
79168 */
79169 case OP_RealAffinity: { /* in1 */
79170  pIn1 = &aMem[pOp->p1];
79171  if( pIn1->flags & MEM_Int ){
79172  sqlite3VdbeMemRealify(pIn1);
79173  }
79174  break;
79175 }
79176 #endif
79177 
79178 #ifndef SQLITE_OMIT_CAST
79179 /* Opcode: Cast P1 P2 * * *
79180 ** Synopsis: affinity(r[P1])
79181 **
79182 ** Force the value in register P1 to be the type defined by P2.
79183 **
79184 ** <ul>
79185 ** <li value="97"> TEXT
79186 ** <li value="98"> BLOB
79187 ** <li value="99"> NUMERIC
79188 ** <li value="100"> INTEGER
79189 ** <li value="101"> REAL
79190 ** </ul>
79191 **
79192 ** A NULL value is not changed by this routine. It remains NULL.
79193 */
79194 case OP_Cast: { /* in1 */
79195  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
79196  testcase( pOp->p2==SQLITE_AFF_TEXT );
79197  testcase( pOp->p2==SQLITE_AFF_BLOB );
79198  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
79199  testcase( pOp->p2==SQLITE_AFF_INTEGER );
79200  testcase( pOp->p2==SQLITE_AFF_REAL );
79201  pIn1 = &aMem[pOp->p1];
79202  memAboutToChange(p, pIn1);
79203  rc = ExpandBlob(pIn1);
79204  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
79205  UPDATE_MAX_BLOBSIZE(pIn1);
79206  if( rc ) goto abort_due_to_error;
79207  break;
79208 }
79209 #endif /* SQLITE_OMIT_CAST */
79210 
79211 /* Opcode: Eq P1 P2 P3 P4 P5
79212 ** Synopsis: IF r[P3]==r[P1]
79213 **
79214 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
79215 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
79216 ** store the result of comparison in register P2.
79217 **
79218 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
79219 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
79220 ** to coerce both inputs according to this affinity before the
79221 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
79222 ** affinity is used. Note that the affinity conversions are stored
79223 ** back into the input registers P1 and P3. So this opcode can cause
79224 ** persistent changes to registers P1 and P3.
79225 **
79226 ** Once any conversions have taken place, and neither value is NULL,
79227 ** the values are compared. If both values are blobs then memcmp() is
79228 ** used to determine the results of the comparison. If both values
79229 ** are text, then the appropriate collating function specified in
79230 ** P4 is used to do the comparison. If P4 is not specified then
79231 ** memcmp() is used to compare text string. If both values are
79232 ** numeric, then a numeric comparison is used. If the two values
79233 ** are of different types, then numbers are considered less than
79234 ** strings and strings are considered less than blobs.
79235 **
79236 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
79237 ** true or false and is never NULL. If both operands are NULL then the result
79238 ** of comparison is true. If either operand is NULL then the result is false.
79239 ** If neither operand is NULL the result is the same as it would be if
79240 ** the SQLITE_NULLEQ flag were omitted from P5.
79241 **
79242 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
79243 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
79244 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
79245 */
79246 /* Opcode: Ne P1 P2 P3 P4 P5
79247 ** Synopsis: IF r[P3]!=r[P1]
79248 **
79249 ** This works just like the Eq opcode except that the jump is taken if
79250 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
79251 ** additional information.
79252 **
79253 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
79254 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
79255 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
79256 */
79257 /* Opcode: Lt P1 P2 P3 P4 P5
79258 ** Synopsis: IF r[P3]<r[P1]
79259 **
79260 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
79261 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
79262 ** the result of comparison (0 or 1 or NULL) into register P2.
79263 **
79264 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
79265 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
79266 ** bit is clear then fall through if either operand is NULL.
79267 **
79268 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
79269 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
79270 ** to coerce both inputs according to this affinity before the
79271 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
79272 ** affinity is used. Note that the affinity conversions are stored
79273 ** back into the input registers P1 and P3. So this opcode can cause
79274 ** persistent changes to registers P1 and P3.
79275 **
79276 ** Once any conversions have taken place, and neither value is NULL,
79277 ** the values are compared. If both values are blobs then memcmp() is
79278 ** used to determine the results of the comparison. If both values
79279 ** are text, then the appropriate collating function specified in
79280 ** P4 is used to do the comparison. If P4 is not specified then
79281 ** memcmp() is used to compare text string. If both values are
79282 ** numeric, then a numeric comparison is used. If the two values
79283 ** are of different types, then numbers are considered less than
79284 ** strings and strings are considered less than blobs.
79285 */
79286 /* Opcode: Le P1 P2 P3 P4 P5
79287 ** Synopsis: IF r[P3]<=r[P1]
79288 **
79289 ** This works just like the Lt opcode except that the jump is taken if
79290 ** the content of register P3 is less than or equal to the content of
79291 ** register P1. See the Lt opcode for additional information.
79292 */
79293 /* Opcode: Gt P1 P2 P3 P4 P5
79294 ** Synopsis: IF r[P3]>r[P1]
79295 **
79296 ** This works just like the Lt opcode except that the jump is taken if
79297 ** the content of register P3 is greater than the content of
79298 ** register P1. See the Lt opcode for additional information.
79299 */
79300 /* Opcode: Ge P1 P2 P3 P4 P5
79301 ** Synopsis: IF r[P3]>=r[P1]
79302 **
79303 ** This works just like the Lt opcode except that the jump is taken if
79304 ** the content of register P3 is greater than or equal to the content of
79305 ** register P1. See the Lt opcode for additional information.
79306 */
79307 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
79308 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
79309 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
79310 case OP_Le: /* same as TK_LE, jump, in1, in3 */
79311 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
79312 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
79313  int res, res2; /* Result of the comparison of pIn1 against pIn3 */
79314  char affinity; /* Affinity to use for comparison */
79315  u16 flags1; /* Copy of initial value of pIn1->flags */
79316  u16 flags3; /* Copy of initial value of pIn3->flags */
79317 
79318  pIn1 = &aMem[pOp->p1];
79319  pIn3 = &aMem[pOp->p3];
79320  flags1 = pIn1->flags;
79321  flags3 = pIn3->flags;
79322  if( (flags1 | flags3)&MEM_Null ){
79323  /* One or both operands are NULL */
79324  if( pOp->p5 & SQLITE_NULLEQ ){
79325  /* If SQLITE_NULLEQ is set (which will only happen if the operator is
79326  ** OP_Eq or OP_Ne) then take the jump or not depending on whether
79327  ** or not both operands are null.
79328  */
79329  assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
79330  assert( (flags1 & MEM_Cleared)==0 );
79331  assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
79332  if( (flags1&MEM_Null)!=0
79333  && (flags3&MEM_Null)!=0
79334  && (flags3&MEM_Cleared)==0
79335  ){
79336  res = 0; /* Operands are equal */
79337  }else{
79338  res = 1; /* Operands are not equal */
79339  }
79340  }else{
79341  /* SQLITE_NULLEQ is clear and at least one operand is NULL,
79342  ** then the result is always NULL.
79343  ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
79344  */
79345  if( pOp->p5 & SQLITE_STOREP2 ){
79346  pOut = &aMem[pOp->p2];
79347  iCompare = 1; /* Operands are not equal */
79348  memAboutToChange(p, pOut);
79349  MemSetTypeFlag(pOut, MEM_Null);
79350  REGISTER_TRACE(pOp->p2, pOut);
79351  }else{
79352  VdbeBranchTaken(2,3);
79353  if( pOp->p5 & SQLITE_JUMPIFNULL ){
79354  goto jump_to_p2;
79355  }
79356  }
79357  break;
79358  }
79359  }else{
79360  /* Neither operand is NULL. Do a comparison. */
79361  affinity = pOp->p5 & SQLITE_AFF_MASK;
79362  if( affinity>=SQLITE_AFF_NUMERIC ){
79363  if( (flags1 | flags3)&MEM_Str ){
79364  if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79365  applyNumericAffinity(pIn1,0);
79366  testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
79367  flags3 = pIn3->flags;
79368  }
79369  if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79370  applyNumericAffinity(pIn3,0);
79371  }
79372  }
79373  /* Handle the common case of integer comparison here, as an
79374  ** optimization, to avoid a call to sqlite3MemCompare() */
79375  if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
79376  if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
79377  if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
79378  res = 0;
79379  goto compare_op;
79380  }
79381  }else if( affinity==SQLITE_AFF_TEXT ){
79382  if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
79383  testcase( pIn1->flags & MEM_Int );
79384  testcase( pIn1->flags & MEM_Real );
79385  sqlite3VdbeMemStringify(pIn1, encoding, 1);
79386  testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
79387  flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
79388  assert( pIn1!=pIn3 );
79389  }
79390  if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
79391  testcase( pIn3->flags & MEM_Int );
79392  testcase( pIn3->flags & MEM_Real );
79393  sqlite3VdbeMemStringify(pIn3, encoding, 1);
79394  testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
79395  flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
79396  }
79397  }
79398  assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
79399  res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
79400  }
79401 compare_op:
79402  switch( pOp->opcode ){
79403  case OP_Eq: res2 = res==0; break;
79404  case OP_Ne: res2 = res; break;
79405  case OP_Lt: res2 = res<0; break;
79406  case OP_Le: res2 = res<=0; break;
79407  case OP_Gt: res2 = res>0; break;
79408  default: res2 = res>=0; break;
79409  }
79410 
79411  /* Undo any changes made by applyAffinity() to the input registers. */
79412  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
79413  pIn1->flags = flags1;
79414  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
79415  pIn3->flags = flags3;
79416 
79417  if( pOp->p5 & SQLITE_STOREP2 ){
79418  pOut = &aMem[pOp->p2];
79419  iCompare = res;
79420  res2 = res2!=0; /* For this path res2 must be exactly 0 or 1 */
79421  if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
79422  /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
79423  ** and prevents OP_Ne from overwriting NULL with 0. This flag
79424  ** is only used in contexts where either:
79425  ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
79426  ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
79427  ** Therefore it is not necessary to check the content of r[P2] for
79428  ** NULL. */
79429  assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
79430  assert( res2==0 || res2==1 );
79431  testcase( res2==0 && pOp->opcode==OP_Eq );
79432  testcase( res2==1 && pOp->opcode==OP_Eq );
79433  testcase( res2==0 && pOp->opcode==OP_Ne );
79434  testcase( res2==1 && pOp->opcode==OP_Ne );
79435  if( (pOp->opcode==OP_Eq)==res2 ) break;
79436  }
79437  memAboutToChange(p, pOut);
79438  MemSetTypeFlag(pOut, MEM_Int);
79439  pOut->u.i = res2;
79440  REGISTER_TRACE(pOp->p2, pOut);
79441  }else{
79442  VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
79443  if( res2 ){
79444  goto jump_to_p2;
79445  }
79446  }
79447  break;
79448 }
79449 
79450 /* Opcode: ElseNotEq * P2 * * *
79451 **
79452 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
79453 ** If result of an OP_Eq comparison on the same two operands
79454 ** would have be NULL or false (0), then then jump to P2.
79455 ** If the result of an OP_Eq comparison on the two previous operands
79456 ** would have been true (1), then fall through.
79457 */
79458 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
79459  assert( pOp>aOp );
79460  assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
79461  assert( pOp[-1].p5 & SQLITE_STOREP2 );
79462  VdbeBranchTaken(iCompare!=0, 2);
79463  if( iCompare!=0 ) goto jump_to_p2;
79464  break;
79465 }
79466 
79467 
79468 /* Opcode: Permutation * * * P4 *
79469 **
79470 ** Set the permutation used by the OP_Compare operator to be the array
79471 ** of integers in P4.
79472 **
79473 ** The permutation is only valid until the next OP_Compare that has
79474 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
79475 ** occur immediately prior to the OP_Compare.
79476 **
79477 ** The first integer in the P4 integer array is the length of the array
79478 ** and does not become part of the permutation.
79479 */
79480 case OP_Permutation: {
79481  assert( pOp->p4type==P4_INTARRAY );
79482  assert( pOp->p4.ai );
79483  aPermute = pOp->p4.ai + 1;
79484  break;
79485 }
79486 
79487 /* Opcode: Compare P1 P2 P3 P4 P5
79488 ** Synopsis: r[P1@P3] <-> r[P2@P3]
79489 **
79490 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
79491 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
79492 ** the comparison for use by the next OP_Jump instruct.
79493 **
79494 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
79495 ** determined by the most recent OP_Permutation operator. If the
79496 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
79497 ** order.
79498 **
79499 ** P4 is a KeyInfo structure that defines collating sequences and sort
79500 ** orders for the comparison. The permutation applies to registers
79501 ** only. The KeyInfo elements are used sequentially.
79502 **
79503 ** The comparison is a sort comparison, so NULLs compare equal,
79504 ** NULLs are less than numbers, numbers are less than strings,
79505 ** and strings are less than blobs.
79506 */
79507 case OP_Compare: {
79508  int n;
79509  int i;
79510  int p1;
79511  int p2;
79512  const KeyInfo *pKeyInfo;
79513  int idx;
79514  CollSeq *pColl; /* Collating sequence to use on this term */
79515  int bRev; /* True for DESCENDING sort order */
79516 
79517  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
79518  n = pOp->p3;
79519  pKeyInfo = pOp->p4.pKeyInfo;
79520  assert( n>0 );
79521  assert( pKeyInfo!=0 );
79522  p1 = pOp->p1;
79523  p2 = pOp->p2;
79524 #if SQLITE_DEBUG
79525  if( aPermute ){
79526  int k, mx = 0;
79527  for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
79528  assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
79529  assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
79530  }else{
79531  assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
79532  assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
79533  }
79534 #endif /* SQLITE_DEBUG */
79535  for(i=0; i<n; i++){
79536  idx = aPermute ? aPermute[i] : i;
79537  assert( memIsValid(&aMem[p1+idx]) );
79538  assert( memIsValid(&aMem[p2+idx]) );
79539  REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
79540  REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
79541  assert( i<pKeyInfo->nField );
79542  pColl = pKeyInfo->aColl[i];
79543  bRev = pKeyInfo->aSortOrder[i];
79544  iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
79545  if( iCompare ){
79546  if( bRev ) iCompare = -iCompare;
79547  break;
79548  }
79549  }
79550  aPermute = 0;
79551  break;
79552 }
79553 
79554 /* Opcode: Jump P1 P2 P3 * *
79555 **
79556 ** Jump to the instruction at address P1, P2, or P3 depending on whether
79557 ** in the most recent OP_Compare instruction the P1 vector was less than
79558 ** equal to, or greater than the P2 vector, respectively.
79559 */
79560 case OP_Jump: { /* jump */
79561  if( iCompare<0 ){
79562  VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
79563  }else if( iCompare==0 ){
79564  VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
79565  }else{
79566  VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
79567  }
79568  break;
79569 }
79570 
79571 /* Opcode: And P1 P2 P3 * *
79572 ** Synopsis: r[P3]=(r[P1] && r[P2])
79573 **
79574 ** Take the logical AND of the values in registers P1 and P2 and
79575 ** write the result into register P3.
79576 **
79577 ** If either P1 or P2 is 0 (false) then the result is 0 even if
79578 ** the other input is NULL. A NULL and true or two NULLs give
79579 ** a NULL output.
79580 */
79581 /* Opcode: Or P1 P2 P3 * *
79582 ** Synopsis: r[P3]=(r[P1] || r[P2])
79583 **
79584 ** Take the logical OR of the values in register P1 and P2 and
79585 ** store the answer in register P3.
79586 **
79587 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
79588 ** even if the other input is NULL. A NULL and false or two NULLs
79589 ** give a NULL output.
79590 */
79591 case OP_And: /* same as TK_AND, in1, in2, out3 */
79592 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
79593  int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79594  int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79595 
79596  pIn1 = &aMem[pOp->p1];
79597  if( pIn1->flags & MEM_Null ){
79598  v1 = 2;
79599  }else{
79600  v1 = sqlite3VdbeIntValue(pIn1)!=0;
79601  }
79602  pIn2 = &aMem[pOp->p2];
79603  if( pIn2->flags & MEM_Null ){
79604  v2 = 2;
79605  }else{
79606  v2 = sqlite3VdbeIntValue(pIn2)!=0;
79607  }
79608  if( pOp->opcode==OP_And ){
79609  static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
79610  v1 = and_logic[v1*3+v2];
79611  }else{
79612  static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
79613  v1 = or_logic[v1*3+v2];
79614  }
79615  pOut = &aMem[pOp->p3];
79616  if( v1==2 ){
79617  MemSetTypeFlag(pOut, MEM_Null);
79618  }else{
79619  pOut->u.i = v1;
79620  MemSetTypeFlag(pOut, MEM_Int);
79621  }
79622  break;
79623 }
79624 
79625 /* Opcode: Not P1 P2 * * *
79626 ** Synopsis: r[P2]= !r[P1]
79627 **
79628 ** Interpret the value in register P1 as a boolean value. Store the
79629 ** boolean complement in register P2. If the value in register P1 is
79630 ** NULL, then a NULL is stored in P2.
79631 */
79632 case OP_Not: { /* same as TK_NOT, in1, out2 */
79633  pIn1 = &aMem[pOp->p1];
79634  pOut = &aMem[pOp->p2];
79635  sqlite3VdbeMemSetNull(pOut);
79636  if( (pIn1->flags & MEM_Null)==0 ){
79637  pOut->flags = MEM_Int;
79638  pOut->u.i = !sqlite3VdbeIntValue(pIn1);
79639  }
79640  break;
79641 }
79642 
79643 /* Opcode: BitNot P1 P2 * * *
79644 ** Synopsis: r[P1]= ~r[P1]
79645 **
79646 ** Interpret the content of register P1 as an integer. Store the
79647 ** ones-complement of the P1 value into register P2. If P1 holds
79648 ** a NULL then store a NULL in P2.
79649 */
79650 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
79651  pIn1 = &aMem[pOp->p1];
79652  pOut = &aMem[pOp->p2];
79653  sqlite3VdbeMemSetNull(pOut);
79654  if( (pIn1->flags & MEM_Null)==0 ){
79655  pOut->flags = MEM_Int;
79656  pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
79657  }
79658  break;
79659 }
79660 
79661 /* Opcode: Once P1 P2 * * *
79662 **
79663 ** If the P1 value is equal to the P1 value on the OP_Init opcode at
79664 ** instruction 0, then jump to P2. If the two P1 values differ, then
79665 ** set the P1 value on this opcode to equal the P1 value on the OP_Init
79666 ** and fall through.
79667 */
79668 case OP_Once: { /* jump */
79669  assert( p->aOp[0].opcode==OP_Init );
79670  VdbeBranchTaken(p->aOp[0].p1==pOp->p1, 2);
79671  if( p->aOp[0].p1==pOp->p1 ){
79672  goto jump_to_p2;
79673  }else{
79674  pOp->p1 = p->aOp[0].p1;
79675  }
79676  break;
79677 }
79678 
79679 /* Opcode: If P1 P2 P3 * *
79680 **
79681 ** Jump to P2 if the value in register P1 is true. The value
79682 ** is considered true if it is numeric and non-zero. If the value
79683 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
79684 */
79685 /* Opcode: IfNot P1 P2 P3 * *
79686 **
79687 ** Jump to P2 if the value in register P1 is False. The value
79688 ** is considered false if it has a numeric value of zero. If the value
79689 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
79690 */
79691 case OP_If: /* jump, in1 */
79692 case OP_IfNot: { /* jump, in1 */
79693  int c;
79694  pIn1 = &aMem[pOp->p1];
79695  if( pIn1->flags & MEM_Null ){
79696  c = pOp->p3;
79697  }else{
79698 #ifdef SQLITE_OMIT_FLOATING_POINT
79699  c = sqlite3VdbeIntValue(pIn1)!=0;
79700 #else
79701  c = sqlite3VdbeRealValue(pIn1)!=0.0;
79702 #endif
79703  if( pOp->opcode==OP_IfNot ) c = !c;
79704  }
79705  VdbeBranchTaken(c!=0, 2);
79706  if( c ){
79707  goto jump_to_p2;
79708  }
79709  break;
79710 }
79711 
79712 /* Opcode: IsNull P1 P2 * * *
79713 ** Synopsis: if r[P1]==NULL goto P2
79714 **
79715 ** Jump to P2 if the value in register P1 is NULL.
79716 */
79717 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
79718  pIn1 = &aMem[pOp->p1];
79719  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
79720  if( (pIn1->flags & MEM_Null)!=0 ){
79721  goto jump_to_p2;
79722  }
79723  break;
79724 }
79725 
79726 /* Opcode: NotNull P1 P2 * * *
79727 ** Synopsis: if r[P1]!=NULL goto P2
79728 **
79729 ** Jump to P2 if the value in register P1 is not NULL.
79730 */
79731 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
79732  pIn1 = &aMem[pOp->p1];
79733  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
79734  if( (pIn1->flags & MEM_Null)==0 ){
79735  goto jump_to_p2;
79736  }
79737  break;
79738 }
79739 
79740 /* Opcode: Column P1 P2 P3 P4 P5
79741 ** Synopsis: r[P3]=PX
79742 **
79743 ** Interpret the data that cursor P1 points to as a structure built using
79744 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
79745 ** information about the format of the data.) Extract the P2-th column
79746 ** from this record. If there are less that (P2+1)
79747 ** values in the record, extract a NULL.
79748 **
79749 ** The value extracted is stored in register P3.
79750 **
79751 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
79752 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
79753 ** the result.
79754 **
79755 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
79756 ** then the cache of the cursor is reset prior to extracting the column.
79757 ** The first OP_Column against a pseudo-table after the value of the content
79758 ** register has changed should have this bit set.
79759 **
79760 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
79761 ** the result is guaranteed to only be used as the argument of a length()
79762 ** or typeof() function, respectively. The loading of large blobs can be
79763 ** skipped for length() and all content loading can be skipped for typeof().
79764 */
79765 case OP_Column: {
79766  int p2; /* column number to retrieve */
79767  VdbeCursor *pC; /* The VDBE cursor */
79768  BtCursor *pCrsr; /* The BTree cursor */
79769  u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
79770  int len; /* The length of the serialized data for the column */
79771  int i; /* Loop counter */
79772  Mem *pDest; /* Where to write the extracted value */
79773  Mem sMem; /* For storing the record being decoded */
79774  const u8 *zData; /* Part of the record being decoded */
79775  const u8 *zHdr; /* Next unparsed byte of the header */
79776  const u8 *zEndHdr; /* Pointer to first byte after the header */
79777  u32 offset; /* Offset into the data */
79778  u64 offset64; /* 64-bit offset */
79779  u32 avail; /* Number of bytes of available data */
79780  u32 t; /* A type code from the record header */
79781  Mem *pReg; /* PseudoTable input register */
79782 
79783  pC = p->apCsr[pOp->p1];
79784  p2 = pOp->p2;
79785 
79786  /* If the cursor cache is stale, bring it up-to-date */
79787  rc = sqlite3VdbeCursorMoveto(&pC, &p2);
79788  if( rc ) goto abort_due_to_error;
79789 
79790  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79791  pDest = &aMem[pOp->p3];
79792  memAboutToChange(p, pDest);
79793  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
79794  assert( pC!=0 );
79795  assert( p2<pC->nField );
79796  aOffset = pC->aOffset;
79797  assert( pC->eCurType!=CURTYPE_VTAB );
79798  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
79799  assert( pC->eCurType!=CURTYPE_SORTER );
79800  pCrsr = pC->uc.pCursor;
79801 
79802  if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
79803  if( pC->nullRow ){
79804  if( pC->eCurType==CURTYPE_PSEUDO ){
79805  assert( pC->uc.pseudoTableReg>0 );
79806  pReg = &aMem[pC->uc.pseudoTableReg];
79807  assert( pReg->flags & MEM_Blob );
79808  assert( memIsValid(pReg) );
79809  pC->payloadSize = pC->szRow = avail = pReg->n;
79810  pC->aRow = (u8*)pReg->z;
79811  }else{
79812  sqlite3VdbeMemSetNull(pDest);
79813  goto op_column_out;
79814  }
79815  }else{
79816  assert( pC->eCurType==CURTYPE_BTREE );
79817  assert( pCrsr );
79818  assert( sqlite3BtreeCursorIsValid(pCrsr) );
79819  pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
79820  pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail);
79821  assert( avail<=65536 ); /* Maximum page size is 64KiB */
79822  if( pC->payloadSize <= (u32)avail ){
79823  pC->szRow = pC->payloadSize;
79824  }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
79825  goto too_big;
79826  }else{
79827  pC->szRow = avail;
79828  }
79829  }
79830  pC->cacheStatus = p->cacheCtr;
79831  pC->iHdrOffset = getVarint32(pC->aRow, offset);
79832  pC->nHdrParsed = 0;
79833  aOffset[0] = offset;
79834 
79835 
79836  if( avail<offset ){ /*OPTIMIZATION-IF-FALSE*/
79837  /* pC->aRow does not have to hold the entire row, but it does at least
79838  ** need to cover the header of the record. If pC->aRow does not contain
79839  ** the complete header, then set it to zero, forcing the header to be
79840  ** dynamically allocated. */
79841  pC->aRow = 0;
79842  pC->szRow = 0;
79843 
79844  /* Make sure a corrupt database has not given us an oversize header.
79845  ** Do this now to avoid an oversize memory allocation.
79846  **
79847  ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
79848  ** types use so much data space that there can only be 4096 and 32 of
79849  ** them, respectively. So the maximum header length results from a
79850  ** 3-byte type for each of the maximum of 32768 columns plus three
79851  ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
79852  */
79853  if( offset > 98307 || offset > pC->payloadSize ){
79854  rc = SQLITE_CORRUPT_BKPT;
79855  goto abort_due_to_error;
79856  }
79857  }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/
79858  /* The following goto is an optimization. It can be omitted and
79859  ** everything will still work. But OP_Column is measurably faster
79860  ** by skipping the subsequent conditional, which is always true.
79861  */
79862  zData = pC->aRow;
79863  assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
79864  goto op_column_read_header;
79865  }
79866  }
79867 
79868  /* Make sure at least the first p2+1 entries of the header have been
79869  ** parsed and valid information is in aOffset[] and pC->aType[].
79870  */
79871  if( pC->nHdrParsed<=p2 ){
79872  /* If there is more header available for parsing in the record, try
79873  ** to extract additional fields up through the p2+1-th field
79874  */
79875  if( pC->iHdrOffset<aOffset[0] ){
79876  /* Make sure zData points to enough of the record to cover the header. */
79877  if( pC->aRow==0 ){
79878  memset(&sMem, 0, sizeof(sMem));
79879  rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem);
79880  if( rc!=SQLITE_OK ) goto abort_due_to_error;
79881  zData = (u8*)sMem.z;
79882  }else{
79883  zData = pC->aRow;
79884  }
79885 
79886  /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
79887  op_column_read_header:
79888  i = pC->nHdrParsed;
79889  offset64 = aOffset[i];
79890  zHdr = zData + pC->iHdrOffset;
79891  zEndHdr = zData + aOffset[0];
79892  do{
79893  if( (t = zHdr[0])<0x80 ){
79894  zHdr++;
79895  offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
79896  }else{
79897  zHdr += sqlite3GetVarint32(zHdr, &t);
79898  offset64 += sqlite3VdbeSerialTypeLen(t);
79899  }
79900  pC->aType[i++] = t;
79901  aOffset[i] = (u32)(offset64 & 0xffffffff);
79902  }while( i<=p2 && zHdr<zEndHdr );
79903 
79904  /* The record is corrupt if any of the following are true:
79905  ** (1) the bytes of the header extend past the declared header size
79906  ** (2) the entire header was used but not all data was used
79907  ** (3) the end of the data extends beyond the end of the record.
79908  */
79909  if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
79910  || (offset64 > pC->payloadSize)
79911  ){
79912  if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79913  rc = SQLITE_CORRUPT_BKPT;
79914  goto abort_due_to_error;
79915  }
79916 
79917  pC->nHdrParsed = i;
79918  pC->iHdrOffset = (u32)(zHdr - zData);
79919  if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79920  }else{
79921  t = 0;
79922  }
79923 
79924  /* If after trying to extract new entries from the header, nHdrParsed is
79925  ** still not up to p2, that means that the record has fewer than p2
79926  ** columns. So the result will be either the default value or a NULL.
79927  */
79928  if( pC->nHdrParsed<=p2 ){
79929  if( pOp->p4type==P4_MEM ){
79930  sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
79931  }else{
79932  sqlite3VdbeMemSetNull(pDest);
79933  }
79934  goto op_column_out;
79935  }
79936  }else{
79937  t = pC->aType[p2];
79938  }
79939 
79940  /* Extract the content for the p2+1-th column. Control can only
79941  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
79942  ** all valid.
79943  */
79944  assert( p2<pC->nHdrParsed );
79945  assert( rc==SQLITE_OK );
79946  assert( sqlite3VdbeCheckMemInvariants(pDest) );
79947  if( VdbeMemDynamic(pDest) ){
79948  sqlite3VdbeMemSetNull(pDest);
79949  }
79950  assert( t==pC->aType[p2] );
79951  if( pC->szRow>=aOffset[p2+1] ){
79952  /* This is the common case where the desired content fits on the original
79953  ** page - where the content is not on an overflow page */
79954  zData = pC->aRow + aOffset[p2];
79955  if( t<12 ){
79956  sqlite3VdbeSerialGet(zData, t, pDest);
79957  }else{
79958  /* If the column value is a string, we need a persistent value, not
79959  ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
79960  ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
79961  */
79962  static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
79963  pDest->n = len = (t-12)/2;
79964  pDest->enc = encoding;
79965  if( pDest->szMalloc < len+2 ){
79966  pDest->flags = MEM_Null;
79967  if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
79968  }else{
79969  pDest->z = pDest->zMalloc;
79970  }
79971  memcpy(pDest->z, zData, len);
79972  pDest->z[len] = 0;
79973  pDest->z[len+1] = 0;
79974  pDest->flags = aFlag[t&1];
79975  }
79976  }else{
79977  pDest->enc = encoding;
79978  /* This branch happens only when content is on overflow pages */
79979  if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
79980  && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
79981  || (len = sqlite3VdbeSerialTypeLen(t))==0
79982  ){
79983  /* Content is irrelevant for
79984  ** 1. the typeof() function,
79985  ** 2. the length(X) function if X is a blob, and
79986  ** 3. if the content length is zero.
79987  ** So we might as well use bogus content rather than reading
79988  ** content from disk. */
79989  static u8 aZero[8]; /* This is the bogus content */
79990  sqlite3VdbeSerialGet(aZero, t, pDest);
79991  }else{
79992  rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
79993  pDest);
79994  if( rc!=SQLITE_OK ) goto abort_due_to_error;
79995  sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
79996  pDest->flags &= ~MEM_Ephem;
79997  }
79998  }
79999 
80000 op_column_out:
80001  UPDATE_MAX_BLOBSIZE(pDest);
80002  REGISTER_TRACE(pOp->p3, pDest);
80003  break;
80004 }
80005 
80006 /* Opcode: Affinity P1 P2 * P4 *
80007 ** Synopsis: affinity(r[P1@P2])
80008 **
80009 ** Apply affinities to a range of P2 registers starting with P1.
80010 **
80011 ** P4 is a string that is P2 characters long. The nth character of the
80012 ** string indicates the column affinity that should be used for the nth
80013 ** memory cell in the range.
80014 */
80015 case OP_Affinity: {
80016  const char *zAffinity; /* The affinity to be applied */
80017  char cAff; /* A single character of affinity */
80018 
80019  zAffinity = pOp->p4.z;
80020  assert( zAffinity!=0 );
80021  assert( zAffinity[pOp->p2]==0 );
80022  pIn1 = &aMem[pOp->p1];
80023  while( (cAff = *(zAffinity++))!=0 ){
80024  assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
80025  assert( memIsValid(pIn1) );
80026  applyAffinity(pIn1, cAff, encoding);
80027  pIn1++;
80028  }
80029  break;
80030 }
80031 
80032 /* Opcode: MakeRecord P1 P2 P3 P4 *
80033 ** Synopsis: r[P3]=mkrec(r[P1@P2])
80034 **
80035 ** Convert P2 registers beginning with P1 into the [record format]
80036 ** use as a data record in a database table or as a key
80037 ** in an index. The OP_Column opcode can decode the record later.
80038 **
80039 ** P4 may be a string that is P2 characters long. The nth character of the
80040 ** string indicates the column affinity that should be used for the nth
80041 ** field of the index key.
80042 **
80043 ** The mapping from character to affinity is given by the SQLITE_AFF_
80044 ** macros defined in sqliteInt.h.
80045 **
80046 ** If P4 is NULL then all index fields have the affinity BLOB.
80047 */
80048 case OP_MakeRecord: {
80049  u8 *zNewRecord; /* A buffer to hold the data for the new record */
80050  Mem *pRec; /* The new record */
80051  u64 nData; /* Number of bytes of data space */
80052  int nHdr; /* Number of bytes of header space */
80053  i64 nByte; /* Data space required for this record */
80054  i64 nZero; /* Number of zero bytes at the end of the record */
80055  int nVarint; /* Number of bytes in a varint */
80056  u32 serial_type; /* Type field */
80057  Mem *pData0; /* First field to be combined into the record */
80058  Mem *pLast; /* Last field of the record */
80059  int nField; /* Number of fields in the record */
80060  char *zAffinity; /* The affinity string for the record */
80061  int file_format; /* File format to use for encoding */
80062  int i; /* Space used in zNewRecord[] header */
80063  int j; /* Space used in zNewRecord[] content */
80064  u32 len; /* Length of a field */
80065 
80066  /* Assuming the record contains N fields, the record format looks
80067  ** like this:
80068  **
80069  ** ------------------------------------------------------------------------
80070  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
80071  ** ------------------------------------------------------------------------
80072  **
80073  ** Data(0) is taken from register P1. Data(1) comes from register P1+1
80074  ** and so forth.
80075  **
80076  ** Each type field is a varint representing the serial type of the
80077  ** corresponding data element (see sqlite3VdbeSerialType()). The
80078  ** hdr-size field is also a varint which is the offset from the beginning
80079  ** of the record to data0.
80080  */
80081  nData = 0; /* Number of bytes of data space */
80082  nHdr = 0; /* Number of bytes of header space */
80083  nZero = 0; /* Number of zero bytes at the end of the record */
80084  nField = pOp->p1;
80085  zAffinity = pOp->p4.z;
80086  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
80087  pData0 = &aMem[nField];
80088  nField = pOp->p2;
80089  pLast = &pData0[nField-1];
80090  file_format = p->minWriteFileFormat;
80091 
80092  /* Identify the output register */
80093  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
80094  pOut = &aMem[pOp->p3];
80095  memAboutToChange(p, pOut);
80096 
80097  /* Apply the requested affinity to all inputs
80098  */
80099  assert( pData0<=pLast );
80100  if( zAffinity ){
80101  pRec = pData0;
80102  do{
80103  applyAffinity(pRec++, *(zAffinity++), encoding);
80104  assert( zAffinity[0]==0 || pRec<=pLast );
80105  }while( zAffinity[0] );
80106  }
80107 
80108  /* Loop through the elements that will make up the record to figure
80109  ** out how much space is required for the new record.
80110  */
80111  pRec = pLast;
80112  do{
80113  assert( memIsValid(pRec) );
80114  pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
80115  if( pRec->flags & MEM_Zero ){
80116  if( nData ){
80117  if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
80118  }else{
80119  nZero += pRec->u.nZero;
80120  len -= pRec->u.nZero;
80121  }
80122  }
80123  nData += len;
80124  testcase( serial_type==127 );
80125  testcase( serial_type==128 );
80126  nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
80127  if( pRec==pData0 ) break;
80128  pRec--;
80129  }while(1);
80130 
80131  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
80132  ** which determines the total number of bytes in the header. The varint
80133  ** value is the size of the header in bytes including the size varint
80134  ** itself. */
80135  testcase( nHdr==126 );
80136  testcase( nHdr==127 );
80137  if( nHdr<=126 ){
80138  /* The common case */
80139  nHdr += 1;
80140  }else{
80141  /* Rare case of a really large header */
80142  nVarint = sqlite3VarintLen(nHdr);
80143  nHdr += nVarint;
80144  if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
80145  }
80146  nByte = nHdr+nData;
80147  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80148  goto too_big;
80149  }
80150 
80151  /* Make sure the output register has a buffer large enough to store
80152  ** the new record. The output register (pOp->p3) is not allowed to
80153  ** be one of the input registers (because the following call to
80154  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
80155  */
80156  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
80157  goto no_mem;
80158  }
80159  zNewRecord = (u8 *)pOut->z;
80160 
80161  /* Write the record */
80162  i = putVarint32(zNewRecord, nHdr);
80163  j = nHdr;
80164  assert( pData0<=pLast );
80165  pRec = pData0;
80166  do{
80167  serial_type = pRec->uTemp;
80168  /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
80169  ** additional varints, one per column. */
80170  i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
80171  /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
80172  ** immediately follow the header. */
80173  j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
80174  }while( (++pRec)<=pLast );
80175  assert( i==nHdr );
80176  assert( j==nByte );
80177 
80178  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
80179  pOut->n = (int)nByte;
80180  pOut->flags = MEM_Blob;
80181  if( nZero ){
80182  pOut->u.nZero = nZero;
80183  pOut->flags |= MEM_Zero;
80184  }
80185  pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
80186  REGISTER_TRACE(pOp->p3, pOut);
80187  UPDATE_MAX_BLOBSIZE(pOut);
80188  break;
80189 }
80190 
80191 /* Opcode: Count P1 P2 * * *
80192 ** Synopsis: r[P2]=count()
80193 **
80194 ** Store the number of entries (an integer value) in the table or index
80195 ** opened by cursor P1 in register P2
80196 */
80197 #ifndef SQLITE_OMIT_BTREECOUNT
80198 case OP_Count: { /* out2 */
80199  i64 nEntry;
80200  BtCursor *pCrsr;
80201 
80202  assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
80203  pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
80204  assert( pCrsr );
80205  nEntry = 0; /* Not needed. Only used to silence a warning. */
80206  rc = sqlite3BtreeCount(pCrsr, &nEntry);
80207  if( rc ) goto abort_due_to_error;
80208  pOut = out2Prerelease(p, pOp);
80209  pOut->u.i = nEntry;
80210  break;
80211 }
80212 #endif
80213 
80214 /* Opcode: Savepoint P1 * * P4 *
80215 **
80216 ** Open, release or rollback the savepoint named by parameter P4, depending
80217 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
80218 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
80219 */
80220 case OP_Savepoint: {
80221  int p1; /* Value of P1 operand */
80222  char *zName; /* Name of savepoint */
80223  int nName;
80224  Savepoint *pNew;
80225  Savepoint *pSavepoint;
80226  Savepoint *pTmp;
80227  int iSavepoint;
80228  int ii;
80229 
80230  p1 = pOp->p1;
80231  zName = pOp->p4.z;
80232 
80233  /* Assert that the p1 parameter is valid. Also that if there is no open
80234  ** transaction, then there cannot be any savepoints.
80235  */
80236  assert( db->pSavepoint==0 || db->autoCommit==0 );
80237  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
80238  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
80239  assert( checkSavepointCount(db) );
80240  assert( p->bIsReader );
80241 
80242  if( p1==SAVEPOINT_BEGIN ){
80243  if( db->nVdbeWrite>0 ){
80244  /* A new savepoint cannot be created if there are active write
80245  ** statements (i.e. open read/write incremental blob handles).
80246  */
80247  sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
80248  rc = SQLITE_BUSY;
80249  }else{
80250  nName = sqlite3Strlen30(zName);
80251 
80252 #ifndef SQLITE_OMIT_VIRTUALTABLE
80253  /* This call is Ok even if this savepoint is actually a transaction
80254  ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
80255  ** If this is a transaction savepoint being opened, it is guaranteed
80256  ** that the db->aVTrans[] array is empty. */
80257  assert( db->autoCommit==0 || db->nVTrans==0 );
80258  rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
80259  db->nStatement+db->nSavepoint);
80260  if( rc!=SQLITE_OK ) goto abort_due_to_error;
80261 #endif
80262 
80263  /* Create a new savepoint structure. */
80264  pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
80265  if( pNew ){
80266  pNew->zName = (char *)&pNew[1];
80267  memcpy(pNew->zName, zName, nName+1);
80268 
80269  /* If there is no open transaction, then mark this as a special
80270  ** "transaction savepoint". */
80271  if( db->autoCommit ){
80272  db->autoCommit = 0;
80273  db->isTransactionSavepoint = 1;
80274  }else{
80275  db->nSavepoint++;
80276  }
80277 
80278  /* Link the new savepoint into the database handle's list. */
80279  pNew->pNext = db->pSavepoint;
80280  db->pSavepoint = pNew;
80281  pNew->nDeferredCons = db->nDeferredCons;
80282  pNew->nDeferredImmCons = db->nDeferredImmCons;
80283  }
80284  }
80285  }else{
80286  iSavepoint = 0;
80287 
80288  /* Find the named savepoint. If there is no such savepoint, then an
80289  ** an error is returned to the user. */
80290  for(
80291  pSavepoint = db->pSavepoint;
80292  pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
80293  pSavepoint = pSavepoint->pNext
80294  ){
80295  iSavepoint++;
80296  }
80297  if( !pSavepoint ){
80298  sqlite3VdbeError(p, "no such savepoint: %s", zName);
80299  rc = SQLITE_ERROR;
80300  }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
80301  /* It is not possible to release (commit) a savepoint if there are
80302  ** active write statements.
80303  */
80304  sqlite3VdbeError(p, "cannot release savepoint - "
80305  "SQL statements in progress");
80306  rc = SQLITE_BUSY;
80307  }else{
80308 
80309  /* Determine whether or not this is a transaction savepoint. If so,
80310  ** and this is a RELEASE command, then the current transaction
80311  ** is committed.
80312  */
80313  int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
80314  if( isTransaction && p1==SAVEPOINT_RELEASE ){
80315  if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80316  goto vdbe_return;
80317  }
80318  db->autoCommit = 1;
80319  if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80320  p->pc = (int)(pOp - aOp);
80321  db->autoCommit = 0;
80322  p->rc = rc = SQLITE_BUSY;
80323  goto vdbe_return;
80324  }
80325  db->isTransactionSavepoint = 0;
80326  rc = p->rc;
80327  }else{
80328  int isSchemaChange;
80329  iSavepoint = db->nSavepoint - iSavepoint - 1;
80330  if( p1==SAVEPOINT_ROLLBACK ){
80331  isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
80332  for(ii=0; ii<db->nDb; ii++){
80333  rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
80334  SQLITE_ABORT_ROLLBACK,
80335  isSchemaChange==0);
80336  if( rc!=SQLITE_OK ) goto abort_due_to_error;
80337  }
80338  }else{
80339  isSchemaChange = 0;
80340  }
80341  for(ii=0; ii<db->nDb; ii++){
80342  rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
80343  if( rc!=SQLITE_OK ){
80344  goto abort_due_to_error;
80345  }
80346  }
80347  if( isSchemaChange ){
80348  sqlite3ExpirePreparedStatements(db);
80349  sqlite3ResetAllSchemasOfConnection(db);
80350  db->flags = (db->flags | SQLITE_InternChanges);
80351  }
80352  }
80353 
80354  /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
80355  ** savepoints nested inside of the savepoint being operated on. */
80356  while( db->pSavepoint!=pSavepoint ){
80357  pTmp = db->pSavepoint;
80358  db->pSavepoint = pTmp->pNext;
80359  sqlite3DbFree(db, pTmp);
80360  db->nSavepoint--;
80361  }
80362 
80363  /* If it is a RELEASE, then destroy the savepoint being operated on
80364  ** too. If it is a ROLLBACK TO, then set the number of deferred
80365  ** constraint violations present in the database to the value stored
80366  ** when the savepoint was created. */
80367  if( p1==SAVEPOINT_RELEASE ){
80368  assert( pSavepoint==db->pSavepoint );
80369  db->pSavepoint = pSavepoint->pNext;
80370  sqlite3DbFree(db, pSavepoint);
80371  if( !isTransaction ){
80372  db->nSavepoint--;
80373  }
80374  }else{
80375  db->nDeferredCons = pSavepoint->nDeferredCons;
80376  db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
80377  }
80378 
80379  if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
80380  rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
80381  if( rc!=SQLITE_OK ) goto abort_due_to_error;
80382  }
80383  }
80384  }
80385  if( rc ) goto abort_due_to_error;
80386 
80387  break;
80388 }
80389 
80390 /* Opcode: AutoCommit P1 P2 * * *
80391 **
80392 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
80393 ** back any currently active btree transactions. If there are any active
80394 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
80395 ** there are active writing VMs or active VMs that use shared cache.
80396 **
80397 ** This instruction causes the VM to halt.
80398 */
80399 case OP_AutoCommit: {
80400  int desiredAutoCommit;
80401  int iRollback;
80402 
80403  desiredAutoCommit = pOp->p1;
80404  iRollback = pOp->p2;
80405  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
80406  assert( desiredAutoCommit==1 || iRollback==0 );
80407  assert( db->nVdbeActive>0 ); /* At least this one VM is active */
80408  assert( p->bIsReader );
80409 
80410  if( desiredAutoCommit!=db->autoCommit ){
80411  if( iRollback ){
80412  assert( desiredAutoCommit==1 );
80413  sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
80414  db->autoCommit = 1;
80415  }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
80416  /* If this instruction implements a COMMIT and other VMs are writing
80417  ** return an error indicating that the other VMs must complete first.
80418  */
80419  sqlite3VdbeError(p, "cannot commit transaction - "
80420  "SQL statements in progress");
80421  rc = SQLITE_BUSY;
80422  goto abort_due_to_error;
80423  }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80424  goto vdbe_return;
80425  }else{
80426  db->autoCommit = (u8)desiredAutoCommit;
80427  }
80428  if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80429  p->pc = (int)(pOp - aOp);
80430  db->autoCommit = (u8)(1-desiredAutoCommit);
80431  p->rc = rc = SQLITE_BUSY;
80432  goto vdbe_return;
80433  }
80434  assert( db->nStatement==0 );
80435  sqlite3CloseSavepoints(db);
80436  if( p->rc==SQLITE_OK ){
80437  rc = SQLITE_DONE;
80438  }else{
80439  rc = SQLITE_ERROR;
80440  }
80441  goto vdbe_return;
80442  }else{
80443  sqlite3VdbeError(p,
80444  (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
80445  (iRollback)?"cannot rollback - no transaction is active":
80446  "cannot commit - no transaction is active"));
80447 
80448  rc = SQLITE_ERROR;
80449  goto abort_due_to_error;
80450  }
80451  break;
80452 }
80453 
80454 /* Opcode: Transaction P1 P2 P3 P4 P5
80455 **
80456 ** Begin a transaction on database P1 if a transaction is not already
80457 ** active.
80458 ** If P2 is non-zero, then a write-transaction is started, or if a
80459 ** read-transaction is already active, it is upgraded to a write-transaction.
80460 ** If P2 is zero, then a read-transaction is started.
80461 **
80462 ** P1 is the index of the database file on which the transaction is
80463 ** started. Index 0 is the main database file and index 1 is the
80464 ** file used for temporary tables. Indices of 2 or more are used for
80465 ** attached databases.
80466 **
80467 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
80468 ** true (this flag is set if the Vdbe may modify more than one row and may
80469 ** throw an ABORT exception), a statement transaction may also be opened.
80470 ** More specifically, a statement transaction is opened iff the database
80471 ** connection is currently not in autocommit mode, or if there are other
80472 ** active statements. A statement transaction allows the changes made by this
80473 ** VDBE to be rolled back after an error without having to roll back the
80474 ** entire transaction. If no error is encountered, the statement transaction
80475 ** will automatically commit when the VDBE halts.
80476 **
80477 ** If P5!=0 then this opcode also checks the schema cookie against P3
80478 ** and the schema generation counter against P4.
80479 ** The cookie changes its value whenever the database schema changes.
80480 ** This operation is used to detect when that the cookie has changed
80481 ** and that the current process needs to reread the schema. If the schema
80482 ** cookie in P3 differs from the schema cookie in the database header or
80483 ** if the schema generation counter in P4 differs from the current
80484 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
80485 ** halts. The sqlite3_step() wrapper function might then reprepare the
80486 ** statement and rerun it from the beginning.
80487 */
80488 case OP_Transaction: {
80489  Btree *pBt;
80490  int iMeta;
80491  int iGen;
80492 
80493  assert( p->bIsReader );
80494  assert( p->readOnly==0 || pOp->p2==0 );
80495  assert( pOp->p1>=0 && pOp->p1<db->nDb );
80496  assert( DbMaskTest(p->btreeMask, pOp->p1) );
80497  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
80498  rc = SQLITE_READONLY;
80499  goto abort_due_to_error;
80500  }
80501  pBt = db->aDb[pOp->p1].pBt;
80502 
80503  if( pBt ){
80504  rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
80505  testcase( rc==SQLITE_BUSY_SNAPSHOT );
80506  testcase( rc==SQLITE_BUSY_RECOVERY );
80507  if( rc!=SQLITE_OK ){
80508  if( (rc&0xff)==SQLITE_BUSY ){
80509  p->pc = (int)(pOp - aOp);
80510  p->rc = rc;
80511  goto vdbe_return;
80512  }
80513  goto abort_due_to_error;
80514  }
80515 
80516  if( pOp->p2 && p->usesStmtJournal
80517  && (db->autoCommit==0 || db->nVdbeRead>1)
80518  ){
80519  assert( sqlite3BtreeIsInTrans(pBt) );
80520  if( p->iStatement==0 ){
80521  assert( db->nStatement>=0 && db->nSavepoint>=0 );
80522  db->nStatement++;
80523  p->iStatement = db->nSavepoint + db->nStatement;
80524  }
80525 
80526  rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
80527  if( rc==SQLITE_OK ){
80528  rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
80529  }
80530 
80531  /* Store the current value of the database handles deferred constraint
80532  ** counter. If the statement transaction needs to be rolled back,
80533  ** the value of this counter needs to be restored too. */
80534  p->nStmtDefCons = db->nDeferredCons;
80535  p->nStmtDefImmCons = db->nDeferredImmCons;
80536  }
80537 
80538  /* Gather the schema version number for checking:
80539  ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
80540  ** version is checked to ensure that the schema has not changed since the
80541  ** SQL statement was prepared.
80542  */
80543  sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
80544  iGen = db->aDb[pOp->p1].pSchema->iGeneration;
80545  }else{
80546  iGen = iMeta = 0;
80547  }
80548  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
80549  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
80550  sqlite3DbFree(db, p->zErrMsg);
80551  p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
80552  /* If the schema-cookie from the database file matches the cookie
80553  ** stored with the in-memory representation of the schema, do
80554  ** not reload the schema from the database file.
80555  **
80556  ** If virtual-tables are in use, this is not just an optimization.
80557  ** Often, v-tables store their data in other SQLite tables, which
80558  ** are queried from within xNext() and other v-table methods using
80559  ** prepared queries. If such a query is out-of-date, we do not want to
80560  ** discard the database schema, as the user code implementing the
80561  ** v-table would have to be ready for the sqlite3_vtab structure itself
80562  ** to be invalidated whenever sqlite3_step() is called from within
80563  ** a v-table method.
80564  */
80565  if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
80566  sqlite3ResetOneSchema(db, pOp->p1);
80567  }
80568  p->expired = 1;
80569  rc = SQLITE_SCHEMA;
80570  }
80571  if( rc ) goto abort_due_to_error;
80572  break;
80573 }
80574 
80575 /* Opcode: ReadCookie P1 P2 P3 * *
80576 **
80577 ** Read cookie number P3 from database P1 and write it into register P2.
80578 ** P3==1 is the schema version. P3==2 is the database format.
80579 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
80580 ** the main database file and P1==1 is the database file used to store
80581 ** temporary tables.
80582 **
80583 ** There must be a read-lock on the database (either a transaction
80584 ** must be started or there must be an open cursor) before
80585 ** executing this instruction.
80586 */
80587 case OP_ReadCookie: { /* out2 */
80588  int iMeta;
80589  int iDb;
80590  int iCookie;
80591 
80592  assert( p->bIsReader );
80593  iDb = pOp->p1;
80594  iCookie = pOp->p3;
80595  assert( pOp->p3<SQLITE_N_BTREE_META );
80596  assert( iDb>=0 && iDb<db->nDb );
80597  assert( db->aDb[iDb].pBt!=0 );
80598  assert( DbMaskTest(p->btreeMask, iDb) );
80599 
80600  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
80601  pOut = out2Prerelease(p, pOp);
80602  pOut->u.i = iMeta;
80603  break;
80604 }
80605 
80606 /* Opcode: SetCookie P1 P2 P3 * *
80607 **
80608 ** Write the integer value P3 into cookie number P2 of database P1.
80609 ** P2==1 is the schema version. P2==2 is the database format.
80610 ** P2==3 is the recommended pager cache
80611 ** size, and so forth. P1==0 is the main database file and P1==1 is the
80612 ** database file used to store temporary tables.
80613 **
80614 ** A transaction must be started before executing this opcode.
80615 */
80616 case OP_SetCookie: {
80617  Db *pDb;
80618  assert( pOp->p2<SQLITE_N_BTREE_META );
80619  assert( pOp->p1>=0 && pOp->p1<db->nDb );
80620  assert( DbMaskTest(p->btreeMask, pOp->p1) );
80621  assert( p->readOnly==0 );
80622  pDb = &db->aDb[pOp->p1];
80623  assert( pDb->pBt!=0 );
80624  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
80625  /* See note about index shifting on OP_ReadCookie */
80626  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
80627  if( pOp->p2==BTREE_SCHEMA_VERSION ){
80628  /* When the schema cookie changes, record the new cookie internally */
80629  pDb->pSchema->schema_cookie = pOp->p3;
80630  db->flags |= SQLITE_InternChanges;
80631  }else if( pOp->p2==BTREE_FILE_FORMAT ){
80632  /* Record changes in the file format */
80633  pDb->pSchema->file_format = pOp->p3;
80634  }
80635  if( pOp->p1==1 ){
80636  /* Invalidate all prepared statements whenever the TEMP database
80637  ** schema is changed. Ticket #1644 */
80638  sqlite3ExpirePreparedStatements(db);
80639  p->expired = 0;
80640  }
80641  if( rc ) goto abort_due_to_error;
80642  break;
80643 }
80644 
80645 /* Opcode: OpenRead P1 P2 P3 P4 P5
80646 ** Synopsis: root=P2 iDb=P3
80647 **
80648 ** Open a read-only cursor for the database table whose root page is
80649 ** P2 in a database file. The database file is determined by P3.
80650 ** P3==0 means the main database, P3==1 means the database used for
80651 ** temporary tables, and P3>1 means used the corresponding attached
80652 ** database. Give the new cursor an identifier of P1. The P1
80653 ** values need not be contiguous but all P1 values should be small integers.
80654 ** It is an error for P1 to be negative.
80655 **
80656 ** If P5!=0 then use the content of register P2 as the root page, not
80657 ** the value of P2 itself.
80658 **
80659 ** There will be a read lock on the database whenever there is an
80660 ** open cursor. If the database was unlocked prior to this instruction
80661 ** then a read lock is acquired as part of this instruction. A read
80662 ** lock allows other processes to read the database but prohibits
80663 ** any other process from modifying the database. The read lock is
80664 ** released when all cursors are closed. If this instruction attempts
80665 ** to get a read lock but fails, the script terminates with an
80666 ** SQLITE_BUSY error code.
80667 **
80668 ** The P4 value may be either an integer (P4_INT32) or a pointer to
80669 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
80670 ** structure, then said structure defines the content and collating
80671 ** sequence of the index being opened. Otherwise, if P4 is an integer
80672 ** value, it is set to the number of columns in the table.
80673 **
80674 ** See also: OpenWrite, ReopenIdx
80675 */
80676 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
80677 ** Synopsis: root=P2 iDb=P3
80678 **
80679 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
80680 ** checks to see if the cursor on P1 is already open with a root page
80681 ** number of P2 and if it is this opcode becomes a no-op. In other words,
80682 ** if the cursor is already open, do not reopen it.
80683 **
80684 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
80685 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
80686 ** every other ReopenIdx or OpenRead for the same cursor number.
80687 **
80688 ** See the OpenRead opcode documentation for additional information.
80689 */
80690 /* Opcode: OpenWrite P1 P2 P3 P4 P5
80691 ** Synopsis: root=P2 iDb=P3
80692 **
80693 ** Open a read/write cursor named P1 on the table or index whose root
80694 ** page is P2. Or if P5!=0 use the content of register P2 to find the
80695 ** root page.
80696 **
80697 ** The P4 value may be either an integer (P4_INT32) or a pointer to
80698 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
80699 ** structure, then said structure defines the content and collating
80700 ** sequence of the index being opened. Otherwise, if P4 is an integer
80701 ** value, it is set to the number of columns in the table, or to the
80702 ** largest index of any column of the table that is actually used.
80703 **
80704 ** This instruction works just like OpenRead except that it opens the cursor
80705 ** in read/write mode. For a given table, there can be one or more read-only
80706 ** cursors or a single read/write cursor but not both.
80707 **
80708 ** See also OpenRead.
80709 */
80710 case OP_ReopenIdx: {
80711  int nField;
80712  KeyInfo *pKeyInfo;
80713  int p2;
80714  int iDb;
80715  int wrFlag;
80716  Btree *pX;
80717  VdbeCursor *pCur;
80718  Db *pDb;
80719 
80720  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80721  assert( pOp->p4type==P4_KEYINFO );
80722  pCur = p->apCsr[pOp->p1];
80723  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
80724  assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
80725  goto open_cursor_set_hints;
80726  }
80727  /* If the cursor is not currently open or is open on a different
80728  ** index, then fall through into OP_OpenRead to force a reopen */
80729 case OP_OpenRead:
80730 case OP_OpenWrite:
80731 
80732  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80733  assert( p->bIsReader );
80734  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
80735  || p->readOnly==0 );
80736 
80737  if( p->expired ){
80738  rc = SQLITE_ABORT_ROLLBACK;
80739  goto abort_due_to_error;
80740  }
80741 
80742  nField = 0;
80743  pKeyInfo = 0;
80744  p2 = pOp->p2;
80745  iDb = pOp->p3;
80746  assert( iDb>=0 && iDb<db->nDb );
80747  assert( DbMaskTest(p->btreeMask, iDb) );
80748  pDb = &db->aDb[iDb];
80749  pX = pDb->pBt;
80750  assert( pX!=0 );
80751  if( pOp->opcode==OP_OpenWrite ){
80752  assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
80753  wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
80754  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80755  if( pDb->pSchema->file_format < p->minWriteFileFormat ){
80756  p->minWriteFileFormat = pDb->pSchema->file_format;
80757  }
80758  }else{
80759  wrFlag = 0;
80760  }
80761  if( pOp->p5 & OPFLAG_P2ISREG ){
80762  assert( p2>0 );
80763  assert( p2<=(p->nMem+1 - p->nCursor) );
80764  pIn2 = &aMem[p2];
80765  assert( memIsValid(pIn2) );
80766  assert( (pIn2->flags & MEM_Int)!=0 );
80767  sqlite3VdbeMemIntegerify(pIn2);
80768  p2 = (int)pIn2->u.i;
80769  /* The p2 value always comes from a prior OP_CreateTable opcode and
80770  ** that opcode will always set the p2 value to 2 or more or else fail.
80771  ** If there were a failure, the prepared statement would have halted
80772  ** before reaching this instruction. */
80773  assert( p2>=2 );
80774  }
80775  if( pOp->p4type==P4_KEYINFO ){
80776  pKeyInfo = pOp->p4.pKeyInfo;
80777  assert( pKeyInfo->enc==ENC(db) );
80778  assert( pKeyInfo->db==db );
80779  nField = pKeyInfo->nField+pKeyInfo->nXField;
80780  }else if( pOp->p4type==P4_INT32 ){
80781  nField = pOp->p4.i;
80782  }
80783  assert( pOp->p1>=0 );
80784  assert( nField>=0 );
80785  testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
80786  pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
80787  if( pCur==0 ) goto no_mem;
80788  pCur->nullRow = 1;
80789  pCur->isOrdered = 1;
80790  pCur->pgnoRoot = p2;
80791 #ifdef SQLITE_DEBUG
80792  pCur->wrFlag = wrFlag;
80793 #endif
80794  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
80795  pCur->pKeyInfo = pKeyInfo;
80796  /* Set the VdbeCursor.isTable variable. Previous versions of
80797  ** SQLite used to check if the root-page flags were sane at this point
80798  ** and report database corruption if they were not, but this check has
80799  ** since moved into the btree layer. */
80800  pCur->isTable = pOp->p4type!=P4_KEYINFO;
80801 
80802 open_cursor_set_hints:
80803  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
80804  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
80805  testcase( pOp->p5 & OPFLAG_BULKCSR );
80806 #ifdef SQLITE_ENABLE_CURSOR_HINTS
80807  testcase( pOp->p2 & OPFLAG_SEEKEQ );
80808 #endif
80809  sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
80810  (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
80811  if( rc ) goto abort_due_to_error;
80812  break;
80813 }
80814 
80815 /* Opcode: OpenEphemeral P1 P2 * P4 P5
80816 ** Synopsis: nColumn=P2
80817 **
80818 ** Open a new cursor P1 to a transient table.
80819 ** The cursor is always opened read/write even if
80820 ** the main database is read-only. The ephemeral
80821 ** table is deleted automatically when the cursor is closed.
80822 **
80823 ** P2 is the number of columns in the ephemeral table.
80824 ** The cursor points to a BTree table if P4==0 and to a BTree index
80825 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
80826 ** that defines the format of keys in the index.
80827 **
80828 ** The P5 parameter can be a mask of the BTREE_* flags defined
80829 ** in btree.h. These flags control aspects of the operation of
80830 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
80831 ** added automatically.
80832 */
80833 /* Opcode: OpenAutoindex P1 P2 * P4 *
80834 ** Synopsis: nColumn=P2
80835 **
80836 ** This opcode works the same as OP_OpenEphemeral. It has a
80837 ** different name to distinguish its use. Tables created using
80838 ** by this opcode will be used for automatically created transient
80839 ** indices in joins.
80840 */
80841 case OP_OpenAutoindex:
80842 case OP_OpenEphemeral: {
80843  VdbeCursor *pCx;
80844  KeyInfo *pKeyInfo;
80845 
80846  static const int vfsFlags =
80847  SQLITE_OPEN_READWRITE |
80848  SQLITE_OPEN_CREATE |
80849  SQLITE_OPEN_EXCLUSIVE |
80850  SQLITE_OPEN_DELETEONCLOSE |
80851  SQLITE_OPEN_TRANSIENT_DB;
80852  assert( pOp->p1>=0 );
80853  assert( pOp->p2>=0 );
80854  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
80855  if( pCx==0 ) goto no_mem;
80856  pCx->nullRow = 1;
80857  pCx->isEphemeral = 1;
80858  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
80859  BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
80860  if( rc==SQLITE_OK ){
80861  rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
80862  }
80863  if( rc==SQLITE_OK ){
80864  /* If a transient index is required, create it by calling
80865  ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
80866  ** opening it. If a transient table is required, just use the
80867  ** automatically created table with root-page 1 (an BLOB_INTKEY table).
80868  */
80869  if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
80870  int pgno;
80871  assert( pOp->p4type==P4_KEYINFO );
80872  rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
80873  if( rc==SQLITE_OK ){
80874  assert( pgno==MASTER_ROOT+1 );
80875  assert( pKeyInfo->db==db );
80876  assert( pKeyInfo->enc==ENC(db) );
80877  pCx->pKeyInfo = pKeyInfo;
80878  rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR,
80879  pKeyInfo, pCx->uc.pCursor);
80880  }
80881  pCx->isTable = 0;
80882  }else{
80883  rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, BTREE_WRCSR,
80884  0, pCx->uc.pCursor);
80885  pCx->isTable = 1;
80886  }
80887  }
80888  if( rc ) goto abort_due_to_error;
80889  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
80890  break;
80891 }
80892 
80893 /* Opcode: SorterOpen P1 P2 P3 P4 *
80894 **
80895 ** This opcode works like OP_OpenEphemeral except that it opens
80896 ** a transient index that is specifically designed to sort large
80897 ** tables using an external merge-sort algorithm.
80898 **
80899 ** If argument P3 is non-zero, then it indicates that the sorter may
80900 ** assume that a stable sort considering the first P3 fields of each
80901 ** key is sufficient to produce the required results.
80902 */
80903 case OP_SorterOpen: {
80904  VdbeCursor *pCx;
80905 
80906  assert( pOp->p1>=0 );
80907  assert( pOp->p2>=0 );
80908  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
80909  if( pCx==0 ) goto no_mem;
80910  pCx->pKeyInfo = pOp->p4.pKeyInfo;
80911  assert( pCx->pKeyInfo->db==db );
80912  assert( pCx->pKeyInfo->enc==ENC(db) );
80913  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
80914  if( rc ) goto abort_due_to_error;
80915  break;
80916 }
80917 
80918 /* Opcode: SequenceTest P1 P2 * * *
80919 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
80920 **
80921 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
80922 ** to P2. Regardless of whether or not the jump is taken, increment the
80923 ** the sequence value.
80924 */
80925 case OP_SequenceTest: {
80926  VdbeCursor *pC;
80927  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80928  pC = p->apCsr[pOp->p1];
80929  assert( isSorter(pC) );
80930  if( (pC->seqCount++)==0 ){
80931  goto jump_to_p2;
80932  }
80933  break;
80934 }
80935 
80936 /* Opcode: OpenPseudo P1 P2 P3 * *
80937 ** Synopsis: P3 columns in r[P2]
80938 **
80939 ** Open a new cursor that points to a fake table that contains a single
80940 ** row of data. The content of that one row is the content of memory
80941 ** register P2. In other words, cursor P1 becomes an alias for the
80942 ** MEM_Blob content contained in register P2.
80943 **
80944 ** A pseudo-table created by this opcode is used to hold a single
80945 ** row output from the sorter so that the row can be decomposed into
80946 ** individual columns using the OP_Column opcode. The OP_Column opcode
80947 ** is the only cursor opcode that works with a pseudo-table.
80948 **
80949 ** P3 is the number of fields in the records that will be stored by
80950 ** the pseudo-table.
80951 */
80952 case OP_OpenPseudo: {
80953  VdbeCursor *pCx;
80954 
80955  assert( pOp->p1>=0 );
80956  assert( pOp->p3>=0 );
80957  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
80958  if( pCx==0 ) goto no_mem;
80959  pCx->nullRow = 1;
80960  pCx->uc.pseudoTableReg = pOp->p2;
80961  pCx->isTable = 1;
80962  assert( pOp->p5==0 );
80963  break;
80964 }
80965 
80966 /* Opcode: Close P1 * * * *
80967 **
80968 ** Close a cursor previously opened as P1. If P1 is not
80969 ** currently open, this instruction is a no-op.
80970 */
80971 case OP_Close: {
80972  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80973  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
80974  p->apCsr[pOp->p1] = 0;
80975  break;
80976 }
80977 
80978 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
80979 /* Opcode: ColumnsUsed P1 * * P4 *
80980 **
80981 ** This opcode (which only exists if SQLite was compiled with
80982 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
80983 ** table or index for cursor P1 are used. P4 is a 64-bit integer
80984 ** (P4_INT64) in which the first 63 bits are one for each of the
80985 ** first 63 columns of the table or index that are actually used
80986 ** by the cursor. The high-order bit is set if any column after
80987 ** the 64th is used.
80988 */
80989 case OP_ColumnsUsed: {
80990  VdbeCursor *pC;
80991  pC = p->apCsr[pOp->p1];
80992  assert( pC->eCurType==CURTYPE_BTREE );
80993  pC->maskUsed = *(u64*)pOp->p4.pI64;
80994  break;
80995 }
80996 #endif
80997 
80998 /* Opcode: SeekGE P1 P2 P3 P4 *
80999 ** Synopsis: key=r[P3@P4]
81000 **
81001 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81002 ** use the value in register P3 as the key. If cursor P1 refers
81003 ** to an SQL index, then P3 is the first in an array of P4 registers
81004 ** that are used as an unpacked index key.
81005 **
81006 ** Reposition cursor P1 so that it points to the smallest entry that
81007 ** is greater than or equal to the key value. If there are no records
81008 ** greater than or equal to the key and P2 is not zero, then jump to P2.
81009 **
81010 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
81011 ** opcode will always land on a record that equally equals the key, or
81012 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
81013 ** opcode must be followed by an IdxLE opcode with the same arguments.
81014 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
81015 ** IdxLE opcode will be used on subsequent loop iterations.
81016 **
81017 ** This opcode leaves the cursor configured to move in forward order,
81018 ** from the beginning toward the end. In other words, the cursor is
81019 ** configured to use Next, not Prev.
81020 **
81021 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
81022 */
81023 /* Opcode: SeekGT P1 P2 P3 P4 *
81024 ** Synopsis: key=r[P3@P4]
81025 **
81026 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81027 ** use the value in register P3 as a key. If cursor P1 refers
81028 ** to an SQL index, then P3 is the first in an array of P4 registers
81029 ** that are used as an unpacked index key.
81030 **
81031 ** Reposition cursor P1 so that it points to the smallest entry that
81032 ** is greater than the key value. If there are no records greater than
81033 ** the key and P2 is not zero, then jump to P2.
81034 **
81035 ** This opcode leaves the cursor configured to move in forward order,
81036 ** from the beginning toward the end. In other words, the cursor is
81037 ** configured to use Next, not Prev.
81038 **
81039 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
81040 */
81041 /* Opcode: SeekLT P1 P2 P3 P4 *
81042 ** Synopsis: key=r[P3@P4]
81043 **
81044 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81045 ** use the value in register P3 as a key. If cursor P1 refers
81046 ** to an SQL index, then P3 is the first in an array of P4 registers
81047 ** that are used as an unpacked index key.
81048 **
81049 ** Reposition cursor P1 so that it points to the largest entry that
81050 ** is less than the key value. If there are no records less than
81051 ** the key and P2 is not zero, then jump to P2.
81052 **
81053 ** This opcode leaves the cursor configured to move in reverse order,
81054 ** from the end toward the beginning. In other words, the cursor is
81055 ** configured to use Prev, not Next.
81056 **
81057 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
81058 */
81059 /* Opcode: SeekLE P1 P2 P3 P4 *
81060 ** Synopsis: key=r[P3@P4]
81061 **
81062 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81063 ** use the value in register P3 as a key. If cursor P1 refers
81064 ** to an SQL index, then P3 is the first in an array of P4 registers
81065 ** that are used as an unpacked index key.
81066 **
81067 ** Reposition cursor P1 so that it points to the largest entry that
81068 ** is less than or equal to the key value. If there are no records
81069 ** less than or equal to the key and P2 is not zero, then jump to P2.
81070 **
81071 ** This opcode leaves the cursor configured to move in reverse order,
81072 ** from the end toward the beginning. In other words, the cursor is
81073 ** configured to use Prev, not Next.
81074 **
81075 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
81076 ** opcode will always land on a record that equally equals the key, or
81077 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
81078 ** opcode must be followed by an IdxGE opcode with the same arguments.
81079 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
81080 ** IdxGE opcode will be used on subsequent loop iterations.
81081 **
81082 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
81083 */
81084 case OP_SeekLT: /* jump, in3 */
81085 case OP_SeekLE: /* jump, in3 */
81086 case OP_SeekGE: /* jump, in3 */
81087 case OP_SeekGT: { /* jump, in3 */
81088  int res; /* Comparison result */
81089  int oc; /* Opcode */
81090  VdbeCursor *pC; /* The cursor to seek */
81091  UnpackedRecord r; /* The key to seek for */
81092  int nField; /* Number of columns or fields in the key */
81093  i64 iKey; /* The rowid we are to seek to */
81094  int eqOnly; /* Only interested in == results */
81095 
81096  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81097  assert( pOp->p2!=0 );
81098  pC = p->apCsr[pOp->p1];
81099  assert( pC!=0 );
81100  assert( pC->eCurType==CURTYPE_BTREE );
81101  assert( OP_SeekLE == OP_SeekLT+1 );
81102  assert( OP_SeekGE == OP_SeekLT+2 );
81103  assert( OP_SeekGT == OP_SeekLT+3 );
81104  assert( pC->isOrdered );
81105  assert( pC->uc.pCursor!=0 );
81106  oc = pOp->opcode;
81107  eqOnly = 0;
81108  pC->nullRow = 0;
81109 #ifdef SQLITE_DEBUG
81110  pC->seekOp = pOp->opcode;
81111 #endif
81112 
81113  if( pC->isTable ){
81114  /* The BTREE_SEEK_EQ flag is only set on index cursors */
81115  assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 );
81116 
81117  /* The input value in P3 might be of any type: integer, real, string,
81118  ** blob, or NULL. But it needs to be an integer before we can do
81119  ** the seek, so convert it. */
81120  pIn3 = &aMem[pOp->p3];
81121  if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
81122  applyNumericAffinity(pIn3, 0);
81123  }
81124  iKey = sqlite3VdbeIntValue(pIn3);
81125 
81126  /* If the P3 value could not be converted into an integer without
81127  ** loss of information, then special processing is required... */
81128  if( (pIn3->flags & MEM_Int)==0 ){
81129  if( (pIn3->flags & MEM_Real)==0 ){
81130  /* If the P3 value cannot be converted into any kind of a number,
81131  ** then the seek is not possible, so jump to P2 */
81132  VdbeBranchTaken(1,2); goto jump_to_p2;
81133  break;
81134  }
81135 
81136  /* If the approximation iKey is larger than the actual real search
81137  ** term, substitute >= for > and < for <=. e.g. if the search term
81138  ** is 4.9 and the integer approximation 5:
81139  **
81140  ** (x > 4.9) -> (x >= 5)
81141  ** (x <= 4.9) -> (x < 5)
81142  */
81143  if( pIn3->u.r<(double)iKey ){
81144  assert( OP_SeekGE==(OP_SeekGT-1) );
81145  assert( OP_SeekLT==(OP_SeekLE-1) );
81146  assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
81147  if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
81148  }
81149 
81150  /* If the approximation iKey is smaller than the actual real search
81151  ** term, substitute <= for < and > for >=. */
81152  else if( pIn3->u.r>(double)iKey ){
81153  assert( OP_SeekLE==(OP_SeekLT+1) );
81154  assert( OP_SeekGT==(OP_SeekGE+1) );
81155  assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
81156  if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
81157  }
81158  }
81159  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
81160  pC->movetoTarget = iKey; /* Used by OP_Delete */
81161  if( rc!=SQLITE_OK ){
81162  goto abort_due_to_error;
81163  }
81164  }else{
81165  /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
81166  ** OP_SeekLE opcodes are allowed, and these must be immediately followed
81167  ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
81168  */
81169  if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
81170  eqOnly = 1;
81171  assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
81172  assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
81173  assert( pOp[1].p1==pOp[0].p1 );
81174  assert( pOp[1].p2==pOp[0].p2 );
81175  assert( pOp[1].p3==pOp[0].p3 );
81176  assert( pOp[1].p4.i==pOp[0].p4.i );
81177  }
81178 
81179  nField = pOp->p4.i;
81180  assert( pOp->p4type==P4_INT32 );
81181  assert( nField>0 );
81182  r.pKeyInfo = pC->pKeyInfo;
81183  r.nField = (u16)nField;
81184 
81185  /* The next line of code computes as follows, only faster:
81186  ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
81187  ** r.default_rc = -1;
81188  ** }else{
81189  ** r.default_rc = +1;
81190  ** }
81191  */
81192  r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
81193  assert( oc!=OP_SeekGT || r.default_rc==-1 );
81194  assert( oc!=OP_SeekLE || r.default_rc==-1 );
81195  assert( oc!=OP_SeekGE || r.default_rc==+1 );
81196  assert( oc!=OP_SeekLT || r.default_rc==+1 );
81197 
81198  r.aMem = &aMem[pOp->p3];
81199 #ifdef SQLITE_DEBUG
81200  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
81201 #endif
81202  r.eqSeen = 0;
81203  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
81204  if( rc!=SQLITE_OK ){
81205  goto abort_due_to_error;
81206  }
81207  if( eqOnly && r.eqSeen==0 ){
81208  assert( res!=0 );
81209  goto seek_not_found;
81210  }
81211  }
81212  pC->deferredMoveto = 0;
81213  pC->cacheStatus = CACHE_STALE;
81214 #ifdef SQLITE_TEST
81215  sqlite3_search_count++;
81216 #endif
81217  if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
81218  if( res<0 || (res==0 && oc==OP_SeekGT) ){
81219  res = 0;
81220  rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
81221  if( rc!=SQLITE_OK ) goto abort_due_to_error;
81222  }else{
81223  res = 0;
81224  }
81225  }else{
81226  assert( oc==OP_SeekLT || oc==OP_SeekLE );
81227  if( res>0 || (res==0 && oc==OP_SeekLT) ){
81228  res = 0;
81229  rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
81230  if( rc!=SQLITE_OK ) goto abort_due_to_error;
81231  }else{
81232  /* res might be negative because the table is empty. Check to
81233  ** see if this is the case.
81234  */
81235  res = sqlite3BtreeEof(pC->uc.pCursor);
81236  }
81237  }
81238 seek_not_found:
81239  assert( pOp->p2>0 );
81240  VdbeBranchTaken(res!=0,2);
81241  if( res ){
81242  goto jump_to_p2;
81243  }else if( eqOnly ){
81244  assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
81245  pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
81246  }
81247  break;
81248 }
81249 
81250 /* Opcode: Found P1 P2 P3 P4 *
81251 ** Synopsis: key=r[P3@P4]
81252 **
81253 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
81254 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
81255 ** record.
81256 **
81257 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
81258 ** is a prefix of any entry in P1 then a jump is made to P2 and
81259 ** P1 is left pointing at the matching entry.
81260 **
81261 ** This operation leaves the cursor in a state where it can be
81262 ** advanced in the forward direction. The Next instruction will work,
81263 ** but not the Prev instruction.
81264 **
81265 ** See also: NotFound, NoConflict, NotExists. SeekGe
81266 */
81267 /* Opcode: NotFound P1 P2 P3 P4 *
81268 ** Synopsis: key=r[P3@P4]
81269 **
81270 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
81271 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
81272 ** record.
81273 **
81274 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
81275 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
81276 ** does contain an entry whose prefix matches the P3/P4 record then control
81277 ** falls through to the next instruction and P1 is left pointing at the
81278 ** matching entry.
81279 **
81280 ** This operation leaves the cursor in a state where it cannot be
81281 ** advanced in either direction. In other words, the Next and Prev
81282 ** opcodes do not work after this operation.
81283 **
81284 ** See also: Found, NotExists, NoConflict
81285 */
81286 /* Opcode: NoConflict P1 P2 P3 P4 *
81287 ** Synopsis: key=r[P3@P4]
81288 **
81289 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
81290 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
81291 ** record.
81292 **
81293 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
81294 ** contains any NULL value, jump immediately to P2. If all terms of the
81295 ** record are not-NULL then a check is done to determine if any row in the
81296 ** P1 index btree has a matching key prefix. If there are no matches, jump
81297 ** immediately to P2. If there is a match, fall through and leave the P1
81298 ** cursor pointing to the matching row.
81299 **
81300 ** This opcode is similar to OP_NotFound with the exceptions that the
81301 ** branch is always taken if any part of the search key input is NULL.
81302 **
81303 ** This operation leaves the cursor in a state where it cannot be
81304 ** advanced in either direction. In other words, the Next and Prev
81305 ** opcodes do not work after this operation.
81306 **
81307 ** See also: NotFound, Found, NotExists
81308 */
81309 case OP_NoConflict: /* jump, in3 */
81310 case OP_NotFound: /* jump, in3 */
81311 case OP_Found: { /* jump, in3 */
81312  int alreadyExists;
81313  int takeJump;
81314  int ii;
81315  VdbeCursor *pC;
81316  int res;
81317  char *pFree;
81318  UnpackedRecord *pIdxKey;
81319  UnpackedRecord r;
81320  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
81321 
81322 #ifdef SQLITE_TEST
81323  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
81324 #endif
81325 
81326  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81327  assert( pOp->p4type==P4_INT32 );
81328  pC = p->apCsr[pOp->p1];
81329  assert( pC!=0 );
81330 #ifdef SQLITE_DEBUG
81331  pC->seekOp = pOp->opcode;
81332 #endif
81333  pIn3 = &aMem[pOp->p3];
81334  assert( pC->eCurType==CURTYPE_BTREE );
81335  assert( pC->uc.pCursor!=0 );
81336  assert( pC->isTable==0 );
81337  pFree = 0;
81338  if( pOp->p4.i>0 ){
81339  r.pKeyInfo = pC->pKeyInfo;
81340  r.nField = (u16)pOp->p4.i;
81341  r.aMem = pIn3;
81342 #ifdef SQLITE_DEBUG
81343  for(ii=0; ii<r.nField; ii++){
81344  assert( memIsValid(&r.aMem[ii]) );
81345  assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
81346  if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
81347  }
81348 #endif
81349  pIdxKey = &r;
81350  }else{
81351  pIdxKey = sqlite3VdbeAllocUnpackedRecord(
81352  pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
81353  );
81354  if( pIdxKey==0 ) goto no_mem;
81355  assert( pIn3->flags & MEM_Blob );
81356  (void)ExpandBlob(pIn3);
81357  sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
81358  }
81359  pIdxKey->default_rc = 0;
81360  takeJump = 0;
81361  if( pOp->opcode==OP_NoConflict ){
81362  /* For the OP_NoConflict opcode, take the jump if any of the
81363  ** input fields are NULL, since any key with a NULL will not
81364  ** conflict */
81365  for(ii=0; ii<pIdxKey->nField; ii++){
81366  if( pIdxKey->aMem[ii].flags & MEM_Null ){
81367  takeJump = 1;
81368  break;
81369  }
81370  }
81371  }
81372  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
81373  sqlite3DbFree(db, pFree);
81374  if( rc!=SQLITE_OK ){
81375  goto abort_due_to_error;
81376  }
81377  pC->seekResult = res;
81378  alreadyExists = (res==0);
81379  pC->nullRow = 1-alreadyExists;
81380  pC->deferredMoveto = 0;
81381  pC->cacheStatus = CACHE_STALE;
81382  if( pOp->opcode==OP_Found ){
81383  VdbeBranchTaken(alreadyExists!=0,2);
81384  if( alreadyExists ) goto jump_to_p2;
81385  }else{
81386  VdbeBranchTaken(takeJump||alreadyExists==0,2);
81387  if( takeJump || !alreadyExists ) goto jump_to_p2;
81388  }
81389  break;
81390 }
81391 
81392 /* Opcode: SeekRowid P1 P2 P3 * *
81393 ** Synopsis: intkey=r[P3]
81394 **
81395 ** P1 is the index of a cursor open on an SQL table btree (with integer
81396 ** keys). If register P3 does not contain an integer or if P1 does not
81397 ** contain a record with rowid P3 then jump immediately to P2.
81398 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
81399 ** a record with rowid P3 then
81400 ** leave the cursor pointing at that record and fall through to the next
81401 ** instruction.
81402 **
81403 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
81404 ** the P3 register must be guaranteed to contain an integer value. With this
81405 ** opcode, register P3 might not contain an integer.
81406 **
81407 ** The OP_NotFound opcode performs the same operation on index btrees
81408 ** (with arbitrary multi-value keys).
81409 **
81410 ** This opcode leaves the cursor in a state where it cannot be advanced
81411 ** in either direction. In other words, the Next and Prev opcodes will
81412 ** not work following this opcode.
81413 **
81414 ** See also: Found, NotFound, NoConflict, SeekRowid
81415 */
81416 /* Opcode: NotExists P1 P2 P3 * *
81417 ** Synopsis: intkey=r[P3]
81418 **
81419 ** P1 is the index of a cursor open on an SQL table btree (with integer
81420 ** keys). P3 is an integer rowid. If P1 does not contain a record with
81421 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
81422 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
81423 ** leave the cursor pointing at that record and fall through to the next
81424 ** instruction.
81425 **
81426 ** The OP_SeekRowid opcode performs the same operation but also allows the
81427 ** P3 register to contain a non-integer value, in which case the jump is
81428 ** always taken. This opcode requires that P3 always contain an integer.
81429 **
81430 ** The OP_NotFound opcode performs the same operation on index btrees
81431 ** (with arbitrary multi-value keys).
81432 **
81433 ** This opcode leaves the cursor in a state where it cannot be advanced
81434 ** in either direction. In other words, the Next and Prev opcodes will
81435 ** not work following this opcode.
81436 **
81437 ** See also: Found, NotFound, NoConflict, SeekRowid
81438 */
81439 case OP_SeekRowid: { /* jump, in3 */
81440  VdbeCursor *pC;
81441  BtCursor *pCrsr;
81442  int res;
81443  u64 iKey;
81444 
81445  pIn3 = &aMem[pOp->p3];
81446  if( (pIn3->flags & MEM_Int)==0 ){
81447  applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
81448  if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
81449  }
81450  /* Fall through into OP_NotExists */
81451 case OP_NotExists: /* jump, in3 */
81452  pIn3 = &aMem[pOp->p3];
81453  assert( pIn3->flags & MEM_Int );
81454  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81455  pC = p->apCsr[pOp->p1];
81456  assert( pC!=0 );
81457 #ifdef SQLITE_DEBUG
81458  pC->seekOp = 0;
81459 #endif
81460  assert( pC->isTable );
81461  assert( pC->eCurType==CURTYPE_BTREE );
81462  pCrsr = pC->uc.pCursor;
81463  assert( pCrsr!=0 );
81464  res = 0;
81465  iKey = pIn3->u.i;
81466  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
81467  assert( rc==SQLITE_OK || res==0 );
81468  pC->movetoTarget = iKey; /* Used by OP_Delete */
81469  pC->nullRow = 0;
81470  pC->cacheStatus = CACHE_STALE;
81471  pC->deferredMoveto = 0;
81472  VdbeBranchTaken(res!=0,2);
81473  pC->seekResult = res;
81474  if( res!=0 ){
81475  assert( rc==SQLITE_OK );
81476  if( pOp->p2==0 ){
81477  rc = SQLITE_CORRUPT_BKPT;
81478  }else{
81479  goto jump_to_p2;
81480  }
81481  }
81482  if( rc ) goto abort_due_to_error;
81483  break;
81484 }
81485 
81486 /* Opcode: Sequence P1 P2 * * *
81487 ** Synopsis: r[P2]=cursor[P1].ctr++
81488 **
81489 ** Find the next available sequence number for cursor P1.
81490 ** Write the sequence number into register P2.
81491 ** The sequence number on the cursor is incremented after this
81492 ** instruction.
81493 */
81494 case OP_Sequence: { /* out2 */
81495  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81496  assert( p->apCsr[pOp->p1]!=0 );
81497  assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
81498  pOut = out2Prerelease(p, pOp);
81499  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
81500  break;
81501 }
81502 
81503 
81504 /* Opcode: NewRowid P1 P2 P3 * *
81505 ** Synopsis: r[P2]=rowid
81506 **
81507 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
81508 ** The record number is not previously used as a key in the database
81509 ** table that cursor P1 points to. The new record number is written
81510 ** written to register P2.
81511 **
81512 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
81513 ** the largest previously generated record number. No new record numbers are
81514 ** allowed to be less than this value. When this value reaches its maximum,
81515 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
81516 ** generated record number. This P3 mechanism is used to help implement the
81517 ** AUTOINCREMENT feature.
81518 */
81519 case OP_NewRowid: { /* out2 */
81520  i64 v; /* The new rowid */
81521  VdbeCursor *pC; /* Cursor of table to get the new rowid */
81522  int res; /* Result of an sqlite3BtreeLast() */
81523  int cnt; /* Counter to limit the number of searches */
81524  Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
81525  VdbeFrame *pFrame; /* Root frame of VDBE */
81526 
81527  v = 0;
81528  res = 0;
81529  pOut = out2Prerelease(p, pOp);
81530  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81531  pC = p->apCsr[pOp->p1];
81532  assert( pC!=0 );
81533  assert( pC->eCurType==CURTYPE_BTREE );
81534  assert( pC->uc.pCursor!=0 );
81535  {
81536  /* The next rowid or record number (different terms for the same
81537  ** thing) is obtained in a two-step algorithm.
81538  **
81539  ** First we attempt to find the largest existing rowid and add one
81540  ** to that. But if the largest existing rowid is already the maximum
81541  ** positive integer, we have to fall through to the second
81542  ** probabilistic algorithm
81543  **
81544  ** The second algorithm is to select a rowid at random and see if
81545  ** it already exists in the table. If it does not exist, we have
81546  ** succeeded. If the random rowid does exist, we select a new one
81547  ** and try again, up to 100 times.
81548  */
81549  assert( pC->isTable );
81550 
81551 #ifdef SQLITE_32BIT_ROWID
81552 # define MAX_ROWID 0x7fffffff
81553 #else
81554  /* Some compilers complain about constants of the form 0x7fffffffffffffff.
81555  ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
81556  ** to provide the constant while making all compilers happy.
81557  */
81558 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
81559 #endif
81560 
81561  if( !pC->useRandomRowid ){
81562  rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
81563  if( rc!=SQLITE_OK ){
81564  goto abort_due_to_error;
81565  }
81566  if( res ){
81567  v = 1; /* IMP: R-61914-48074 */
81568  }else{
81569  assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
81570  v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81571  if( v>=MAX_ROWID ){
81572  pC->useRandomRowid = 1;
81573  }else{
81574  v++; /* IMP: R-29538-34987 */
81575  }
81576  }
81577  }
81578 
81579 #ifndef SQLITE_OMIT_AUTOINCREMENT
81580  if( pOp->p3 ){
81581  /* Assert that P3 is a valid memory cell. */
81582  assert( pOp->p3>0 );
81583  if( p->pFrame ){
81584  for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
81585  /* Assert that P3 is a valid memory cell. */
81586  assert( pOp->p3<=pFrame->nMem );
81587  pMem = &pFrame->aMem[pOp->p3];
81588  }else{
81589  /* Assert that P3 is a valid memory cell. */
81590  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
81591  pMem = &aMem[pOp->p3];
81592  memAboutToChange(p, pMem);
81593  }
81594  assert( memIsValid(pMem) );
81595 
81596  REGISTER_TRACE(pOp->p3, pMem);
81597  sqlite3VdbeMemIntegerify(pMem);
81598  assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
81599  if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
81600  rc = SQLITE_FULL; /* IMP: R-12275-61338 */
81601  goto abort_due_to_error;
81602  }
81603  if( v<pMem->u.i+1 ){
81604  v = pMem->u.i + 1;
81605  }
81606  pMem->u.i = v;
81607  }
81608 #endif
81609  if( pC->useRandomRowid ){
81610  /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
81611  ** largest possible integer (9223372036854775807) then the database
81612  ** engine starts picking positive candidate ROWIDs at random until
81613  ** it finds one that is not previously used. */
81614  assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
81615  ** an AUTOINCREMENT table. */
81616  cnt = 0;
81617  do{
81618  sqlite3_randomness(sizeof(v), &v);
81619  v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
81620  }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
81621  0, &res))==SQLITE_OK)
81622  && (res==0)
81623  && (++cnt<100));
81624  if( rc ) goto abort_due_to_error;
81625  if( res==0 ){
81626  rc = SQLITE_FULL; /* IMP: R-38219-53002 */
81627  goto abort_due_to_error;
81628  }
81629  assert( v>0 ); /* EV: R-40812-03570 */
81630  }
81631  pC->deferredMoveto = 0;
81632  pC->cacheStatus = CACHE_STALE;
81633  }
81634  pOut->u.i = v;
81635  break;
81636 }
81637 
81638 /* Opcode: Insert P1 P2 P3 P4 P5
81639 ** Synopsis: intkey=r[P3] data=r[P2]
81640 **
81641 ** Write an entry into the table of cursor P1. A new entry is
81642 ** created if it doesn't already exist or the data for an existing
81643 ** entry is overwritten. The data is the value MEM_Blob stored in register
81644 ** number P2. The key is stored in register P3. The key must
81645 ** be a MEM_Int.
81646 **
81647 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
81648 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
81649 ** then rowid is stored for subsequent return by the
81650 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
81651 **
81652 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
81653 ** the last seek operation (OP_NotExists or OP_SeekRowid) was a success,
81654 ** then this
81655 ** operation will not attempt to find the appropriate row before doing
81656 ** the insert but will instead overwrite the row that the cursor is
81657 ** currently pointing to. Presumably, the prior OP_NotExists or
81658 ** OP_SeekRowid opcode
81659 ** has already positioned the cursor correctly. This is an optimization
81660 ** that boosts performance by avoiding redundant seeks.
81661 **
81662 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
81663 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
81664 ** is part of an INSERT operation. The difference is only important to
81665 ** the update hook.
81666 **
81667 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
81668 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
81669 ** following a successful insert.
81670 **
81671 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
81672 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
81673 ** and register P2 becomes ephemeral. If the cursor is changed, the
81674 ** value of register P2 will then change. Make sure this does not
81675 ** cause any problems.)
81676 **
81677 ** This instruction only works on tables. The equivalent instruction
81678 ** for indices is OP_IdxInsert.
81679 */
81680 /* Opcode: InsertInt P1 P2 P3 P4 P5
81681 ** Synopsis: intkey=P3 data=r[P2]
81682 **
81683 ** This works exactly like OP_Insert except that the key is the
81684 ** integer value P3, not the value of the integer stored in register P3.
81685 */
81686 case OP_Insert:
81687 case OP_InsertInt: {
81688  Mem *pData; /* MEM cell holding data for the record to be inserted */
81689  Mem *pKey; /* MEM cell holding key for the record */
81690  VdbeCursor *pC; /* Cursor to table into which insert is written */
81691  int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
81692  const char *zDb; /* database name - used by the update hook */
81693  Table *pTab; /* Table structure - used by update and pre-update hooks */
81694  int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
81695  BtreePayload x; /* Payload to be inserted */
81696 
81697  op = 0;
81698  pData = &aMem[pOp->p2];
81699  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81700  assert( memIsValid(pData) );
81701  pC = p->apCsr[pOp->p1];
81702  assert( pC!=0 );
81703  assert( pC->eCurType==CURTYPE_BTREE );
81704  assert( pC->uc.pCursor!=0 );
81705  assert( pC->isTable );
81706  assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
81707  REGISTER_TRACE(pOp->p2, pData);
81708 
81709  if( pOp->opcode==OP_Insert ){
81710  pKey = &aMem[pOp->p3];
81711  assert( pKey->flags & MEM_Int );
81712  assert( memIsValid(pKey) );
81713  REGISTER_TRACE(pOp->p3, pKey);
81714  x.nKey = pKey->u.i;
81715  }else{
81716  assert( pOp->opcode==OP_InsertInt );
81717  x.nKey = pOp->p3;
81718  }
81719 
81720  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81721  assert( pC->isTable );
81722  assert( pC->iDb>=0 );
81723  zDb = db->aDb[pC->iDb].zDbSName;
81724  pTab = pOp->p4.pTab;
81725  assert( HasRowid(pTab) );
81726  op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
81727  }else{
81728  pTab = 0; /* Not needed. Silence a comiler warning. */
81729  zDb = 0; /* Not needed. Silence a compiler warning. */
81730  }
81731 
81732 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81733  /* Invoke the pre-update hook, if any */
81734  if( db->xPreUpdateCallback
81735  && pOp->p4type==P4_TABLE
81736  && !(pOp->p5 & OPFLAG_ISUPDATE)
81737  ){
81738  sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
81739  }
81740 #endif
81741 
81742  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
81743  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = x.nKey;
81744  if( pData->flags & MEM_Null ){
81745  x.pData = 0;
81746  x.nData = 0;
81747  }else{
81748  assert( pData->flags & (MEM_Blob|MEM_Str) );
81749  x.pData = pData->z;
81750  x.nData = pData->n;
81751  }
81752  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
81753  if( pData->flags & MEM_Zero ){
81754  x.nZero = pData->u.nZero;
81755  }else{
81756  x.nZero = 0;
81757  }
81758  x.pKey = 0;
81759  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
81760  (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
81761  );
81762  pC->deferredMoveto = 0;
81763  pC->cacheStatus = CACHE_STALE;
81764 
81765  /* Invoke the update-hook if required. */
81766  if( rc ) goto abort_due_to_error;
81767  if( db->xUpdateCallback && op ){
81768  db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
81769  }
81770  break;
81771 }
81772 
81773 /* Opcode: Delete P1 P2 P3 P4 P5
81774 **
81775 ** Delete the record at which the P1 cursor is currently pointing.
81776 **
81777 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
81778 ** the cursor will be left pointing at either the next or the previous
81779 ** record in the table. If it is left pointing at the next record, then
81780 ** the next Next instruction will be a no-op. As a result, in this case
81781 ** it is ok to delete a record from within a Next loop. If
81782 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
81783 ** left in an undefined state.
81784 **
81785 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
81786 ** delete one of several associated with deleting a table row and all its
81787 ** associated index entries. Exactly one of those deletes is the "primary"
81788 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
81789 ** marked with the AUXDELETE flag.
81790 **
81791 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
81792 ** change count is incremented (otherwise not).
81793 **
81794 ** P1 must not be pseudo-table. It has to be a real table with
81795 ** multiple rows.
81796 **
81797 ** If P4 is not NULL then it points to a Table object. In this case either
81798 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
81799 ** have been positioned using OP_NotFound prior to invoking this opcode in
81800 ** this case. Specifically, if one is configured, the pre-update hook is
81801 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
81802 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
81803 **
81804 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
81805 ** of the memory cell that contains the value that the rowid of the row will
81806 ** be set to by the update.
81807 */
81808 case OP_Delete: {
81809  VdbeCursor *pC;
81810  const char *zDb;
81811  Table *pTab;
81812  int opflags;
81813 
81814  opflags = pOp->p2;
81815  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81816  pC = p->apCsr[pOp->p1];
81817  assert( pC!=0 );
81818  assert( pC->eCurType==CURTYPE_BTREE );
81819  assert( pC->uc.pCursor!=0 );
81820  assert( pC->deferredMoveto==0 );
81821 
81822 #ifdef SQLITE_DEBUG
81823  if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
81824  /* If p5 is zero, the seek operation that positioned the cursor prior to
81825  ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
81826  ** the row that is being deleted */
81827  i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81828  assert( pC->movetoTarget==iKey );
81829  }
81830 #endif
81831 
81832  /* If the update-hook or pre-update-hook will be invoked, set zDb to
81833  ** the name of the db to pass as to it. Also set local pTab to a copy
81834  ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
81835  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
81836  ** VdbeCursor.movetoTarget to the current rowid. */
81837  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81838  assert( pC->iDb>=0 );
81839  assert( pOp->p4.pTab!=0 );
81840  zDb = db->aDb[pC->iDb].zDbSName;
81841  pTab = pOp->p4.pTab;
81842  if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
81843  pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81844  }
81845  }else{
81846  zDb = 0; /* Not needed. Silence a compiler warning. */
81847  pTab = 0; /* Not needed. Silence a compiler warning. */
81848  }
81849 
81850 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81851  /* Invoke the pre-update-hook if required. */
81852  if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){
81853  assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) );
81854  sqlite3VdbePreUpdateHook(p, pC,
81855  (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
81856  zDb, pTab, pC->movetoTarget,
81857  pOp->p3
81858  );
81859  }
81860  if( opflags & OPFLAG_ISNOOP ) break;
81861 #endif
81862 
81863  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
81864  assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
81865  assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
81866  assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
81867 
81868 #ifdef SQLITE_DEBUG
81869  if( p->pFrame==0 ){
81870  if( pC->isEphemeral==0
81871  && (pOp->p5 & OPFLAG_AUXDELETE)==0
81872  && (pC->wrFlag & OPFLAG_FORDELETE)==0
81873  ){
81874  nExtraDelete++;
81875  }
81876  if( pOp->p2 & OPFLAG_NCHANGE ){
81877  nExtraDelete--;
81878  }
81879  }
81880 #endif
81881 
81882  rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
81883  pC->cacheStatus = CACHE_STALE;
81884  if( rc ) goto abort_due_to_error;
81885 
81886  /* Invoke the update-hook if required. */
81887  if( opflags & OPFLAG_NCHANGE ){
81888  p->nChange++;
81889  if( db->xUpdateCallback && HasRowid(pTab) ){
81890  db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
81891  pC->movetoTarget);
81892  assert( pC->iDb>=0 );
81893  }
81894  }
81895 
81896  break;
81897 }
81898 /* Opcode: ResetCount * * * * *
81899 **
81900 ** The value of the change counter is copied to the database handle
81901 ** change counter (returned by subsequent calls to sqlite3_changes()).
81902 ** Then the VMs internal change counter resets to 0.
81903 ** This is used by trigger programs.
81904 */
81905 case OP_ResetCount: {
81906  sqlite3VdbeSetChanges(db, p->nChange);
81907  p->nChange = 0;
81908  break;
81909 }
81910 
81911 /* Opcode: SorterCompare P1 P2 P3 P4
81912 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
81913 **
81914 ** P1 is a sorter cursor. This instruction compares a prefix of the
81915 ** record blob in register P3 against a prefix of the entry that
81916 ** the sorter cursor currently points to. Only the first P4 fields
81917 ** of r[P3] and the sorter record are compared.
81918 **
81919 ** If either P3 or the sorter contains a NULL in one of their significant
81920 ** fields (not counting the P4 fields at the end which are ignored) then
81921 ** the comparison is assumed to be equal.
81922 **
81923 ** Fall through to next instruction if the two records compare equal to
81924 ** each other. Jump to P2 if they are different.
81925 */
81926 case OP_SorterCompare: {
81927  VdbeCursor *pC;
81928  int res;
81929  int nKeyCol;
81930 
81931  pC = p->apCsr[pOp->p1];
81932  assert( isSorter(pC) );
81933  assert( pOp->p4type==P4_INT32 );
81934  pIn3 = &aMem[pOp->p3];
81935  nKeyCol = pOp->p4.i;
81936  res = 0;
81937  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
81938  VdbeBranchTaken(res!=0,2);
81939  if( rc ) goto abort_due_to_error;
81940  if( res ) goto jump_to_p2;
81941  break;
81942 };
81943 
81944 /* Opcode: SorterData P1 P2 P3 * *
81945 ** Synopsis: r[P2]=data
81946 **
81947 ** Write into register P2 the current sorter data for sorter cursor P1.
81948 ** Then clear the column header cache on cursor P3.
81949 **
81950 ** This opcode is normally use to move a record out of the sorter and into
81951 ** a register that is the source for a pseudo-table cursor created using
81952 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
81953 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
81954 ** us from having to issue a separate NullRow instruction to clear that cache.
81955 */
81956 case OP_SorterData: {
81957  VdbeCursor *pC;
81958 
81959  pOut = &aMem[pOp->p2];
81960  pC = p->apCsr[pOp->p1];
81961  assert( isSorter(pC) );
81962  rc = sqlite3VdbeSorterRowkey(pC, pOut);
81963  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
81964  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81965  if( rc ) goto abort_due_to_error;
81966  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
81967  break;
81968 }
81969 
81970 /* Opcode: RowData P1 P2 * * *
81971 ** Synopsis: r[P2]=data
81972 **
81973 ** Write into register P2 the complete row data for cursor P1.
81974 ** There is no interpretation of the data.
81975 ** It is just copied onto the P2 register exactly as
81976 ** it is found in the database file.
81977 **
81978 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
81979 ** of a real table, not a pseudo-table.
81980 */
81981 /* Opcode: RowKey P1 P2 * * *
81982 ** Synopsis: r[P2]=key
81983 **
81984 ** Write into register P2 the complete row key for cursor P1.
81985 ** There is no interpretation of the data.
81986 ** The key is copied onto the P2 register exactly as
81987 ** it is found in the database file.
81988 **
81989 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
81990 ** of a real table, not a pseudo-table.
81991 */
81992 case OP_RowKey:
81993 case OP_RowData: {
81994  VdbeCursor *pC;
81995  BtCursor *pCrsr;
81996  u32 n;
81997 
81998  pOut = &aMem[pOp->p2];
81999  memAboutToChange(p, pOut);
82000 
82001  /* Note that RowKey and RowData are really exactly the same instruction */
82002  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82003  pC = p->apCsr[pOp->p1];
82004  assert( pC!=0 );
82005  assert( pC->eCurType==CURTYPE_BTREE );
82006  assert( isSorter(pC)==0 );
82007  assert( pC->isTable || pOp->opcode!=OP_RowData );
82008  assert( pC->isTable==0 || pOp->opcode==OP_RowData );
82009  assert( pC->nullRow==0 );
82010  assert( pC->uc.pCursor!=0 );
82011  pCrsr = pC->uc.pCursor;
82012 
82013  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
82014  ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
82015  ** that might invalidate the cursor.
82016  ** If this where not the case, on of the following assert()s
82017  ** would fail. Should this ever change (because of changes in the code
82018  ** generator) then the fix would be to insert a call to
82019  ** sqlite3VdbeCursorMoveto().
82020  */
82021  assert( pC->deferredMoveto==0 );
82022  assert( sqlite3BtreeCursorIsValid(pCrsr) );
82023 #if 0 /* Not required due to the previous to assert() statements */
82024  rc = sqlite3VdbeCursorMoveto(pC);
82025  if( rc!=SQLITE_OK ) goto abort_due_to_error;
82026 #endif
82027 
82028  n = sqlite3BtreePayloadSize(pCrsr);
82029  if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
82030  goto too_big;
82031  }
82032  testcase( n==0 );
82033  if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
82034  goto no_mem;
82035  }
82036  pOut->n = n;
82037  MemSetTypeFlag(pOut, MEM_Blob);
82038  if( pC->isTable==0 ){
82039  rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
82040  }else{
82041  rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
82042  }
82043  if( rc ) goto abort_due_to_error;
82044  pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
82045  UPDATE_MAX_BLOBSIZE(pOut);
82046  REGISTER_TRACE(pOp->p2, pOut);
82047  break;
82048 }
82049 
82050 /* Opcode: Rowid P1 P2 * * *
82051 ** Synopsis: r[P2]=rowid
82052 **
82053 ** Store in register P2 an integer which is the key of the table entry that
82054 ** P1 is currently point to.
82055 **
82056 ** P1 can be either an ordinary table or a virtual table. There used to
82057 ** be a separate OP_VRowid opcode for use with virtual tables, but this
82058 ** one opcode now works for both table types.
82059 */
82060 case OP_Rowid: { /* out2 */
82061  VdbeCursor *pC;
82062  i64 v;
82063  sqlite3_vtab *pVtab;
82064  const sqlite3_module *pModule;
82065 
82066  pOut = out2Prerelease(p, pOp);
82067  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82068  pC = p->apCsr[pOp->p1];
82069  assert( pC!=0 );
82070  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
82071  if( pC->nullRow ){
82072  pOut->flags = MEM_Null;
82073  break;
82074  }else if( pC->deferredMoveto ){
82075  v = pC->movetoTarget;
82076 #ifndef SQLITE_OMIT_VIRTUALTABLE
82077  }else if( pC->eCurType==CURTYPE_VTAB ){
82078  assert( pC->uc.pVCur!=0 );
82079  pVtab = pC->uc.pVCur->pVtab;
82080  pModule = pVtab->pModule;
82081  assert( pModule->xRowid );
82082  rc = pModule->xRowid(pC->uc.pVCur, &v);
82083  sqlite3VtabImportErrmsg(p, pVtab);
82084  if( rc ) goto abort_due_to_error;
82085 #endif /* SQLITE_OMIT_VIRTUALTABLE */
82086  }else{
82087  assert( pC->eCurType==CURTYPE_BTREE );
82088  assert( pC->uc.pCursor!=0 );
82089  rc = sqlite3VdbeCursorRestore(pC);
82090  if( rc ) goto abort_due_to_error;
82091  if( pC->nullRow ){
82092  pOut->flags = MEM_Null;
82093  break;
82094  }
82095  v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
82096  }
82097  pOut->u.i = v;
82098  break;
82099 }
82100 
82101 /* Opcode: NullRow P1 * * * *
82102 **
82103 ** Move the cursor P1 to a null row. Any OP_Column operations
82104 ** that occur while the cursor is on the null row will always
82105 ** write a NULL.
82106 */
82107 case OP_NullRow: {
82108  VdbeCursor *pC;
82109 
82110  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82111  pC = p->apCsr[pOp->p1];
82112  assert( pC!=0 );
82113  pC->nullRow = 1;
82114  pC->cacheStatus = CACHE_STALE;
82115  if( pC->eCurType==CURTYPE_BTREE ){
82116  assert( pC->uc.pCursor!=0 );
82117  sqlite3BtreeClearCursor(pC->uc.pCursor);
82118  }
82119  break;
82120 }
82121 
82122 /* Opcode: Last P1 P2 P3 * *
82123 **
82124 ** The next use of the Rowid or Column or Prev instruction for P1
82125 ** will refer to the last entry in the database table or index.
82126 ** If the table or index is empty and P2>0, then jump immediately to P2.
82127 ** If P2 is 0 or if the table or index is not empty, fall through
82128 ** to the following instruction.
82129 **
82130 ** This opcode leaves the cursor configured to move in reverse order,
82131 ** from the end toward the beginning. In other words, the cursor is
82132 ** configured to use Prev, not Next.
82133 */
82134 case OP_Last: { /* jump */
82135  VdbeCursor *pC;
82136  BtCursor *pCrsr;
82137  int res;
82138 
82139  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82140  pC = p->apCsr[pOp->p1];
82141  assert( pC!=0 );
82142  assert( pC->eCurType==CURTYPE_BTREE );
82143  pCrsr = pC->uc.pCursor;
82144  res = 0;
82145  assert( pCrsr!=0 );
82146  rc = sqlite3BtreeLast(pCrsr, &res);
82147  pC->nullRow = (u8)res;
82148  pC->deferredMoveto = 0;
82149  pC->cacheStatus = CACHE_STALE;
82150  pC->seekResult = pOp->p3;
82151 #ifdef SQLITE_DEBUG
82152  pC->seekOp = OP_Last;
82153 #endif
82154  if( rc ) goto abort_due_to_error;
82155  if( pOp->p2>0 ){
82156  VdbeBranchTaken(res!=0,2);
82157  if( res ) goto jump_to_p2;
82158  }
82159  break;
82160 }
82161 
82162 
82163 /* Opcode: Sort P1 P2 * * *
82164 **
82165 ** This opcode does exactly the same thing as OP_Rewind except that
82166 ** it increments an undocumented global variable used for testing.
82167 **
82168 ** Sorting is accomplished by writing records into a sorting index,
82169 ** then rewinding that index and playing it back from beginning to
82170 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
82171 ** rewinding so that the global variable will be incremented and
82172 ** regression tests can determine whether or not the optimizer is
82173 ** correctly optimizing out sorts.
82174 */
82175 case OP_SorterSort: /* jump */
82176 case OP_Sort: { /* jump */
82177 #ifdef SQLITE_TEST
82178  sqlite3_sort_count++;
82179  sqlite3_search_count--;
82180 #endif
82181  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
82182  /* Fall through into OP_Rewind */
82183 }
82184 /* Opcode: Rewind P1 P2 * * *
82185 **
82186 ** The next use of the Rowid or Column or Next instruction for P1
82187 ** will refer to the first entry in the database table or index.
82188 ** If the table or index is empty, jump immediately to P2.
82189 ** If the table or index is not empty, fall through to the following
82190 ** instruction.
82191 **
82192 ** This opcode leaves the cursor configured to move in forward order,
82193 ** from the beginning toward the end. In other words, the cursor is
82194 ** configured to use Next, not Prev.
82195 */
82196 case OP_Rewind: { /* jump */
82197  VdbeCursor *pC;
82198  BtCursor *pCrsr;
82199  int res;
82200 
82201  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82202  pC = p->apCsr[pOp->p1];
82203  assert( pC!=0 );
82204  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
82205  res = 1;
82206 #ifdef SQLITE_DEBUG
82207  pC->seekOp = OP_Rewind;
82208 #endif
82209  if( isSorter(pC) ){
82210  rc = sqlite3VdbeSorterRewind(pC, &res);
82211  }else{
82212  assert( pC->eCurType==CURTYPE_BTREE );
82213  pCrsr = pC->uc.pCursor;
82214  assert( pCrsr );
82215  rc = sqlite3BtreeFirst(pCrsr, &res);
82216  pC->deferredMoveto = 0;
82217  pC->cacheStatus = CACHE_STALE;
82218  }
82219  if( rc ) goto abort_due_to_error;
82220  pC->nullRow = (u8)res;
82221  assert( pOp->p2>0 && pOp->p2<p->nOp );
82222  VdbeBranchTaken(res!=0,2);
82223  if( res ) goto jump_to_p2;
82224  break;
82225 }
82226 
82227 /* Opcode: Next P1 P2 P3 P4 P5
82228 **
82229 ** Advance cursor P1 so that it points to the next key/data pair in its
82230 ** table or index. If there are no more key/value pairs then fall through
82231 ** to the following instruction. But if the cursor advance was successful,
82232 ** jump immediately to P2.
82233 **
82234 ** The Next opcode is only valid following an SeekGT, SeekGE, or
82235 ** OP_Rewind opcode used to position the cursor. Next is not allowed
82236 ** to follow SeekLT, SeekLE, or OP_Last.
82237 **
82238 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
82239 ** been opened prior to this opcode or the program will segfault.
82240 **
82241 ** The P3 value is a hint to the btree implementation. If P3==1, that
82242 ** means P1 is an SQL index and that this instruction could have been
82243 ** omitted if that index had been unique. P3 is usually 0. P3 is
82244 ** always either 0 or 1.
82245 **
82246 ** P4 is always of type P4_ADVANCE. The function pointer points to
82247 ** sqlite3BtreeNext().
82248 **
82249 ** If P5 is positive and the jump is taken, then event counter
82250 ** number P5-1 in the prepared statement is incremented.
82251 **
82252 ** See also: Prev, NextIfOpen
82253 */
82254 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
82255 **
82256 ** This opcode works just like Next except that if cursor P1 is not
82257 ** open it behaves a no-op.
82258 */
82259 /* Opcode: Prev P1 P2 P3 P4 P5
82260 **
82261 ** Back up cursor P1 so that it points to the previous key/data pair in its
82262 ** table or index. If there is no previous key/value pairs then fall through
82263 ** to the following instruction. But if the cursor backup was successful,
82264 ** jump immediately to P2.
82265 **
82266 **
82267 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
82268 ** OP_Last opcode used to position the cursor. Prev is not allowed
82269 ** to follow SeekGT, SeekGE, or OP_Rewind.
82270 **
82271 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
82272 ** not open then the behavior is undefined.
82273 **
82274 ** The P3 value is a hint to the btree implementation. If P3==1, that
82275 ** means P1 is an SQL index and that this instruction could have been
82276 ** omitted if that index had been unique. P3 is usually 0. P3 is
82277 ** always either 0 or 1.
82278 **
82279 ** P4 is always of type P4_ADVANCE. The function pointer points to
82280 ** sqlite3BtreePrevious().
82281 **
82282 ** If P5 is positive and the jump is taken, then event counter
82283 ** number P5-1 in the prepared statement is incremented.
82284 */
82285 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
82286 **
82287 ** This opcode works just like Prev except that if cursor P1 is not
82288 ** open it behaves a no-op.
82289 */
82290 case OP_SorterNext: { /* jump */
82291  VdbeCursor *pC;
82292  int res;
82293 
82294  pC = p->apCsr[pOp->p1];
82295  assert( isSorter(pC) );
82296  res = 0;
82297  rc = sqlite3VdbeSorterNext(db, pC, &res);
82298  goto next_tail;
82299 case OP_PrevIfOpen: /* jump */
82300 case OP_NextIfOpen: /* jump */
82301  if( p->apCsr[pOp->p1]==0 ) break;
82302  /* Fall through */
82303 case OP_Prev: /* jump */
82304 case OP_Next: /* jump */
82305  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82306  assert( pOp->p5<ArraySize(p->aCounter) );
82307  pC = p->apCsr[pOp->p1];
82308  res = pOp->p3;
82309  assert( pC!=0 );
82310  assert( pC->deferredMoveto==0 );
82311  assert( pC->eCurType==CURTYPE_BTREE );
82312  assert( res==0 || (res==1 && pC->isTable==0) );
82313  testcase( res==1 );
82314  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
82315  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
82316  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
82317  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
82318 
82319  /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
82320  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
82321  assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
82322  || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
82323  || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
82324  assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
82325  || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
82326  || pC->seekOp==OP_Last );
82327 
82328  rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
82329 next_tail:
82330  pC->cacheStatus = CACHE_STALE;
82331  VdbeBranchTaken(res==0,2);
82332  if( rc ) goto abort_due_to_error;
82333  if( res==0 ){
82334  pC->nullRow = 0;
82335  p->aCounter[pOp->p5]++;
82336 #ifdef SQLITE_TEST
82337  sqlite3_search_count++;
82338 #endif
82339  goto jump_to_p2_and_check_for_interrupt;
82340  }else{
82341  pC->nullRow = 1;
82342  }
82343  goto check_for_interrupt;
82344 }
82345 
82346 /* Opcode: IdxInsert P1 P2 P3 * P5
82347 ** Synopsis: key=r[P2]
82348 **
82349 ** Register P2 holds an SQL index key made using the
82350 ** MakeRecord instructions. This opcode writes that key
82351 ** into the index P1. Data for the entry is nil.
82352 **
82353 ** P3 is a flag that provides a hint to the b-tree layer that this
82354 ** insert is likely to be an append.
82355 **
82356 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
82357 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
82358 ** then the change counter is unchanged.
82359 **
82360 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
82361 ** just done a seek to the spot where the new entry is to be inserted.
82362 ** This flag avoids doing an extra seek.
82363 **
82364 ** This instruction only works for indices. The equivalent instruction
82365 ** for tables is OP_Insert.
82366 */
82367 case OP_SorterInsert: /* in2 */
82368 case OP_IdxInsert: { /* in2 */
82369  VdbeCursor *pC;
82370  BtreePayload x;
82371 
82372  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82373  pC = p->apCsr[pOp->p1];
82374  assert( pC!=0 );
82375  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
82376  pIn2 = &aMem[pOp->p2];
82377  assert( pIn2->flags & MEM_Blob );
82378  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
82379  assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
82380  assert( pC->isTable==0 );
82381  rc = ExpandBlob(pIn2);
82382  if( rc ) goto abort_due_to_error;
82383  if( pOp->opcode==OP_SorterInsert ){
82384  rc = sqlite3VdbeSorterWrite(pC, pIn2);
82385  }else{
82386  x.nKey = pIn2->n;
82387  x.pKey = pIn2->z;
82388  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, pOp->p3,
82389  ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
82390  );
82391  assert( pC->deferredMoveto==0 );
82392  pC->cacheStatus = CACHE_STALE;
82393  }
82394  if( rc) goto abort_due_to_error;
82395  break;
82396 }
82397 
82398 /* Opcode: IdxDelete P1 P2 P3 * *
82399 ** Synopsis: key=r[P2@P3]
82400 **
82401 ** The content of P3 registers starting at register P2 form
82402 ** an unpacked index key. This opcode removes that entry from the
82403 ** index opened by cursor P1.
82404 */
82405 case OP_IdxDelete: {
82406  VdbeCursor *pC;
82407  BtCursor *pCrsr;
82408  int res;
82409  UnpackedRecord r;
82410 
82411  assert( pOp->p3>0 );
82412  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
82413  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82414  pC = p->apCsr[pOp->p1];
82415  assert( pC!=0 );
82416  assert( pC->eCurType==CURTYPE_BTREE );
82417  pCrsr = pC->uc.pCursor;
82418  assert( pCrsr!=0 );
82419  assert( pOp->p5==0 );
82420  r.pKeyInfo = pC->pKeyInfo;
82421  r.nField = (u16)pOp->p3;
82422  r.default_rc = 0;
82423  r.aMem = &aMem[pOp->p2];
82424  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
82425  if( rc ) goto abort_due_to_error;
82426  if( res==0 ){
82427  rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
82428  if( rc ) goto abort_due_to_error;
82429  }
82430  assert( pC->deferredMoveto==0 );
82431  pC->cacheStatus = CACHE_STALE;
82432  break;
82433 }
82434 
82435 /* Opcode: Seek P1 * P3 P4 *
82436 ** Synopsis: Move P3 to P1.rowid
82437 **
82438 ** P1 is an open index cursor and P3 is a cursor on the corresponding
82439 ** table. This opcode does a deferred seek of the P3 table cursor
82440 ** to the row that corresponds to the current row of P1.
82441 **
82442 ** This is a deferred seek. Nothing actually happens until
82443 ** the cursor is used to read a record. That way, if no reads
82444 ** occur, no unnecessary I/O happens.
82445 **
82446 ** P4 may be an array of integers (type P4_INTARRAY) containing
82447 ** one entry for each column in the P3 table. If array entry a(i)
82448 ** is non-zero, then reading column a(i)-1 from cursor P3 is
82449 ** equivalent to performing the deferred seek and then reading column i
82450 ** from P1. This information is stored in P3 and used to redirect
82451 ** reads against P3 over to P1, thus possibly avoiding the need to
82452 ** seek and read cursor P3.
82453 */
82454 /* Opcode: IdxRowid P1 P2 * * *
82455 ** Synopsis: r[P2]=rowid
82456 **
82457 ** Write into register P2 an integer which is the last entry in the record at
82458 ** the end of the index key pointed to by cursor P1. This integer should be
82459 ** the rowid of the table entry to which this index entry points.
82460 **
82461 ** See also: Rowid, MakeRecord.
82462 */
82463 case OP_Seek:
82464 case OP_IdxRowid: { /* out2 */
82465  VdbeCursor *pC; /* The P1 index cursor */
82466  VdbeCursor *pTabCur; /* The P2 table cursor (OP_Seek only) */
82467  i64 rowid; /* Rowid that P1 current points to */
82468 
82469  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82470  pC = p->apCsr[pOp->p1];
82471  assert( pC!=0 );
82472  assert( pC->eCurType==CURTYPE_BTREE );
82473  assert( pC->uc.pCursor!=0 );
82474  assert( pC->isTable==0 );
82475  assert( pC->deferredMoveto==0 );
82476  assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
82477 
82478  /* The IdxRowid and Seek opcodes are combined because of the commonality
82479  ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
82480  rc = sqlite3VdbeCursorRestore(pC);
82481 
82482  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
82483  ** out from under the cursor. That will never happens for an IdxRowid
82484  ** or Seek opcode */
82485  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
82486 
82487  if( !pC->nullRow ){
82488  rowid = 0; /* Not needed. Only used to silence a warning. */
82489  rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
82490  if( rc!=SQLITE_OK ){
82491  goto abort_due_to_error;
82492  }
82493  if( pOp->opcode==OP_Seek ){
82494  assert( pOp->p3>=0 && pOp->p3<p->nCursor );
82495  pTabCur = p->apCsr[pOp->p3];
82496  assert( pTabCur!=0 );
82497  assert( pTabCur->eCurType==CURTYPE_BTREE );
82498  assert( pTabCur->uc.pCursor!=0 );
82499  assert( pTabCur->isTable );
82500  pTabCur->nullRow = 0;
82501  pTabCur->movetoTarget = rowid;
82502  pTabCur->deferredMoveto = 1;
82503  assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
82504  pTabCur->aAltMap = pOp->p4.ai;
82505  pTabCur->pAltCursor = pC;
82506  }else{
82507  pOut = out2Prerelease(p, pOp);
82508  pOut->u.i = rowid;
82509  pOut->flags = MEM_Int;
82510  }
82511  }else{
82512  assert( pOp->opcode==OP_IdxRowid );
82513  sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
82514  }
82515  break;
82516 }
82517 
82518 /* Opcode: IdxGE P1 P2 P3 P4 P5
82519 ** Synopsis: key=r[P3@P4]
82520 **
82521 ** The P4 register values beginning with P3 form an unpacked index
82522 ** key that omits the PRIMARY KEY. Compare this key value against the index
82523 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
82524 ** fields at the end.
82525 **
82526 ** If the P1 index entry is greater than or equal to the key value
82527 ** then jump to P2. Otherwise fall through to the next instruction.
82528 */
82529 /* Opcode: IdxGT P1 P2 P3 P4 P5
82530 ** Synopsis: key=r[P3@P4]
82531 **
82532 ** The P4 register values beginning with P3 form an unpacked index
82533 ** key that omits the PRIMARY KEY. Compare this key value against the index
82534 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
82535 ** fields at the end.
82536 **
82537 ** If the P1 index entry is greater than the key value
82538 ** then jump to P2. Otherwise fall through to the next instruction.
82539 */
82540 /* Opcode: IdxLT P1 P2 P3 P4 P5
82541 ** Synopsis: key=r[P3@P4]
82542 **
82543 ** The P4 register values beginning with P3 form an unpacked index
82544 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
82545 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82546 ** ROWID on the P1 index.
82547 **
82548 ** If the P1 index entry is less than the key value then jump to P2.
82549 ** Otherwise fall through to the next instruction.
82550 */
82551 /* Opcode: IdxLE P1 P2 P3 P4 P5
82552 ** Synopsis: key=r[P3@P4]
82553 **
82554 ** The P4 register values beginning with P3 form an unpacked index
82555 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
82556 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82557 ** ROWID on the P1 index.
82558 **
82559 ** If the P1 index entry is less than or equal to the key value then jump
82560 ** to P2. Otherwise fall through to the next instruction.
82561 */
82562 case OP_IdxLE: /* jump */
82563 case OP_IdxGT: /* jump */
82564 case OP_IdxLT: /* jump */
82565 case OP_IdxGE: { /* jump */
82566  VdbeCursor *pC;
82567  int res;
82568  UnpackedRecord r;
82569 
82570  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82571  pC = p->apCsr[pOp->p1];
82572  assert( pC!=0 );
82573  assert( pC->isOrdered );
82574  assert( pC->eCurType==CURTYPE_BTREE );
82575  assert( pC->uc.pCursor!=0);
82576  assert( pC->deferredMoveto==0 );
82577  assert( pOp->p5==0 || pOp->p5==1 );
82578  assert( pOp->p4type==P4_INT32 );
82579  r.pKeyInfo = pC->pKeyInfo;
82580  r.nField = (u16)pOp->p4.i;
82581  if( pOp->opcode<OP_IdxLT ){
82582  assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
82583  r.default_rc = -1;
82584  }else{
82585  assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
82586  r.default_rc = 0;
82587  }
82588  r.aMem = &aMem[pOp->p3];
82589 #ifdef SQLITE_DEBUG
82590  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
82591 #endif
82592  res = 0; /* Not needed. Only used to silence a warning. */
82593  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
82594  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
82595  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
82596  assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
82597  res = -res;
82598  }else{
82599  assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
82600  res++;
82601  }
82602  VdbeBranchTaken(res>0,2);
82603  if( rc ) goto abort_due_to_error;
82604  if( res>0 ) goto jump_to_p2;
82605  break;
82606 }
82607 
82608 /* Opcode: Destroy P1 P2 P3 * *
82609 **
82610 ** Delete an entire database table or index whose root page in the database
82611 ** file is given by P1.
82612 **
82613 ** The table being destroyed is in the main database file if P3==0. If
82614 ** P3==1 then the table to be clear is in the auxiliary database file
82615 ** that is used to store tables create using CREATE TEMPORARY TABLE.
82616 **
82617 ** If AUTOVACUUM is enabled then it is possible that another root page
82618 ** might be moved into the newly deleted root page in order to keep all
82619 ** root pages contiguous at the beginning of the database. The former
82620 ** value of the root page that moved - its value before the move occurred -
82621 ** is stored in register P2. If no page
82622 ** movement was required (because the table being dropped was already
82623 ** the last one in the database) then a zero is stored in register P2.
82624 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
82625 **
82626 ** See also: Clear
82627 */
82628 case OP_Destroy: { /* out2 */
82629  int iMoved;
82630  int iDb;
82631 
82632  assert( p->readOnly==0 );
82633  assert( pOp->p1>1 );
82634  pOut = out2Prerelease(p, pOp);
82635  pOut->flags = MEM_Null;
82636  if( db->nVdbeRead > db->nVDestroy+1 ){
82637  rc = SQLITE_LOCKED;
82638  p->errorAction = OE_Abort;
82639  goto abort_due_to_error;
82640  }else{
82641  iDb = pOp->p3;
82642  assert( DbMaskTest(p->btreeMask, iDb) );
82643  iMoved = 0; /* Not needed. Only to silence a warning. */
82644  rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
82645  pOut->flags = MEM_Int;
82646  pOut->u.i = iMoved;
82647  if( rc ) goto abort_due_to_error;
82648 #ifndef SQLITE_OMIT_AUTOVACUUM
82649  if( iMoved!=0 ){
82650  sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
82651  /* All OP_Destroy operations occur on the same btree */
82652  assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
82653  resetSchemaOnFault = iDb+1;
82654  }
82655 #endif
82656  }
82657  break;
82658 }
82659 
82660 /* Opcode: Clear P1 P2 P3
82661 **
82662 ** Delete all contents of the database table or index whose root page
82663 ** in the database file is given by P1. But, unlike Destroy, do not
82664 ** remove the table or index from the database file.
82665 **
82666 ** The table being clear is in the main database file if P2==0. If
82667 ** P2==1 then the table to be clear is in the auxiliary database file
82668 ** that is used to store tables create using CREATE TEMPORARY TABLE.
82669 **
82670 ** If the P3 value is non-zero, then the table referred to must be an
82671 ** intkey table (an SQL table, not an index). In this case the row change
82672 ** count is incremented by the number of rows in the table being cleared.
82673 ** If P3 is greater than zero, then the value stored in register P3 is
82674 ** also incremented by the number of rows in the table being cleared.
82675 **
82676 ** See also: Destroy
82677 */
82678 case OP_Clear: {
82679  int nChange;
82680 
82681  nChange = 0;
82682  assert( p->readOnly==0 );
82683  assert( DbMaskTest(p->btreeMask, pOp->p2) );
82684  rc = sqlite3BtreeClearTable(
82685  db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
82686  );
82687  if( pOp->p3 ){
82688  p->nChange += nChange;
82689  if( pOp->p3>0 ){
82690  assert( memIsValid(&aMem[pOp->p3]) );
82691  memAboutToChange(p, &aMem[pOp->p3]);
82692  aMem[pOp->p3].u.i += nChange;
82693  }
82694  }
82695  if( rc ) goto abort_due_to_error;
82696  break;
82697 }
82698 
82699 /* Opcode: ResetSorter P1 * * * *
82700 **
82701 ** Delete all contents from the ephemeral table or sorter
82702 ** that is open on cursor P1.
82703 **
82704 ** This opcode only works for cursors used for sorting and
82705 ** opened with OP_OpenEphemeral or OP_SorterOpen.
82706 */
82707 case OP_ResetSorter: {
82708  VdbeCursor *pC;
82709 
82710  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82711  pC = p->apCsr[pOp->p1];
82712  assert( pC!=0 );
82713  if( isSorter(pC) ){
82714  sqlite3VdbeSorterReset(db, pC->uc.pSorter);
82715  }else{
82716  assert( pC->eCurType==CURTYPE_BTREE );
82717  assert( pC->isEphemeral );
82718  rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
82719  if( rc ) goto abort_due_to_error;
82720  }
82721  break;
82722 }
82723 
82724 /* Opcode: CreateTable P1 P2 * * *
82725 ** Synopsis: r[P2]=root iDb=P1
82726 **
82727 ** Allocate a new table in the main database file if P1==0 or in the
82728 ** auxiliary database file if P1==1 or in an attached database if
82729 ** P1>1. Write the root page number of the new table into
82730 ** register P2
82731 **
82732 ** The difference between a table and an index is this: A table must
82733 ** have a 4-byte integer key and can have arbitrary data. An index
82734 ** has an arbitrary key but no data.
82735 **
82736 ** See also: CreateIndex
82737 */
82738 /* Opcode: CreateIndex P1 P2 * * *
82739 ** Synopsis: r[P2]=root iDb=P1
82740 **
82741 ** Allocate a new index in the main database file if P1==0 or in the
82742 ** auxiliary database file if P1==1 or in an attached database if
82743 ** P1>1. Write the root page number of the new table into
82744 ** register P2.
82745 **
82746 ** See documentation on OP_CreateTable for additional information.
82747 */
82748 case OP_CreateIndex: /* out2 */
82749 case OP_CreateTable: { /* out2 */
82750  int pgno;
82751  int flags;
82752  Db *pDb;
82753 
82754  pOut = out2Prerelease(p, pOp);
82755  pgno = 0;
82756  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82757  assert( DbMaskTest(p->btreeMask, pOp->p1) );
82758  assert( p->readOnly==0 );
82759  pDb = &db->aDb[pOp->p1];
82760  assert( pDb->pBt!=0 );
82761  if( pOp->opcode==OP_CreateTable ){
82762  /* flags = BTREE_INTKEY; */
82763  flags = BTREE_INTKEY;
82764  }else{
82765  flags = BTREE_BLOBKEY;
82766  }
82767  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
82768  if( rc ) goto abort_due_to_error;
82769  pOut->u.i = pgno;
82770  break;
82771 }
82772 
82773 /* Opcode: ParseSchema P1 * * P4 *
82774 **
82775 ** Read and parse all entries from the SQLITE_MASTER table of database P1
82776 ** that match the WHERE clause P4.
82777 **
82778 ** This opcode invokes the parser to create a new virtual machine,
82779 ** then runs the new virtual machine. It is thus a re-entrant opcode.
82780 */
82781 case OP_ParseSchema: {
82782  int iDb;
82783  const char *zMaster;
82784  char *zSql;
82785  InitData initData;
82786 
82787  /* Any prepared statement that invokes this opcode will hold mutexes
82788  ** on every btree. This is a prerequisite for invoking
82789  ** sqlite3InitCallback().
82790  */
82791 #ifdef SQLITE_DEBUG
82792  for(iDb=0; iDb<db->nDb; iDb++){
82793  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
82794  }
82795 #endif
82796 
82797  iDb = pOp->p1;
82798  assert( iDb>=0 && iDb<db->nDb );
82799  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
82800  /* Used to be a conditional */ {
82801  zMaster = SCHEMA_TABLE(iDb);
82802  initData.db = db;
82803  initData.iDb = pOp->p1;
82804  initData.pzErrMsg = &p->zErrMsg;
82805  zSql = sqlite3MPrintf(db,
82806  "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
82807  db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
82808  if( zSql==0 ){
82809  rc = SQLITE_NOMEM_BKPT;
82810  }else{
82811  assert( db->init.busy==0 );
82812  db->init.busy = 1;
82813  initData.rc = SQLITE_OK;
82814  assert( !db->mallocFailed );
82815  rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
82816  if( rc==SQLITE_OK ) rc = initData.rc;
82817  sqlite3DbFree(db, zSql);
82818  db->init.busy = 0;
82819  }
82820  }
82821  if( rc ){
82822  sqlite3ResetAllSchemasOfConnection(db);
82823  if( rc==SQLITE_NOMEM ){
82824  goto no_mem;
82825  }
82826  goto abort_due_to_error;
82827  }
82828  break;
82829 }
82830 
82831 #if !defined(SQLITE_OMIT_ANALYZE)
82832 /* Opcode: LoadAnalysis P1 * * * *
82833 **
82834 ** Read the sqlite_stat1 table for database P1 and load the content
82835 ** of that table into the internal index hash table. This will cause
82836 ** the analysis to be used when preparing all subsequent queries.
82837 */
82838 case OP_LoadAnalysis: {
82839  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82840  rc = sqlite3AnalysisLoad(db, pOp->p1);
82841  if( rc ) goto abort_due_to_error;
82842  break;
82843 }
82844 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
82845 
82846 /* Opcode: DropTable P1 * * P4 *
82847 **
82848 ** Remove the internal (in-memory) data structures that describe
82849 ** the table named P4 in database P1. This is called after a table
82850 ** is dropped from disk (using the Destroy opcode) in order to keep
82851 ** the internal representation of the
82852 ** schema consistent with what is on disk.
82853 */
82854 case OP_DropTable: {
82855  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
82856  break;
82857 }
82858 
82859 /* Opcode: DropIndex P1 * * P4 *
82860 **
82861 ** Remove the internal (in-memory) data structures that describe
82862 ** the index named P4 in database P1. This is called after an index
82863 ** is dropped from disk (using the Destroy opcode)
82864 ** in order to keep the internal representation of the
82865 ** schema consistent with what is on disk.
82866 */
82867 case OP_DropIndex: {
82868  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
82869  break;
82870 }
82871 
82872 /* Opcode: DropTrigger P1 * * P4 *
82873 **
82874 ** Remove the internal (in-memory) data structures that describe
82875 ** the trigger named P4 in database P1. This is called after a trigger
82876 ** is dropped from disk (using the Destroy opcode) in order to keep
82877 ** the internal representation of the
82878 ** schema consistent with what is on disk.
82879 */
82880 case OP_DropTrigger: {
82881  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
82882  break;
82883 }
82884 
82885 
82886 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
82887 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
82888 **
82889 ** Do an analysis of the currently open database. Store in
82890 ** register P1 the text of an error message describing any problems.
82891 ** If no problems are found, store a NULL in register P1.
82892 **
82893 ** The register P3 contains the maximum number of allowed errors.
82894 ** At most reg(P3) errors will be reported.
82895 ** In other words, the analysis stops as soon as reg(P1) errors are
82896 ** seen. Reg(P1) is updated with the number of errors remaining.
82897 **
82898 ** The root page numbers of all tables in the database are integers
82899 ** stored in P4_INTARRAY argument.
82900 **
82901 ** If P5 is not zero, the check is done on the auxiliary database
82902 ** file, not the main database file.
82903 **
82904 ** This opcode is used to implement the integrity_check pragma.
82905 */
82906 case OP_IntegrityCk: {
82907  int nRoot; /* Number of tables to check. (Number of root pages.) */
82908  int *aRoot; /* Array of rootpage numbers for tables to be checked */
82909  int nErr; /* Number of errors reported */
82910  char *z; /* Text of the error report */
82911  Mem *pnErr; /* Register keeping track of errors remaining */
82912 
82913  assert( p->bIsReader );
82914  nRoot = pOp->p2;
82915  aRoot = pOp->p4.ai;
82916  assert( nRoot>0 );
82917  assert( aRoot[nRoot]==0 );
82918  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
82919  pnErr = &aMem[pOp->p3];
82920  assert( (pnErr->flags & MEM_Int)!=0 );
82921  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
82922  pIn1 = &aMem[pOp->p1];
82923  assert( pOp->p5<db->nDb );
82924  assert( DbMaskTest(p->btreeMask, pOp->p5) );
82925  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
82926  (int)pnErr->u.i, &nErr);
82927  pnErr->u.i -= nErr;
82928  sqlite3VdbeMemSetNull(pIn1);
82929  if( nErr==0 ){
82930  assert( z==0 );
82931  }else if( z==0 ){
82932  goto no_mem;
82933  }else{
82934  sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
82935  }
82936  UPDATE_MAX_BLOBSIZE(pIn1);
82937  sqlite3VdbeChangeEncoding(pIn1, encoding);
82938  break;
82939 }
82940 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
82941 
82942 /* Opcode: RowSetAdd P1 P2 * * *
82943 ** Synopsis: rowset(P1)=r[P2]
82944 **
82945 ** Insert the integer value held by register P2 into a boolean index
82946 ** held in register P1.
82947 **
82948 ** An assertion fails if P2 is not an integer.
82949 */
82950 case OP_RowSetAdd: { /* in1, in2 */
82951  pIn1 = &aMem[pOp->p1];
82952  pIn2 = &aMem[pOp->p2];
82953  assert( (pIn2->flags & MEM_Int)!=0 );
82954  if( (pIn1->flags & MEM_RowSet)==0 ){
82955  sqlite3VdbeMemSetRowSet(pIn1);
82956  if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82957  }
82958  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
82959  break;
82960 }
82961 
82962 /* Opcode: RowSetRead P1 P2 P3 * *
82963 ** Synopsis: r[P3]=rowset(P1)
82964 **
82965 ** Extract the smallest value from boolean index P1 and put that value into
82966 ** register P3. Or, if boolean index P1 is initially empty, leave P3
82967 ** unchanged and jump to instruction P2.
82968 */
82969 case OP_RowSetRead: { /* jump, in1, out3 */
82970  i64 val;
82971 
82972  pIn1 = &aMem[pOp->p1];
82973  if( (pIn1->flags & MEM_RowSet)==0
82974  || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
82975  ){
82976  /* The boolean index is empty */
82977  sqlite3VdbeMemSetNull(pIn1);
82978  VdbeBranchTaken(1,2);
82979  goto jump_to_p2_and_check_for_interrupt;
82980  }else{
82981  /* A value was pulled from the index */
82982  VdbeBranchTaken(0,2);
82983  sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
82984  }
82985  goto check_for_interrupt;
82986 }
82987 
82988 /* Opcode: RowSetTest P1 P2 P3 P4
82989 ** Synopsis: if r[P3] in rowset(P1) goto P2
82990 **
82991 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
82992 ** contains a RowSet object and that RowSet object contains
82993 ** the value held in P3, jump to register P2. Otherwise, insert the
82994 ** integer in P3 into the RowSet and continue on to the
82995 ** next opcode.
82996 **
82997 ** The RowSet object is optimized for the case where successive sets
82998 ** of integers, where each set contains no duplicates. Each set
82999 ** of values is identified by a unique P4 value. The first set
83000 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
83001 ** non-negative. For non-negative values of P4 only the lower 4
83002 ** bits are significant.
83003 **
83004 ** This allows optimizations: (a) when P4==0 there is no need to test
83005 ** the rowset object for P3, as it is guaranteed not to contain it,
83006 ** (b) when P4==-1 there is no need to insert the value, as it will
83007 ** never be tested for, and (c) when a value that is part of set X is
83008 ** inserted, there is no need to search to see if the same value was
83009 ** previously inserted as part of set X (only if it was previously
83010 ** inserted as part of some other set).
83011 */
83012 case OP_RowSetTest: { /* jump, in1, in3 */
83013  int iSet;
83014  int exists;
83015 
83016  pIn1 = &aMem[pOp->p1];
83017  pIn3 = &aMem[pOp->p3];
83018  iSet = pOp->p4.i;
83019  assert( pIn3->flags&MEM_Int );
83020 
83021  /* If there is anything other than a rowset object in memory cell P1,
83022  ** delete it now and initialize P1 with an empty rowset
83023  */
83024  if( (pIn1->flags & MEM_RowSet)==0 ){
83025  sqlite3VdbeMemSetRowSet(pIn1);
83026  if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
83027  }
83028 
83029  assert( pOp->p4type==P4_INT32 );
83030  assert( iSet==-1 || iSet>=0 );
83031  if( iSet ){
83032  exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
83033  VdbeBranchTaken(exists!=0,2);
83034  if( exists ) goto jump_to_p2;
83035  }
83036  if( iSet>=0 ){
83037  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
83038  }
83039  break;
83040 }
83041 
83042 
83043 #ifndef SQLITE_OMIT_TRIGGER
83044 
83045 /* Opcode: Program P1 P2 P3 P4 P5
83046 **
83047 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
83048 **
83049 ** P1 contains the address of the memory cell that contains the first memory
83050 ** cell in an array of values used as arguments to the sub-program. P2
83051 ** contains the address to jump to if the sub-program throws an IGNORE
83052 ** exception using the RAISE() function. Register P3 contains the address
83053 ** of a memory cell in this (the parent) VM that is used to allocate the
83054 ** memory required by the sub-vdbe at runtime.
83055 **
83056 ** P4 is a pointer to the VM containing the trigger program.
83057 **
83058 ** If P5 is non-zero, then recursive program invocation is enabled.
83059 */
83060 case OP_Program: { /* jump */
83061  int nMem; /* Number of memory registers for sub-program */
83062  int nByte; /* Bytes of runtime space required for sub-program */
83063  Mem *pRt; /* Register to allocate runtime space */
83064  Mem *pMem; /* Used to iterate through memory cells */
83065  Mem *pEnd; /* Last memory cell in new array */
83066  VdbeFrame *pFrame; /* New vdbe frame to execute in */
83067  SubProgram *pProgram; /* Sub-program to execute */
83068  void *t; /* Token identifying trigger */
83069 
83070  pProgram = pOp->p4.pProgram;
83071  pRt = &aMem[pOp->p3];
83072  assert( pProgram->nOp>0 );
83073 
83074  /* If the p5 flag is clear, then recursive invocation of triggers is
83075  ** disabled for backwards compatibility (p5 is set if this sub-program
83076  ** is really a trigger, not a foreign key action, and the flag set
83077  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
83078  **
83079  ** It is recursive invocation of triggers, at the SQL level, that is
83080  ** disabled. In some cases a single trigger may generate more than one
83081  ** SubProgram (if the trigger may be executed with more than one different
83082  ** ON CONFLICT algorithm). SubProgram structures associated with a
83083  ** single trigger all have the same value for the SubProgram.token
83084  ** variable. */
83085  if( pOp->p5 ){
83086  t = pProgram->token;
83087  for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
83088  if( pFrame ) break;
83089  }
83090 
83091  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
83092  rc = SQLITE_ERROR;
83093  sqlite3VdbeError(p, "too many levels of trigger recursion");
83094  goto abort_due_to_error;
83095  }
83096 
83097  /* Register pRt is used to store the memory required to save the state
83098  ** of the current program, and the memory required at runtime to execute
83099  ** the trigger program. If this trigger has been fired before, then pRt
83100  ** is already allocated. Otherwise, it must be initialized. */
83101  if( (pRt->flags&MEM_Frame)==0 ){
83102  /* SubProgram.nMem is set to the number of memory cells used by the
83103  ** program stored in SubProgram.aOp. As well as these, one memory
83104  ** cell is required for each cursor used by the program. Set local
83105  ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
83106  */
83107  nMem = pProgram->nMem + pProgram->nCsr;
83108  assert( nMem>0 );
83109  if( pProgram->nCsr==0 ) nMem++;
83110  nByte = ROUND8(sizeof(VdbeFrame))
83111  + nMem * sizeof(Mem)
83112  + pProgram->nCsr * sizeof(VdbeCursor *);
83113  pFrame = sqlite3DbMallocZero(db, nByte);
83114  if( !pFrame ){
83115  goto no_mem;
83116  }
83117  sqlite3VdbeMemRelease(pRt);
83118  pRt->flags = MEM_Frame;
83119  pRt->u.pFrame = pFrame;
83120 
83121  pFrame->v = p;
83122  pFrame->nChildMem = nMem;
83123  pFrame->nChildCsr = pProgram->nCsr;
83124  pFrame->pc = (int)(pOp - aOp);
83125  pFrame->aMem = p->aMem;
83126  pFrame->nMem = p->nMem;
83127  pFrame->apCsr = p->apCsr;
83128  pFrame->nCursor = p->nCursor;
83129  pFrame->aOp = p->aOp;
83130  pFrame->nOp = p->nOp;
83131  pFrame->token = pProgram->token;
83132 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
83133  pFrame->anExec = p->anExec;
83134 #endif
83135 
83136  pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
83137  for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
83138  pMem->flags = MEM_Undefined;
83139  pMem->db = db;
83140  }
83141  }else{
83142  pFrame = pRt->u.pFrame;
83143  assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
83144  || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
83145  assert( pProgram->nCsr==pFrame->nChildCsr );
83146  assert( (int)(pOp - aOp)==pFrame->pc );
83147  }
83148 
83149  p->nFrame++;
83150  pFrame->pParent = p->pFrame;
83151  pFrame->lastRowid = lastRowid;
83152  pFrame->nChange = p->nChange;
83153  pFrame->nDbChange = p->db->nChange;
83154  assert( pFrame->pAuxData==0 );
83155  pFrame->pAuxData = p->pAuxData;
83156  p->pAuxData = 0;
83157  p->nChange = 0;
83158  p->pFrame = pFrame;
83159  p->aMem = aMem = VdbeFrameMem(pFrame);
83160  p->nMem = pFrame->nChildMem;
83161  p->nCursor = (u16)pFrame->nChildCsr;
83162  p->apCsr = (VdbeCursor **)&aMem[p->nMem];
83163  p->aOp = aOp = pProgram->aOp;
83164  p->nOp = pProgram->nOp;
83165 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
83166  p->anExec = 0;
83167 #endif
83168  pOp = &aOp[-1];
83169 
83170  break;
83171 }
83172 
83173 /* Opcode: Param P1 P2 * * *
83174 **
83175 ** This opcode is only ever present in sub-programs called via the
83176 ** OP_Program instruction. Copy a value currently stored in a memory
83177 ** cell of the calling (parent) frame to cell P2 in the current frames
83178 ** address space. This is used by trigger programs to access the new.*
83179 ** and old.* values.
83180 **
83181 ** The address of the cell in the parent frame is determined by adding
83182 ** the value of the P1 argument to the value of the P1 argument to the
83183 ** calling OP_Program instruction.
83184 */
83185 case OP_Param: { /* out2 */
83186  VdbeFrame *pFrame;
83187  Mem *pIn;
83188  pOut = out2Prerelease(p, pOp);
83189  pFrame = p->pFrame;
83190  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
83191  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
83192  break;
83193 }
83194 
83195 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
83196 
83197 #ifndef SQLITE_OMIT_FOREIGN_KEY
83198 /* Opcode: FkCounter P1 P2 * * *
83199 ** Synopsis: fkctr[P1]+=P2
83200 **
83201 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
83202 ** If P1 is non-zero, the database constraint counter is incremented
83203 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
83204 ** statement counter is incremented (immediate foreign key constraints).
83205 */
83206 case OP_FkCounter: {
83207  if( db->flags & SQLITE_DeferFKs ){
83208  db->nDeferredImmCons += pOp->p2;
83209  }else if( pOp->p1 ){
83210  db->nDeferredCons += pOp->p2;
83211  }else{
83212  p->nFkConstraint += pOp->p2;
83213  }
83214  break;
83215 }
83216 
83217 /* Opcode: FkIfZero P1 P2 * * *
83218 ** Synopsis: if fkctr[P1]==0 goto P2
83219 **
83220 ** This opcode tests if a foreign key constraint-counter is currently zero.
83221 ** If so, jump to instruction P2. Otherwise, fall through to the next
83222 ** instruction.
83223 **
83224 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
83225 ** is zero (the one that counts deferred constraint violations). If P1 is
83226 ** zero, the jump is taken if the statement constraint-counter is zero
83227 ** (immediate foreign key constraint violations).
83228 */
83229 case OP_FkIfZero: { /* jump */
83230  if( pOp->p1 ){
83231  VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
83232  if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
83233  }else{
83234  VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
83235  if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
83236  }
83237  break;
83238 }
83239 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
83240 
83241 #ifndef SQLITE_OMIT_AUTOINCREMENT
83242 /* Opcode: MemMax P1 P2 * * *
83243 ** Synopsis: r[P1]=max(r[P1],r[P2])
83244 **
83245 ** P1 is a register in the root frame of this VM (the root frame is
83246 ** different from the current frame if this instruction is being executed
83247 ** within a sub-program). Set the value of register P1 to the maximum of
83248 ** its current value and the value in register P2.
83249 **
83250 ** This instruction throws an error if the memory cell is not initially
83251 ** an integer.
83252 */
83253 case OP_MemMax: { /* in2 */
83254  VdbeFrame *pFrame;
83255  if( p->pFrame ){
83256  for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
83257  pIn1 = &pFrame->aMem[pOp->p1];
83258  }else{
83259  pIn1 = &aMem[pOp->p1];
83260  }
83261  assert( memIsValid(pIn1) );
83262  sqlite3VdbeMemIntegerify(pIn1);
83263  pIn2 = &aMem[pOp->p2];
83264  sqlite3VdbeMemIntegerify(pIn2);
83265  if( pIn1->u.i<pIn2->u.i){
83266  pIn1->u.i = pIn2->u.i;
83267  }
83268  break;
83269 }
83270 #endif /* SQLITE_OMIT_AUTOINCREMENT */
83271 
83272 /* Opcode: IfPos P1 P2 P3 * *
83273 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
83274 **
83275 ** Register P1 must contain an integer.
83276 ** If the value of register P1 is 1 or greater, subtract P3 from the
83277 ** value in P1 and jump to P2.
83278 **
83279 ** If the initial value of register P1 is less than 1, then the
83280 ** value is unchanged and control passes through to the next instruction.
83281 */
83282 case OP_IfPos: { /* jump, in1 */
83283  pIn1 = &aMem[pOp->p1];
83284  assert( pIn1->flags&MEM_Int );
83285  VdbeBranchTaken( pIn1->u.i>0, 2);
83286  if( pIn1->u.i>0 ){
83287  pIn1->u.i -= pOp->p3;
83288  goto jump_to_p2;
83289  }
83290  break;
83291 }
83292 
83293 /* Opcode: OffsetLimit P1 P2 P3 * *
83294 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
83295 **
83296 ** This opcode performs a commonly used computation associated with
83297 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
83298 ** holds the offset counter. The opcode computes the combined value
83299 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
83300 ** value computed is the total number of rows that will need to be
83301 ** visited in order to complete the query.
83302 **
83303 ** If r[P3] is zero or negative, that means there is no OFFSET
83304 ** and r[P2] is set to be the value of the LIMIT, r[P1].
83305 **
83306 ** if r[P1] is zero or negative, that means there is no LIMIT
83307 ** and r[P2] is set to -1.
83308 **
83309 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
83310 */
83311 case OP_OffsetLimit: { /* in1, out2, in3 */
83312  pIn1 = &aMem[pOp->p1];
83313  pIn3 = &aMem[pOp->p3];
83314  pOut = out2Prerelease(p, pOp);
83315  assert( pIn1->flags & MEM_Int );
83316  assert( pIn3->flags & MEM_Int );
83317  pOut->u.i = pIn1->u.i<=0 ? -1 : pIn1->u.i+(pIn3->u.i>0?pIn3->u.i:0);
83318  break;
83319 }
83320 
83321 /* Opcode: IfNotZero P1 P2 P3 * *
83322 ** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
83323 **
83324 ** Register P1 must contain an integer. If the content of register P1 is
83325 ** initially nonzero, then subtract P3 from the value in register P1 and
83326 ** jump to P2. If register P1 is initially zero, leave it unchanged
83327 ** and fall through.
83328 */
83329 case OP_IfNotZero: { /* jump, in1 */
83330  pIn1 = &aMem[pOp->p1];
83331  assert( pIn1->flags&MEM_Int );
83332  VdbeBranchTaken(pIn1->u.i<0, 2);
83333  if( pIn1->u.i ){
83334  pIn1->u.i -= pOp->p3;
83335  goto jump_to_p2;
83336  }
83337  break;
83338 }
83339 
83340 /* Opcode: DecrJumpZero P1 P2 * * *
83341 ** Synopsis: if (--r[P1])==0 goto P2
83342 **
83343 ** Register P1 must hold an integer. Decrement the value in register P1
83344 ** then jump to P2 if the new value is exactly zero.
83345 */
83346 case OP_DecrJumpZero: { /* jump, in1 */
83347  pIn1 = &aMem[pOp->p1];
83348  assert( pIn1->flags&MEM_Int );
83349  pIn1->u.i--;
83350  VdbeBranchTaken(pIn1->u.i==0, 2);
83351  if( pIn1->u.i==0 ) goto jump_to_p2;
83352  break;
83353 }
83354 
83355 
83356 /* Opcode: AggStep0 * P2 P3 P4 P5
83357 ** Synopsis: accum=r[P3] step(r[P2@P5])
83358 **
83359 ** Execute the step function for an aggregate. The
83360 ** function has P5 arguments. P4 is a pointer to the FuncDef
83361 ** structure that specifies the function. Register P3 is the
83362 ** accumulator.
83363 **
83364 ** The P5 arguments are taken from register P2 and its
83365 ** successors.
83366 */
83367 /* Opcode: AggStep * P2 P3 P4 P5
83368 ** Synopsis: accum=r[P3] step(r[P2@P5])
83369 **
83370 ** Execute the step function for an aggregate. The
83371 ** function has P5 arguments. P4 is a pointer to an sqlite3_context
83372 ** object that is used to run the function. Register P3 is
83373 ** as the accumulator.
83374 **
83375 ** The P5 arguments are taken from register P2 and its
83376 ** successors.
83377 **
83378 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
83379 ** the FuncDef stored in P4 is converted into an sqlite3_context and
83380 ** the opcode is changed. In this way, the initialization of the
83381 ** sqlite3_context only happens once, instead of on each call to the
83382 ** step function.
83383 */
83384 case OP_AggStep0: {
83385  int n;
83386  sqlite3_context *pCtx;
83387 
83388  assert( pOp->p4type==P4_FUNCDEF );
83389  n = pOp->p5;
83390  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83391  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
83392  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
83393  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
83394  if( pCtx==0 ) goto no_mem;
83395  pCtx->pMem = 0;
83396  pCtx->pFunc = pOp->p4.pFunc;
83397  pCtx->iOp = (int)(pOp - aOp);
83398  pCtx->pVdbe = p;
83399  pCtx->argc = n;
83400  pOp->p4type = P4_FUNCCTX;
83401  pOp->p4.pCtx = pCtx;
83402  pOp->opcode = OP_AggStep;
83403  /* Fall through into OP_AggStep */
83404 }
83405 case OP_AggStep: {
83406  int i;
83407  sqlite3_context *pCtx;
83408  Mem *pMem;
83409  Mem t;
83410 
83411  assert( pOp->p4type==P4_FUNCCTX );
83412  pCtx = pOp->p4.pCtx;
83413  pMem = &aMem[pOp->p3];
83414 
83415  /* If this function is inside of a trigger, the register array in aMem[]
83416  ** might change from one evaluation to the next. The next block of code
83417  ** checks to see if the register array has changed, and if so it
83418  ** reinitializes the relavant parts of the sqlite3_context object */
83419  if( pCtx->pMem != pMem ){
83420  pCtx->pMem = pMem;
83421  for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
83422  }
83423 
83424 #ifdef SQLITE_DEBUG
83425  for(i=0; i<pCtx->argc; i++){
83426  assert( memIsValid(pCtx->argv[i]) );
83427  REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
83428  }
83429 #endif
83430 
83431  pMem->n++;
83432  sqlite3VdbeMemInit(&t, db, MEM_Null);
83433  pCtx->pOut = &t;
83434  pCtx->fErrorOrAux = 0;
83435  pCtx->skipFlag = 0;
83436  (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
83437  if( pCtx->fErrorOrAux ){
83438  if( pCtx->isError ){
83439  sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
83440  rc = pCtx->isError;
83441  }
83442  sqlite3VdbeMemRelease(&t);
83443  if( rc ) goto abort_due_to_error;
83444  }else{
83445  assert( t.flags==MEM_Null );
83446  }
83447  if( pCtx->skipFlag ){
83448  assert( pOp[-1].opcode==OP_CollSeq );
83449  i = pOp[-1].p1;
83450  if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
83451  }
83452  break;
83453 }
83454 
83455 /* Opcode: AggFinal P1 P2 * P4 *
83456 ** Synopsis: accum=r[P1] N=P2
83457 **
83458 ** Execute the finalizer function for an aggregate. P1 is
83459 ** the memory location that is the accumulator for the aggregate.
83460 **
83461 ** P2 is the number of arguments that the step function takes and
83462 ** P4 is a pointer to the FuncDef for this function. The P2
83463 ** argument is not used by this opcode. It is only there to disambiguate
83464 ** functions that can take varying numbers of arguments. The
83465 ** P4 argument is only needed for the degenerate case where
83466 ** the step function was not previously called.
83467 */
83468 case OP_AggFinal: {
83469  Mem *pMem;
83470  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
83471  pMem = &aMem[pOp->p1];
83472  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
83473  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
83474  if( rc ){
83475  sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
83476  goto abort_due_to_error;
83477  }
83478  sqlite3VdbeChangeEncoding(pMem, encoding);
83479  UPDATE_MAX_BLOBSIZE(pMem);
83480  if( sqlite3VdbeMemTooBig(pMem) ){
83481  goto too_big;
83482  }
83483  break;
83484 }
83485 
83486 #ifndef SQLITE_OMIT_WAL
83487 /* Opcode: Checkpoint P1 P2 P3 * *
83488 **
83489 ** Checkpoint database P1. This is a no-op if P1 is not currently in
83490 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
83491 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
83492 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
83493 ** WAL after the checkpoint into mem[P3+1] and the number of pages
83494 ** in the WAL that have been checkpointed after the checkpoint
83495 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
83496 ** mem[P3+2] are initialized to -1.
83497 */
83498 case OP_Checkpoint: {
83499  int i; /* Loop counter */
83500  int aRes[3]; /* Results */
83501  Mem *pMem; /* Write results here */
83502 
83503  assert( p->readOnly==0 );
83504  aRes[0] = 0;
83505  aRes[1] = aRes[2] = -1;
83506  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
83507  || pOp->p2==SQLITE_CHECKPOINT_FULL
83508  || pOp->p2==SQLITE_CHECKPOINT_RESTART
83509  || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
83510  );
83511  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
83512  if( rc ){
83513  if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
83514  rc = SQLITE_OK;
83515  aRes[0] = 1;
83516  }
83517  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
83518  sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
83519  }
83520  break;
83521 };
83522 #endif
83523 
83524 #ifndef SQLITE_OMIT_PRAGMA
83525 /* Opcode: JournalMode P1 P2 P3 * *
83526 **
83527 ** Change the journal mode of database P1 to P3. P3 must be one of the
83528 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
83529 ** modes (delete, truncate, persist, off and memory), this is a simple
83530 ** operation. No IO is required.
83531 **
83532 ** If changing into or out of WAL mode the procedure is more complicated.
83533 **
83534 ** Write a string containing the final journal-mode to register P2.
83535 */
83536 case OP_JournalMode: { /* out2 */
83537  Btree *pBt; /* Btree to change journal mode of */
83538  Pager *pPager; /* Pager associated with pBt */
83539  int eNew; /* New journal mode */
83540  int eOld; /* The old journal mode */
83541 #ifndef SQLITE_OMIT_WAL
83542  const char *zFilename; /* Name of database file for pPager */
83543 #endif
83544 
83545  pOut = out2Prerelease(p, pOp);
83546  eNew = pOp->p3;
83547  assert( eNew==PAGER_JOURNALMODE_DELETE
83548  || eNew==PAGER_JOURNALMODE_TRUNCATE
83549  || eNew==PAGER_JOURNALMODE_PERSIST
83550  || eNew==PAGER_JOURNALMODE_OFF
83551  || eNew==PAGER_JOURNALMODE_MEMORY
83552  || eNew==PAGER_JOURNALMODE_WAL
83553  || eNew==PAGER_JOURNALMODE_QUERY
83554  );
83555  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83556  assert( p->readOnly==0 );
83557 
83558  pBt = db->aDb[pOp->p1].pBt;
83559  pPager = sqlite3BtreePager(pBt);
83560  eOld = sqlite3PagerGetJournalMode(pPager);
83561  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
83562  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
83563 
83564 #ifndef SQLITE_OMIT_WAL
83565  zFilename = sqlite3PagerFilename(pPager, 1);
83566 
83567  /* Do not allow a transition to journal_mode=WAL for a database
83568  ** in temporary storage or if the VFS does not support shared memory
83569  */
83570  if( eNew==PAGER_JOURNALMODE_WAL
83571  && (sqlite3Strlen30(zFilename)==0 /* Temp file */
83572  || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
83573  ){
83574  eNew = eOld;
83575  }
83576 
83577  if( (eNew!=eOld)
83578  && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
83579  ){
83580  if( !db->autoCommit || db->nVdbeRead>1 ){
83581  rc = SQLITE_ERROR;
83582  sqlite3VdbeError(p,
83583  "cannot change %s wal mode from within a transaction",
83584  (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
83585  );
83586  goto abort_due_to_error;
83587  }else{
83588 
83589  if( eOld==PAGER_JOURNALMODE_WAL ){
83590  /* If leaving WAL mode, close the log file. If successful, the call
83591  ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
83592  ** file. An EXCLUSIVE lock may still be held on the database file
83593  ** after a successful return.
83594  */
83595  rc = sqlite3PagerCloseWal(pPager);
83596  if( rc==SQLITE_OK ){
83597  sqlite3PagerSetJournalMode(pPager, eNew);
83598  }
83599  }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
83600  /* Cannot transition directly from MEMORY to WAL. Use mode OFF
83601  ** as an intermediate */
83602  sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
83603  }
83604 
83605  /* Open a transaction on the database file. Regardless of the journal
83606  ** mode, this transaction always uses a rollback journal.
83607  */
83608  assert( sqlite3BtreeIsInTrans(pBt)==0 );
83609  if( rc==SQLITE_OK ){
83610  rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
83611  }
83612  }
83613  }
83614 #endif /* ifndef SQLITE_OMIT_WAL */
83615 
83616  if( rc ) eNew = eOld;
83617  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
83618 
83619  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
83620  pOut->z = (char *)sqlite3JournalModename(eNew);
83621  pOut->n = sqlite3Strlen30(pOut->z);
83622  pOut->enc = SQLITE_UTF8;
83623  sqlite3VdbeChangeEncoding(pOut, encoding);
83624  if( rc ) goto abort_due_to_error;
83625  break;
83626 };
83627 #endif /* SQLITE_OMIT_PRAGMA */
83628 
83629 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
83630 /* Opcode: Vacuum P1 * * * *
83631 **
83632 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
83633 ** for an attached database. The "temp" database may not be vacuumed.
83634 */
83635 case OP_Vacuum: {
83636  assert( p->readOnly==0 );
83637  rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
83638  if( rc ) goto abort_due_to_error;
83639  break;
83640 }
83641 #endif
83642 
83643 #if !defined(SQLITE_OMIT_AUTOVACUUM)
83644 /* Opcode: IncrVacuum P1 P2 * * *
83645 **
83646 ** Perform a single step of the incremental vacuum procedure on
83647 ** the P1 database. If the vacuum has finished, jump to instruction
83648 ** P2. Otherwise, fall through to the next instruction.
83649 */
83650 case OP_IncrVacuum: { /* jump */
83651  Btree *pBt;
83652 
83653  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83654  assert( DbMaskTest(p->btreeMask, pOp->p1) );
83655  assert( p->readOnly==0 );
83656  pBt = db->aDb[pOp->p1].pBt;
83657  rc = sqlite3BtreeIncrVacuum(pBt);
83658  VdbeBranchTaken(rc==SQLITE_DONE,2);
83659  if( rc ){
83660  if( rc!=SQLITE_DONE ) goto abort_due_to_error;
83661  rc = SQLITE_OK;
83662  goto jump_to_p2;
83663  }
83664  break;
83665 }
83666 #endif
83667 
83668 /* Opcode: Expire P1 * * * *
83669 **
83670 ** Cause precompiled statements to expire. When an expired statement
83671 ** is executed using sqlite3_step() it will either automatically
83672 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
83673 ** or it will fail with SQLITE_SCHEMA.
83674 **
83675 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
83676 ** then only the currently executing statement is expired.
83677 */
83678 case OP_Expire: {
83679  if( !pOp->p1 ){
83680  sqlite3ExpirePreparedStatements(db);
83681  }else{
83682  p->expired = 1;
83683  }
83684  break;
83685 }
83686 
83687 #ifndef SQLITE_OMIT_SHARED_CACHE
83688 /* Opcode: TableLock P1 P2 P3 P4 *
83689 ** Synopsis: iDb=P1 root=P2 write=P3
83690 **
83691 ** Obtain a lock on a particular table. This instruction is only used when
83692 ** the shared-cache feature is enabled.
83693 **
83694 ** P1 is the index of the database in sqlite3.aDb[] of the database
83695 ** on which the lock is acquired. A readlock is obtained if P3==0 or
83696 ** a write lock if P3==1.
83697 **
83698 ** P2 contains the root-page of the table to lock.
83699 **
83700 ** P4 contains a pointer to the name of the table being locked. This is only
83701 ** used to generate an error message if the lock cannot be obtained.
83702 */
83703 case OP_TableLock: {
83704  u8 isWriteLock = (u8)pOp->p3;
83705  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
83706  int p1 = pOp->p1;
83707  assert( p1>=0 && p1<db->nDb );
83708  assert( DbMaskTest(p->btreeMask, p1) );
83709  assert( isWriteLock==0 || isWriteLock==1 );
83710  rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
83711  if( rc ){
83712  if( (rc&0xFF)==SQLITE_LOCKED ){
83713  const char *z = pOp->p4.z;
83714  sqlite3VdbeError(p, "database table is locked: %s", z);
83715  }
83716  goto abort_due_to_error;
83717  }
83718  }
83719  break;
83720 }
83721 #endif /* SQLITE_OMIT_SHARED_CACHE */
83722 
83723 #ifndef SQLITE_OMIT_VIRTUALTABLE
83724 /* Opcode: VBegin * * * P4 *
83725 **
83726 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
83727 ** xBegin method for that table.
83728 **
83729 ** Also, whether or not P4 is set, check that this is not being called from
83730 ** within a callback to a virtual table xSync() method. If it is, the error
83731 ** code will be set to SQLITE_LOCKED.
83732 */
83733 case OP_VBegin: {
83734  VTable *pVTab;
83735  pVTab = pOp->p4.pVtab;
83736  rc = sqlite3VtabBegin(db, pVTab);
83737  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
83738  if( rc ) goto abort_due_to_error;
83739  break;
83740 }
83741 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83742 
83743 #ifndef SQLITE_OMIT_VIRTUALTABLE
83744 /* Opcode: VCreate P1 P2 * * *
83745 **
83746 ** P2 is a register that holds the name of a virtual table in database
83747 ** P1. Call the xCreate method for that table.
83748 */
83749 case OP_VCreate: {
83750  Mem sMem; /* For storing the record being decoded */
83751  const char *zTab; /* Name of the virtual table */
83752 
83753  memset(&sMem, 0, sizeof(sMem));
83754  sMem.db = db;
83755  /* Because P2 is always a static string, it is impossible for the
83756  ** sqlite3VdbeMemCopy() to fail */
83757  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
83758  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
83759  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
83760  assert( rc==SQLITE_OK );
83761  zTab = (const char*)sqlite3_value_text(&sMem);
83762  assert( zTab || db->mallocFailed );
83763  if( zTab ){
83764  rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
83765  }
83766  sqlite3VdbeMemRelease(&sMem);
83767  if( rc ) goto abort_due_to_error;
83768  break;
83769 }
83770 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83771 
83772 #ifndef SQLITE_OMIT_VIRTUALTABLE
83773 /* Opcode: VDestroy P1 * * P4 *
83774 **
83775 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
83776 ** of that table.
83777 */
83778 case OP_VDestroy: {
83779  db->nVDestroy++;
83780  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
83781  db->nVDestroy--;
83782  if( rc ) goto abort_due_to_error;
83783  break;
83784 }
83785 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83786 
83787 #ifndef SQLITE_OMIT_VIRTUALTABLE
83788 /* Opcode: VOpen P1 * * P4 *
83789 **
83790 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83791 ** P1 is a cursor number. This opcode opens a cursor to the virtual
83792 ** table and stores that cursor in P1.
83793 */
83794 case OP_VOpen: {
83795  VdbeCursor *pCur;
83796  sqlite3_vtab_cursor *pVCur;
83797  sqlite3_vtab *pVtab;
83798  const sqlite3_module *pModule;
83799 
83800  assert( p->bIsReader );
83801  pCur = 0;
83802  pVCur = 0;
83803  pVtab = pOp->p4.pVtab->pVtab;
83804  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83805  rc = SQLITE_LOCKED;
83806  goto abort_due_to_error;
83807  }
83808  pModule = pVtab->pModule;
83809  rc = pModule->xOpen(pVtab, &pVCur);
83810  sqlite3VtabImportErrmsg(p, pVtab);
83811  if( rc ) goto abort_due_to_error;
83812 
83813  /* Initialize sqlite3_vtab_cursor base class */
83814  pVCur->pVtab = pVtab;
83815 
83816  /* Initialize vdbe cursor object */
83817  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
83818  if( pCur ){
83819  pCur->uc.pVCur = pVCur;
83820  pVtab->nRef++;
83821  }else{
83822  assert( db->mallocFailed );
83823  pModule->xClose(pVCur);
83824  goto no_mem;
83825  }
83826  break;
83827 }
83828 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83829 
83830 #ifndef SQLITE_OMIT_VIRTUALTABLE
83831 /* Opcode: VFilter P1 P2 P3 P4 *
83832 ** Synopsis: iplan=r[P3] zplan='P4'
83833 **
83834 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
83835 ** the filtered result set is empty.
83836 **
83837 ** P4 is either NULL or a string that was generated by the xBestIndex
83838 ** method of the module. The interpretation of the P4 string is left
83839 ** to the module implementation.
83840 **
83841 ** This opcode invokes the xFilter method on the virtual table specified
83842 ** by P1. The integer query plan parameter to xFilter is stored in register
83843 ** P3. Register P3+1 stores the argc parameter to be passed to the
83844 ** xFilter method. Registers P3+2..P3+1+argc are the argc
83845 ** additional parameters which are passed to
83846 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
83847 **
83848 ** A jump is made to P2 if the result set after filtering would be empty.
83849 */
83850 case OP_VFilter: { /* jump */
83851  int nArg;
83852  int iQuery;
83853  const sqlite3_module *pModule;
83854  Mem *pQuery;
83855  Mem *pArgc;
83856  sqlite3_vtab_cursor *pVCur;
83857  sqlite3_vtab *pVtab;
83858  VdbeCursor *pCur;
83859  int res;
83860  int i;
83861  Mem **apArg;
83862 
83863  pQuery = &aMem[pOp->p3];
83864  pArgc = &pQuery[1];
83865  pCur = p->apCsr[pOp->p1];
83866  assert( memIsValid(pQuery) );
83867  REGISTER_TRACE(pOp->p3, pQuery);
83868  assert( pCur->eCurType==CURTYPE_VTAB );
83869  pVCur = pCur->uc.pVCur;
83870  pVtab = pVCur->pVtab;
83871  pModule = pVtab->pModule;
83872 
83873  /* Grab the index number and argc parameters */
83874  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
83875  nArg = (int)pArgc->u.i;
83876  iQuery = (int)pQuery->u.i;
83877 
83878  /* Invoke the xFilter method */
83879  res = 0;
83880  apArg = p->apArg;
83881  for(i = 0; i<nArg; i++){
83882  apArg[i] = &pArgc[i+1];
83883  }
83884  rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
83885  sqlite3VtabImportErrmsg(p, pVtab);
83886  if( rc ) goto abort_due_to_error;
83887  res = pModule->xEof(pVCur);
83888  pCur->nullRow = 0;
83889  VdbeBranchTaken(res!=0,2);
83890  if( res ) goto jump_to_p2;
83891  break;
83892 }
83893 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83894 
83895 #ifndef SQLITE_OMIT_VIRTUALTABLE
83896 /* Opcode: VColumn P1 P2 P3 * *
83897 ** Synopsis: r[P3]=vcolumn(P2)
83898 **
83899 ** Store the value of the P2-th column of
83900 ** the row of the virtual-table that the
83901 ** P1 cursor is pointing to into register P3.
83902 */
83903 case OP_VColumn: {
83904  sqlite3_vtab *pVtab;
83905  const sqlite3_module *pModule;
83906  Mem *pDest;
83907  sqlite3_context sContext;
83908 
83909  VdbeCursor *pCur = p->apCsr[pOp->p1];
83910  assert( pCur->eCurType==CURTYPE_VTAB );
83911  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83912  pDest = &aMem[pOp->p3];
83913  memAboutToChange(p, pDest);
83914  if( pCur->nullRow ){
83915  sqlite3VdbeMemSetNull(pDest);
83916  break;
83917  }
83918  pVtab = pCur->uc.pVCur->pVtab;
83919  pModule = pVtab->pModule;
83920  assert( pModule->xColumn );
83921  memset(&sContext, 0, sizeof(sContext));
83922  sContext.pOut = pDest;
83923  MemSetTypeFlag(pDest, MEM_Null);
83924  rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
83925  sqlite3VtabImportErrmsg(p, pVtab);
83926  if( sContext.isError ){
83927  rc = sContext.isError;
83928  }
83929  sqlite3VdbeChangeEncoding(pDest, encoding);
83930  REGISTER_TRACE(pOp->p3, pDest);
83931  UPDATE_MAX_BLOBSIZE(pDest);
83932 
83933  if( sqlite3VdbeMemTooBig(pDest) ){
83934  goto too_big;
83935  }
83936  if( rc ) goto abort_due_to_error;
83937  break;
83938 }
83939 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83940 
83941 #ifndef SQLITE_OMIT_VIRTUALTABLE
83942 /* Opcode: VNext P1 P2 * * *
83943 **
83944 ** Advance virtual table P1 to the next row in its result set and
83945 ** jump to instruction P2. Or, if the virtual table has reached
83946 ** the end of its result set, then fall through to the next instruction.
83947 */
83948 case OP_VNext: { /* jump */
83949  sqlite3_vtab *pVtab;
83950  const sqlite3_module *pModule;
83951  int res;
83952  VdbeCursor *pCur;
83953 
83954  res = 0;
83955  pCur = p->apCsr[pOp->p1];
83956  assert( pCur->eCurType==CURTYPE_VTAB );
83957  if( pCur->nullRow ){
83958  break;
83959  }
83960  pVtab = pCur->uc.pVCur->pVtab;
83961  pModule = pVtab->pModule;
83962  assert( pModule->xNext );
83963 
83964  /* Invoke the xNext() method of the module. There is no way for the
83965  ** underlying implementation to return an error if one occurs during
83966  ** xNext(). Instead, if an error occurs, true is returned (indicating that
83967  ** data is available) and the error code returned when xColumn or
83968  ** some other method is next invoked on the save virtual table cursor.
83969  */
83970  rc = pModule->xNext(pCur->uc.pVCur);
83971  sqlite3VtabImportErrmsg(p, pVtab);
83972  if( rc ) goto abort_due_to_error;
83973  res = pModule->xEof(pCur->uc.pVCur);
83974  VdbeBranchTaken(!res,2);
83975  if( !res ){
83976  /* If there is data, jump to P2 */
83977  goto jump_to_p2_and_check_for_interrupt;
83978  }
83979  goto check_for_interrupt;
83980 }
83981 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83982 
83983 #ifndef SQLITE_OMIT_VIRTUALTABLE
83984 /* Opcode: VRename P1 * * P4 *
83985 **
83986 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83987 ** This opcode invokes the corresponding xRename method. The value
83988 ** in register P1 is passed as the zName argument to the xRename method.
83989 */
83990 case OP_VRename: {
83991  sqlite3_vtab *pVtab;
83992  Mem *pName;
83993 
83994  pVtab = pOp->p4.pVtab->pVtab;
83995  pName = &aMem[pOp->p1];
83996  assert( pVtab->pModule->xRename );
83997  assert( memIsValid(pName) );
83998  assert( p->readOnly==0 );
83999  REGISTER_TRACE(pOp->p1, pName);
84000  assert( pName->flags & MEM_Str );
84001  testcase( pName->enc==SQLITE_UTF8 );
84002  testcase( pName->enc==SQLITE_UTF16BE );
84003  testcase( pName->enc==SQLITE_UTF16LE );
84004  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
84005  if( rc ) goto abort_due_to_error;
84006  rc = pVtab->pModule->xRename(pVtab, pName->z);
84007  sqlite3VtabImportErrmsg(p, pVtab);
84008  p->expired = 0;
84009  if( rc ) goto abort_due_to_error;
84010  break;
84011 }
84012 #endif
84013 
84014 #ifndef SQLITE_OMIT_VIRTUALTABLE
84015 /* Opcode: VUpdate P1 P2 P3 P4 P5
84016 ** Synopsis: data=r[P3@P2]
84017 **
84018 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
84019 ** This opcode invokes the corresponding xUpdate method. P2 values
84020 ** are contiguous memory cells starting at P3 to pass to the xUpdate
84021 ** invocation. The value in register (P3+P2-1) corresponds to the
84022 ** p2th element of the argv array passed to xUpdate.
84023 **
84024 ** The xUpdate method will do a DELETE or an INSERT or both.
84025 ** The argv[0] element (which corresponds to memory cell P3)
84026 ** is the rowid of a row to delete. If argv[0] is NULL then no
84027 ** deletion occurs. The argv[1] element is the rowid of the new
84028 ** row. This can be NULL to have the virtual table select the new
84029 ** rowid for itself. The subsequent elements in the array are
84030 ** the values of columns in the new row.
84031 **
84032 ** If P2==1 then no insert is performed. argv[0] is the rowid of
84033 ** a row to delete.
84034 **
84035 ** P1 is a boolean flag. If it is set to true and the xUpdate call
84036 ** is successful, then the value returned by sqlite3_last_insert_rowid()
84037 ** is set to the value of the rowid for the row just inserted.
84038 **
84039 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
84040 ** apply in the case of a constraint failure on an insert or update.
84041 */
84042 case OP_VUpdate: {
84043  sqlite3_vtab *pVtab;
84044  const sqlite3_module *pModule;
84045  int nArg;
84046  int i;
84047  sqlite_int64 rowid;
84048  Mem **apArg;
84049  Mem *pX;
84050 
84051  assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
84052  || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
84053  );
84054  assert( p->readOnly==0 );
84055  pVtab = pOp->p4.pVtab->pVtab;
84056  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
84057  rc = SQLITE_LOCKED;
84058  goto abort_due_to_error;
84059  }
84060  pModule = pVtab->pModule;
84061  nArg = pOp->p2;
84062  assert( pOp->p4type==P4_VTAB );
84063  if( ALWAYS(pModule->xUpdate) ){
84064  u8 vtabOnConflict = db->vtabOnConflict;
84065  apArg = p->apArg;
84066  pX = &aMem[pOp->p3];
84067  for(i=0; i<nArg; i++){
84068  assert( memIsValid(pX) );
84069  memAboutToChange(p, pX);
84070  apArg[i] = pX;
84071  pX++;
84072  }
84073  db->vtabOnConflict = pOp->p5;
84074  rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
84075  db->vtabOnConflict = vtabOnConflict;
84076  sqlite3VtabImportErrmsg(p, pVtab);
84077  if( rc==SQLITE_OK && pOp->p1 ){
84078  assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
84079  db->lastRowid = lastRowid = rowid;
84080  }
84081  if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
84082  if( pOp->p5==OE_Ignore ){
84083  rc = SQLITE_OK;
84084  }else{
84085  p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
84086  }
84087  }else{
84088  p->nChange++;
84089  }
84090  if( rc ) goto abort_due_to_error;
84091  }
84092  break;
84093 }
84094 #endif /* SQLITE_OMIT_VIRTUALTABLE */
84095 
84096 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84097 /* Opcode: Pagecount P1 P2 * * *
84098 **
84099 ** Write the current number of pages in database P1 to memory cell P2.
84100 */
84101 case OP_Pagecount: { /* out2 */
84102  pOut = out2Prerelease(p, pOp);
84103  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
84104  break;
84105 }
84106 #endif
84107 
84108 
84109 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84110 /* Opcode: MaxPgcnt P1 P2 P3 * *
84111 **
84112 ** Try to set the maximum page count for database P1 to the value in P3.
84113 ** Do not let the maximum page count fall below the current page count and
84114 ** do not change the maximum page count value if P3==0.
84115 **
84116 ** Store the maximum page count after the change in register P2.
84117 */
84118 case OP_MaxPgcnt: { /* out2 */
84119  unsigned int newMax;
84120  Btree *pBt;
84121 
84122  pOut = out2Prerelease(p, pOp);
84123  pBt = db->aDb[pOp->p1].pBt;
84124  newMax = 0;
84125  if( pOp->p3 ){
84126  newMax = sqlite3BtreeLastPage(pBt);
84127  if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
84128  }
84129  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
84130  break;
84131 }
84132 #endif
84133 
84134 
84135 /* Opcode: Init P1 P2 * P4 *
84136 ** Synopsis: Start at P2
84137 **
84138 ** Programs contain a single instance of this opcode as the very first
84139 ** opcode.
84140 **
84141 ** If tracing is enabled (by the sqlite3_trace()) interface, then
84142 ** the UTF-8 string contained in P4 is emitted on the trace callback.
84143 ** Or if P4 is blank, use the string returned by sqlite3_sql().
84144 **
84145 ** If P2 is not zero, jump to instruction P2.
84146 **
84147 ** Increment the value of P1 so that OP_Once opcodes will jump the
84148 ** first time they are evaluated for this run.
84149 */
84150 case OP_Init: { /* jump */
84151  char *zTrace;
84152  int i;
84153 
84154  /* If the P4 argument is not NULL, then it must be an SQL comment string.
84155  ** The "--" string is broken up to prevent false-positives with srcck1.c.
84156  **
84157  ** This assert() provides evidence for:
84158  ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
84159  ** would have been returned by the legacy sqlite3_trace() interface by
84160  ** using the X argument when X begins with "--" and invoking
84161  ** sqlite3_expanded_sql(P) otherwise.
84162  */
84163  assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
84164  assert( pOp==p->aOp ); /* Always instruction 0 */
84165 
84166 #ifndef SQLITE_OMIT_TRACE
84167  if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
84168  && !p->doingRerun
84169  && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
84170  ){
84171 #ifndef SQLITE_OMIT_DEPRECATED
84172  if( db->mTrace & SQLITE_TRACE_LEGACY ){
84173  void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
84174  char *z = sqlite3VdbeExpandSql(p, zTrace);
84175  x(db->pTraceArg, z);
84176  sqlite3_free(z);
84177  }else
84178 #endif
84179  {
84180  (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
84181  }
84182  }
84183 #ifdef SQLITE_USE_FCNTL_TRACE
84184  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
84185  if( zTrace ){
84186  int j;
84187  for(j=0; j<db->nDb; j++){
84188  if( DbMaskTest(p->btreeMask, j)==0 ) continue;
84189  sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
84190  }
84191  }
84192 #endif /* SQLITE_USE_FCNTL_TRACE */
84193 #ifdef SQLITE_DEBUG
84194  if( (db->flags & SQLITE_SqlTrace)!=0
84195  && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
84196  ){
84197  sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
84198  }
84199 #endif /* SQLITE_DEBUG */
84200 #endif /* SQLITE_OMIT_TRACE */
84201  assert( pOp->p2>0 );
84202  if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
84203  for(i=1; i<p->nOp; i++){
84204  if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
84205  }
84206  pOp->p1 = 0;
84207  }
84208  pOp->p1++;
84209  goto jump_to_p2;
84210 }
84211 
84212 #ifdef SQLITE_ENABLE_CURSOR_HINTS
84213 /* Opcode: CursorHint P1 * * P4 *
84214 **
84215 ** Provide a hint to cursor P1 that it only needs to return rows that
84216 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
84217 ** to values currently held in registers. TK_COLUMN terms in the P4
84218 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
84219 */
84220 case OP_CursorHint: {
84221  VdbeCursor *pC;
84222 
84223  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84224  assert( pOp->p4type==P4_EXPR );
84225  pC = p->apCsr[pOp->p1];
84226  if( pC ){
84227  assert( pC->eCurType==CURTYPE_BTREE );
84228  sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
84229  pOp->p4.pExpr, aMem);
84230  }
84231  break;
84232 }
84233 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
84234 
84235 /* Opcode: Noop * * * * *
84236 **
84237 ** Do nothing. This instruction is often useful as a jump
84238 ** destination.
84239 */
84240 /*
84241 ** The magic Explain opcode are only inserted when explain==2 (which
84242 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
84243 ** This opcode records information from the optimizer. It is the
84244 ** the same as a no-op. This opcodesnever appears in a real VM program.
84245 */
84246 default: { /* This is really OP_Noop and OP_Explain */
84247  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
84248  break;
84249 }
84250 
84251 /*****************************************************************************
84252 ** The cases of the switch statement above this line should all be indented
84253 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
84254 ** readability. From this point on down, the normal indentation rules are
84255 ** restored.
84256 *****************************************************************************/
84257  }
84258 
84259 #ifdef VDBE_PROFILE
84260  {
84261  u64 endTime = sqlite3Hwtime();
84262  if( endTime>start ) pOrigOp->cycles += endTime - start;
84263  pOrigOp->cnt++;
84264  }
84265 #endif
84266 
84267  /* The following code adds nothing to the actual functionality
84268  ** of the program. It is only here for testing and debugging.
84269  ** On the other hand, it does burn CPU cycles every time through
84270  ** the evaluator loop. So we can leave it out when NDEBUG is defined.
84271  */
84272 #ifndef NDEBUG
84273  assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
84274 
84275 #ifdef SQLITE_DEBUG
84276  if( db->flags & SQLITE_VdbeTrace ){
84277  u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
84278  if( rc!=0 ) printf("rc=%d\n",rc);
84279  if( opProperty & (OPFLG_OUT2) ){
84280  registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
84281  }
84282  if( opProperty & OPFLG_OUT3 ){
84283  registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
84284  }
84285  }
84286 #endif /* SQLITE_DEBUG */
84287 #endif /* NDEBUG */
84288  } /* The end of the for(;;) loop the loops through opcodes */
84289 
84290  /* If we reach this point, it means that execution is finished with
84291  ** an error of some kind.
84292  */
84293 abort_due_to_error:
84294  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
84295  assert( rc );
84296  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
84297  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84298  }
84299  p->rc = rc;
84300  sqlite3SystemError(db, rc);
84301  testcase( sqlite3GlobalConfig.xLog!=0 );
84302  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
84303  (int)(pOp - aOp), p->zSql, p->zErrMsg);
84304  sqlite3VdbeHalt(p);
84305  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
84306  rc = SQLITE_ERROR;
84307  if( resetSchemaOnFault>0 ){
84308  sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
84309  }
84310 
84311  /* This is the only way out of this procedure. We have to
84312  ** release the mutexes on btrees that were acquired at the
84313  ** top. */
84314 vdbe_return:
84315  db->lastRowid = lastRowid;
84316  testcase( nVmStep>0 );
84317  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
84318  sqlite3VdbeLeave(p);
84319  assert( rc!=SQLITE_OK || nExtraDelete==0
84320  || sqlite3_strlike("DELETE%",p->zSql,0)!=0
84321  );
84322  return rc;
84323 
84324  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
84325  ** is encountered.
84326  */
84327 too_big:
84328  sqlite3VdbeError(p, "string or blob too big");
84329  rc = SQLITE_TOOBIG;
84330  goto abort_due_to_error;
84331 
84332  /* Jump to here if a malloc() fails.
84333  */
84334 no_mem:
84335  sqlite3OomFault(db);
84336  sqlite3VdbeError(p, "out of memory");
84337  rc = SQLITE_NOMEM_BKPT;
84338  goto abort_due_to_error;
84339 
84340  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
84341  ** flag.
84342  */
84343 abort_due_to_interrupt:
84344  assert( db->u1.isInterrupted );
84345  rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
84346  p->rc = rc;
84347  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84348  goto abort_due_to_error;
84349 }
84350 
84351 
84352 /************** End of vdbe.c ************************************************/
84353 /************** Begin file vdbeblob.c ****************************************/
84354 /*
84355 ** 2007 May 1
84356 **
84357 ** The author disclaims copyright to this source code. In place of
84358 ** a legal notice, here is a blessing:
84359 **
84360 ** May you do good and not evil.
84361 ** May you find forgiveness for yourself and forgive others.
84362 ** May you share freely, never taking more than you give.
84363 **
84364 *************************************************************************
84365 **
84366 ** This file contains code used to implement incremental BLOB I/O.
84367 */
84368 
84369 /* #include "sqliteInt.h" */
84370 /* #include "vdbeInt.h" */
84371 
84372 #ifndef SQLITE_OMIT_INCRBLOB
84373 
84374 /*
84375 ** Valid sqlite3_blob* handles point to Incrblob structures.
84376 */
84377 typedef struct Incrblob Incrblob;
84378 struct Incrblob {
84379  int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
84380  int nByte; /* Size of open blob, in bytes */
84381  int iOffset; /* Byte offset of blob in cursor data */
84382  int iCol; /* Table column this handle is open on */
84383  BtCursor *pCsr; /* Cursor pointing at blob row */
84384  sqlite3_stmt *pStmt; /* Statement holding cursor open */
84385  sqlite3 *db; /* The associated database */
84386  char *zDb; /* Database name */
84387  Table *pTab; /* Table object */
84388 };
84389 
84390 
84391 /*
84392 ** This function is used by both blob_open() and blob_reopen(). It seeks
84393 ** the b-tree cursor associated with blob handle p to point to row iRow.
84394 ** If successful, SQLITE_OK is returned and subsequent calls to
84395 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
84396 **
84397 ** If an error occurs, or if the specified row does not exist or does not
84398 ** contain a value of type TEXT or BLOB in the column nominated when the
84399 ** blob handle was opened, then an error code is returned and *pzErr may
84400 ** be set to point to a buffer containing an error message. It is the
84401 ** responsibility of the caller to free the error message buffer using
84402 ** sqlite3DbFree().
84403 **
84404 ** If an error does occur, then the b-tree cursor is closed. All subsequent
84405 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
84406 ** immediately return SQLITE_ABORT.
84407 */
84408 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
84409  int rc; /* Error code */
84410  char *zErr = 0; /* Error message */
84411  Vdbe *v = (Vdbe *)p->pStmt;
84412 
84413  /* Set the value of the SQL statements only variable to integer iRow.
84414  ** This is done directly instead of using sqlite3_bind_int64() to avoid
84415  ** triggering asserts related to mutexes.
84416  */
84417  assert( v->aVar[0].flags&MEM_Int );
84418  v->aVar[0].u.i = iRow;
84419 
84420  rc = sqlite3_step(p->pStmt);
84421  if( rc==SQLITE_ROW ){
84422  VdbeCursor *pC = v->apCsr[0];
84423  u32 type = pC->aType[p->iCol];
84424  if( type<12 ){
84425  zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
84426  type==0?"null": type==7?"real": "integer"
84427  );
84428  rc = SQLITE_ERROR;
84429  sqlite3_finalize(p->pStmt);
84430  p->pStmt = 0;
84431  }else{
84432  p->iOffset = pC->aType[p->iCol + pC->nField];
84433  p->nByte = sqlite3VdbeSerialTypeLen(type);
84434  p->pCsr = pC->uc.pCursor;
84435  sqlite3BtreeIncrblobCursor(p->pCsr);
84436  }
84437  }
84438 
84439  if( rc==SQLITE_ROW ){
84440  rc = SQLITE_OK;
84441  }else if( p->pStmt ){
84442  rc = sqlite3_finalize(p->pStmt);
84443  p->pStmt = 0;
84444  if( rc==SQLITE_OK ){
84445  zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
84446  rc = SQLITE_ERROR;
84447  }else{
84448  zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
84449  }
84450  }
84451 
84452  assert( rc!=SQLITE_OK || zErr==0 );
84453  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
84454 
84455  *pzErr = zErr;
84456  return rc;
84457 }
84458 
84459 /*
84460 ** Open a blob handle.
84461 */
84462 SQLITE_API int sqlite3_blob_open(
84463  sqlite3* db, /* The database connection */
84464  const char *zDb, /* The attached database containing the blob */
84465  const char *zTable, /* The table containing the blob */
84466  const char *zColumn, /* The column containing the blob */
84467  sqlite_int64 iRow, /* The row containing the glob */
84468  int flags, /* True -> read/write access, false -> read-only */
84469  sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
84470 ){
84471  int nAttempt = 0;
84472  int iCol; /* Index of zColumn in row-record */
84473  int rc = SQLITE_OK;
84474  char *zErr = 0;
84475  Table *pTab;
84476  Parse *pParse = 0;
84477  Incrblob *pBlob = 0;
84478 
84479 #ifdef SQLITE_ENABLE_API_ARMOR
84480  if( ppBlob==0 ){
84481  return SQLITE_MISUSE_BKPT;
84482  }
84483 #endif
84484  *ppBlob = 0;
84485 #ifdef SQLITE_ENABLE_API_ARMOR
84486  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
84487  return SQLITE_MISUSE_BKPT;
84488  }
84489 #endif
84490  flags = !!flags; /* flags = (flags ? 1 : 0); */
84491 
84492  sqlite3_mutex_enter(db->mutex);
84493 
84494  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
84495  if( !pBlob ) goto blob_open_out;
84496  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
84497  if( !pParse ) goto blob_open_out;
84498 
84499  do {
84500  memset(pParse, 0, sizeof(Parse));
84501  pParse->db = db;
84502  sqlite3DbFree(db, zErr);
84503  zErr = 0;
84504 
84505  sqlite3BtreeEnterAll(db);
84506  pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
84507  if( pTab && IsVirtual(pTab) ){
84508  pTab = 0;
84509  sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
84510  }
84511  if( pTab && !HasRowid(pTab) ){
84512  pTab = 0;
84513  sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
84514  }
84515 #ifndef SQLITE_OMIT_VIEW
84516  if( pTab && pTab->pSelect ){
84517  pTab = 0;
84518  sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
84519  }
84520 #endif
84521  if( !pTab ){
84522  if( pParse->zErrMsg ){
84523  sqlite3DbFree(db, zErr);
84524  zErr = pParse->zErrMsg;
84525  pParse->zErrMsg = 0;
84526  }
84527  rc = SQLITE_ERROR;
84528  sqlite3BtreeLeaveAll(db);
84529  goto blob_open_out;
84530  }
84531  pBlob->pTab = pTab;
84532  pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
84533 
84534  /* Now search pTab for the exact column. */
84535  for(iCol=0; iCol<pTab->nCol; iCol++) {
84536  if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
84537  break;
84538  }
84539  }
84540  if( iCol==pTab->nCol ){
84541  sqlite3DbFree(db, zErr);
84542  zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
84543  rc = SQLITE_ERROR;
84544  sqlite3BtreeLeaveAll(db);
84545  goto blob_open_out;
84546  }
84547 
84548  /* If the value is being opened for writing, check that the
84549  ** column is not indexed, and that it is not part of a foreign key.
84550  ** It is against the rules to open a column to which either of these
84551  ** descriptions applies for writing. */
84552  if( flags ){
84553  const char *zFault = 0;
84554  Index *pIdx;
84555 #ifndef SQLITE_OMIT_FOREIGN_KEY
84556  if( db->flags&SQLITE_ForeignKeys ){
84557  /* Check that the column is not part of an FK child key definition. It
84558  ** is not necessary to check if it is part of a parent key, as parent
84559  ** key columns must be indexed. The check below will pick up this
84560  ** case. */
84561  FKey *pFKey;
84562  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
84563  int j;
84564  for(j=0; j<pFKey->nCol; j++){
84565  if( pFKey->aCol[j].iFrom==iCol ){
84566  zFault = "foreign key";
84567  }
84568  }
84569  }
84570  }
84571 #endif
84572  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84573  int j;
84574  for(j=0; j<pIdx->nKeyCol; j++){
84575  /* FIXME: Be smarter about indexes that use expressions */
84576  if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
84577  zFault = "indexed";
84578  }
84579  }
84580  }
84581  if( zFault ){
84582  sqlite3DbFree(db, zErr);
84583  zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
84584  rc = SQLITE_ERROR;
84585  sqlite3BtreeLeaveAll(db);
84586  goto blob_open_out;
84587  }
84588  }
84589 
84590  pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
84591  assert( pBlob->pStmt || db->mallocFailed );
84592  if( pBlob->pStmt ){
84593 
84594  /* This VDBE program seeks a btree cursor to the identified
84595  ** db/table/row entry. The reason for using a vdbe program instead
84596  ** of writing code to use the b-tree layer directly is that the
84597  ** vdbe program will take advantage of the various transaction,
84598  ** locking and error handling infrastructure built into the vdbe.
84599  **
84600  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
84601  ** Code external to the Vdbe then "borrows" the b-tree cursor and
84602  ** uses it to implement the blob_read(), blob_write() and
84603  ** blob_bytes() functions.
84604  **
84605  ** The sqlite3_blob_close() function finalizes the vdbe program,
84606  ** which closes the b-tree cursor and (possibly) commits the
84607  ** transaction.
84608  */
84609  static const int iLn = VDBE_OFFSET_LINENO(2);
84610  static const VdbeOpList openBlob[] = {
84611  {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
84612  {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
84613  {OP_Variable, 1, 1, 0}, /* 2: Move ?1 into reg[1] */
84614  {OP_NotExists, 0, 7, 1}, /* 3: Seek the cursor */
84615  {OP_Column, 0, 0, 1}, /* 4 */
84616  {OP_ResultRow, 1, 0, 0}, /* 5 */
84617  {OP_Goto, 0, 2, 0}, /* 6 */
84618  {OP_Close, 0, 0, 0}, /* 7 */
84619  {OP_Halt, 0, 0, 0}, /* 8 */
84620  };
84621  Vdbe *v = (Vdbe *)pBlob->pStmt;
84622  int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84623  VdbeOp *aOp;
84624 
84625  sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
84626  pTab->pSchema->schema_cookie,
84627  pTab->pSchema->iGeneration);
84628  sqlite3VdbeChangeP5(v, 1);
84629  aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
84630 
84631  /* Make sure a mutex is held on the table to be accessed */
84632  sqlite3VdbeUsesBtree(v, iDb);
84633 
84634  if( db->mallocFailed==0 ){
84635  assert( aOp!=0 );
84636  /* Configure the OP_TableLock instruction */
84637 #ifdef SQLITE_OMIT_SHARED_CACHE
84638  aOp[0].opcode = OP_Noop;
84639 #else
84640  aOp[0].p1 = iDb;
84641  aOp[0].p2 = pTab->tnum;
84642  aOp[0].p3 = flags;
84643  sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
84644  }
84645  if( db->mallocFailed==0 ){
84646 #endif
84647 
84648  /* Remove either the OP_OpenWrite or OpenRead. Set the P2
84649  ** parameter of the other to pTab->tnum. */
84650  if( flags ) aOp[1].opcode = OP_OpenWrite;
84651  aOp[1].p2 = pTab->tnum;
84652  aOp[1].p3 = iDb;
84653 
84654  /* Configure the number of columns. Configure the cursor to
84655  ** think that the table has one more column than it really
84656  ** does. An OP_Column to retrieve this imaginary column will
84657  ** always return an SQL NULL. This is useful because it means
84658  ** we can invoke OP_Column to fill in the vdbe cursors type
84659  ** and offset cache without causing any IO.
84660  */
84661  aOp[1].p4type = P4_INT32;
84662  aOp[1].p4.i = pTab->nCol+1;
84663  aOp[4].p2 = pTab->nCol;
84664 
84665  pParse->nVar = 1;
84666  pParse->nMem = 1;
84667  pParse->nTab = 1;
84668  sqlite3VdbeMakeReady(v, pParse);
84669  }
84670  }
84671 
84672  pBlob->flags = flags;
84673  pBlob->iCol = iCol;
84674  pBlob->db = db;
84675  sqlite3BtreeLeaveAll(db);
84676  if( db->mallocFailed ){
84677  goto blob_open_out;
84678  }
84679  sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
84680  rc = blobSeekToRow(pBlob, iRow, &zErr);
84681  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
84682 
84683 blob_open_out:
84684  if( rc==SQLITE_OK && db->mallocFailed==0 ){
84685  *ppBlob = (sqlite3_blob *)pBlob;
84686  }else{
84687  if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
84688  sqlite3DbFree(db, pBlob);
84689  }
84690  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84691  sqlite3DbFree(db, zErr);
84692  sqlite3ParserReset(pParse);
84693  sqlite3StackFree(db, pParse);
84694  rc = sqlite3ApiExit(db, rc);
84695  sqlite3_mutex_leave(db->mutex);
84696  return rc;
84697 }
84698 
84699 /*
84700 ** Close a blob handle that was previously created using
84701 ** sqlite3_blob_open().
84702 */
84703 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
84704  Incrblob *p = (Incrblob *)pBlob;
84705  int rc;
84706  sqlite3 *db;
84707 
84708  if( p ){
84709  db = p->db;
84710  sqlite3_mutex_enter(db->mutex);
84711  rc = sqlite3_finalize(p->pStmt);
84712  sqlite3DbFree(db, p);
84713  sqlite3_mutex_leave(db->mutex);
84714  }else{
84715  rc = SQLITE_OK;
84716  }
84717  return rc;
84718 }
84719 
84720 /*
84721 ** Perform a read or write operation on a blob
84722 */
84723 static int blobReadWrite(
84724  sqlite3_blob *pBlob,
84725  void *z,
84726  int n,
84727  int iOffset,
84728  int (*xCall)(BtCursor*, u32, u32, void*)
84729 ){
84730  int rc;
84731  Incrblob *p = (Incrblob *)pBlob;
84732  Vdbe *v;
84733  sqlite3 *db;
84734 
84735  if( p==0 ) return SQLITE_MISUSE_BKPT;
84736  db = p->db;
84737  sqlite3_mutex_enter(db->mutex);
84738  v = (Vdbe*)p->pStmt;
84739 
84740  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
84741  /* Request is out of range. Return a transient error. */
84742  rc = SQLITE_ERROR;
84743  }else if( v==0 ){
84744  /* If there is no statement handle, then the blob-handle has
84745  ** already been invalidated. Return SQLITE_ABORT in this case.
84746  */
84747  rc = SQLITE_ABORT;
84748  }else{
84749  /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
84750  ** returned, clean-up the statement handle.
84751  */
84752  assert( db == v->db );
84753  sqlite3BtreeEnterCursor(p->pCsr);
84754 
84755 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
84756  if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
84757  /* If a pre-update hook is registered and this is a write cursor,
84758  ** invoke it here.
84759  **
84760  ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
84761  ** operation should really be an SQLITE_UPDATE. This is probably
84762  ** incorrect, but is convenient because at this point the new.* values
84763  ** are not easily obtainable. And for the sessions module, an
84764  ** SQLITE_UPDATE where the PK columns do not change is handled in the
84765  ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
84766  ** slightly more efficient). Since you cannot write to a PK column
84767  ** using the incremental-blob API, this works. For the sessions module
84768  ** anyhow.
84769  */
84770  sqlite3_int64 iKey;
84771  iKey = sqlite3BtreeIntegerKey(p->pCsr);
84772  sqlite3VdbePreUpdateHook(
84773  v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
84774  );
84775  }
84776 #endif
84777 
84778  rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
84779  sqlite3BtreeLeaveCursor(p->pCsr);
84780  if( rc==SQLITE_ABORT ){
84781  sqlite3VdbeFinalize(v);
84782  p->pStmt = 0;
84783  }else{
84784  v->rc = rc;
84785  }
84786  }
84787  sqlite3Error(db, rc);
84788  rc = sqlite3ApiExit(db, rc);
84789  sqlite3_mutex_leave(db->mutex);
84790  return rc;
84791 }
84792 
84793 /*
84794 ** Read data from a blob handle.
84795 */
84796 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
84797  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
84798 }
84799 
84800 /*
84801 ** Write data to a blob handle.
84802 */
84803 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
84804  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
84805 }
84806 
84807 /*
84808 ** Query a blob handle for the size of the data.
84809 **
84810 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
84811 ** so no mutex is required for access.
84812 */
84813 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
84814  Incrblob *p = (Incrblob *)pBlob;
84815  return (p && p->pStmt) ? p->nByte : 0;
84816 }
84817 
84818 /*
84819 ** Move an existing blob handle to point to a different row of the same
84820 ** database table.
84821 **
84822 ** If an error occurs, or if the specified row does not exist or does not
84823 ** contain a blob or text value, then an error code is returned and the
84824 ** database handle error code and message set. If this happens, then all
84825 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
84826 ** immediately return SQLITE_ABORT.
84827 */
84828 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
84829  int rc;
84830  Incrblob *p = (Incrblob *)pBlob;
84831  sqlite3 *db;
84832 
84833  if( p==0 ) return SQLITE_MISUSE_BKPT;
84834  db = p->db;
84835  sqlite3_mutex_enter(db->mutex);
84836 
84837  if( p->pStmt==0 ){
84838  /* If there is no statement handle, then the blob-handle has
84839  ** already been invalidated. Return SQLITE_ABORT in this case.
84840  */
84841  rc = SQLITE_ABORT;
84842  }else{
84843  char *zErr;
84844  rc = blobSeekToRow(p, iRow, &zErr);
84845  if( rc!=SQLITE_OK ){
84846  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84847  sqlite3DbFree(db, zErr);
84848  }
84849  assert( rc!=SQLITE_SCHEMA );
84850  }
84851 
84852  rc = sqlite3ApiExit(db, rc);
84853  assert( rc==SQLITE_OK || p->pStmt==0 );
84854  sqlite3_mutex_leave(db->mutex);
84855  return rc;
84856 }
84857 
84858 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
84859 
84860 /************** End of vdbeblob.c ********************************************/
84861 /************** Begin file vdbesort.c ****************************************/
84862 /*
84863 ** 2011-07-09
84864 **
84865 ** The author disclaims copyright to this source code. In place of
84866 ** a legal notice, here is a blessing:
84867 **
84868 ** May you do good and not evil.
84869 ** May you find forgiveness for yourself and forgive others.
84870 ** May you share freely, never taking more than you give.
84871 **
84872 *************************************************************************
84873 ** This file contains code for the VdbeSorter object, used in concert with
84874 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
84875 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
84876 ** using indexes and without LIMIT clauses.
84877 **
84878 ** The VdbeSorter object implements a multi-threaded external merge sort
84879 ** algorithm that is efficient even if the number of elements being sorted
84880 ** exceeds the available memory.
84881 **
84882 ** Here is the (internal, non-API) interface between this module and the
84883 ** rest of the SQLite system:
84884 **
84885 ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
84886 **
84887 ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
84888 ** object. The row is a binary blob in the
84889 ** OP_MakeRecord format that contains both
84890 ** the ORDER BY key columns and result columns
84891 ** in the case of a SELECT w/ ORDER BY, or
84892 ** the complete record for an index entry
84893 ** in the case of a CREATE INDEX.
84894 **
84895 ** sqlite3VdbeSorterRewind() Sort all content previously added.
84896 ** Position the read cursor on the
84897 ** first sorted element.
84898 **
84899 ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
84900 ** element.
84901 **
84902 ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
84903 ** row currently under the read cursor.
84904 **
84905 ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
84906 ** currently under the read cursor against
84907 ** another binary blob X and report if
84908 ** X is strictly less than the read cursor.
84909 ** Used to enforce uniqueness in a
84910 ** CREATE UNIQUE INDEX statement.
84911 **
84912 ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
84913 ** all resources.
84914 **
84915 ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
84916 ** is like Close() followed by Init() only
84917 ** much faster.
84918 **
84919 ** The interfaces above must be called in a particular order. Write() can
84920 ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
84921 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
84922 **
84923 ** Init()
84924 ** for each record: Write()
84925 ** Rewind()
84926 ** Rowkey()/Compare()
84927 ** Next()
84928 ** Close()
84929 **
84930 ** Algorithm:
84931 **
84932 ** Records passed to the sorter via calls to Write() are initially held
84933 ** unsorted in main memory. Assuming the amount of memory used never exceeds
84934 ** a threshold, when Rewind() is called the set of records is sorted using
84935 ** an in-memory merge sort. In this case, no temporary files are required
84936 ** and subsequent calls to Rowkey(), Next() and Compare() read records
84937 ** directly from main memory.
84938 **
84939 ** If the amount of space used to store records in main memory exceeds the
84940 ** threshold, then the set of records currently in memory are sorted and
84941 ** written to a temporary file in "Packed Memory Array" (PMA) format.
84942 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
84943 ** of PMAs may be created by merging existing PMAs together - for example
84944 ** merging two or more level-0 PMAs together creates a level-1 PMA.
84945 **
84946 ** The threshold for the amount of main memory to use before flushing
84947 ** records to a PMA is roughly the same as the limit configured for the
84948 ** page-cache of the main database. Specifically, the threshold is set to
84949 ** the value returned by "PRAGMA main.page_size" multipled by
84950 ** that returned by "PRAGMA main.cache_size", in bytes.
84951 **
84952 ** If the sorter is running in single-threaded mode, then all PMAs generated
84953 ** are appended to a single temporary file. Or, if the sorter is running in
84954 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
84955 ** N is the configured number of worker threads. In this case, instead of
84956 ** sorting the records and writing the PMA to a temporary file itself, the
84957 ** calling thread usually launches a worker thread to do so. Except, if
84958 ** there are already N worker threads running, the main thread does the work
84959 ** itself.
84960 **
84961 ** The sorter is running in multi-threaded mode if (a) the library was built
84962 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
84963 ** than zero, and (b) worker threads have been enabled at runtime by calling
84964 ** "PRAGMA threads=N" with some value of N greater than 0.
84965 **
84966 ** When Rewind() is called, any data remaining in memory is flushed to a
84967 ** final PMA. So at this point the data is stored in some number of sorted
84968 ** PMAs within temporary files on disk.
84969 **
84970 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
84971 ** sorter is running in single-threaded mode, then these PMAs are merged
84972 ** incrementally as keys are retreived from the sorter by the VDBE. The
84973 ** MergeEngine object, described in further detail below, performs this
84974 ** merge.
84975 **
84976 ** Or, if running in multi-threaded mode, then a background thread is
84977 ** launched to merge the existing PMAs. Once the background thread has
84978 ** merged T bytes of data into a single sorted PMA, the main thread
84979 ** begins reading keys from that PMA while the background thread proceeds
84980 ** with merging the next T bytes of data. And so on.
84981 **
84982 ** Parameter T is set to half the value of the memory threshold used
84983 ** by Write() above to determine when to create a new PMA.
84984 **
84985 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
84986 ** Rewind() is called, then a hierarchy of incremental-merges is used.
84987 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
84988 ** disk are merged together. Then T bytes of data from the second set, and
84989 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
84990 ** PMAs at a time. This done is to improve locality.
84991 **
84992 ** If running in multi-threaded mode and there are more than
84993 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
84994 ** than one background thread may be created. Specifically, there may be
84995 ** one background thread for each temporary file on disk, and one background
84996 ** thread to merge the output of each of the others to a single PMA for
84997 ** the main thread to read from.
84998 */
84999 /* #include "sqliteInt.h" */
85000 /* #include "vdbeInt.h" */
85001 
85002 /*
85003 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
85004 ** messages to stderr that may be helpful in understanding the performance
85005 ** characteristics of the sorter in multi-threaded mode.
85006 */
85007 #if 0
85008 # define SQLITE_DEBUG_SORTER_THREADS 1
85009 #endif
85010 
85011 /*
85012 ** Hard-coded maximum amount of data to accumulate in memory before flushing
85013 ** to a level 0 PMA. The purpose of this limit is to prevent various integer
85014 ** overflows. 512MiB.
85015 */
85016 #define SQLITE_MAX_PMASZ (1<<29)
85017 
85018 /*
85019 ** Private objects used by the sorter
85020 */
85021 typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
85022 typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
85023 typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
85024 typedef struct SorterRecord SorterRecord; /* A record being sorted */
85025 typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
85026 typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
85027 typedef struct SorterList SorterList; /* In-memory list of records */
85028 typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
85029 
85030 /*
85031 ** A container for a temp file handle and the current amount of data
85032 ** stored in the file.
85033 */
85034 struct SorterFile {
85035  sqlite3_file *pFd; /* File handle */
85036  i64 iEof; /* Bytes of data stored in pFd */
85037 };
85038 
85039 /*
85040 ** An in-memory list of objects to be sorted.
85041 **
85042 ** If aMemory==0 then each object is allocated separately and the objects
85043 ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
85044 ** are stored in the aMemory[] bulk memory, one right after the other, and
85045 ** are connected using SorterRecord.u.iNext.
85046 */
85047 struct SorterList {
85048  SorterRecord *pList; /* Linked list of records */
85049  u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
85050  int szPMA; /* Size of pList as PMA in bytes */
85051 };
85052 
85053 /*
85054 ** The MergeEngine object is used to combine two or more smaller PMAs into
85055 ** one big PMA using a merge operation. Separate PMAs all need to be
85056 ** combined into one big PMA in order to be able to step through the sorted
85057 ** records in order.
85058 **
85059 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
85060 ** merged. An aReadr[] object either points to a valid key or else is at EOF.
85061 ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
85062 ** For the purposes of the paragraphs below, we assume that the array is
85063 ** actually N elements in size, where N is the smallest power of 2 greater
85064 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
85065 ** are treated as if they are empty (always at EOF).
85066 **
85067 ** The aTree[] array is also N elements in size. The value of N is stored in
85068 ** the MergeEngine.nTree variable.
85069 **
85070 ** The final (N/2) elements of aTree[] contain the results of comparing
85071 ** pairs of PMA keys together. Element i contains the result of
85072 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
85073 ** aTree element is set to the index of it.
85074 **
85075 ** For the purposes of this comparison, EOF is considered greater than any
85076 ** other key value. If the keys are equal (only possible with two EOF
85077 ** values), it doesn't matter which index is stored.
85078 **
85079 ** The (N/4) elements of aTree[] that precede the final (N/2) described
85080 ** above contains the index of the smallest of each block of 4 PmaReaders
85081 ** And so on. So that aTree[1] contains the index of the PmaReader that
85082 ** currently points to the smallest key value. aTree[0] is unused.
85083 **
85084 ** Example:
85085 **
85086 ** aReadr[0] -> Banana
85087 ** aReadr[1] -> Feijoa
85088 ** aReadr[2] -> Elderberry
85089 ** aReadr[3] -> Currant
85090 ** aReadr[4] -> Grapefruit
85091 ** aReadr[5] -> Apple
85092 ** aReadr[6] -> Durian
85093 ** aReadr[7] -> EOF
85094 **
85095 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
85096 **
85097 ** The current element is "Apple" (the value of the key indicated by
85098 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
85099 ** be advanced to the next key in its segment. Say the next key is
85100 ** "Eggplant":
85101 **
85102 ** aReadr[5] -> Eggplant
85103 **
85104 ** The contents of aTree[] are updated first by comparing the new PmaReader
85105 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
85106 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
85107 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
85108 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
85109 ** so the value written into element 1 of the array is 0. As follows:
85110 **
85111 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
85112 **
85113 ** In other words, each time we advance to the next sorter element, log2(N)
85114 ** key comparison operations are required, where N is the number of segments
85115 ** being merged (rounded up to the next power of 2).
85116 */
85117 struct MergeEngine {
85118  int nTree; /* Used size of aTree/aReadr (power of 2) */
85119  SortSubtask *pTask; /* Used by this thread only */
85120  int *aTree; /* Current state of incremental merge */
85121  PmaReader *aReadr; /* Array of PmaReaders to merge data from */
85122 };
85123 
85124 /*
85125 ** This object represents a single thread of control in a sort operation.
85126 ** Exactly VdbeSorter.nTask instances of this object are allocated
85127 ** as part of each VdbeSorter object. Instances are never allocated any
85128 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
85129 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
85130 ** single-threaded operation, there is exactly one instance of this object
85131 ** and for multi-threaded operation there are two or more instances.
85132 **
85133 ** Essentially, this structure contains all those fields of the VdbeSorter
85134 ** structure for which each thread requires a separate instance. For example,
85135 ** each thread requries its own UnpackedRecord object to unpack records in
85136 ** as part of comparison operations.
85137 **
85138 ** Before a background thread is launched, variable bDone is set to 0. Then,
85139 ** right before it exits, the thread itself sets bDone to 1. This is used for
85140 ** two purposes:
85141 **
85142 ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
85143 ** attempt to select a SortSubtask for which there is not already an
85144 ** active background thread (since doing so causes the main thread
85145 ** to block until it finishes).
85146 **
85147 ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
85148 ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
85149 ** block provoke debugging output.
85150 **
85151 ** In both cases, the effects of the main thread seeing (bDone==0) even
85152 ** after the thread has finished are not dire. So we don't worry about
85153 ** memory barriers and such here.
85154 */
85155 typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
85156 struct SortSubtask {
85157  SQLiteThread *pThread; /* Background thread, if any */
85158  int bDone; /* Set if thread is finished but not joined */
85159  VdbeSorter *pSorter; /* Sorter that owns this sub-task */
85160  UnpackedRecord *pUnpacked; /* Space to unpack a record */
85161  SorterList list; /* List for thread to write to a PMA */
85162  int nPMA; /* Number of PMAs currently in file */
85163  SorterCompare xCompare; /* Compare function to use */
85164  SorterFile file; /* Temp file for level-0 PMAs */
85165  SorterFile file2; /* Space for other PMAs */
85166 };
85167 
85168 
85169 /*
85170 ** Main sorter structure. A single instance of this is allocated for each
85171 ** sorter cursor created by the VDBE.
85172 **
85173 ** mxKeysize:
85174 ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
85175 ** this variable is updated so as to be set to the size on disk of the
85176 ** largest record in the sorter.
85177 */
85178 struct VdbeSorter {
85179  int mnPmaSize; /* Minimum PMA size, in bytes */
85180  int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
85181  int mxKeysize; /* Largest serialized key seen so far */
85182  int pgsz; /* Main database page size */
85183  PmaReader *pReader; /* Readr data from here after Rewind() */
85184  MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
85185  sqlite3 *db; /* Database connection */
85186  KeyInfo *pKeyInfo; /* How to compare records */
85187  UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
85188  SorterList list; /* List of in-memory records */
85189  int iMemory; /* Offset of free space in list.aMemory */
85190  int nMemory; /* Size of list.aMemory allocation in bytes */
85191  u8 bUsePMA; /* True if one or more PMAs created */
85192  u8 bUseThreads; /* True to use background threads */
85193  u8 iPrev; /* Previous thread used to flush PMA */
85194  u8 nTask; /* Size of aTask[] array */
85195  u8 typeMask;
85196  SortSubtask aTask[1]; /* One or more subtasks */
85197 };
85198 
85199 #define SORTER_TYPE_INTEGER 0x01
85200 #define SORTER_TYPE_TEXT 0x02
85201 
85202 /*
85203 ** An instance of the following object is used to read records out of a
85204 ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
85205 ** aKey might point into aMap or into aBuffer. If neither of those locations
85206 ** contain a contiguous representation of the key, then aAlloc is allocated
85207 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
85208 **
85209 ** pFd==0 at EOF.
85210 */
85211 struct PmaReader {
85212  i64 iReadOff; /* Current read offset */
85213  i64 iEof; /* 1 byte past EOF for this PmaReader */
85214  int nAlloc; /* Bytes of space at aAlloc */
85215  int nKey; /* Number of bytes in key */
85216  sqlite3_file *pFd; /* File handle we are reading from */
85217  u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
85218  u8 *aKey; /* Pointer to current key */
85219  u8 *aBuffer; /* Current read buffer */
85220  int nBuffer; /* Size of read buffer in bytes */
85221  u8 *aMap; /* Pointer to mapping of entire file */
85222  IncrMerger *pIncr; /* Incremental merger */
85223 };
85224 
85225 /*
85226 ** Normally, a PmaReader object iterates through an existing PMA stored
85227 ** within a temp file. However, if the PmaReader.pIncr variable points to
85228 ** an object of the following type, it may be used to iterate/merge through
85229 ** multiple PMAs simultaneously.
85230 **
85231 ** There are two types of IncrMerger object - single (bUseThread==0) and
85232 ** multi-threaded (bUseThread==1).
85233 **
85234 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
85235 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
85236 ** size. When the IncrMerger is initialized, it reads enough data from
85237 ** pMerger to populate aFile[0]. It then sets variables within the
85238 ** corresponding PmaReader object to read from that file and kicks off
85239 ** a background thread to populate aFile[1] with the next mxSz bytes of
85240 ** sorted record data from pMerger.
85241 **
85242 ** When the PmaReader reaches the end of aFile[0], it blocks until the
85243 ** background thread has finished populating aFile[1]. It then exchanges
85244 ** the contents of the aFile[0] and aFile[1] variables within this structure,
85245 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
85246 ** another background thread to populate the new aFile[1]. And so on, until
85247 ** the contents of pMerger are exhausted.
85248 **
85249 ** A single-threaded IncrMerger does not open any temporary files of its
85250 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
85251 ** at offset iStartOff of file pTask->file2. And instead of using a
85252 ** background thread to prepare data for the PmaReader, with a single
85253 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
85254 ** keys from pMerger by the calling thread whenever the PmaReader runs out
85255 ** of data.
85256 */
85257 struct IncrMerger {
85258  SortSubtask *pTask; /* Task that owns this merger */
85259  MergeEngine *pMerger; /* Merge engine thread reads data from */
85260  i64 iStartOff; /* Offset to start writing file at */
85261  int mxSz; /* Maximum bytes of data to store */
85262  int bEof; /* Set to true when merge is finished */
85263  int bUseThread; /* True to use a bg thread for this object */
85264  SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
85265 };
85266 
85267 /*
85268 ** An instance of this object is used for writing a PMA.
85269 **
85270 ** The PMA is written one record at a time. Each record is of an arbitrary
85271 ** size. But I/O is more efficient if it occurs in page-sized blocks where
85272 ** each block is aligned on a page boundary. This object caches writes to
85273 ** the PMA so that aligned, page-size blocks are written.
85274 */
85275 struct PmaWriter {
85276  int eFWErr; /* Non-zero if in an error state */
85277  u8 *aBuffer; /* Pointer to write buffer */
85278  int nBuffer; /* Size of write buffer in bytes */
85279  int iBufStart; /* First byte of buffer to write */
85280  int iBufEnd; /* Last byte of buffer to write */
85281  i64 iWriteOff; /* Offset of start of buffer in file */
85282  sqlite3_file *pFd; /* File handle to write to */
85283 };
85284 
85285 /*
85286 ** This object is the header on a single record while that record is being
85287 ** held in memory and prior to being written out as part of a PMA.
85288 **
85289 ** How the linked list is connected depends on how memory is being managed
85290 ** by this module. If using a separate allocation for each in-memory record
85291 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
85292 ** SorterRecord.u.pNext pointers.
85293 **
85294 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
85295 ** then while records are being accumulated the list is linked using the
85296 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
85297 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
85298 ** has finished passing records to the sorter, or when the in-memory buffer
85299 ** is full, the list is sorted. As part of the sorting process, it is
85300 ** converted to use the SorterRecord.u.pNext pointers. See function
85301 ** vdbeSorterSort() for details.
85302 */
85303 struct SorterRecord {
85304  int nVal; /* Size of the record in bytes */
85305  union {
85306  SorterRecord *pNext; /* Pointer to next record in list */
85307  int iNext; /* Offset within aMemory of next record */
85308  } u;
85309  /* The data for the record immediately follows this header */
85310 };
85311 
85312 /* Return a pointer to the buffer containing the record data for SorterRecord
85313 ** object p. Should be used as if:
85314 **
85315 ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
85316 */
85317 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
85318 
85319 
85320 /* Maximum number of PMAs that a single MergeEngine can merge */
85321 #define SORTER_MAX_MERGE_COUNT 16
85322 
85323 static int vdbeIncrSwap(IncrMerger*);
85324 static void vdbeIncrFree(IncrMerger *);
85325 
85326 /*
85327 ** Free all memory belonging to the PmaReader object passed as the
85328 ** argument. All structure fields are set to zero before returning.
85329 */
85330 static void vdbePmaReaderClear(PmaReader *pReadr){
85331  sqlite3_free(pReadr->aAlloc);
85332  sqlite3_free(pReadr->aBuffer);
85333  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85334  vdbeIncrFree(pReadr->pIncr);
85335  memset(pReadr, 0, sizeof(PmaReader));
85336 }
85337 
85338 /*
85339 ** Read the next nByte bytes of data from the PMA p.
85340 ** If successful, set *ppOut to point to a buffer containing the data
85341 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
85342 ** error code.
85343 **
85344 ** The buffer returned in *ppOut is only valid until the
85345 ** next call to this function.
85346 */
85347 static int vdbePmaReadBlob(
85348  PmaReader *p, /* PmaReader from which to take the blob */
85349  int nByte, /* Bytes of data to read */
85350  u8 **ppOut /* OUT: Pointer to buffer containing data */
85351 ){
85352  int iBuf; /* Offset within buffer to read from */
85353  int nAvail; /* Bytes of data available in buffer */
85354 
85355  if( p->aMap ){
85356  *ppOut = &p->aMap[p->iReadOff];
85357  p->iReadOff += nByte;
85358  return SQLITE_OK;
85359  }
85360 
85361  assert( p->aBuffer );
85362 
85363  /* If there is no more data to be read from the buffer, read the next
85364  ** p->nBuffer bytes of data from the file into it. Or, if there are less
85365  ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
85366  iBuf = p->iReadOff % p->nBuffer;
85367  if( iBuf==0 ){
85368  int nRead; /* Bytes to read from disk */
85369  int rc; /* sqlite3OsRead() return code */
85370 
85371  /* Determine how many bytes of data to read. */
85372  if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
85373  nRead = p->nBuffer;
85374  }else{
85375  nRead = (int)(p->iEof - p->iReadOff);
85376  }
85377  assert( nRead>0 );
85378 
85379  /* Readr data from the file. Return early if an error occurs. */
85380  rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
85381  assert( rc!=SQLITE_IOERR_SHORT_READ );
85382  if( rc!=SQLITE_OK ) return rc;
85383  }
85384  nAvail = p->nBuffer - iBuf;
85385 
85386  if( nByte<=nAvail ){
85387  /* The requested data is available in the in-memory buffer. In this
85388  ** case there is no need to make a copy of the data, just return a
85389  ** pointer into the buffer to the caller. */
85390  *ppOut = &p->aBuffer[iBuf];
85391  p->iReadOff += nByte;
85392  }else{
85393  /* The requested data is not all available in the in-memory buffer.
85394  ** In this case, allocate space at p->aAlloc[] to copy the requested
85395  ** range into. Then return a copy of pointer p->aAlloc to the caller. */
85396  int nRem; /* Bytes remaining to copy */
85397 
85398  /* Extend the p->aAlloc[] allocation if required. */
85399  if( p->nAlloc<nByte ){
85400  u8 *aNew;
85401  int nNew = MAX(128, p->nAlloc*2);
85402  while( nByte>nNew ) nNew = nNew*2;
85403  aNew = sqlite3Realloc(p->aAlloc, nNew);
85404  if( !aNew ) return SQLITE_NOMEM_BKPT;
85405  p->nAlloc = nNew;
85406  p->aAlloc = aNew;
85407  }
85408 
85409  /* Copy as much data as is available in the buffer into the start of
85410  ** p->aAlloc[]. */
85411  memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
85412  p->iReadOff += nAvail;
85413  nRem = nByte - nAvail;
85414 
85415  /* The following loop copies up to p->nBuffer bytes per iteration into
85416  ** the p->aAlloc[] buffer. */
85417  while( nRem>0 ){
85418  int rc; /* vdbePmaReadBlob() return code */
85419  int nCopy; /* Number of bytes to copy */
85420  u8 *aNext; /* Pointer to buffer to copy data from */
85421 
85422  nCopy = nRem;
85423  if( nRem>p->nBuffer ) nCopy = p->nBuffer;
85424  rc = vdbePmaReadBlob(p, nCopy, &aNext);
85425  if( rc!=SQLITE_OK ) return rc;
85426  assert( aNext!=p->aAlloc );
85427  memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
85428  nRem -= nCopy;
85429  }
85430 
85431  *ppOut = p->aAlloc;
85432  }
85433 
85434  return SQLITE_OK;
85435 }
85436 
85437 /*
85438 ** Read a varint from the stream of data accessed by p. Set *pnOut to
85439 ** the value read.
85440 */
85441 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
85442  int iBuf;
85443 
85444  if( p->aMap ){
85445  p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
85446  }else{
85447  iBuf = p->iReadOff % p->nBuffer;
85448  if( iBuf && (p->nBuffer-iBuf)>=9 ){
85449  p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
85450  }else{
85451  u8 aVarint[16], *a;
85452  int i = 0, rc;
85453  do{
85454  rc = vdbePmaReadBlob(p, 1, &a);
85455  if( rc ) return rc;
85456  aVarint[(i++)&0xf] = a[0];
85457  }while( (a[0]&0x80)!=0 );
85458  sqlite3GetVarint(aVarint, pnOut);
85459  }
85460  }
85461 
85462  return SQLITE_OK;
85463 }
85464 
85465 /*
85466 ** Attempt to memory map file pFile. If successful, set *pp to point to the
85467 ** new mapping and return SQLITE_OK. If the mapping is not attempted
85468 ** (because the file is too large or the VFS layer is configured not to use
85469 ** mmap), return SQLITE_OK and set *pp to NULL.
85470 **
85471 ** Or, if an error occurs, return an SQLite error code. The final value of
85472 ** *pp is undefined in this case.
85473 */
85474 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
85475  int rc = SQLITE_OK;
85476  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
85477  sqlite3_file *pFd = pFile->pFd;
85478  if( pFd->pMethods->iVersion>=3 ){
85479  rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
85480  testcase( rc!=SQLITE_OK );
85481  }
85482  }
85483  return rc;
85484 }
85485 
85486 /*
85487 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
85488 ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
85489 ** if successful, or an SQLite error code if an error occurs.
85490 */
85491 static int vdbePmaReaderSeek(
85492  SortSubtask *pTask, /* Task context */
85493  PmaReader *pReadr, /* Reader whose cursor is to be moved */
85494  SorterFile *pFile, /* Sorter file to read from */
85495  i64 iOff /* Offset in pFile */
85496 ){
85497  int rc = SQLITE_OK;
85498 
85499  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
85500 
85501  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
85502  if( pReadr->aMap ){
85503  sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85504  pReadr->aMap = 0;
85505  }
85506  pReadr->iReadOff = iOff;
85507  pReadr->iEof = pFile->iEof;
85508  pReadr->pFd = pFile->pFd;
85509 
85510  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
85511  if( rc==SQLITE_OK && pReadr->aMap==0 ){
85512  int pgsz = pTask->pSorter->pgsz;
85513  int iBuf = pReadr->iReadOff % pgsz;
85514  if( pReadr->aBuffer==0 ){
85515  pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
85516  if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
85517  pReadr->nBuffer = pgsz;
85518  }
85519  if( rc==SQLITE_OK && iBuf ){
85520  int nRead = pgsz - iBuf;
85521  if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
85522  nRead = (int)(pReadr->iEof - pReadr->iReadOff);
85523  }
85524  rc = sqlite3OsRead(
85525  pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
85526  );
85527  testcase( rc!=SQLITE_OK );
85528  }
85529  }
85530 
85531  return rc;
85532 }
85533 
85534 /*
85535 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
85536 ** no error occurs, or an SQLite error code if one does.
85537 */
85538 static int vdbePmaReaderNext(PmaReader *pReadr){
85539  int rc = SQLITE_OK; /* Return Code */
85540  u64 nRec = 0; /* Size of record in bytes */
85541 
85542 
85543  if( pReadr->iReadOff>=pReadr->iEof ){
85544  IncrMerger *pIncr = pReadr->pIncr;
85545  int bEof = 1;
85546  if( pIncr ){
85547  rc = vdbeIncrSwap(pIncr);
85548  if( rc==SQLITE_OK && pIncr->bEof==0 ){
85549  rc = vdbePmaReaderSeek(
85550  pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
85551  );
85552  bEof = 0;
85553  }
85554  }
85555 
85556  if( bEof ){
85557  /* This is an EOF condition */
85558  vdbePmaReaderClear(pReadr);
85559  testcase( rc!=SQLITE_OK );
85560  return rc;
85561  }
85562  }
85563 
85564  if( rc==SQLITE_OK ){
85565  rc = vdbePmaReadVarint(pReadr, &nRec);
85566  }
85567  if( rc==SQLITE_OK ){
85568  pReadr->nKey = (int)nRec;
85569  rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
85570  testcase( rc!=SQLITE_OK );
85571  }
85572 
85573  return rc;
85574 }
85575 
85576 /*
85577 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
85578 ** starting at offset iStart and ending at offset iEof-1. This function
85579 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
85580 ** PMA is empty).
85581 **
85582 ** If the pnByte parameter is NULL, then it is assumed that the file
85583 ** contains a single PMA, and that that PMA omits the initial length varint.
85584 */
85585 static int vdbePmaReaderInit(
85586  SortSubtask *pTask, /* Task context */
85587  SorterFile *pFile, /* Sorter file to read from */
85588  i64 iStart, /* Start offset in pFile */
85589  PmaReader *pReadr, /* PmaReader to populate */
85590  i64 *pnByte /* IN/OUT: Increment this value by PMA size */
85591 ){
85592  int rc;
85593 
85594  assert( pFile->iEof>iStart );
85595  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
85596  assert( pReadr->aBuffer==0 );
85597  assert( pReadr->aMap==0 );
85598 
85599  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
85600  if( rc==SQLITE_OK ){
85601  u64 nByte = 0; /* Size of PMA in bytes */
85602  rc = vdbePmaReadVarint(pReadr, &nByte);
85603  pReadr->iEof = pReadr->iReadOff + nByte;
85604  *pnByte += nByte;
85605  }
85606 
85607  if( rc==SQLITE_OK ){
85608  rc = vdbePmaReaderNext(pReadr);
85609  }
85610  return rc;
85611 }
85612 
85613 /*
85614 ** A version of vdbeSorterCompare() that assumes that it has already been
85615 ** determined that the first field of key1 is equal to the first field of
85616 ** key2.
85617 */
85618 static int vdbeSorterCompareTail(
85619  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
85620  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
85621  const void *pKey1, int nKey1, /* Left side of comparison */
85622  const void *pKey2, int nKey2 /* Right side of comparison */
85623 ){
85624  UnpackedRecord *r2 = pTask->pUnpacked;
85625  if( *pbKey2Cached==0 ){
85626  sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85627  *pbKey2Cached = 1;
85628  }
85629  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
85630 }
85631 
85632 /*
85633 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
85634 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
85635 ** used by the comparison. Return the result of the comparison.
85636 **
85637 ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
85638 ** it is assumed that (pTask->pUnpacked) contains the unpacked version
85639 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
85640 ** version of key2 and *pbKey2Cached set to true before returning.
85641 **
85642 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
85643 ** to SQLITE_NOMEM.
85644 */
85645 static int vdbeSorterCompare(
85646  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
85647  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
85648  const void *pKey1, int nKey1, /* Left side of comparison */
85649  const void *pKey2, int nKey2 /* Right side of comparison */
85650 ){
85651  UnpackedRecord *r2 = pTask->pUnpacked;
85652  if( !*pbKey2Cached ){
85653  sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85654  *pbKey2Cached = 1;
85655  }
85656  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
85657 }
85658 
85659 /*
85660 ** A specially optimized version of vdbeSorterCompare() that assumes that
85661 ** the first field of each key is a TEXT value and that the collation
85662 ** sequence to compare them with is BINARY.
85663 */
85664 static int vdbeSorterCompareText(
85665  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
85666  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
85667  const void *pKey1, int nKey1, /* Left side of comparison */
85668  const void *pKey2, int nKey2 /* Right side of comparison */
85669 ){
85670  const u8 * const p1 = (const u8 * const)pKey1;
85671  const u8 * const p2 = (const u8 * const)pKey2;
85672  const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
85673  const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
85674 
85675  int n1;
85676  int n2;
85677  int res;
85678 
85679  getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
85680  getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
85681  res = memcmp(v1, v2, MIN(n1, n2));
85682  if( res==0 ){
85683  res = n1 - n2;
85684  }
85685 
85686  if( res==0 ){
85687  if( pTask->pSorter->pKeyInfo->nField>1 ){
85688  res = vdbeSorterCompareTail(
85689  pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85690  );
85691  }
85692  }else{
85693  if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85694  res = res * -1;
85695  }
85696  }
85697 
85698  return res;
85699 }
85700 
85701 /*
85702 ** A specially optimized version of vdbeSorterCompare() that assumes that
85703 ** the first field of each key is an INTEGER value.
85704 */
85705 static int vdbeSorterCompareInt(
85706  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
85707  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
85708  const void *pKey1, int nKey1, /* Left side of comparison */
85709  const void *pKey2, int nKey2 /* Right side of comparison */
85710 ){
85711  const u8 * const p1 = (const u8 * const)pKey1;
85712  const u8 * const p2 = (const u8 * const)pKey2;
85713  const int s1 = p1[1]; /* Left hand serial type */
85714  const int s2 = p2[1]; /* Right hand serial type */
85715  const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
85716  const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
85717  int res; /* Return value */
85718 
85719  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
85720  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
85721 
85722  if( s1>7 && s2>7 ){
85723  res = s1 - s2;
85724  }else{
85725  if( s1==s2 ){
85726  if( (*v1 ^ *v2) & 0x80 ){
85727  /* The two values have different signs */
85728  res = (*v1 & 0x80) ? -1 : +1;
85729  }else{
85730  /* The two values have the same sign. Compare using memcmp(). */
85731  static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
85732  int i;
85733  res = 0;
85734  for(i=0; i<aLen[s1]; i++){
85735  if( (res = v1[i] - v2[i]) ) break;
85736  }
85737  }
85738  }else{
85739  if( s2>7 ){
85740  res = +1;
85741  }else if( s1>7 ){
85742  res = -1;
85743  }else{
85744  res = s1 - s2;
85745  }
85746  assert( res!=0 );
85747 
85748  if( res>0 ){
85749  if( *v1 & 0x80 ) res = -1;
85750  }else{
85751  if( *v2 & 0x80 ) res = +1;
85752  }
85753  }
85754  }
85755 
85756  if( res==0 ){
85757  if( pTask->pSorter->pKeyInfo->nField>1 ){
85758  res = vdbeSorterCompareTail(
85759  pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85760  );
85761  }
85762  }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85763  res = res * -1;
85764  }
85765 
85766  return res;
85767 }
85768 
85769 /*
85770 ** Initialize the temporary index cursor just opened as a sorter cursor.
85771 **
85772 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
85773 ** to determine the number of fields that should be compared from the
85774 ** records being sorted. However, if the value passed as argument nField
85775 ** is non-zero and the sorter is able to guarantee a stable sort, nField
85776 ** is used instead. This is used when sorting records for a CREATE INDEX
85777 ** statement. In this case, keys are always delivered to the sorter in
85778 ** order of the primary key, which happens to be make up the final part
85779 ** of the records being sorted. So if the sort is stable, there is never
85780 ** any reason to compare PK fields and they can be ignored for a small
85781 ** performance boost.
85782 **
85783 ** The sorter can guarantee a stable sort when running in single-threaded
85784 ** mode, but not in multi-threaded mode.
85785 **
85786 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
85787 */
85788 SQLITE_PRIVATE int sqlite3VdbeSorterInit(
85789  sqlite3 *db, /* Database connection (for malloc()) */
85790  int nField, /* Number of key fields in each record */
85791  VdbeCursor *pCsr /* Cursor that holds the new sorter */
85792 ){
85793  int pgsz; /* Page size of main database */
85794  int i; /* Used to iterate through aTask[] */
85795  VdbeSorter *pSorter; /* The new sorter */
85796  KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
85797  int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
85798  int sz; /* Size of pSorter in bytes */
85799  int rc = SQLITE_OK;
85800 #if SQLITE_MAX_WORKER_THREADS==0
85801 # define nWorker 0
85802 #else
85803  int nWorker;
85804 #endif
85805 
85806  /* Initialize the upper limit on the number of worker threads */
85807 #if SQLITE_MAX_WORKER_THREADS>0
85808  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
85809  nWorker = 0;
85810  }else{
85811  nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
85812  }
85813 #endif
85814 
85815  /* Do not allow the total number of threads (main thread + all workers)
85816  ** to exceed the maximum merge count */
85817 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
85818  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
85819  nWorker = SORTER_MAX_MERGE_COUNT-1;
85820  }
85821 #endif
85822 
85823  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
85824  assert( pCsr->eCurType==CURTYPE_SORTER );
85825  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
85826  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
85827 
85828  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
85829  pCsr->uc.pSorter = pSorter;
85830  if( pSorter==0 ){
85831  rc = SQLITE_NOMEM_BKPT;
85832  }else{
85833  pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
85834  memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
85835  pKeyInfo->db = 0;
85836  if( nField && nWorker==0 ){
85837  pKeyInfo->nXField += (pKeyInfo->nField - nField);
85838  pKeyInfo->nField = nField;
85839  }
85840  pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
85841  pSorter->nTask = nWorker + 1;
85842  pSorter->iPrev = (u8)(nWorker - 1);
85843  pSorter->bUseThreads = (pSorter->nTask>1);
85844  pSorter->db = db;
85845  for(i=0; i<pSorter->nTask; i++){
85846  SortSubtask *pTask = &pSorter->aTask[i];
85847  pTask->pSorter = pSorter;
85848  }
85849 
85850  if( !sqlite3TempInMemory(db) ){
85851  i64 mxCache; /* Cache size in bytes*/
85852  u32 szPma = sqlite3GlobalConfig.szPma;
85853  pSorter->mnPmaSize = szPma * pgsz;
85854 
85855  mxCache = db->aDb[0].pSchema->cache_size;
85856  if( mxCache<0 ){
85857  /* A negative cache-size value C indicates that the cache is abs(C)
85858  ** KiB in size. */
85859  mxCache = mxCache * -1024;
85860  }else{
85861  mxCache = mxCache * pgsz;
85862  }
85863  mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
85864  pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
85865 
85866  /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
85867  ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
85868  ** large heap allocations.
85869  */
85870  if( sqlite3GlobalConfig.pScratch==0 ){
85871  assert( pSorter->iMemory==0 );
85872  pSorter->nMemory = pgsz;
85873  pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
85874  if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
85875  }
85876  }
85877 
85878  if( (pKeyInfo->nField+pKeyInfo->nXField)<13
85879  && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
85880  ){
85881  pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
85882  }
85883  }
85884 
85885  return rc;
85886 }
85887 #undef nWorker /* Defined at the top of this function */
85888 
85889 /*
85890 ** Free the list of sorted records starting at pRecord.
85891 */
85892 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
85893  SorterRecord *p;
85894  SorterRecord *pNext;
85895  for(p=pRecord; p; p=pNext){
85896  pNext = p->u.pNext;
85897  sqlite3DbFree(db, p);
85898  }
85899 }
85900 
85901 /*
85902 ** Free all resources owned by the object indicated by argument pTask. All
85903 ** fields of *pTask are zeroed before returning.
85904 */
85905 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
85906  sqlite3DbFree(db, pTask->pUnpacked);
85907 #if SQLITE_MAX_WORKER_THREADS>0
85908  /* pTask->list.aMemory can only be non-zero if it was handed memory
85909  ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
85910  if( pTask->list.aMemory ){
85911  sqlite3_free(pTask->list.aMemory);
85912  }else
85913 #endif
85914  {
85915  assert( pTask->list.aMemory==0 );
85916  vdbeSorterRecordFree(0, pTask->list.pList);
85917  }
85918  if( pTask->file.pFd ){
85919  sqlite3OsCloseFree(pTask->file.pFd);
85920  }
85921  if( pTask->file2.pFd ){
85922  sqlite3OsCloseFree(pTask->file2.pFd);
85923  }
85924  memset(pTask, 0, sizeof(SortSubtask));
85925 }
85926 
85927 #ifdef SQLITE_DEBUG_SORTER_THREADS
85928 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
85929  i64 t;
85930  int iTask = (pTask - pTask->pSorter->aTask);
85931  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85932  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
85933 }
85934 static void vdbeSorterRewindDebug(const char *zEvent){
85935  i64 t;
85936  sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
85937  fprintf(stderr, "%lld:X %s\n", t, zEvent);
85938 }
85939 static void vdbeSorterPopulateDebug(
85940  SortSubtask *pTask,
85941  const char *zEvent
85942 ){
85943  i64 t;
85944  int iTask = (pTask - pTask->pSorter->aTask);
85945  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85946  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
85947 }
85948 static void vdbeSorterBlockDebug(
85949  SortSubtask *pTask,
85950  int bBlocked,
85951  const char *zEvent
85952 ){
85953  if( bBlocked ){
85954  i64 t;
85955  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85956  fprintf(stderr, "%lld:main %s\n", t, zEvent);
85957  }
85958 }
85959 #else
85960 # define vdbeSorterWorkDebug(x,y)
85961 # define vdbeSorterRewindDebug(y)
85962 # define vdbeSorterPopulateDebug(x,y)
85963 # define vdbeSorterBlockDebug(x,y,z)
85964 #endif
85965 
85966 #if SQLITE_MAX_WORKER_THREADS>0
85967 /*
85968 ** Join thread pTask->thread.
85969 */
85970 static int vdbeSorterJoinThread(SortSubtask *pTask){
85971  int rc = SQLITE_OK;
85972  if( pTask->pThread ){
85973 #ifdef SQLITE_DEBUG_SORTER_THREADS
85974  int bDone = pTask->bDone;
85975 #endif
85976  void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
85977  vdbeSorterBlockDebug(pTask, !bDone, "enter");
85978  (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
85979  vdbeSorterBlockDebug(pTask, !bDone, "exit");
85980  rc = SQLITE_PTR_TO_INT(pRet);
85981  assert( pTask->bDone==1 );
85982  pTask->bDone = 0;
85983  pTask->pThread = 0;
85984  }
85985  return rc;
85986 }
85987 
85988 /*
85989 ** Launch a background thread to run xTask(pIn).
85990 */
85991 static int vdbeSorterCreateThread(
85992  SortSubtask *pTask, /* Thread will use this task object */
85993  void *(*xTask)(void*), /* Routine to run in a separate thread */
85994  void *pIn /* Argument passed into xTask() */
85995 ){
85996  assert( pTask->pThread==0 && pTask->bDone==0 );
85997  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
85998 }
85999 
86000 /*
86001 ** Join all outstanding threads launched by SorterWrite() to create
86002 ** level-0 PMAs.
86003 */
86004 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
86005  int rc = rcin;
86006  int i;
86007 
86008  /* This function is always called by the main user thread.
86009  **
86010  ** If this function is being called after SorterRewind() has been called,
86011  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
86012  ** is currently attempt to join one of the other threads. To avoid a race
86013  ** condition where this thread also attempts to join the same object, join
86014  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
86015  for(i=pSorter->nTask-1; i>=0; i--){
86016  SortSubtask *pTask = &pSorter->aTask[i];
86017  int rc2 = vdbeSorterJoinThread(pTask);
86018  if( rc==SQLITE_OK ) rc = rc2;
86019  }
86020  return rc;
86021 }
86022 #else
86023 # define vdbeSorterJoinAll(x,rcin) (rcin)
86024 # define vdbeSorterJoinThread(pTask) SQLITE_OK
86025 #endif
86026 
86027 /*
86028 ** Allocate a new MergeEngine object capable of handling up to
86029 ** nReader PmaReader inputs.
86030 **
86031 ** nReader is automatically rounded up to the next power of two.
86032 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
86033 */
86034 static MergeEngine *vdbeMergeEngineNew(int nReader){
86035  int N = 2; /* Smallest power of two >= nReader */
86036  int nByte; /* Total bytes of space to allocate */
86037  MergeEngine *pNew; /* Pointer to allocated object to return */
86038 
86039  assert( nReader<=SORTER_MAX_MERGE_COUNT );
86040 
86041  while( N<nReader ) N += N;
86042  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
86043 
86044  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
86045  if( pNew ){
86046  pNew->nTree = N;
86047  pNew->pTask = 0;
86048  pNew->aReadr = (PmaReader*)&pNew[1];
86049  pNew->aTree = (int*)&pNew->aReadr[N];
86050  }
86051  return pNew;
86052 }
86053 
86054 /*
86055 ** Free the MergeEngine object passed as the only argument.
86056 */
86057 static void vdbeMergeEngineFree(MergeEngine *pMerger){
86058  int i;
86059  if( pMerger ){
86060  for(i=0; i<pMerger->nTree; i++){
86061  vdbePmaReaderClear(&pMerger->aReadr[i]);
86062  }
86063  }
86064  sqlite3_free(pMerger);
86065 }
86066 
86067 /*
86068 ** Free all resources associated with the IncrMerger object indicated by
86069 ** the first argument.
86070 */
86071 static void vdbeIncrFree(IncrMerger *pIncr){
86072  if( pIncr ){
86073 #if SQLITE_MAX_WORKER_THREADS>0
86074  if( pIncr->bUseThread ){
86075  vdbeSorterJoinThread(pIncr->pTask);
86076  if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
86077  if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
86078  }
86079 #endif
86080  vdbeMergeEngineFree(pIncr->pMerger);
86081  sqlite3_free(pIncr);
86082  }
86083 }
86084 
86085 /*
86086 ** Reset a sorting cursor back to its original empty state.
86087 */
86088 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
86089  int i;
86090  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
86091  assert( pSorter->bUseThreads || pSorter->pReader==0 );
86092 #if SQLITE_MAX_WORKER_THREADS>0
86093  if( pSorter->pReader ){
86094  vdbePmaReaderClear(pSorter->pReader);
86095  sqlite3DbFree(db, pSorter->pReader);
86096  pSorter->pReader = 0;
86097  }
86098 #endif
86099  vdbeMergeEngineFree(pSorter->pMerger);
86100  pSorter->pMerger = 0;
86101  for(i=0; i<pSorter->nTask; i++){
86102  SortSubtask *pTask = &pSorter->aTask[i];
86103  vdbeSortSubtaskCleanup(db, pTask);
86104  pTask->pSorter = pSorter;
86105  }
86106  if( pSorter->list.aMemory==0 ){
86107  vdbeSorterRecordFree(0, pSorter->list.pList);
86108  }
86109  pSorter->list.pList = 0;
86110  pSorter->list.szPMA = 0;
86111  pSorter->bUsePMA = 0;
86112  pSorter->iMemory = 0;
86113  pSorter->mxKeysize = 0;
86114  sqlite3DbFree(db, pSorter->pUnpacked);
86115  pSorter->pUnpacked = 0;
86116 }
86117 
86118 /*
86119 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
86120 */
86121 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
86122  VdbeSorter *pSorter;
86123  assert( pCsr->eCurType==CURTYPE_SORTER );
86124  pSorter = pCsr->uc.pSorter;
86125  if( pSorter ){
86126  sqlite3VdbeSorterReset(db, pSorter);
86127  sqlite3_free(pSorter->list.aMemory);
86128  sqlite3DbFree(db, pSorter);
86129  pCsr->uc.pSorter = 0;
86130  }
86131 }
86132 
86133 #if SQLITE_MAX_MMAP_SIZE>0
86134 /*
86135 ** The first argument is a file-handle open on a temporary file. The file
86136 ** is guaranteed to be nByte bytes or smaller in size. This function
86137 ** attempts to extend the file to nByte bytes in size and to ensure that
86138 ** the VFS has memory mapped it.
86139 **
86140 ** Whether or not the file does end up memory mapped of course depends on
86141 ** the specific VFS implementation.
86142 */
86143 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
86144  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
86145  void *p = 0;
86146  int chunksize = 4*1024;
86147  sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
86148  sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
86149  sqlite3OsFetch(pFd, 0, (int)nByte, &p);
86150  sqlite3OsUnfetch(pFd, 0, p);
86151  }
86152 }
86153 #else
86154 # define vdbeSorterExtendFile(x,y,z)
86155 #endif
86156 
86157 /*
86158 ** Allocate space for a file-handle and open a temporary file. If successful,
86159 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
86160 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
86161 */
86162 static int vdbeSorterOpenTempFile(
86163  sqlite3 *db, /* Database handle doing sort */
86164  i64 nExtend, /* Attempt to extend file to this size */
86165  sqlite3_file **ppFd
86166 ){
86167  int rc;
86168  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
86169  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
86170  SQLITE_OPEN_TEMP_JOURNAL |
86171  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
86172  SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
86173  );
86174  if( rc==SQLITE_OK ){
86175  i64 max = SQLITE_MAX_MMAP_SIZE;
86176  sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
86177  if( nExtend>0 ){
86178  vdbeSorterExtendFile(db, *ppFd, nExtend);
86179  }
86180  }
86181  return rc;
86182 }
86183 
86184 /*
86185 ** If it has not already been allocated, allocate the UnpackedRecord
86186 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
86187 ** if no allocation was required), or SQLITE_NOMEM otherwise.
86188 */
86189 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
86190  if( pTask->pUnpacked==0 ){
86191  char *pFree;
86192  pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
86193  pTask->pSorter->pKeyInfo, 0, 0, &pFree
86194  );
86195  assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
86196  if( pFree==0 ) return SQLITE_NOMEM_BKPT;
86197  pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
86198  pTask->pUnpacked->errCode = 0;
86199  }
86200  return SQLITE_OK;
86201 }
86202 
86203 
86204 /*
86205 ** Merge the two sorted lists p1 and p2 into a single list.
86206 */
86207 static SorterRecord *vdbeSorterMerge(
86208  SortSubtask *pTask, /* Calling thread context */
86209  SorterRecord *p1, /* First list to merge */
86210  SorterRecord *p2 /* Second list to merge */
86211 ){
86212  SorterRecord *pFinal = 0;
86213  SorterRecord **pp = &pFinal;
86214  int bCached = 0;
86215 
86216  assert( p1!=0 && p2!=0 );
86217  for(;;){
86218  int res;
86219  res = pTask->xCompare(
86220  pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
86221  );
86222 
86223  if( res<=0 ){
86224  *pp = p1;
86225  pp = &p1->u.pNext;
86226  p1 = p1->u.pNext;
86227  if( p1==0 ){
86228  *pp = p2;
86229  break;
86230  }
86231  }else{
86232  *pp = p2;
86233  pp = &p2->u.pNext;
86234  p2 = p2->u.pNext;
86235  bCached = 0;
86236  if( p2==0 ){
86237  *pp = p1;
86238  break;
86239  }
86240  }
86241  }
86242  return pFinal;
86243 }
86244 
86245 /*
86246 ** Return the SorterCompare function to compare values collected by the
86247 ** sorter object passed as the only argument.
86248 */
86249 static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
86250  if( p->typeMask==SORTER_TYPE_INTEGER ){
86251  return vdbeSorterCompareInt;
86252  }else if( p->typeMask==SORTER_TYPE_TEXT ){
86253  return vdbeSorterCompareText;
86254  }
86255  return vdbeSorterCompare;
86256 }
86257 
86258 /*
86259 ** Sort the linked list of records headed at pTask->pList. Return
86260 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
86261 ** an error occurs.
86262 */
86263 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
86264  int i;
86265  SorterRecord **aSlot;
86266  SorterRecord *p;
86267  int rc;
86268 
86269  rc = vdbeSortAllocUnpacked(pTask);
86270  if( rc!=SQLITE_OK ) return rc;
86271 
86272  p = pList->pList;
86273  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
86274 
86275  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
86276  if( !aSlot ){
86277  return SQLITE_NOMEM_BKPT;
86278  }
86279 
86280  while( p ){
86281  SorterRecord *pNext;
86282  if( pList->aMemory ){
86283  if( (u8*)p==pList->aMemory ){
86284  pNext = 0;
86285  }else{
86286  assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
86287  pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
86288  }
86289  }else{
86290  pNext = p->u.pNext;
86291  }
86292 
86293  p->u.pNext = 0;
86294  for(i=0; aSlot[i]; i++){
86295  p = vdbeSorterMerge(pTask, p, aSlot[i]);
86296  aSlot[i] = 0;
86297  }
86298  aSlot[i] = p;
86299  p = pNext;
86300  }
86301 
86302  p = 0;
86303  for(i=0; i<64; i++){
86304  if( aSlot[i]==0 ) continue;
86305  p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
86306  }
86307  pList->pList = p;
86308 
86309  sqlite3_free(aSlot);
86310  assert( pTask->pUnpacked->errCode==SQLITE_OK
86311  || pTask->pUnpacked->errCode==SQLITE_NOMEM
86312  );
86313  return pTask->pUnpacked->errCode;
86314 }
86315 
86316 /*
86317 ** Initialize a PMA-writer object.
86318 */
86319 static void vdbePmaWriterInit(
86320  sqlite3_file *pFd, /* File handle to write to */
86321  PmaWriter *p, /* Object to populate */
86322  int nBuf, /* Buffer size */
86323  i64 iStart /* Offset of pFd to begin writing at */
86324 ){
86325  memset(p, 0, sizeof(PmaWriter));
86326  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
86327  if( !p->aBuffer ){
86328  p->eFWErr = SQLITE_NOMEM_BKPT;
86329  }else{
86330  p->iBufEnd = p->iBufStart = (iStart % nBuf);
86331  p->iWriteOff = iStart - p->iBufStart;
86332  p->nBuffer = nBuf;
86333  p->pFd = pFd;
86334  }
86335 }
86336 
86337 /*
86338 ** Write nData bytes of data to the PMA. Return SQLITE_OK
86339 ** if successful, or an SQLite error code if an error occurs.
86340 */
86341 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
86342  int nRem = nData;
86343  while( nRem>0 && p->eFWErr==0 ){
86344  int nCopy = nRem;
86345  if( nCopy>(p->nBuffer - p->iBufEnd) ){
86346  nCopy = p->nBuffer - p->iBufEnd;
86347  }
86348 
86349  memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
86350  p->iBufEnd += nCopy;
86351  if( p->iBufEnd==p->nBuffer ){
86352  p->eFWErr = sqlite3OsWrite(p->pFd,
86353  &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
86354  p->iWriteOff + p->iBufStart
86355  );
86356  p->iBufStart = p->iBufEnd = 0;
86357  p->iWriteOff += p->nBuffer;
86358  }
86359  assert( p->iBufEnd<p->nBuffer );
86360 
86361  nRem -= nCopy;
86362  }
86363 }
86364 
86365 /*
86366 ** Flush any buffered data to disk and clean up the PMA-writer object.
86367 ** The results of using the PMA-writer after this call are undefined.
86368 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
86369 ** required. Otherwise, return an SQLite error code.
86370 **
86371 ** Before returning, set *piEof to the offset immediately following the
86372 ** last byte written to the file.
86373 */
86374 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
86375  int rc;
86376  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
86377  p->eFWErr = sqlite3OsWrite(p->pFd,
86378  &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
86379  p->iWriteOff + p->iBufStart
86380  );
86381  }
86382  *piEof = (p->iWriteOff + p->iBufEnd);
86383  sqlite3_free(p->aBuffer);
86384  rc = p->eFWErr;
86385  memset(p, 0, sizeof(PmaWriter));
86386  return rc;
86387 }
86388 
86389 /*
86390 ** Write value iVal encoded as a varint to the PMA. Return
86391 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
86392 */
86393 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
86394  int nByte;
86395  u8 aByte[10];
86396  nByte = sqlite3PutVarint(aByte, iVal);
86397  vdbePmaWriteBlob(p, aByte, nByte);
86398 }
86399 
86400 /*
86401 ** Write the current contents of in-memory linked-list pList to a level-0
86402 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
86403 ** successful, or an SQLite error code otherwise.
86404 **
86405 ** The format of a PMA is:
86406 **
86407 ** * A varint. This varint contains the total number of bytes of content
86408 ** in the PMA (not including the varint itself).
86409 **
86410 ** * One or more records packed end-to-end in order of ascending keys.
86411 ** Each record consists of a varint followed by a blob of data (the
86412 ** key). The varint is the number of bytes in the blob of data.
86413 */
86414 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
86415  sqlite3 *db = pTask->pSorter->db;
86416  int rc = SQLITE_OK; /* Return code */
86417  PmaWriter writer; /* Object used to write to the file */
86418 
86419 #ifdef SQLITE_DEBUG
86420  /* Set iSz to the expected size of file pTask->file after writing the PMA.
86421  ** This is used by an assert() statement at the end of this function. */
86422  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
86423 #endif
86424 
86425  vdbeSorterWorkDebug(pTask, "enter");
86426  memset(&writer, 0, sizeof(PmaWriter));
86427  assert( pList->szPMA>0 );
86428 
86429  /* If the first temporary PMA file has not been opened, open it now. */
86430  if( pTask->file.pFd==0 ){
86431  rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
86432  assert( rc!=SQLITE_OK || pTask->file.pFd );
86433  assert( pTask->file.iEof==0 );
86434  assert( pTask->nPMA==0 );
86435  }
86436 
86437  /* Try to get the file to memory map */
86438  if( rc==SQLITE_OK ){
86439  vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
86440  }
86441 
86442  /* Sort the list */
86443  if( rc==SQLITE_OK ){
86444  rc = vdbeSorterSort(pTask, pList);
86445  }
86446 
86447  if( rc==SQLITE_OK ){
86448  SorterRecord *p;
86449  SorterRecord *pNext = 0;
86450 
86451  vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
86452  pTask->file.iEof);
86453  pTask->nPMA++;
86454  vdbePmaWriteVarint(&writer, pList->szPMA);
86455  for(p=pList->pList; p; p=pNext){
86456  pNext = p->u.pNext;
86457  vdbePmaWriteVarint(&writer, p->nVal);
86458  vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
86459  if( pList->aMemory==0 ) sqlite3_free(p);
86460  }
86461  pList->pList = p;
86462  rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
86463  }
86464 
86465  vdbeSorterWorkDebug(pTask, "exit");
86466  assert( rc!=SQLITE_OK || pList->pList==0 );
86467  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
86468  return rc;
86469 }
86470 
86471 /*
86472 ** Advance the MergeEngine to its next entry.
86473 ** Set *pbEof to true there is no next entry because
86474 ** the MergeEngine has reached the end of all its inputs.
86475 **
86476 ** Return SQLITE_OK if successful or an error code if an error occurs.
86477 */
86478 static int vdbeMergeEngineStep(
86479  MergeEngine *pMerger, /* The merge engine to advance to the next row */
86480  int *pbEof /* Set TRUE at EOF. Set false for more content */
86481 ){
86482  int rc;
86483  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
86484  SortSubtask *pTask = pMerger->pTask;
86485 
86486  /* Advance the current PmaReader */
86487  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
86488 
86489  /* Update contents of aTree[] */
86490  if( rc==SQLITE_OK ){
86491  int i; /* Index of aTree[] to recalculate */
86492  PmaReader *pReadr1; /* First PmaReader to compare */
86493  PmaReader *pReadr2; /* Second PmaReader to compare */
86494  int bCached = 0;
86495 
86496  /* Find the first two PmaReaders to compare. The one that was just
86497  ** advanced (iPrev) and the one next to it in the array. */
86498  pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
86499  pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
86500 
86501  for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
86502  /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
86503  int iRes;
86504  if( pReadr1->pFd==0 ){
86505  iRes = +1;
86506  }else if( pReadr2->pFd==0 ){
86507  iRes = -1;
86508  }else{
86509  iRes = pTask->xCompare(pTask, &bCached,
86510  pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
86511  );
86512  }
86513 
86514  /* If pReadr1 contained the smaller value, set aTree[i] to its index.
86515  ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
86516  ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
86517  ** pKey2 to point to the record belonging to pReadr2.
86518  **
86519  ** Alternatively, if pReadr2 contains the smaller of the two values,
86520  ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
86521  ** was actually called above, then pTask->pUnpacked now contains
86522  ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
86523  ** vdbeSorterCompare() from decoding pReadr2 again.
86524  **
86525  ** If the two values were equal, then the value from the oldest
86526  ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
86527  ** is sorted from oldest to newest, so pReadr1 contains older values
86528  ** than pReadr2 iff (pReadr1<pReadr2). */
86529  if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
86530  pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
86531  pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86532  bCached = 0;
86533  }else{
86534  if( pReadr1->pFd ) bCached = 0;
86535  pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
86536  pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86537  }
86538  }
86539  *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
86540  }
86541 
86542  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
86543 }
86544 
86545 #if SQLITE_MAX_WORKER_THREADS>0
86546 /*
86547 ** The main routine for background threads that write level-0 PMAs.
86548 */
86549 static void *vdbeSorterFlushThread(void *pCtx){
86550  SortSubtask *pTask = (SortSubtask*)pCtx;
86551  int rc; /* Return code */
86552  assert( pTask->bDone==0 );
86553  rc = vdbeSorterListToPMA(pTask, &pTask->list);
86554  pTask->bDone = 1;
86555  return SQLITE_INT_TO_PTR(rc);
86556 }
86557 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
86558 
86559 /*
86560 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
86561 ** using a background thread.
86562 */
86563 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
86564 #if SQLITE_MAX_WORKER_THREADS==0
86565  pSorter->bUsePMA = 1;
86566  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
86567 #else
86568  int rc = SQLITE_OK;
86569  int i;
86570  SortSubtask *pTask = 0; /* Thread context used to create new PMA */
86571  int nWorker = (pSorter->nTask-1);
86572 
86573  /* Set the flag to indicate that at least one PMA has been written.
86574  ** Or will be, anyhow. */
86575  pSorter->bUsePMA = 1;
86576 
86577  /* Select a sub-task to sort and flush the current list of in-memory
86578  ** records to disk. If the sorter is running in multi-threaded mode,
86579  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
86580  ** the background thread from a sub-tasks previous turn is still running,
86581  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
86582  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
86583  ** sub-tasks are prefered as they use background threads - the final
86584  ** sub-task uses the main thread. */
86585  for(i=0; i<nWorker; i++){
86586  int iTest = (pSorter->iPrev + i + 1) % nWorker;
86587  pTask = &pSorter->aTask[iTest];
86588  if( pTask->bDone ){
86589  rc = vdbeSorterJoinThread(pTask);
86590  }
86591  if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
86592  }
86593 
86594  if( rc==SQLITE_OK ){
86595  if( i==nWorker ){
86596  /* Use the foreground thread for this operation */
86597  rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
86598  }else{
86599  /* Launch a background thread for this operation */
86600  u8 *aMem = pTask->list.aMemory;
86601  void *pCtx = (void*)pTask;
86602 
86603  assert( pTask->pThread==0 && pTask->bDone==0 );
86604  assert( pTask->list.pList==0 );
86605  assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
86606 
86607  pSorter->iPrev = (u8)(pTask - pSorter->aTask);
86608  pTask->list = pSorter->list;
86609  pSorter->list.pList = 0;
86610  pSorter->list.szPMA = 0;
86611  if( aMem ){
86612  pSorter->list.aMemory = aMem;
86613  pSorter->nMemory = sqlite3MallocSize(aMem);
86614  }else if( pSorter->list.aMemory ){
86615  pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
86616  if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
86617  }
86618 
86619  rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
86620  }
86621  }
86622 
86623  return rc;
86624 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
86625 }
86626 
86627 /*
86628 ** Add a record to the sorter.
86629 */
86630 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
86631  const VdbeCursor *pCsr, /* Sorter cursor */
86632  Mem *pVal /* Memory cell containing record */
86633 ){
86634  VdbeSorter *pSorter;
86635  int rc = SQLITE_OK; /* Return Code */
86636  SorterRecord *pNew; /* New list element */
86637  int bFlush; /* True to flush contents of memory to PMA */
86638  int nReq; /* Bytes of memory required */
86639  int nPMA; /* Bytes of PMA space required */
86640  int t; /* serial type of first record field */
86641 
86642  assert( pCsr->eCurType==CURTYPE_SORTER );
86643  pSorter = pCsr->uc.pSorter;
86644  getVarint32((const u8*)&pVal->z[1], t);
86645  if( t>0 && t<10 && t!=7 ){
86646  pSorter->typeMask &= SORTER_TYPE_INTEGER;
86647  }else if( t>10 && (t & 0x01) ){
86648  pSorter->typeMask &= SORTER_TYPE_TEXT;
86649  }else{
86650  pSorter->typeMask = 0;
86651  }
86652 
86653  assert( pSorter );
86654 
86655  /* Figure out whether or not the current contents of memory should be
86656  ** flushed to a PMA before continuing. If so, do so.
86657  **
86658  ** If using the single large allocation mode (pSorter->aMemory!=0), then
86659  ** flush the contents of memory to a new PMA if (a) at least one value is
86660  ** already in memory and (b) the new value will not fit in memory.
86661  **
86662  ** Or, if using separate allocations for each record, flush the contents
86663  ** of memory to a PMA if either of the following are true:
86664  **
86665  ** * The total memory allocated for the in-memory list is greater
86666  ** than (page-size * cache-size), or
86667  **
86668  ** * The total memory allocated for the in-memory list is greater
86669  ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
86670  */
86671  nReq = pVal->n + sizeof(SorterRecord);
86672  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
86673  if( pSorter->mxPmaSize ){
86674  if( pSorter->list.aMemory ){
86675  bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
86676  }else{
86677  bFlush = (
86678  (pSorter->list.szPMA > pSorter->mxPmaSize)
86679  || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
86680  );
86681  }
86682  if( bFlush ){
86683  rc = vdbeSorterFlushPMA(pSorter);
86684  pSorter->list.szPMA = 0;
86685  pSorter->iMemory = 0;
86686  assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
86687  }
86688  }
86689 
86690  pSorter->list.szPMA += nPMA;
86691  if( nPMA>pSorter->mxKeysize ){
86692  pSorter->mxKeysize = nPMA;
86693  }
86694 
86695  if( pSorter->list.aMemory ){
86696  int nMin = pSorter->iMemory + nReq;
86697 
86698  if( nMin>pSorter->nMemory ){
86699  u8 *aNew;
86700  int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
86701  int nNew = pSorter->nMemory * 2;
86702  while( nNew < nMin ) nNew = nNew*2;
86703  if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
86704  if( nNew < nMin ) nNew = nMin;
86705 
86706  aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
86707  if( !aNew ) return SQLITE_NOMEM_BKPT;
86708  pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
86709  pSorter->list.aMemory = aNew;
86710  pSorter->nMemory = nNew;
86711  }
86712 
86713  pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
86714  pSorter->iMemory += ROUND8(nReq);
86715  if( pSorter->list.pList ){
86716  pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
86717  }
86718  }else{
86719  pNew = (SorterRecord *)sqlite3Malloc(nReq);
86720  if( pNew==0 ){
86721  return SQLITE_NOMEM_BKPT;
86722  }
86723  pNew->u.pNext = pSorter->list.pList;
86724  }
86725 
86726  memcpy(SRVAL(pNew), pVal->z, pVal->n);
86727  pNew->nVal = pVal->n;
86728  pSorter->list.pList = pNew;
86729 
86730  return rc;
86731 }
86732 
86733 /*
86734 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
86735 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
86736 ** except that the number-of-bytes varint is omitted from the start.
86737 */
86738 static int vdbeIncrPopulate(IncrMerger *pIncr){
86739  int rc = SQLITE_OK;
86740  int rc2;
86741  i64 iStart = pIncr->iStartOff;
86742  SorterFile *pOut = &pIncr->aFile[1];
86743  SortSubtask *pTask = pIncr->pTask;
86744  MergeEngine *pMerger = pIncr->pMerger;
86745  PmaWriter writer;
86746  assert( pIncr->bEof==0 );
86747 
86748  vdbeSorterPopulateDebug(pTask, "enter");
86749 
86750  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
86751  while( rc==SQLITE_OK ){
86752  int dummy;
86753  PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
86754  int nKey = pReader->nKey;
86755  i64 iEof = writer.iWriteOff + writer.iBufEnd;
86756 
86757  /* Check if the output file is full or if the input has been exhausted.
86758  ** In either case exit the loop. */
86759  if( pReader->pFd==0 ) break;
86760  if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
86761 
86762  /* Write the next key to the output. */
86763  vdbePmaWriteVarint(&writer, nKey);
86764  vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
86765  assert( pIncr->pMerger->pTask==pTask );
86766  rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
86767  }
86768 
86769  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
86770  if( rc==SQLITE_OK ) rc = rc2;
86771  vdbeSorterPopulateDebug(pTask, "exit");
86772  return rc;
86773 }
86774 
86775 #if SQLITE_MAX_WORKER_THREADS>0
86776 /*
86777 ** The main routine for background threads that populate aFile[1] of
86778 ** multi-threaded IncrMerger objects.
86779 */
86780 static void *vdbeIncrPopulateThread(void *pCtx){
86781  IncrMerger *pIncr = (IncrMerger*)pCtx;
86782  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
86783  pIncr->pTask->bDone = 1;
86784  return pRet;
86785 }
86786 
86787 /*
86788 ** Launch a background thread to populate aFile[1] of pIncr.
86789 */
86790 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
86791  void *p = (void*)pIncr;
86792  assert( pIncr->bUseThread );
86793  return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
86794 }
86795 #endif
86796 
86797 /*
86798 ** This function is called when the PmaReader corresponding to pIncr has
86799 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
86800 ** aFile[0] such that the PmaReader should start rereading it from the
86801 ** beginning.
86802 **
86803 ** For single-threaded objects, this is accomplished by literally reading
86804 ** keys from pIncr->pMerger and repopulating aFile[0].
86805 **
86806 ** For multi-threaded objects, all that is required is to wait until the
86807 ** background thread is finished (if it is not already) and then swap
86808 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
86809 ** been exhausted, this function also launches a new background thread
86810 ** to populate the new aFile[1].
86811 **
86812 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
86813 */
86814 static int vdbeIncrSwap(IncrMerger *pIncr){
86815  int rc = SQLITE_OK;
86816 
86817 #if SQLITE_MAX_WORKER_THREADS>0
86818  if( pIncr->bUseThread ){
86819  rc = vdbeSorterJoinThread(pIncr->pTask);
86820 
86821  if( rc==SQLITE_OK ){
86822  SorterFile f0 = pIncr->aFile[0];
86823  pIncr->aFile[0] = pIncr->aFile[1];
86824  pIncr->aFile[1] = f0;
86825  }
86826 
86827  if( rc==SQLITE_OK ){
86828  if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86829  pIncr->bEof = 1;
86830  }else{
86831  rc = vdbeIncrBgPopulate(pIncr);
86832  }
86833  }
86834  }else
86835 #endif
86836  {
86837  rc = vdbeIncrPopulate(pIncr);
86838  pIncr->aFile[0] = pIncr->aFile[1];
86839  if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86840  pIncr->bEof = 1;
86841  }
86842  }
86843 
86844  return rc;
86845 }
86846 
86847 /*
86848 ** Allocate and return a new IncrMerger object to read data from pMerger.
86849 **
86850 ** If an OOM condition is encountered, return NULL. In this case free the
86851 ** pMerger argument before returning.
86852 */
86853 static int vdbeIncrMergerNew(
86854  SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
86855  MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
86856  IncrMerger **ppOut /* Write the new IncrMerger here */
86857 ){
86858  int rc = SQLITE_OK;
86859  IncrMerger *pIncr = *ppOut = (IncrMerger*)
86860  (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
86861  if( pIncr ){
86862  pIncr->pMerger = pMerger;
86863  pIncr->pTask = pTask;
86864  pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
86865  pTask->file2.iEof += pIncr->mxSz;
86866  }else{
86867  vdbeMergeEngineFree(pMerger);
86868  rc = SQLITE_NOMEM_BKPT;
86869  }
86870  return rc;
86871 }
86872 
86873 #if SQLITE_MAX_WORKER_THREADS>0
86874 /*
86875 ** Set the "use-threads" flag on object pIncr.
86876 */
86877 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
86878  pIncr->bUseThread = 1;
86879  pIncr->pTask->file2.iEof -= pIncr->mxSz;
86880 }
86881 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
86882 
86883 
86884 
86885 /*
86886 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
86887 ** two PmaReaders that feed that entry. Neither of the PmaReaders
86888 ** are advanced. This routine merely does the comparison.
86889 */
86890 static void vdbeMergeEngineCompare(
86891  MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
86892  int iOut /* Store the result in pMerger->aTree[iOut] */
86893 ){
86894  int i1;
86895  int i2;
86896  int iRes;
86897  PmaReader *p1;
86898  PmaReader *p2;
86899 
86900  assert( iOut<pMerger->nTree && iOut>0 );
86901 
86902  if( iOut>=(pMerger->nTree/2) ){
86903  i1 = (iOut - pMerger->nTree/2) * 2;
86904  i2 = i1 + 1;
86905  }else{
86906  i1 = pMerger->aTree[iOut*2];
86907  i2 = pMerger->aTree[iOut*2+1];
86908  }
86909 
86910  p1 = &pMerger->aReadr[i1];
86911  p2 = &pMerger->aReadr[i2];
86912 
86913  if( p1->pFd==0 ){
86914  iRes = i2;
86915  }else if( p2->pFd==0 ){
86916  iRes = i1;
86917  }else{
86918  SortSubtask *pTask = pMerger->pTask;
86919  int bCached = 0;
86920  int res;
86921  assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
86922  res = pTask->xCompare(
86923  pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
86924  );
86925  if( res<=0 ){
86926  iRes = i1;
86927  }else{
86928  iRes = i2;
86929  }
86930  }
86931 
86932  pMerger->aTree[iOut] = iRes;
86933 }
86934 
86935 /*
86936 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
86937 ** and vdbePmaReaderIncrMergeInit().
86938 **
86939 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
86940 ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
86941 ** when there exists one or more separate worker threads.
86942 */
86943 #define INCRINIT_NORMAL 0
86944 #define INCRINIT_TASK 1
86945 #define INCRINIT_ROOT 2
86946 
86947 /*
86948 ** Forward reference required as the vdbeIncrMergeInit() and
86949 ** vdbePmaReaderIncrInit() routines are called mutually recursively when
86950 ** building a merge tree.
86951 */
86952 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
86953 
86954 /*
86955 ** Initialize the MergeEngine object passed as the second argument. Once this
86956 ** function returns, the first key of merged data may be read from the
86957 ** MergeEngine object in the usual fashion.
86958 **
86959 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
86960 ** objects attached to the PmaReader objects that the merger reads from have
86961 ** already been populated, but that they have not yet populated aFile[0] and
86962 ** set the PmaReader objects up to read from it. In this case all that is
86963 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
86964 ** its first key.
86965 **
86966 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
86967 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
86968 ** to pMerger.
86969 **
86970 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86971 */
86972 static int vdbeMergeEngineInit(
86973  SortSubtask *pTask, /* Thread that will run pMerger */
86974  MergeEngine *pMerger, /* MergeEngine to initialize */
86975  int eMode /* One of the INCRINIT_XXX constants */
86976 ){
86977  int rc = SQLITE_OK; /* Return code */
86978  int i; /* For looping over PmaReader objects */
86979  int nTree = pMerger->nTree;
86980 
86981  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86982  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
86983 
86984  /* Verify that the MergeEngine is assigned to a single thread */
86985  assert( pMerger->pTask==0 );
86986  pMerger->pTask = pTask;
86987 
86988  for(i=0; i<nTree; i++){
86989  if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
86990  /* PmaReaders should be normally initialized in order, as if they are
86991  ** reading from the same temp file this makes for more linear file IO.
86992  ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
86993  ** in use it will block the vdbePmaReaderNext() call while it uses
86994  ** the main thread to fill its buffer. So calling PmaReaderNext()
86995  ** on this PmaReader before any of the multi-threaded PmaReaders takes
86996  ** better advantage of multi-processor hardware. */
86997  rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
86998  }else{
86999  rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
87000  }
87001  if( rc!=SQLITE_OK ) return rc;
87002  }
87003 
87004  for(i=pMerger->nTree-1; i>0; i--){
87005  vdbeMergeEngineCompare(pMerger, i);
87006  }
87007  return pTask->pUnpacked->errCode;
87008 }
87009 
87010 /*
87011 ** The PmaReader passed as the first argument is guaranteed to be an
87012 ** incremental-reader (pReadr->pIncr!=0). This function serves to open
87013 ** and/or initialize the temp file related fields of the IncrMerge
87014 ** object at (pReadr->pIncr).
87015 **
87016 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
87017 ** in the sub-tree headed by pReadr are also initialized. Data is then
87018 ** loaded into the buffers belonging to pReadr and it is set to point to
87019 ** the first key in its range.
87020 **
87021 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
87022 ** to be a multi-threaded PmaReader and this function is being called in a
87023 ** background thread. In this case all PmaReaders in the sub-tree are
87024 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
87025 ** pReadr is populated. However, pReadr itself is not set up to point
87026 ** to its first key. A call to vdbePmaReaderNext() is still required to do
87027 ** that.
87028 **
87029 ** The reason this function does not call vdbePmaReaderNext() immediately
87030 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
87031 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
87032 ** this entire function is being run by thread (pTask->thread), that will
87033 ** lead to the current background thread attempting to join itself.
87034 **
87035 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
87036 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
87037 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
87038 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
87039 ** the current PmaReader set to point to the first key in its range.
87040 **
87041 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87042 */
87043 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
87044  int rc = SQLITE_OK;
87045  IncrMerger *pIncr = pReadr->pIncr;
87046  SortSubtask *pTask = pIncr->pTask;
87047  sqlite3 *db = pTask->pSorter->db;
87048 
87049  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
87050  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
87051 
87052  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
87053 
87054  /* Set up the required files for pIncr. A multi-theaded IncrMerge object
87055  ** requires two temp files to itself, whereas a single-threaded object
87056  ** only requires a region of pTask->file2. */
87057  if( rc==SQLITE_OK ){
87058  int mxSz = pIncr->mxSz;
87059 #if SQLITE_MAX_WORKER_THREADS>0
87060  if( pIncr->bUseThread ){
87061  rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
87062  if( rc==SQLITE_OK ){
87063  rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
87064  }
87065  }else
87066 #endif
87067  /*if( !pIncr->bUseThread )*/{
87068  if( pTask->file2.pFd==0 ){
87069  assert( pTask->file2.iEof>0 );
87070  rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
87071  pTask->file2.iEof = 0;
87072  }
87073  if( rc==SQLITE_OK ){
87074  pIncr->aFile[1].pFd = pTask->file2.pFd;
87075  pIncr->iStartOff = pTask->file2.iEof;
87076  pTask->file2.iEof += mxSz;
87077  }
87078  }
87079  }
87080 
87081 #if SQLITE_MAX_WORKER_THREADS>0
87082  if( rc==SQLITE_OK && pIncr->bUseThread ){
87083  /* Use the current thread to populate aFile[1], even though this
87084  ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
87085  ** then this function is already running in background thread
87086  ** pIncr->pTask->thread.
87087  **
87088  ** If this is the INCRINIT_ROOT object, then it is running in the
87089  ** main VDBE thread. But that is Ok, as that thread cannot return
87090  ** control to the VDBE or proceed with anything useful until the
87091  ** first results are ready from this merger object anyway.
87092  */
87093  assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
87094  rc = vdbeIncrPopulate(pIncr);
87095  }
87096 #endif
87097 
87098  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
87099  rc = vdbePmaReaderNext(pReadr);
87100  }
87101 
87102  return rc;
87103 }
87104 
87105 #if SQLITE_MAX_WORKER_THREADS>0
87106 /*
87107 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
87108 ** background threads.
87109 */
87110 static void *vdbePmaReaderBgIncrInit(void *pCtx){
87111  PmaReader *pReader = (PmaReader*)pCtx;
87112  void *pRet = SQLITE_INT_TO_PTR(
87113  vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
87114  );
87115  pReader->pIncr->pTask->bDone = 1;
87116  return pRet;
87117 }
87118 #endif
87119 
87120 /*
87121 ** If the PmaReader passed as the first argument is not an incremental-reader
87122 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
87123 ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
87124 ** this routine to initialize the incremental merge.
87125 **
87126 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
87127 ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
87128 ** Or, if the IncrMerger is single threaded, the same function is called
87129 ** using the current thread.
87130 */
87131 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
87132  IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
87133  int rc = SQLITE_OK; /* Return code */
87134  if( pIncr ){
87135 #if SQLITE_MAX_WORKER_THREADS>0
87136  assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
87137  if( pIncr->bUseThread ){
87138  void *pCtx = (void*)pReadr;
87139  rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
87140  }else
87141 #endif
87142  {
87143  rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
87144  }
87145  }
87146  return rc;
87147 }
87148 
87149 /*
87150 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
87151 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
87152 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
87153 ** to NULL and return an SQLite error code.
87154 **
87155 ** When this function is called, *piOffset is set to the offset of the
87156 ** first PMA to read from pTask->file. Assuming no error occurs, it is
87157 ** set to the offset immediately following the last byte of the last
87158 ** PMA before returning. If an error does occur, then the final value of
87159 ** *piOffset is undefined.
87160 */
87161 static int vdbeMergeEngineLevel0(
87162  SortSubtask *pTask, /* Sorter task to read from */
87163  int nPMA, /* Number of PMAs to read */
87164  i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
87165  MergeEngine **ppOut /* OUT: New merge-engine */
87166 ){
87167  MergeEngine *pNew; /* Merge engine to return */
87168  i64 iOff = *piOffset;
87169  int i;
87170  int rc = SQLITE_OK;
87171 
87172  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
87173  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
87174 
87175  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
87176  i64 nDummy = 0;
87177  PmaReader *pReadr = &pNew->aReadr[i];
87178  rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
87179  iOff = pReadr->iEof;
87180  }
87181 
87182  if( rc!=SQLITE_OK ){
87183  vdbeMergeEngineFree(pNew);
87184  *ppOut = 0;
87185  }
87186  *piOffset = iOff;
87187  return rc;
87188 }
87189 
87190 /*
87191 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
87192 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
87193 **
87194 ** i.e.
87195 **
87196 ** nPMA<=16 -> TreeDepth() == 0
87197 ** nPMA<=256 -> TreeDepth() == 1
87198 ** nPMA<=65536 -> TreeDepth() == 2
87199 */
87200 static int vdbeSorterTreeDepth(int nPMA){
87201  int nDepth = 0;
87202  i64 nDiv = SORTER_MAX_MERGE_COUNT;
87203  while( nDiv < (i64)nPMA ){
87204  nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
87205  nDepth++;
87206  }
87207  return nDepth;
87208 }
87209 
87210 /*
87211 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
87212 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
87213 ** tree, counting from zero. This function adds pLeaf to the tree.
87214 **
87215 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
87216 ** code is returned and pLeaf is freed.
87217 */
87218 static int vdbeSorterAddToTree(
87219  SortSubtask *pTask, /* Task context */
87220  int nDepth, /* Depth of tree according to TreeDepth() */
87221  int iSeq, /* Sequence number of leaf within tree */
87222  MergeEngine *pRoot, /* Root of tree */
87223  MergeEngine *pLeaf /* Leaf to add to tree */
87224 ){
87225  int rc = SQLITE_OK;
87226  int nDiv = 1;
87227  int i;
87228  MergeEngine *p = pRoot;
87229  IncrMerger *pIncr;
87230 
87231  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
87232 
87233  for(i=1; i<nDepth; i++){
87234  nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
87235  }
87236 
87237  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
87238  int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
87239  PmaReader *pReadr = &p->aReadr[iIter];
87240 
87241  if( pReadr->pIncr==0 ){
87242  MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
87243  if( pNew==0 ){
87244  rc = SQLITE_NOMEM_BKPT;
87245  }else{
87246  rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
87247  }
87248  }
87249  if( rc==SQLITE_OK ){
87250  p = pReadr->pIncr->pMerger;
87251  nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
87252  }
87253  }
87254 
87255  if( rc==SQLITE_OK ){
87256  p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
87257  }else{
87258  vdbeIncrFree(pIncr);
87259  }
87260  return rc;
87261 }
87262 
87263 /*
87264 ** This function is called as part of a SorterRewind() operation on a sorter
87265 ** that has already written two or more level-0 PMAs to one or more temp
87266 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
87267 ** can be used to incrementally merge all PMAs on disk.
87268 **
87269 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
87270 ** MergeEngine object at the root of the tree before returning. Or, if an
87271 ** error occurs, an SQLite error code is returned and the final value
87272 ** of *ppOut is undefined.
87273 */
87274 static int vdbeSorterMergeTreeBuild(
87275  VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
87276  MergeEngine **ppOut /* Write the MergeEngine here */
87277 ){
87278  MergeEngine *pMain = 0;
87279  int rc = SQLITE_OK;
87280  int iTask;
87281 
87282 #if SQLITE_MAX_WORKER_THREADS>0
87283  /* If the sorter uses more than one task, then create the top-level
87284  ** MergeEngine here. This MergeEngine will read data from exactly
87285  ** one PmaReader per sub-task. */
87286  assert( pSorter->bUseThreads || pSorter->nTask==1 );
87287  if( pSorter->nTask>1 ){
87288  pMain = vdbeMergeEngineNew(pSorter->nTask);
87289  if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
87290  }
87291 #endif
87292 
87293  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87294  SortSubtask *pTask = &pSorter->aTask[iTask];
87295  assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
87296  if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
87297  MergeEngine *pRoot = 0; /* Root node of tree for this task */
87298  int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
87299  i64 iReadOff = 0;
87300 
87301  if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
87302  rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
87303  }else{
87304  int i;
87305  int iSeq = 0;
87306  pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
87307  if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
87308  for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
87309  MergeEngine *pMerger = 0; /* New level-0 PMA merger */
87310  int nReader; /* Number of level-0 PMAs to merge */
87311 
87312  nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
87313  rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
87314  if( rc==SQLITE_OK ){
87315  rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
87316  }
87317  }
87318  }
87319 
87320  if( rc==SQLITE_OK ){
87321 #if SQLITE_MAX_WORKER_THREADS>0
87322  if( pMain!=0 ){
87323  rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
87324  }else
87325 #endif
87326  {
87327  assert( pMain==0 );
87328  pMain = pRoot;
87329  }
87330  }else{
87331  vdbeMergeEngineFree(pRoot);
87332  }
87333  }
87334  }
87335 
87336  if( rc!=SQLITE_OK ){
87337  vdbeMergeEngineFree(pMain);
87338  pMain = 0;
87339  }
87340  *ppOut = pMain;
87341  return rc;
87342 }
87343 
87344 /*
87345 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
87346 ** on a sorter that has written two or more PMAs to temporary files. It sets
87347 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
87348 ** (for multi-threaded sorters) so that it can be used to iterate through
87349 ** all records stored in the sorter.
87350 **
87351 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87352 */
87353 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
87354  int rc; /* Return code */
87355  SortSubtask *pTask0 = &pSorter->aTask[0];
87356  MergeEngine *pMain = 0;
87357 #if SQLITE_MAX_WORKER_THREADS
87358  sqlite3 *db = pTask0->pSorter->db;
87359  int i;
87360  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
87361  for(i=0; i<pSorter->nTask; i++){
87362  pSorter->aTask[i].xCompare = xCompare;
87363  }
87364 #endif
87365 
87366  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
87367  if( rc==SQLITE_OK ){
87368 #if SQLITE_MAX_WORKER_THREADS
87369  assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
87370  if( pSorter->bUseThreads ){
87371  int iTask;
87372  PmaReader *pReadr = 0;
87373  SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
87374  rc = vdbeSortAllocUnpacked(pLast);
87375  if( rc==SQLITE_OK ){
87376  pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
87377  pSorter->pReader = pReadr;
87378  if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
87379  }
87380  if( rc==SQLITE_OK ){
87381  rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
87382  if( rc==SQLITE_OK ){
87383  vdbeIncrMergerSetThreads(pReadr->pIncr);
87384  for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
87385  IncrMerger *pIncr;
87386  if( (pIncr = pMain->aReadr[iTask].pIncr) ){
87387  vdbeIncrMergerSetThreads(pIncr);
87388  assert( pIncr->pTask!=pLast );
87389  }
87390  }
87391  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87392  /* Check that:
87393  **
87394  ** a) The incremental merge object is configured to use the
87395  ** right task, and
87396  ** b) If it is using task (nTask-1), it is configured to run
87397  ** in single-threaded mode. This is important, as the
87398  ** root merge (INCRINIT_ROOT) will be using the same task
87399  ** object.
87400  */
87401  PmaReader *p = &pMain->aReadr[iTask];
87402  assert( p->pIncr==0 || (
87403  (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
87404  && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
87405  ));
87406  rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
87407  }
87408  }
87409  pMain = 0;
87410  }
87411  if( rc==SQLITE_OK ){
87412  rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
87413  }
87414  }else
87415 #endif
87416  {
87417  rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
87418  pSorter->pMerger = pMain;
87419  pMain = 0;
87420  }
87421  }
87422 
87423  if( rc!=SQLITE_OK ){
87424  vdbeMergeEngineFree(pMain);
87425  }
87426  return rc;
87427 }
87428 
87429 
87430 /*
87431 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
87432 ** this function is called to prepare for iterating through the records
87433 ** in sorted order.
87434 */
87435 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
87436  VdbeSorter *pSorter;
87437  int rc = SQLITE_OK; /* Return code */
87438 
87439  assert( pCsr->eCurType==CURTYPE_SORTER );
87440  pSorter = pCsr->uc.pSorter;
87441  assert( pSorter );
87442 
87443  /* If no data has been written to disk, then do not do so now. Instead,
87444  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
87445  ** from the in-memory list. */
87446  if( pSorter->bUsePMA==0 ){
87447  if( pSorter->list.pList ){
87448  *pbEof = 0;
87449  rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
87450  }else{
87451  *pbEof = 1;
87452  }
87453  return rc;
87454  }
87455 
87456  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
87457  ** function flushes the contents of memory to disk, it immediately always
87458  ** creates a new list consisting of a single key immediately afterwards.
87459  ** So the list is never empty at this point. */
87460  assert( pSorter->list.pList );
87461  rc = vdbeSorterFlushPMA(pSorter);
87462 
87463  /* Join all threads */
87464  rc = vdbeSorterJoinAll(pSorter, rc);
87465 
87466  vdbeSorterRewindDebug("rewind");
87467 
87468  /* Assuming no errors have occurred, set up a merger structure to
87469  ** incrementally read and merge all remaining PMAs. */
87470  assert( pSorter->pReader==0 );
87471  if( rc==SQLITE_OK ){
87472  rc = vdbeSorterSetupMerge(pSorter);
87473  *pbEof = 0;
87474  }
87475 
87476  vdbeSorterRewindDebug("rewinddone");
87477  return rc;
87478 }
87479 
87480 /*
87481 ** Advance to the next element in the sorter.
87482 */
87483 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
87484  VdbeSorter *pSorter;
87485  int rc; /* Return code */
87486 
87487  assert( pCsr->eCurType==CURTYPE_SORTER );
87488  pSorter = pCsr->uc.pSorter;
87489  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
87490  if( pSorter->bUsePMA ){
87491  assert( pSorter->pReader==0 || pSorter->pMerger==0 );
87492  assert( pSorter->bUseThreads==0 || pSorter->pReader );
87493  assert( pSorter->bUseThreads==1 || pSorter->pMerger );
87494 #if SQLITE_MAX_WORKER_THREADS>0
87495  if( pSorter->bUseThreads ){
87496  rc = vdbePmaReaderNext(pSorter->pReader);
87497  *pbEof = (pSorter->pReader->pFd==0);
87498  }else
87499 #endif
87500  /*if( !pSorter->bUseThreads )*/ {
87501  assert( pSorter->pMerger!=0 );
87502  assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
87503  rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
87504  }
87505  }else{
87506  SorterRecord *pFree = pSorter->list.pList;
87507  pSorter->list.pList = pFree->u.pNext;
87508  pFree->u.pNext = 0;
87509  if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
87510  *pbEof = !pSorter->list.pList;
87511  rc = SQLITE_OK;
87512  }
87513  return rc;
87514 }
87515 
87516 /*
87517 ** Return a pointer to a buffer owned by the sorter that contains the
87518 ** current key.
87519 */
87520 static void *vdbeSorterRowkey(
87521  const VdbeSorter *pSorter, /* Sorter object */
87522  int *pnKey /* OUT: Size of current key in bytes */
87523 ){
87524  void *pKey;
87525  if( pSorter->bUsePMA ){
87526  PmaReader *pReader;
87527 #if SQLITE_MAX_WORKER_THREADS>0
87528  if( pSorter->bUseThreads ){
87529  pReader = pSorter->pReader;
87530  }else
87531 #endif
87532  /*if( !pSorter->bUseThreads )*/{
87533  pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
87534  }
87535  *pnKey = pReader->nKey;
87536  pKey = pReader->aKey;
87537  }else{
87538  *pnKey = pSorter->list.pList->nVal;
87539  pKey = SRVAL(pSorter->list.pList);
87540  }
87541  return pKey;
87542 }
87543 
87544 /*
87545 ** Copy the current sorter key into the memory cell pOut.
87546 */
87547 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
87548  VdbeSorter *pSorter;
87549  void *pKey; int nKey; /* Sorter key to copy into pOut */
87550 
87551  assert( pCsr->eCurType==CURTYPE_SORTER );
87552  pSorter = pCsr->uc.pSorter;
87553  pKey = vdbeSorterRowkey(pSorter, &nKey);
87554  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
87555  return SQLITE_NOMEM_BKPT;
87556  }
87557  pOut->n = nKey;
87558  MemSetTypeFlag(pOut, MEM_Blob);
87559  memcpy(pOut->z, pKey, nKey);
87560 
87561  return SQLITE_OK;
87562 }
87563 
87564 /*
87565 ** Compare the key in memory cell pVal with the key that the sorter cursor
87566 ** passed as the first argument currently points to. For the purposes of
87567 ** the comparison, ignore the rowid field at the end of each record.
87568 **
87569 ** If the sorter cursor key contains any NULL values, consider it to be
87570 ** less than pVal. Even if pVal also contains NULL values.
87571 **
87572 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
87573 ** Otherwise, set *pRes to a negative, zero or positive value if the
87574 ** key in pVal is smaller than, equal to or larger than the current sorter
87575 ** key.
87576 **
87577 ** This routine forms the core of the OP_SorterCompare opcode, which in
87578 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
87579 */
87580 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
87581  const VdbeCursor *pCsr, /* Sorter cursor */
87582  Mem *pVal, /* Value to compare to current sorter key */
87583  int nKeyCol, /* Compare this many columns */
87584  int *pRes /* OUT: Result of comparison */
87585 ){
87586  VdbeSorter *pSorter;
87587  UnpackedRecord *r2;
87588  KeyInfo *pKeyInfo;
87589  int i;
87590  void *pKey; int nKey; /* Sorter key to compare pVal with */
87591 
87592  assert( pCsr->eCurType==CURTYPE_SORTER );
87593  pSorter = pCsr->uc.pSorter;
87594  r2 = pSorter->pUnpacked;
87595  pKeyInfo = pCsr->pKeyInfo;
87596  if( r2==0 ){
87597  char *p;
87598  r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
87599  assert( pSorter->pUnpacked==(UnpackedRecord*)p );
87600  if( r2==0 ) return SQLITE_NOMEM_BKPT;
87601  r2->nField = nKeyCol;
87602  }
87603  assert( r2->nField==nKeyCol );
87604 
87605  pKey = vdbeSorterRowkey(pSorter, &nKey);
87606  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
87607  for(i=0; i<nKeyCol; i++){
87608  if( r2->aMem[i].flags & MEM_Null ){
87609  *pRes = -1;
87610  return SQLITE_OK;
87611  }
87612  }
87613 
87614  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
87615  return SQLITE_OK;
87616 }
87617 
87618 /************** End of vdbesort.c ********************************************/
87619 /************** Begin file memjournal.c **************************************/
87620 /*
87621 ** 2008 October 7
87622 **
87623 ** The author disclaims copyright to this source code. In place of
87624 ** a legal notice, here is a blessing:
87625 **
87626 ** May you do good and not evil.
87627 ** May you find forgiveness for yourself and forgive others.
87628 ** May you share freely, never taking more than you give.
87629 **
87630 *************************************************************************
87631 **
87632 ** This file contains code use to implement an in-memory rollback journal.
87633 ** The in-memory rollback journal is used to journal transactions for
87634 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
87635 **
87636 ** Update: The in-memory journal is also used to temporarily cache
87637 ** smaller journals that are not critical for power-loss recovery.
87638 ** For example, statement journals that are not too big will be held
87639 ** entirely in memory, thus reducing the number of file I/O calls, and
87640 ** more importantly, reducing temporary file creation events. If these
87641 ** journals become too large for memory, they are spilled to disk. But
87642 ** in the common case, they are usually small and no file I/O needs to
87643 ** occur.
87644 */
87645 /* #include "sqliteInt.h" */
87646 
87647 /* Forward references to internal structures */
87648 typedef struct MemJournal MemJournal;
87649 typedef struct FilePoint FilePoint;
87650 typedef struct FileChunk FileChunk;
87651 
87652 /*
87653 ** The rollback journal is composed of a linked list of these structures.
87654 **
87655 ** The zChunk array is always at least 8 bytes in size - usually much more.
87656 ** Its actual size is stored in the MemJournal.nChunkSize variable.
87657 */
87658 struct FileChunk {
87659  FileChunk *pNext; /* Next chunk in the journal */
87660  u8 zChunk[8]; /* Content of this chunk */
87661 };
87662 
87663 /*
87664 ** By default, allocate this many bytes of memory for each FileChunk object.
87665 */
87666 #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
87667 
87668 /*
87669 ** For chunk size nChunkSize, return the number of bytes that should
87670 ** be allocated for each FileChunk structure.
87671 */
87672 #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
87673 
87674 /*
87675 ** An instance of this object serves as a cursor into the rollback journal.
87676 ** The cursor can be either for reading or writing.
87677 */
87678 struct FilePoint {
87679  sqlite3_int64 iOffset; /* Offset from the beginning of the file */
87680  FileChunk *pChunk; /* Specific chunk into which cursor points */
87681 };
87682 
87683 /*
87684 ** This structure is a subclass of sqlite3_file. Each open memory-journal
87685 ** is an instance of this class.
87686 */
87687 struct MemJournal {
87688  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
87689  int nChunkSize; /* In-memory chunk-size */
87690 
87691  int nSpill; /* Bytes of data before flushing */
87692  int nSize; /* Bytes of data currently in memory */
87693  FileChunk *pFirst; /* Head of in-memory chunk-list */
87694  FilePoint endpoint; /* Pointer to the end of the file */
87695  FilePoint readpoint; /* Pointer to the end of the last xRead() */
87696 
87697  int flags; /* xOpen flags */
87698  sqlite3_vfs *pVfs; /* The "real" underlying VFS */
87699  const char *zJournal; /* Name of the journal file */
87700 };
87701 
87702 /*
87703 ** Read data from the in-memory journal file. This is the implementation
87704 ** of the sqlite3_vfs.xRead method.
87705 */
87706 static int memjrnlRead(
87707  sqlite3_file *pJfd, /* The journal file from which to read */
87708  void *zBuf, /* Put the results here */
87709  int iAmt, /* Number of bytes to read */
87710  sqlite_int64 iOfst /* Begin reading at this offset */
87711 ){
87712  MemJournal *p = (MemJournal *)pJfd;
87713  u8 *zOut = zBuf;
87714  int nRead = iAmt;
87715  int iChunkOffset;
87716  FileChunk *pChunk;
87717 
87718 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87719  if( (iAmt+iOfst)>p->endpoint.iOffset ){
87720  return SQLITE_IOERR_SHORT_READ;
87721  }
87722 #endif
87723 
87724  assert( (iAmt+iOfst)<=p->endpoint.iOffset );
87725  assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
87726  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
87727  sqlite3_int64 iOff = 0;
87728  for(pChunk=p->pFirst;
87729  ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
87730  pChunk=pChunk->pNext
87731  ){
87732  iOff += p->nChunkSize;
87733  }
87734  }else{
87735  pChunk = p->readpoint.pChunk;
87736  assert( pChunk!=0 );
87737  }
87738 
87739  iChunkOffset = (int)(iOfst%p->nChunkSize);
87740  do {
87741  int iSpace = p->nChunkSize - iChunkOffset;
87742  int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
87743  memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
87744  zOut += nCopy;
87745  nRead -= iSpace;
87746  iChunkOffset = 0;
87747  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
87748  p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
87749  p->readpoint.pChunk = pChunk;
87750 
87751  return SQLITE_OK;
87752 }
87753 
87754 /*
87755 ** Free the list of FileChunk structures headed at MemJournal.pFirst.
87756 */
87757 static void memjrnlFreeChunks(MemJournal *p){
87758  FileChunk *pIter;
87759  FileChunk *pNext;
87760  for(pIter=p->pFirst; pIter; pIter=pNext){
87761  pNext = pIter->pNext;
87762  sqlite3_free(pIter);
87763  }
87764  p->pFirst = 0;
87765 }
87766 
87767 /*
87768 ** Flush the contents of memory to a real file on disk.
87769 */
87770 static int memjrnlCreateFile(MemJournal *p){
87771  int rc;
87772  sqlite3_file *pReal = (sqlite3_file*)p;
87773  MemJournal copy = *p;
87774 
87775  memset(p, 0, sizeof(MemJournal));
87776  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
87777  if( rc==SQLITE_OK ){
87778  int nChunk = copy.nChunkSize;
87779  i64 iOff = 0;
87780  FileChunk *pIter;
87781  for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
87782  if( iOff + nChunk > copy.endpoint.iOffset ){
87783  nChunk = copy.endpoint.iOffset - iOff;
87784  }
87785  rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
87786  if( rc ) break;
87787  iOff += nChunk;
87788  }
87789  if( rc==SQLITE_OK ){
87790  /* No error has occurred. Free the in-memory buffers. */
87791  memjrnlFreeChunks(&copy);
87792  }
87793  }
87794  if( rc!=SQLITE_OK ){
87795  /* If an error occurred while creating or writing to the file, restore
87796  ** the original before returning. This way, SQLite uses the in-memory
87797  ** journal data to roll back changes made to the internal page-cache
87798  ** before this function was called. */
87799  sqlite3OsClose(pReal);
87800  *p = copy;
87801  }
87802  return rc;
87803 }
87804 
87805 
87806 /*
87807 ** Write data to the file.
87808 */
87809 static int memjrnlWrite(
87810  sqlite3_file *pJfd, /* The journal file into which to write */
87811  const void *zBuf, /* Take data to be written from here */
87812  int iAmt, /* Number of bytes to write */
87813  sqlite_int64 iOfst /* Begin writing at this offset into the file */
87814 ){
87815  MemJournal *p = (MemJournal *)pJfd;
87816  int nWrite = iAmt;
87817  u8 *zWrite = (u8 *)zBuf;
87818 
87819  /* If the file should be created now, create it and write the new data
87820  ** into the file on disk. */
87821  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
87822  int rc = memjrnlCreateFile(p);
87823  if( rc==SQLITE_OK ){
87824  rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
87825  }
87826  return rc;
87827  }
87828 
87829  /* If the contents of this write should be stored in memory */
87830  else{
87831  /* An in-memory journal file should only ever be appended to. Random
87832  ** access writes are not required. The only exception to this is when
87833  ** the in-memory journal is being used by a connection using the
87834  ** atomic-write optimization. In this case the first 28 bytes of the
87835  ** journal file may be written as part of committing the transaction. */
87836  assert( iOfst==p->endpoint.iOffset || iOfst==0 );
87837 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87838  if( iOfst==0 && p->pFirst ){
87839  assert( p->nChunkSize>iAmt );
87840  memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
87841  }else
87842 #else
87843  assert( iOfst>0 || p->pFirst==0 );
87844 #endif
87845  {
87846  while( nWrite>0 ){
87847  FileChunk *pChunk = p->endpoint.pChunk;
87848  int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
87849  int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
87850 
87851  if( iChunkOffset==0 ){
87852  /* New chunk is required to extend the file. */
87853  FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
87854  if( !pNew ){
87855  return SQLITE_IOERR_NOMEM_BKPT;
87856  }
87857  pNew->pNext = 0;
87858  if( pChunk ){
87859  assert( p->pFirst );
87860  pChunk->pNext = pNew;
87861  }else{
87862  assert( !p->pFirst );
87863  p->pFirst = pNew;
87864  }
87865  p->endpoint.pChunk = pNew;
87866  }
87867 
87868  memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
87869  zWrite += iSpace;
87870  nWrite -= iSpace;
87871  p->endpoint.iOffset += iSpace;
87872  }
87873  p->nSize = iAmt + iOfst;
87874  }
87875  }
87876 
87877  return SQLITE_OK;
87878 }
87879 
87880 /*
87881 ** Truncate the file.
87882 **
87883 ** If the journal file is already on disk, truncate it there. Or, if it
87884 ** is still in main memory but is being truncated to zero bytes in size,
87885 ** ignore
87886 */
87887 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
87888  MemJournal *p = (MemJournal *)pJfd;
87889  if( ALWAYS(size==0) ){
87890  memjrnlFreeChunks(p);
87891  p->nSize = 0;
87892  p->endpoint.pChunk = 0;
87893  p->endpoint.iOffset = 0;
87894  p->readpoint.pChunk = 0;
87895  p->readpoint.iOffset = 0;
87896  }
87897  return SQLITE_OK;
87898 }
87899 
87900 /*
87901 ** Close the file.
87902 */
87903 static int memjrnlClose(sqlite3_file *pJfd){
87904  MemJournal *p = (MemJournal *)pJfd;
87905  memjrnlFreeChunks(p);
87906  return SQLITE_OK;
87907 }
87908 
87909 /*
87910 ** Sync the file.
87911 **
87912 ** If the real file has been created, call its xSync method. Otherwise,
87913 ** syncing an in-memory journal is a no-op.
87914 */
87915 static int memjrnlSync(sqlite3_file *pJfd, int flags){
87916  UNUSED_PARAMETER2(pJfd, flags);
87917  return SQLITE_OK;
87918 }
87919 
87920 /*
87921 ** Query the size of the file in bytes.
87922 */
87923 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
87924  MemJournal *p = (MemJournal *)pJfd;
87925  *pSize = (sqlite_int64) p->endpoint.iOffset;
87926  return SQLITE_OK;
87927 }
87928 
87929 /*
87930 ** Table of methods for MemJournal sqlite3_file object.
87931 */
87932 static const struct sqlite3_io_methods MemJournalMethods = {
87933  1, /* iVersion */
87934  memjrnlClose, /* xClose */
87935  memjrnlRead, /* xRead */
87936  memjrnlWrite, /* xWrite */
87937  memjrnlTruncate, /* xTruncate */
87938  memjrnlSync, /* xSync */
87939  memjrnlFileSize, /* xFileSize */
87940  0, /* xLock */
87941  0, /* xUnlock */
87942  0, /* xCheckReservedLock */
87943  0, /* xFileControl */
87944  0, /* xSectorSize */
87945  0, /* xDeviceCharacteristics */
87946  0, /* xShmMap */
87947  0, /* xShmLock */
87948  0, /* xShmBarrier */
87949  0, /* xShmUnmap */
87950  0, /* xFetch */
87951  0 /* xUnfetch */
87952 };
87953 
87954 /*
87955 ** Open a journal file.
87956 **
87957 ** The behaviour of the journal file depends on the value of parameter
87958 ** nSpill. If nSpill is 0, then the journal file is always create and
87959 ** accessed using the underlying VFS. If nSpill is less than zero, then
87960 ** all content is always stored in main-memory. Finally, if nSpill is a
87961 ** positive value, then the journal file is initially created in-memory
87962 ** but may be flushed to disk later on. In this case the journal file is
87963 ** flushed to disk either when it grows larger than nSpill bytes in size,
87964 ** or when sqlite3JournalCreate() is called.
87965 */
87966 SQLITE_PRIVATE int sqlite3JournalOpen(
87967  sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
87968  const char *zName, /* Name of the journal file */
87969  sqlite3_file *pJfd, /* Preallocated, blank file handle */
87970  int flags, /* Opening flags */
87971  int nSpill /* Bytes buffered before opening the file */
87972 ){
87973  MemJournal *p = (MemJournal*)pJfd;
87974 
87975  /* Zero the file-handle object. If nSpill was passed zero, initialize
87976  ** it using the sqlite3OsOpen() function of the underlying VFS. In this
87977  ** case none of the code in this module is executed as a result of calls
87978  ** made on the journal file-handle. */
87979  memset(p, 0, sizeof(MemJournal));
87980  if( nSpill==0 ){
87981  return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
87982  }
87983 
87984  if( nSpill>0 ){
87985  p->nChunkSize = nSpill;
87986  }else{
87987  p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
87988  assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
87989  }
87990 
87991  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
87992  p->nSpill = nSpill;
87993  p->flags = flags;
87994  p->zJournal = zName;
87995  p->pVfs = pVfs;
87996  return SQLITE_OK;
87997 }
87998 
87999 /*
88000 ** Open an in-memory journal file.
88001 */
88002 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
88003  sqlite3JournalOpen(0, 0, pJfd, 0, -1);
88004 }
88005 
88006 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
88007 /*
88008 ** If the argument p points to a MemJournal structure that is not an
88009 ** in-memory-only journal file (i.e. is one that was opened with a +ve
88010 ** nSpill parameter), and the underlying file has not yet been created,
88011 ** create it now.
88012 */
88013 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
88014  int rc = SQLITE_OK;
88015  if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
88016  rc = memjrnlCreateFile((MemJournal*)p);
88017  }
88018  return rc;
88019 }
88020 #endif
88021 
88022 /*
88023 ** The file-handle passed as the only argument is open on a journal file.
88024 ** Return true if this "journal file" is currently stored in heap memory,
88025 ** or false otherwise.
88026 */
88027 SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
88028  return p->pMethods==&MemJournalMethods;
88029 }
88030 
88031 /*
88032 ** Return the number of bytes required to store a JournalFile that uses vfs
88033 ** pVfs to create the underlying on-disk files.
88034 */
88035 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
88036  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
88037 }
88038 
88039 /************** End of memjournal.c ******************************************/
88040 /************** Begin file walker.c ******************************************/
88041 /*
88042 ** 2008 August 16
88043 **
88044 ** The author disclaims copyright to this source code. In place of
88045 ** a legal notice, here is a blessing:
88046 **
88047 ** May you do good and not evil.
88048 ** May you find forgiveness for yourself and forgive others.
88049 ** May you share freely, never taking more than you give.
88050 **
88051 *************************************************************************
88052 ** This file contains routines used for walking the parser tree for
88053 ** an SQL statement.
88054 */
88055 /* #include "sqliteInt.h" */
88056 /* #include <stdlib.h> */
88057 /* #include <string.h> */
88058 
88059 
88060 /*
88061 ** Walk an expression tree. Invoke the callback once for each node
88062 ** of the expression, while descending. (In other words, the callback
88063 ** is invoked before visiting children.)
88064 **
88065 ** The return value from the callback should be one of the WRC_*
88066 ** constants to specify how to proceed with the walk.
88067 **
88068 ** WRC_Continue Continue descending down the tree.
88069 **
88070 ** WRC_Prune Do not descend into child nodes. But allow
88071 ** the walk to continue with sibling nodes.
88072 **
88073 ** WRC_Abort Do no more callbacks. Unwind the stack and
88074 ** return the top-level walk call.
88075 **
88076 ** The return value from this routine is WRC_Abort to abandon the tree walk
88077 ** and WRC_Continue to continue.
88078 */
88079 static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
88080  int rc;
88081  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
88082  testcase( ExprHasProperty(pExpr, EP_Reduced) );
88083  rc = pWalker->xExprCallback(pWalker, pExpr);
88084  if( rc || ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
88085  return rc & WRC_Abort;
88086  }
88087  if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
88088  if( pExpr->pRight && walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
88089  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88090  if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
88091  }else if( pExpr->x.pList ){
88092  if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
88093  }
88094  return WRC_Continue;
88095 }
88096 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
88097  return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
88098 }
88099 
88100 /*
88101 ** Call sqlite3WalkExpr() for every expression in list p or until
88102 ** an abort request is seen.
88103 */
88104 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
88105  int i;
88106  struct ExprList_item *pItem;
88107  if( p ){
88108  for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
88109  if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
88110  }
88111  }
88112  return WRC_Continue;
88113 }
88114 
88115 /*
88116 ** Walk all expressions associated with SELECT statement p. Do
88117 ** not invoke the SELECT callback on p, but do (of course) invoke
88118 ** any expr callbacks and SELECT callbacks that come from subqueries.
88119 ** Return WRC_Abort or WRC_Continue.
88120 */
88121 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
88122  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
88123  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
88124  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
88125  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
88126  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
88127  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
88128  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
88129  return WRC_Continue;
88130 }
88131 
88132 /*
88133 ** Walk the parse trees associated with all subqueries in the
88134 ** FROM clause of SELECT statement p. Do not invoke the select
88135 ** callback on p, but do invoke it on each FROM clause subquery
88136 ** and on any subqueries further down in the tree. Return
88137 ** WRC_Abort or WRC_Continue;
88138 */
88139 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
88140  SrcList *pSrc;
88141  int i;
88142  struct SrcList_item *pItem;
88143 
88144  pSrc = p->pSrc;
88145  if( ALWAYS(pSrc) ){
88146  for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
88147  if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
88148  return WRC_Abort;
88149  }
88150  if( pItem->fg.isTabFunc
88151  && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
88152  ){
88153  return WRC_Abort;
88154  }
88155  }
88156  }
88157  return WRC_Continue;
88158 }
88159 
88160 /*
88161 ** Call sqlite3WalkExpr() for every expression in Select statement p.
88162 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
88163 ** on the compound select chain, p->pPrior.
88164 **
88165 ** If it is not NULL, the xSelectCallback() callback is invoked before
88166 ** the walk of the expressions and FROM clause. The xSelectCallback2()
88167 ** method, if it is not NULL, is invoked following the walk of the
88168 ** expressions and FROM clause.
88169 **
88170 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
88171 ** there is an abort request.
88172 **
88173 ** If the Walker does not have an xSelectCallback() then this routine
88174 ** is a no-op returning WRC_Continue.
88175 */
88176 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
88177  int rc;
88178  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
88179  return WRC_Continue;
88180  }
88181  rc = WRC_Continue;
88182  pWalker->walkerDepth++;
88183  while( p ){
88184  if( pWalker->xSelectCallback ){
88185  rc = pWalker->xSelectCallback(pWalker, p);
88186  if( rc ) break;
88187  }
88188  if( sqlite3WalkSelectExpr(pWalker, p)
88189  || sqlite3WalkSelectFrom(pWalker, p)
88190  ){
88191  pWalker->walkerDepth--;
88192  return WRC_Abort;
88193  }
88194  if( pWalker->xSelectCallback2 ){
88195  pWalker->xSelectCallback2(pWalker, p);
88196  }
88197  p = p->pPrior;
88198  }
88199  pWalker->walkerDepth--;
88200  return rc & WRC_Abort;
88201 }
88202 
88203 /************** End of walker.c **********************************************/
88204 /************** Begin file resolve.c *****************************************/
88205 /*
88206 ** 2008 August 18
88207 **
88208 ** The author disclaims copyright to this source code. In place of
88209 ** a legal notice, here is a blessing:
88210 **
88211 ** May you do good and not evil.
88212 ** May you find forgiveness for yourself and forgive others.
88213 ** May you share freely, never taking more than you give.
88214 **
88215 *************************************************************************
88216 **
88217 ** This file contains routines used for walking the parser tree and
88218 ** resolve all identifiers by associating them with a particular
88219 ** table and column.
88220 */
88221 /* #include "sqliteInt.h" */
88222 /* #include <stdlib.h> */
88223 /* #include <string.h> */
88224 
88225 /*
88226 ** Walk the expression tree pExpr and increase the aggregate function
88227 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
88228 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
88229 ** outer query into an inner subquery.
88230 **
88231 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
88232 ** is a helper function - a callback for the tree walker.
88233 */
88234 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
88235  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
88236  return WRC_Continue;
88237 }
88238 static void incrAggFunctionDepth(Expr *pExpr, int N){
88239  if( N>0 ){
88240  Walker w;
88241  memset(&w, 0, sizeof(w));
88242  w.xExprCallback = incrAggDepth;
88243  w.u.n = N;
88244  sqlite3WalkExpr(&w, pExpr);
88245  }
88246 }
88247 
88248 /*
88249 ** Turn the pExpr expression into an alias for the iCol-th column of the
88250 ** result set in pEList.
88251 **
88252 ** If the reference is followed by a COLLATE operator, then make sure
88253 ** the COLLATE operator is preserved. For example:
88254 **
88255 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
88256 **
88257 ** Should be transformed into:
88258 **
88259 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
88260 **
88261 ** The nSubquery parameter specifies how many levels of subquery the
88262 ** alias is removed from the original expression. The usual value is
88263 ** zero but it might be more if the alias is contained within a subquery
88264 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
88265 ** structures must be increased by the nSubquery amount.
88266 */
88267 static void resolveAlias(
88268  Parse *pParse, /* Parsing context */
88269  ExprList *pEList, /* A result set */
88270  int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
88271  Expr *pExpr, /* Transform this into an alias to the result set */
88272  const char *zType, /* "GROUP" or "ORDER" or "" */
88273  int nSubquery /* Number of subqueries that the label is moving */
88274 ){
88275  Expr *pOrig; /* The iCol-th column of the result set */
88276  Expr *pDup; /* Copy of pOrig */
88277  sqlite3 *db; /* The database connection */
88278 
88279  assert( iCol>=0 && iCol<pEList->nExpr );
88280  pOrig = pEList->a[iCol].pExpr;
88281  assert( pOrig!=0 );
88282  db = pParse->db;
88283  pDup = sqlite3ExprDup(db, pOrig, 0);
88284  if( pDup==0 ) return;
88285  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
88286  if( pExpr->op==TK_COLLATE ){
88287  pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
88288  }
88289  ExprSetProperty(pDup, EP_Alias);
88290 
88291  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
88292  ** prevents ExprDelete() from deleting the Expr structure itself,
88293  ** allowing it to be repopulated by the memcpy() on the following line.
88294  ** The pExpr->u.zToken might point into memory that will be freed by the
88295  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
88296  ** make a copy of the token before doing the sqlite3DbFree().
88297  */
88298  ExprSetProperty(pExpr, EP_Static);
88299  sqlite3ExprDelete(db, pExpr);
88300  memcpy(pExpr, pDup, sizeof(*pExpr));
88301  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
88302  assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
88303  pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
88304  pExpr->flags |= EP_MemToken;
88305  }
88306  sqlite3DbFree(db, pDup);
88307 }
88308 
88309 
88310 /*
88311 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
88312 **
88313 ** Return FALSE if the USING clause is NULL or if it does not contain
88314 ** zCol.
88315 */
88316 static int nameInUsingClause(IdList *pUsing, const char *zCol){
88317  if( pUsing ){
88318  int k;
88319  for(k=0; k<pUsing->nId; k++){
88320  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
88321  }
88322  }
88323  return 0;
88324 }
88325 
88326 /*
88327 ** Subqueries stores the original database, table and column names for their
88328 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
88329 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
88330 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
88331 ** match anything.
88332 */
88333 SQLITE_PRIVATE int sqlite3MatchSpanName(
88334  const char *zSpan,
88335  const char *zCol,
88336  const char *zTab,
88337  const char *zDb
88338 ){
88339  int n;
88340  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88341  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
88342  return 0;
88343  }
88344  zSpan += n+1;
88345  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88346  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
88347  return 0;
88348  }
88349  zSpan += n+1;
88350  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
88351  return 0;
88352  }
88353  return 1;
88354 }
88355 
88356 /*
88357 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
88358 ** that name in the set of source tables in pSrcList and make the pExpr
88359 ** expression node refer back to that source column. The following changes
88360 ** are made to pExpr:
88361 **
88362 ** pExpr->iDb Set the index in db->aDb[] of the database X
88363 ** (even if X is implied).
88364 ** pExpr->iTable Set to the cursor number for the table obtained
88365 ** from pSrcList.
88366 ** pExpr->pTab Points to the Table structure of X.Y (even if
88367 ** X and/or Y are implied.)
88368 ** pExpr->iColumn Set to the column number within the table.
88369 ** pExpr->op Set to TK_COLUMN.
88370 ** pExpr->pLeft Any expression this points to is deleted
88371 ** pExpr->pRight Any expression this points to is deleted.
88372 **
88373 ** The zDb variable is the name of the database (the "X"). This value may be
88374 ** NULL meaning that name is of the form Y.Z or Z. Any available database
88375 ** can be used. The zTable variable is the name of the table (the "Y"). This
88376 ** value can be NULL if zDb is also NULL. If zTable is NULL it
88377 ** means that the form of the name is Z and that columns from any table
88378 ** can be used.
88379 **
88380 ** If the name cannot be resolved unambiguously, leave an error message
88381 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
88382 */
88383 static int lookupName(
88384  Parse *pParse, /* The parsing context */
88385  const char *zDb, /* Name of the database containing table, or NULL */
88386  const char *zTab, /* Name of table containing column, or NULL */
88387  const char *zCol, /* Name of the column. */
88388  NameContext *pNC, /* The name context used to resolve the name */
88389  Expr *pExpr /* Make this EXPR node point to the selected column */
88390 ){
88391  int i, j; /* Loop counters */
88392  int cnt = 0; /* Number of matching column names */
88393  int cntTab = 0; /* Number of matching table names */
88394  int nSubquery = 0; /* How many levels of subquery */
88395  sqlite3 *db = pParse->db; /* The database connection */
88396  struct SrcList_item *pItem; /* Use for looping over pSrcList items */
88397  struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
88398  NameContext *pTopNC = pNC; /* First namecontext in the list */
88399  Schema *pSchema = 0; /* Schema of the expression */
88400  int isTrigger = 0; /* True if resolved to a trigger column */
88401  Table *pTab = 0; /* Table hold the row */
88402  Column *pCol; /* A column of pTab */
88403 
88404  assert( pNC ); /* the name context cannot be NULL. */
88405  assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
88406  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
88407 
88408  /* Initialize the node to no-match */
88409  pExpr->iTable = -1;
88410  pExpr->pTab = 0;
88411  ExprSetVVAProperty(pExpr, EP_NoReduce);
88412 
88413  /* Translate the schema name in zDb into a pointer to the corresponding
88414  ** schema. If not found, pSchema will remain NULL and nothing will match
88415  ** resulting in an appropriate error message toward the end of this routine
88416  */
88417  if( zDb ){
88418  testcase( pNC->ncFlags & NC_PartIdx );
88419  testcase( pNC->ncFlags & NC_IsCheck );
88420  if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
88421  /* Silently ignore database qualifiers inside CHECK constraints and
88422  ** partial indices. Do not raise errors because that might break
88423  ** legacy and because it does not hurt anything to just ignore the
88424  ** database name. */
88425  zDb = 0;
88426  }else{
88427  for(i=0; i<db->nDb; i++){
88428  assert( db->aDb[i].zDbSName );
88429  if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
88430  pSchema = db->aDb[i].pSchema;
88431  break;
88432  }
88433  }
88434  }
88435  }
88436 
88437  /* Start at the inner-most context and move outward until a match is found */
88438  while( pNC && cnt==0 ){
88439  ExprList *pEList;
88440  SrcList *pSrcList = pNC->pSrcList;
88441 
88442  if( pSrcList ){
88443  for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
88444  pTab = pItem->pTab;
88445  assert( pTab!=0 && pTab->zName!=0 );
88446  assert( pTab->nCol>0 );
88447  if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
88448  int hit = 0;
88449  pEList = pItem->pSelect->pEList;
88450  for(j=0; j<pEList->nExpr; j++){
88451  if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
88452  cnt++;
88453  cntTab = 2;
88454  pMatch = pItem;
88455  pExpr->iColumn = j;
88456  hit = 1;
88457  }
88458  }
88459  if( hit || zTab==0 ) continue;
88460  }
88461  if( zDb && pTab->pSchema!=pSchema ){
88462  continue;
88463  }
88464  if( zTab ){
88465  const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
88466  assert( zTabName!=0 );
88467  if( sqlite3StrICmp(zTabName, zTab)!=0 ){
88468  continue;
88469  }
88470  }
88471  if( 0==(cntTab++) ){
88472  pMatch = pItem;
88473  }
88474  for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
88475  if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88476  /* If there has been exactly one prior match and this match
88477  ** is for the right-hand table of a NATURAL JOIN or is in a
88478  ** USING clause, then skip this match.
88479  */
88480  if( cnt==1 ){
88481  if( pItem->fg.jointype & JT_NATURAL ) continue;
88482  if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
88483  }
88484  cnt++;
88485  pMatch = pItem;
88486  /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
88487  pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
88488  break;
88489  }
88490  }
88491  }
88492  if( pMatch ){
88493  pExpr->iTable = pMatch->iCursor;
88494  pExpr->pTab = pMatch->pTab;
88495  /* RIGHT JOIN not (yet) supported */
88496  assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
88497  if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
88498  ExprSetProperty(pExpr, EP_CanBeNull);
88499  }
88500  pSchema = pExpr->pTab->pSchema;
88501  }
88502  } /* if( pSrcList ) */
88503 
88504 #ifndef SQLITE_OMIT_TRIGGER
88505  /* If we have not already resolved the name, then maybe
88506  ** it is a new.* or old.* trigger argument reference
88507  */
88508  if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
88509  int op = pParse->eTriggerOp;
88510  assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
88511  if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
88512  pExpr->iTable = 1;
88513  pTab = pParse->pTriggerTab;
88514  }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
88515  pExpr->iTable = 0;
88516  pTab = pParse->pTriggerTab;
88517  }else{
88518  pTab = 0;
88519  }
88520 
88521  if( pTab ){
88522  int iCol;
88523  pSchema = pTab->pSchema;
88524  cntTab++;
88525  for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
88526  if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88527  if( iCol==pTab->iPKey ){
88528  iCol = -1;
88529  }
88530  break;
88531  }
88532  }
88533  if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
88534  /* IMP: R-51414-32910 */
88535  iCol = -1;
88536  }
88537  if( iCol<pTab->nCol ){
88538  cnt++;
88539  if( iCol<0 ){
88540  pExpr->affinity = SQLITE_AFF_INTEGER;
88541  }else if( pExpr->iTable==0 ){
88542  testcase( iCol==31 );
88543  testcase( iCol==32 );
88544  pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88545  }else{
88546  testcase( iCol==31 );
88547  testcase( iCol==32 );
88548  pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88549  }
88550  pExpr->iColumn = (i16)iCol;
88551  pExpr->pTab = pTab;
88552  isTrigger = 1;
88553  }
88554  }
88555  }
88556 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
88557 
88558  /*
88559  ** Perhaps the name is a reference to the ROWID
88560  */
88561  if( cnt==0
88562  && cntTab==1
88563  && pMatch
88564  && (pNC->ncFlags & NC_IdxExpr)==0
88565  && sqlite3IsRowid(zCol)
88566  && VisibleRowid(pMatch->pTab)
88567  ){
88568  cnt = 1;
88569  pExpr->iColumn = -1;
88570  pExpr->affinity = SQLITE_AFF_INTEGER;
88571  }
88572 
88573  /*
88574  ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
88575  ** might refer to an result-set alias. This happens, for example, when
88576  ** we are resolving names in the WHERE clause of the following command:
88577  **
88578  ** SELECT a+b AS x FROM table WHERE x<10;
88579  **
88580  ** In cases like this, replace pExpr with a copy of the expression that
88581  ** forms the result set entry ("a+b" in the example) and return immediately.
88582  ** Note that the expression in the result set should have already been
88583  ** resolved by the time the WHERE clause is resolved.
88584  **
88585  ** The ability to use an output result-set column in the WHERE, GROUP BY,
88586  ** or HAVING clauses, or as part of a larger expression in the ORDER BY
88587  ** clause is not standard SQL. This is a (goofy) SQLite extension, that
88588  ** is supported for backwards compatibility only. Hence, we issue a warning
88589  ** on sqlite3_log() whenever the capability is used.
88590  */
88591  if( (pEList = pNC->pEList)!=0
88592  && zTab==0
88593  && cnt==0
88594  ){
88595  for(j=0; j<pEList->nExpr; j++){
88596  char *zAs = pEList->a[j].zName;
88597  if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
88598  Expr *pOrig;
88599  assert( pExpr->pLeft==0 && pExpr->pRight==0 );
88600  assert( pExpr->x.pList==0 );
88601  assert( pExpr->x.pSelect==0 );
88602  pOrig = pEList->a[j].pExpr;
88603  if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
88604  sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
88605  return WRC_Abort;
88606  }
88607  resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
88608  cnt = 1;
88609  pMatch = 0;
88610  assert( zTab==0 && zDb==0 );
88611  goto lookupname_end;
88612  }
88613  }
88614  }
88615 
88616  /* Advance to the next name context. The loop will exit when either
88617  ** we have a match (cnt>0) or when we run out of name contexts.
88618  */
88619  if( cnt==0 ){
88620  pNC = pNC->pNext;
88621  nSubquery++;
88622  }
88623  }
88624 
88625  /*
88626  ** If X and Y are NULL (in other words if only the column name Z is
88627  ** supplied) and the value of Z is enclosed in double-quotes, then
88628  ** Z is a string literal if it doesn't match any column names. In that
88629  ** case, we need to return right away and not make any changes to
88630  ** pExpr.
88631  **
88632  ** Because no reference was made to outer contexts, the pNC->nRef
88633  ** fields are not changed in any context.
88634  */
88635  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
88636  pExpr->op = TK_STRING;
88637  pExpr->pTab = 0;
88638  return WRC_Prune;
88639  }
88640 
88641  /*
88642  ** cnt==0 means there was not match. cnt>1 means there were two or
88643  ** more matches. Either way, we have an error.
88644  */
88645  if( cnt!=1 ){
88646  const char *zErr;
88647  zErr = cnt==0 ? "no such column" : "ambiguous column name";
88648  if( zDb ){
88649  sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
88650  }else if( zTab ){
88651  sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
88652  }else{
88653  sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
88654  }
88655  pParse->checkSchema = 1;
88656  pTopNC->nErr++;
88657  }
88658 
88659  /* If a column from a table in pSrcList is referenced, then record
88660  ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
88661  ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
88662  ** column number is greater than the number of bits in the bitmask
88663  ** then set the high-order bit of the bitmask.
88664  */
88665  if( pExpr->iColumn>=0 && pMatch!=0 ){
88666  int n = pExpr->iColumn;
88667  testcase( n==BMS-1 );
88668  if( n>=BMS ){
88669  n = BMS-1;
88670  }
88671  assert( pMatch->iCursor==pExpr->iTable );
88672  pMatch->colUsed |= ((Bitmask)1)<<n;
88673  }
88674 
88675  /* Clean up and return
88676  */
88677  sqlite3ExprDelete(db, pExpr->pLeft);
88678  pExpr->pLeft = 0;
88679  sqlite3ExprDelete(db, pExpr->pRight);
88680  pExpr->pRight = 0;
88681  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
88682 lookupname_end:
88683  if( cnt==1 ){
88684  assert( pNC!=0 );
88685  if( !ExprHasProperty(pExpr, EP_Alias) ){
88686  sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
88687  }
88688  /* Increment the nRef value on all name contexts from TopNC up to
88689  ** the point where the name matched. */
88690  for(;;){
88691  assert( pTopNC!=0 );
88692  pTopNC->nRef++;
88693  if( pTopNC==pNC ) break;
88694  pTopNC = pTopNC->pNext;
88695  }
88696  return WRC_Prune;
88697  } else {
88698  return WRC_Abort;
88699  }
88700 }
88701 
88702 /*
88703 ** Allocate and return a pointer to an expression to load the column iCol
88704 ** from datasource iSrc in SrcList pSrc.
88705 */
88706 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
88707  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
88708  if( p ){
88709  struct SrcList_item *pItem = &pSrc->a[iSrc];
88710  p->pTab = pItem->pTab;
88711  p->iTable = pItem->iCursor;
88712  if( p->pTab->iPKey==iCol ){
88713  p->iColumn = -1;
88714  }else{
88715  p->iColumn = (ynVar)iCol;
88716  testcase( iCol==BMS );
88717  testcase( iCol==BMS-1 );
88718  pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
88719  }
88720  ExprSetProperty(p, EP_Resolved);
88721  }
88722  return p;
88723 }
88724 
88725 /*
88726 ** Report an error that an expression is not valid for some set of
88727 ** pNC->ncFlags values determined by validMask.
88728 */
88729 static void notValid(
88730  Parse *pParse, /* Leave error message here */
88731  NameContext *pNC, /* The name context */
88732  const char *zMsg, /* Type of error */
88733  int validMask /* Set of contexts for which prohibited */
88734 ){
88735  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
88736  if( (pNC->ncFlags & validMask)!=0 ){
88737  const char *zIn = "partial index WHERE clauses";
88738  if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
88739 #ifndef SQLITE_OMIT_CHECK
88740  else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
88741 #endif
88742  sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
88743  }
88744 }
88745 
88746 /*
88747 ** Expression p should encode a floating point value between 1.0 and 0.0.
88748 ** Return 1024 times this value. Or return -1 if p is not a floating point
88749 ** value between 1.0 and 0.0.
88750 */
88751 static int exprProbability(Expr *p){
88752  double r = -1.0;
88753  if( p->op!=TK_FLOAT ) return -1;
88754  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
88755  assert( r>=0.0 );
88756  if( r>1.0 ) return -1;
88757  return (int)(r*134217728.0);
88758 }
88759 
88760 /*
88761 ** This routine is callback for sqlite3WalkExpr().
88762 **
88763 ** Resolve symbolic names into TK_COLUMN operators for the current
88764 ** node in the expression tree. Return 0 to continue the search down
88765 ** the tree or 2 to abort the tree walk.
88766 **
88767 ** This routine also does error checking and name resolution for
88768 ** function names. The operator for aggregate functions is changed
88769 ** to TK_AGG_FUNCTION.
88770 */
88771 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
88772  NameContext *pNC;
88773  Parse *pParse;
88774 
88775  pNC = pWalker->u.pNC;
88776  assert( pNC!=0 );
88777  pParse = pNC->pParse;
88778  assert( pParse==pWalker->pParse );
88779 
88780  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
88781  ExprSetProperty(pExpr, EP_Resolved);
88782 #ifndef NDEBUG
88783  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
88784  SrcList *pSrcList = pNC->pSrcList;
88785  int i;
88786  for(i=0; i<pNC->pSrcList->nSrc; i++){
88787  assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
88788  }
88789  }
88790 #endif
88791  switch( pExpr->op ){
88792 
88793 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
88794  /* The special operator TK_ROW means use the rowid for the first
88795  ** column in the FROM clause. This is used by the LIMIT and ORDER BY
88796  ** clause processing on UPDATE and DELETE statements.
88797  */
88798  case TK_ROW: {
88799  SrcList *pSrcList = pNC->pSrcList;
88800  struct SrcList_item *pItem;
88801  assert( pSrcList && pSrcList->nSrc==1 );
88802  pItem = pSrcList->a;
88803  pExpr->op = TK_COLUMN;
88804  pExpr->pTab = pItem->pTab;
88805  pExpr->iTable = pItem->iCursor;
88806  pExpr->iColumn = -1;
88807  pExpr->affinity = SQLITE_AFF_INTEGER;
88808  break;
88809  }
88810 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
88811  && !defined(SQLITE_OMIT_SUBQUERY) */
88812 
88813  /* A lone identifier is the name of a column.
88814  */
88815  case TK_ID: {
88816  return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
88817  }
88818 
88819  /* A table name and column name: ID.ID
88820  ** Or a database, table and column: ID.ID.ID
88821  */
88822  case TK_DOT: {
88823  const char *zColumn;
88824  const char *zTable;
88825  const char *zDb;
88826  Expr *pRight;
88827 
88828  /* if( pSrcList==0 ) break; */
88829  notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
88830  pRight = pExpr->pRight;
88831  if( pRight->op==TK_ID ){
88832  zDb = 0;
88833  zTable = pExpr->pLeft->u.zToken;
88834  zColumn = pRight->u.zToken;
88835  }else{
88836  assert( pRight->op==TK_DOT );
88837  zDb = pExpr->pLeft->u.zToken;
88838  zTable = pRight->pLeft->u.zToken;
88839  zColumn = pRight->pRight->u.zToken;
88840  }
88841  return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
88842  }
88843 
88844  /* Resolve function names
88845  */
88846  case TK_FUNCTION: {
88847  ExprList *pList = pExpr->x.pList; /* The argument list */
88848  int n = pList ? pList->nExpr : 0; /* Number of arguments */
88849  int no_such_func = 0; /* True if no such function exists */
88850  int wrong_num_args = 0; /* True if wrong number of arguments */
88851  int is_agg = 0; /* True if is an aggregate function */
88852  int nId; /* Number of characters in function name */
88853  const char *zId; /* The function name. */
88854  FuncDef *pDef; /* Information about the function */
88855  u8 enc = ENC(pParse->db); /* The database encoding */
88856 
88857  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88858  zId = pExpr->u.zToken;
88859  nId = sqlite3Strlen30(zId);
88860  pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
88861  if( pDef==0 ){
88862  pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
88863  if( pDef==0 ){
88864  no_such_func = 1;
88865  }else{
88866  wrong_num_args = 1;
88867  }
88868  }else{
88869  is_agg = pDef->xFinalize!=0;
88870  if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
88871  ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
88872  if( n==2 ){
88873  pExpr->iTable = exprProbability(pList->a[1].pExpr);
88874  if( pExpr->iTable<0 ){
88875  sqlite3ErrorMsg(pParse,
88876  "second argument to likelihood() must be a "
88877  "constant between 0.0 and 1.0");
88878  pNC->nErr++;
88879  }
88880  }else{
88881  /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
88882  ** equivalent to likelihood(X, 0.0625).
88883  ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
88884  ** short-hand for likelihood(X,0.0625).
88885  ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
88886  ** for likelihood(X,0.9375).
88887  ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
88888  ** to likelihood(X,0.9375). */
88889  /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
88890  pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
88891  }
88892  }
88893 #ifndef SQLITE_OMIT_AUTHORIZATION
88894  {
88895  int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
88896  if( auth!=SQLITE_OK ){
88897  if( auth==SQLITE_DENY ){
88898  sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
88899  pDef->zName);
88900  pNC->nErr++;
88901  }
88902  pExpr->op = TK_NULL;
88903  return WRC_Prune;
88904  }
88905  }
88906 #endif
88907  if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
88908  /* For the purposes of the EP_ConstFunc flag, date and time
88909  ** functions and other functions that change slowly are considered
88910  ** constant because they are constant for the duration of one query */
88911  ExprSetProperty(pExpr,EP_ConstFunc);
88912  }
88913  if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
88914  /* Date/time functions that use 'now', and other functions like
88915  ** sqlite_version() that might change over time cannot be used
88916  ** in an index. */
88917  notValid(pParse, pNC, "non-deterministic functions",
88918  NC_IdxExpr|NC_PartIdx);
88919  }
88920  }
88921  if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
88922  sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
88923  pNC->nErr++;
88924  is_agg = 0;
88925  }else if( no_such_func && pParse->db->init.busy==0
88926 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
88927  && pParse->explain==0
88928 #endif
88929  ){
88930  sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
88931  pNC->nErr++;
88932  }else if( wrong_num_args ){
88933  sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
88934  nId, zId);
88935  pNC->nErr++;
88936  }
88937  if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
88938  sqlite3WalkExprList(pWalker, pList);
88939  if( is_agg ){
88940  NameContext *pNC2 = pNC;
88941  pExpr->op = TK_AGG_FUNCTION;
88942  pExpr->op2 = 0;
88943  while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
88944  pExpr->op2++;
88945  pNC2 = pNC2->pNext;
88946  }
88947  assert( pDef!=0 );
88948  if( pNC2 ){
88949  assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
88950  testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
88951  pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
88952 
88953  }
88954  pNC->ncFlags |= NC_AllowAgg;
88955  }
88956  /* FIX ME: Compute pExpr->affinity based on the expected return
88957  ** type of the function
88958  */
88959  return WRC_Prune;
88960  }
88961 #ifndef SQLITE_OMIT_SUBQUERY
88962  case TK_SELECT:
88963  case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
88964 #endif
88965  case TK_IN: {
88966  testcase( pExpr->op==TK_IN );
88967  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88968  int nRef = pNC->nRef;
88969  notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88970  sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
88971  assert( pNC->nRef>=nRef );
88972  if( nRef!=pNC->nRef ){
88973  ExprSetProperty(pExpr, EP_VarSelect);
88974  pNC->ncFlags |= NC_VarSelect;
88975  }
88976  }
88977  break;
88978  }
88979  case TK_VARIABLE: {
88980  notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88981  break;
88982  }
88983  case TK_EQ:
88984  case TK_NE:
88985  case TK_LT:
88986  case TK_LE:
88987  case TK_GT:
88988  case TK_GE:
88989  case TK_IS:
88990  case TK_ISNOT: {
88991  int nLeft, nRight;
88992  if( pParse->db->mallocFailed ) break;
88993  assert( pExpr->pRight!=0 );
88994  assert( pExpr->pLeft!=0 );
88995  nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
88996  nRight = sqlite3ExprVectorSize(pExpr->pRight);
88997  if( nLeft!=nRight ){
88998  testcase( pExpr->op==TK_EQ );
88999  testcase( pExpr->op==TK_NE );
89000  testcase( pExpr->op==TK_LT );
89001  testcase( pExpr->op==TK_LE );
89002  testcase( pExpr->op==TK_GT );
89003  testcase( pExpr->op==TK_GE );
89004  testcase( pExpr->op==TK_IS );
89005  testcase( pExpr->op==TK_ISNOT );
89006  sqlite3ErrorMsg(pParse, "row value misused");
89007  }
89008  break;
89009  }
89010  }
89011  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
89012 }
89013 
89014 /*
89015 ** pEList is a list of expressions which are really the result set of the
89016 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
89017 ** This routine checks to see if pE is a simple identifier which corresponds
89018 ** to the AS-name of one of the terms of the expression list. If it is,
89019 ** this routine return an integer between 1 and N where N is the number of
89020 ** elements in pEList, corresponding to the matching entry. If there is
89021 ** no match, or if pE is not a simple identifier, then this routine
89022 ** return 0.
89023 **
89024 ** pEList has been resolved. pE has not.
89025 */
89026 static int resolveAsName(
89027  Parse *pParse, /* Parsing context for error messages */
89028  ExprList *pEList, /* List of expressions to scan */
89029  Expr *pE /* Expression we are trying to match */
89030 ){
89031  int i; /* Loop counter */
89032 
89033  UNUSED_PARAMETER(pParse);
89034 
89035  if( pE->op==TK_ID ){
89036  char *zCol = pE->u.zToken;
89037  for(i=0; i<pEList->nExpr; i++){
89038  char *zAs = pEList->a[i].zName;
89039  if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
89040  return i+1;
89041  }
89042  }
89043  }
89044  return 0;
89045 }
89046 
89047 /*
89048 ** pE is a pointer to an expression which is a single term in the
89049 ** ORDER BY of a compound SELECT. The expression has not been
89050 ** name resolved.
89051 **
89052 ** At the point this routine is called, we already know that the
89053 ** ORDER BY term is not an integer index into the result set. That
89054 ** case is handled by the calling routine.
89055 **
89056 ** Attempt to match pE against result set columns in the left-most
89057 ** SELECT statement. Return the index i of the matching column,
89058 ** as an indication to the caller that it should sort by the i-th column.
89059 ** The left-most column is 1. In other words, the value returned is the
89060 ** same integer value that would be used in the SQL statement to indicate
89061 ** the column.
89062 **
89063 ** If there is no match, return 0. Return -1 if an error occurs.
89064 */
89065 static int resolveOrderByTermToExprList(
89066  Parse *pParse, /* Parsing context for error messages */
89067  Select *pSelect, /* The SELECT statement with the ORDER BY clause */
89068  Expr *pE /* The specific ORDER BY term */
89069 ){
89070  int i; /* Loop counter */
89071  ExprList *pEList; /* The columns of the result set */
89072  NameContext nc; /* Name context for resolving pE */
89073  sqlite3 *db; /* Database connection */
89074  int rc; /* Return code from subprocedures */
89075  u8 savedSuppErr; /* Saved value of db->suppressErr */
89076 
89077  assert( sqlite3ExprIsInteger(pE, &i)==0 );
89078  pEList = pSelect->pEList;
89079 
89080  /* Resolve all names in the ORDER BY term expression
89081  */
89082  memset(&nc, 0, sizeof(nc));
89083  nc.pParse = pParse;
89084  nc.pSrcList = pSelect->pSrc;
89085  nc.pEList = pEList;
89086  nc.ncFlags = NC_AllowAgg;
89087  nc.nErr = 0;
89088  db = pParse->db;
89089  savedSuppErr = db->suppressErr;
89090  db->suppressErr = 1;
89091  rc = sqlite3ResolveExprNames(&nc, pE);
89092  db->suppressErr = savedSuppErr;
89093  if( rc ) return 0;
89094 
89095  /* Try to match the ORDER BY expression against an expression
89096  ** in the result set. Return an 1-based index of the matching
89097  ** result-set entry.
89098  */
89099  for(i=0; i<pEList->nExpr; i++){
89100  if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
89101  return i+1;
89102  }
89103  }
89104 
89105  /* If no match, return 0. */
89106  return 0;
89107 }
89108 
89109 /*
89110 ** Generate an ORDER BY or GROUP BY term out-of-range error.
89111 */
89112 static void resolveOutOfRangeError(
89113  Parse *pParse, /* The error context into which to write the error */
89114  const char *zType, /* "ORDER" or "GROUP" */
89115  int i, /* The index (1-based) of the term out of range */
89116  int mx /* Largest permissible value of i */
89117 ){
89118  sqlite3ErrorMsg(pParse,
89119  "%r %s BY term out of range - should be "
89120  "between 1 and %d", i, zType, mx);
89121 }
89122 
89123 /*
89124 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
89125 ** each term of the ORDER BY clause is a constant integer between 1
89126 ** and N where N is the number of columns in the compound SELECT.
89127 **
89128 ** ORDER BY terms that are already an integer between 1 and N are
89129 ** unmodified. ORDER BY terms that are integers outside the range of
89130 ** 1 through N generate an error. ORDER BY terms that are expressions
89131 ** are matched against result set expressions of compound SELECT
89132 ** beginning with the left-most SELECT and working toward the right.
89133 ** At the first match, the ORDER BY expression is transformed into
89134 ** the integer column number.
89135 **
89136 ** Return the number of errors seen.
89137 */
89138 static int resolveCompoundOrderBy(
89139  Parse *pParse, /* Parsing context. Leave error messages here */
89140  Select *pSelect /* The SELECT statement containing the ORDER BY */
89141 ){
89142  int i;
89143  ExprList *pOrderBy;
89144  ExprList *pEList;
89145  sqlite3 *db;
89146  int moreToDo = 1;
89147 
89148  pOrderBy = pSelect->pOrderBy;
89149  if( pOrderBy==0 ) return 0;
89150  db = pParse->db;
89151 #if SQLITE_MAX_COLUMN
89152  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
89153  sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
89154  return 1;
89155  }
89156 #endif
89157  for(i=0; i<pOrderBy->nExpr; i++){
89158  pOrderBy->a[i].done = 0;
89159  }
89160  pSelect->pNext = 0;
89161  while( pSelect->pPrior ){
89162  pSelect->pPrior->pNext = pSelect;
89163  pSelect = pSelect->pPrior;
89164  }
89165  while( pSelect && moreToDo ){
89166  struct ExprList_item *pItem;
89167  moreToDo = 0;
89168  pEList = pSelect->pEList;
89169  assert( pEList!=0 );
89170  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
89171  int iCol = -1;
89172  Expr *pE, *pDup;
89173  if( pItem->done ) continue;
89174  pE = sqlite3ExprSkipCollate(pItem->pExpr);
89175  if( sqlite3ExprIsInteger(pE, &iCol) ){
89176  if( iCol<=0 || iCol>pEList->nExpr ){
89177  resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
89178  return 1;
89179  }
89180  }else{
89181  iCol = resolveAsName(pParse, pEList, pE);
89182  if( iCol==0 ){
89183  pDup = sqlite3ExprDup(db, pE, 0);
89184  if( !db->mallocFailed ){
89185  assert(pDup);
89186  iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
89187  }
89188  sqlite3ExprDelete(db, pDup);
89189  }
89190  }
89191  if( iCol>0 ){
89192  /* Convert the ORDER BY term into an integer column number iCol,
89193  ** taking care to preserve the COLLATE clause if it exists */
89194  Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
89195  if( pNew==0 ) return 1;
89196  pNew->flags |= EP_IntValue;
89197  pNew->u.iValue = iCol;
89198  if( pItem->pExpr==pE ){
89199  pItem->pExpr = pNew;
89200  }else{
89201  Expr *pParent = pItem->pExpr;
89202  assert( pParent->op==TK_COLLATE );
89203  while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
89204  assert( pParent->pLeft==pE );
89205  pParent->pLeft = pNew;
89206  }
89207  sqlite3ExprDelete(db, pE);
89208  pItem->u.x.iOrderByCol = (u16)iCol;
89209  pItem->done = 1;
89210  }else{
89211  moreToDo = 1;
89212  }
89213  }
89214  pSelect = pSelect->pNext;
89215  }
89216  for(i=0; i<pOrderBy->nExpr; i++){
89217  if( pOrderBy->a[i].done==0 ){
89218  sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
89219  "column in the result set", i+1);
89220  return 1;
89221  }
89222  }
89223  return 0;
89224 }
89225 
89226 /*
89227 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
89228 ** the SELECT statement pSelect. If any term is reference to a
89229 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
89230 ** field) then convert that term into a copy of the corresponding result set
89231 ** column.
89232 **
89233 ** If any errors are detected, add an error message to pParse and
89234 ** return non-zero. Return zero if no errors are seen.
89235 */
89236 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
89237  Parse *pParse, /* Parsing context. Leave error messages here */
89238  Select *pSelect, /* The SELECT statement containing the clause */
89239  ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
89240  const char *zType /* "ORDER" or "GROUP" */
89241 ){
89242  int i;
89243  sqlite3 *db = pParse->db;
89244  ExprList *pEList;
89245  struct ExprList_item *pItem;
89246 
89247  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
89248 #if SQLITE_MAX_COLUMN
89249  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
89250  sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
89251  return 1;
89252  }
89253 #endif
89254  pEList = pSelect->pEList;
89255  assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
89256  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
89257  if( pItem->u.x.iOrderByCol ){
89258  if( pItem->u.x.iOrderByCol>pEList->nExpr ){
89259  resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
89260  return 1;
89261  }
89262  resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
89263  zType,0);
89264  }
89265  }
89266  return 0;
89267 }
89268 
89269 /*
89270 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
89271 ** The Name context of the SELECT statement is pNC. zType is either
89272 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
89273 **
89274 ** This routine resolves each term of the clause into an expression.
89275 ** If the order-by term is an integer I between 1 and N (where N is the
89276 ** number of columns in the result set of the SELECT) then the expression
89277 ** in the resolution is a copy of the I-th result-set expression. If
89278 ** the order-by term is an identifier that corresponds to the AS-name of
89279 ** a result-set expression, then the term resolves to a copy of the
89280 ** result-set expression. Otherwise, the expression is resolved in
89281 ** the usual way - using sqlite3ResolveExprNames().
89282 **
89283 ** This routine returns the number of errors. If errors occur, then
89284 ** an appropriate error message might be left in pParse. (OOM errors
89285 ** excepted.)
89286 */
89287 static int resolveOrderGroupBy(
89288  NameContext *pNC, /* The name context of the SELECT statement */
89289  Select *pSelect, /* The SELECT statement holding pOrderBy */
89290  ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
89291  const char *zType /* Either "ORDER" or "GROUP", as appropriate */
89292 ){
89293  int i, j; /* Loop counters */
89294  int iCol; /* Column number */
89295  struct ExprList_item *pItem; /* A term of the ORDER BY clause */
89296  Parse *pParse; /* Parsing context */
89297  int nResult; /* Number of terms in the result set */
89298 
89299  if( pOrderBy==0 ) return 0;
89300  nResult = pSelect->pEList->nExpr;
89301  pParse = pNC->pParse;
89302  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
89303  Expr *pE = pItem->pExpr;
89304  Expr *pE2 = sqlite3ExprSkipCollate(pE);
89305  if( zType[0]!='G' ){
89306  iCol = resolveAsName(pParse, pSelect->pEList, pE2);
89307  if( iCol>0 ){
89308  /* If an AS-name match is found, mark this ORDER BY column as being
89309  ** a copy of the iCol-th result-set column. The subsequent call to
89310  ** sqlite3ResolveOrderGroupBy() will convert the expression to a
89311  ** copy of the iCol-th result-set expression. */
89312  pItem->u.x.iOrderByCol = (u16)iCol;
89313  continue;
89314  }
89315  }
89316  if( sqlite3ExprIsInteger(pE2, &iCol) ){
89317  /* The ORDER BY term is an integer constant. Again, set the column
89318  ** number so that sqlite3ResolveOrderGroupBy() will convert the
89319  ** order-by term to a copy of the result-set expression */
89320  if( iCol<1 || iCol>0xffff ){
89321  resolveOutOfRangeError(pParse, zType, i+1, nResult);
89322  return 1;
89323  }
89324  pItem->u.x.iOrderByCol = (u16)iCol;
89325  continue;
89326  }
89327 
89328  /* Otherwise, treat the ORDER BY term as an ordinary expression */
89329  pItem->u.x.iOrderByCol = 0;
89330  if( sqlite3ResolveExprNames(pNC, pE) ){
89331  return 1;
89332  }
89333  for(j=0; j<pSelect->pEList->nExpr; j++){
89334  if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
89335  pItem->u.x.iOrderByCol = j+1;
89336  }
89337  }
89338  }
89339  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
89340 }
89341 
89342 /*
89343 ** Resolve names in the SELECT statement p and all of its descendants.
89344 */
89345 static int resolveSelectStep(Walker *pWalker, Select *p){
89346  NameContext *pOuterNC; /* Context that contains this SELECT */
89347  NameContext sNC; /* Name context of this SELECT */
89348  int isCompound; /* True if p is a compound select */
89349  int nCompound; /* Number of compound terms processed so far */
89350  Parse *pParse; /* Parsing context */
89351  int i; /* Loop counter */
89352  ExprList *pGroupBy; /* The GROUP BY clause */
89353  Select *pLeftmost; /* Left-most of SELECT of a compound */
89354  sqlite3 *db; /* Database connection */
89355 
89356 
89357  assert( p!=0 );
89358  if( p->selFlags & SF_Resolved ){
89359  return WRC_Prune;
89360  }
89361  pOuterNC = pWalker->u.pNC;
89362  pParse = pWalker->pParse;
89363  db = pParse->db;
89364 
89365  /* Normally sqlite3SelectExpand() will be called first and will have
89366  ** already expanded this SELECT. However, if this is a subquery within
89367  ** an expression, sqlite3ResolveExprNames() will be called without a
89368  ** prior call to sqlite3SelectExpand(). When that happens, let
89369  ** sqlite3SelectPrep() do all of the processing for this SELECT.
89370  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
89371  ** this routine in the correct order.
89372  */
89373  if( (p->selFlags & SF_Expanded)==0 ){
89374  sqlite3SelectPrep(pParse, p, pOuterNC);
89375  return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
89376  }
89377 
89378  isCompound = p->pPrior!=0;
89379  nCompound = 0;
89380  pLeftmost = p;
89381  while( p ){
89382  assert( (p->selFlags & SF_Expanded)!=0 );
89383  assert( (p->selFlags & SF_Resolved)==0 );
89384  p->selFlags |= SF_Resolved;
89385 
89386  /* Resolve the expressions in the LIMIT and OFFSET clauses. These
89387  ** are not allowed to refer to any names, so pass an empty NameContext.
89388  */
89389  memset(&sNC, 0, sizeof(sNC));
89390  sNC.pParse = pParse;
89391  if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
89392  sqlite3ResolveExprNames(&sNC, p->pOffset) ){
89393  return WRC_Abort;
89394  }
89395 
89396  /* If the SF_Converted flags is set, then this Select object was
89397  ** was created by the convertCompoundSelectToSubquery() function.
89398  ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
89399  ** as if it were part of the sub-query, not the parent. This block
89400  ** moves the pOrderBy down to the sub-query. It will be moved back
89401  ** after the names have been resolved. */
89402  if( p->selFlags & SF_Converted ){
89403  Select *pSub = p->pSrc->a[0].pSelect;
89404  assert( p->pSrc->nSrc==1 && p->pOrderBy );
89405  assert( pSub->pPrior && pSub->pOrderBy==0 );
89406  pSub->pOrderBy = p->pOrderBy;
89407  p->pOrderBy = 0;
89408  }
89409 
89410  /* Recursively resolve names in all subqueries
89411  */
89412  for(i=0; i<p->pSrc->nSrc; i++){
89413  struct SrcList_item *pItem = &p->pSrc->a[i];
89414  if( pItem->pSelect ){
89415  NameContext *pNC; /* Used to iterate name contexts */
89416  int nRef = 0; /* Refcount for pOuterNC and outer contexts */
89417  const char *zSavedContext = pParse->zAuthContext;
89418 
89419  /* Count the total number of references to pOuterNC and all of its
89420  ** parent contexts. After resolving references to expressions in
89421  ** pItem->pSelect, check if this value has changed. If so, then
89422  ** SELECT statement pItem->pSelect must be correlated. Set the
89423  ** pItem->fg.isCorrelated flag if this is the case. */
89424  for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
89425 
89426  if( pItem->zName ) pParse->zAuthContext = pItem->zName;
89427  sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
89428  pParse->zAuthContext = zSavedContext;
89429  if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
89430 
89431  for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
89432  assert( pItem->fg.isCorrelated==0 && nRef<=0 );
89433  pItem->fg.isCorrelated = (nRef!=0);
89434  }
89435  }
89436 
89437  /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
89438  ** resolve the result-set expression list.
89439  */
89440  sNC.ncFlags = NC_AllowAgg;
89441  sNC.pSrcList = p->pSrc;
89442  sNC.pNext = pOuterNC;
89443 
89444  /* Resolve names in the result set. */
89445  if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
89446 
89447  /* If there are no aggregate functions in the result-set, and no GROUP BY
89448  ** expression, do not allow aggregates in any of the other expressions.
89449  */
89450  assert( (p->selFlags & SF_Aggregate)==0 );
89451  pGroupBy = p->pGroupBy;
89452  if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
89453  assert( NC_MinMaxAgg==SF_MinMaxAgg );
89454  p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
89455  }else{
89456  sNC.ncFlags &= ~NC_AllowAgg;
89457  }
89458 
89459  /* If a HAVING clause is present, then there must be a GROUP BY clause.
89460  */
89461  if( p->pHaving && !pGroupBy ){
89462  sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
89463  return WRC_Abort;
89464  }
89465 
89466  /* Add the output column list to the name-context before parsing the
89467  ** other expressions in the SELECT statement. This is so that
89468  ** expressions in the WHERE clause (etc.) can refer to expressions by
89469  ** aliases in the result set.
89470  **
89471  ** Minor point: If this is the case, then the expression will be
89472  ** re-evaluated for each reference to it.
89473  */
89474  sNC.pEList = p->pEList;
89475  if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
89476  if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
89477 
89478  /* Resolve names in table-valued-function arguments */
89479  for(i=0; i<p->pSrc->nSrc; i++){
89480  struct SrcList_item *pItem = &p->pSrc->a[i];
89481  if( pItem->fg.isTabFunc
89482  && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
89483  ){
89484  return WRC_Abort;
89485  }
89486  }
89487 
89488  /* The ORDER BY and GROUP BY clauses may not refer to terms in
89489  ** outer queries
89490  */
89491  sNC.pNext = 0;
89492  sNC.ncFlags |= NC_AllowAgg;
89493 
89494  /* If this is a converted compound query, move the ORDER BY clause from
89495  ** the sub-query back to the parent query. At this point each term
89496  ** within the ORDER BY clause has been transformed to an integer value.
89497  ** These integers will be replaced by copies of the corresponding result
89498  ** set expressions by the call to resolveOrderGroupBy() below. */
89499  if( p->selFlags & SF_Converted ){
89500  Select *pSub = p->pSrc->a[0].pSelect;
89501  p->pOrderBy = pSub->pOrderBy;
89502  pSub->pOrderBy = 0;
89503  }
89504 
89505  /* Process the ORDER BY clause for singleton SELECT statements.
89506  ** The ORDER BY clause for compounds SELECT statements is handled
89507  ** below, after all of the result-sets for all of the elements of
89508  ** the compound have been resolved.
89509  **
89510  ** If there is an ORDER BY clause on a term of a compound-select other
89511  ** than the right-most term, then that is a syntax error. But the error
89512  ** is not detected until much later, and so we need to go ahead and
89513  ** resolve those symbols on the incorrect ORDER BY for consistency.
89514  */
89515  if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
89516  && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
89517  ){
89518  return WRC_Abort;
89519  }
89520  if( db->mallocFailed ){
89521  return WRC_Abort;
89522  }
89523 
89524  /* Resolve the GROUP BY clause. At the same time, make sure
89525  ** the GROUP BY clause does not contain aggregate functions.
89526  */
89527  if( pGroupBy ){
89528  struct ExprList_item *pItem;
89529 
89530  if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
89531  return WRC_Abort;
89532  }
89533  for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
89534  if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
89535  sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
89536  "the GROUP BY clause");
89537  return WRC_Abort;
89538  }
89539  }
89540  }
89541 
89542  /* If this is part of a compound SELECT, check that it has the right
89543  ** number of expressions in the select list. */
89544  if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
89545  sqlite3SelectWrongNumTermsError(pParse, p->pNext);
89546  return WRC_Abort;
89547  }
89548 
89549  /* Advance to the next term of the compound
89550  */
89551  p = p->pPrior;
89552  nCompound++;
89553  }
89554 
89555  /* Resolve the ORDER BY on a compound SELECT after all terms of
89556  ** the compound have been resolved.
89557  */
89558  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
89559  return WRC_Abort;
89560  }
89561 
89562  return WRC_Prune;
89563 }
89564 
89565 /*
89566 ** This routine walks an expression tree and resolves references to
89567 ** table columns and result-set columns. At the same time, do error
89568 ** checking on function usage and set a flag if any aggregate functions
89569 ** are seen.
89570 **
89571 ** To resolve table columns references we look for nodes (or subtrees) of the
89572 ** form X.Y.Z or Y.Z or just Z where
89573 **
89574 ** X: The name of a database. Ex: "main" or "temp" or
89575 ** the symbolic name assigned to an ATTACH-ed database.
89576 **
89577 ** Y: The name of a table in a FROM clause. Or in a trigger
89578 ** one of the special names "old" or "new".
89579 **
89580 ** Z: The name of a column in table Y.
89581 **
89582 ** The node at the root of the subtree is modified as follows:
89583 **
89584 ** Expr.op Changed to TK_COLUMN
89585 ** Expr.pTab Points to the Table object for X.Y
89586 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
89587 ** Expr.iTable The VDBE cursor number for X.Y
89588 **
89589 **
89590 ** To resolve result-set references, look for expression nodes of the
89591 ** form Z (with no X and Y prefix) where the Z matches the right-hand
89592 ** size of an AS clause in the result-set of a SELECT. The Z expression
89593 ** is replaced by a copy of the left-hand side of the result-set expression.
89594 ** Table-name and function resolution occurs on the substituted expression
89595 ** tree. For example, in:
89596 **
89597 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
89598 **
89599 ** The "x" term of the order by is replaced by "a+b" to render:
89600 **
89601 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
89602 **
89603 ** Function calls are checked to make sure that the function is
89604 ** defined and that the correct number of arguments are specified.
89605 ** If the function is an aggregate function, then the NC_HasAgg flag is
89606 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
89607 ** If an expression contains aggregate functions then the EP_Agg
89608 ** property on the expression is set.
89609 **
89610 ** An error message is left in pParse if anything is amiss. The number
89611 ** if errors is returned.
89612 */
89613 SQLITE_PRIVATE int sqlite3ResolveExprNames(
89614  NameContext *pNC, /* Namespace to resolve expressions in. */
89615  Expr *pExpr /* The expression to be analyzed. */
89616 ){
89617  u16 savedHasAgg;
89618  Walker w;
89619 
89620  if( pExpr==0 ) return 0;
89621 #if SQLITE_MAX_EXPR_DEPTH>0
89622  {
89623  Parse *pParse = pNC->pParse;
89624  if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
89625  return 1;
89626  }
89627  pParse->nHeight += pExpr->nHeight;
89628  }
89629 #endif
89630  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
89631  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
89632  w.pParse = pNC->pParse;
89633  w.xExprCallback = resolveExprStep;
89634  w.xSelectCallback = resolveSelectStep;
89635  w.xSelectCallback2 = 0;
89636  w.walkerDepth = 0;
89637  w.eCode = 0;
89638  w.u.pNC = pNC;
89639  sqlite3WalkExpr(&w, pExpr);
89640 #if SQLITE_MAX_EXPR_DEPTH>0
89641  pNC->pParse->nHeight -= pExpr->nHeight;
89642 #endif
89643  if( pNC->nErr>0 || w.pParse->nErr>0 ){
89644  ExprSetProperty(pExpr, EP_Error);
89645  }
89646  if( pNC->ncFlags & NC_HasAgg ){
89647  ExprSetProperty(pExpr, EP_Agg);
89648  }
89649  pNC->ncFlags |= savedHasAgg;
89650  return ExprHasProperty(pExpr, EP_Error);
89651 }
89652 
89653 /*
89654 ** Resolve all names for all expression in an expression list. This is
89655 ** just like sqlite3ResolveExprNames() except that it works for an expression
89656 ** list rather than a single expression.
89657 */
89658 SQLITE_PRIVATE int sqlite3ResolveExprListNames(
89659  NameContext *pNC, /* Namespace to resolve expressions in. */
89660  ExprList *pList /* The expression list to be analyzed. */
89661 ){
89662  int i;
89663  if( pList ){
89664  for(i=0; i<pList->nExpr; i++){
89665  if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
89666  }
89667  }
89668  return WRC_Continue;
89669 }
89670 
89671 /*
89672 ** Resolve all names in all expressions of a SELECT and in all
89673 ** decendents of the SELECT, including compounds off of p->pPrior,
89674 ** subqueries in expressions, and subqueries used as FROM clause
89675 ** terms.
89676 **
89677 ** See sqlite3ResolveExprNames() for a description of the kinds of
89678 ** transformations that occur.
89679 **
89680 ** All SELECT statements should have been expanded using
89681 ** sqlite3SelectExpand() prior to invoking this routine.
89682 */
89683 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
89684  Parse *pParse, /* The parser context */
89685  Select *p, /* The SELECT statement being coded. */
89686  NameContext *pOuterNC /* Name context for parent SELECT statement */
89687 ){
89688  Walker w;
89689 
89690  assert( p!=0 );
89691  memset(&w, 0, sizeof(w));
89692  w.xExprCallback = resolveExprStep;
89693  w.xSelectCallback = resolveSelectStep;
89694  w.pParse = pParse;
89695  w.u.pNC = pOuterNC;
89696  sqlite3WalkSelect(&w, p);
89697 }
89698 
89699 /*
89700 ** Resolve names in expressions that can only reference a single table:
89701 **
89702 ** * CHECK constraints
89703 ** * WHERE clauses on partial indices
89704 **
89705 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
89706 ** is set to -1 and the Expr.iColumn value is set to the column number.
89707 **
89708 ** Any errors cause an error message to be set in pParse.
89709 */
89710 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
89711  Parse *pParse, /* Parsing context */
89712  Table *pTab, /* The table being referenced */
89713  int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
89714  Expr *pExpr, /* Expression to resolve. May be NULL. */
89715  ExprList *pList /* Expression list to resolve. May be NUL. */
89716 ){
89717  SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
89718  NameContext sNC; /* Name context for pParse->pNewTable */
89719 
89720  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
89721  memset(&sNC, 0, sizeof(sNC));
89722  memset(&sSrc, 0, sizeof(sSrc));
89723  sSrc.nSrc = 1;
89724  sSrc.a[0].zName = pTab->zName;
89725  sSrc.a[0].pTab = pTab;
89726  sSrc.a[0].iCursor = -1;
89727  sNC.pParse = pParse;
89728  sNC.pSrcList = &sSrc;
89729  sNC.ncFlags = type;
89730  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
89731  if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
89732 }
89733 
89734 /************** End of resolve.c *********************************************/
89735 /************** Begin file expr.c ********************************************/
89736 /*
89737 ** 2001 September 15
89738 **
89739 ** The author disclaims copyright to this source code. In place of
89740 ** a legal notice, here is a blessing:
89741 **
89742 ** May you do good and not evil.
89743 ** May you find forgiveness for yourself and forgive others.
89744 ** May you share freely, never taking more than you give.
89745 **
89746 *************************************************************************
89747 ** This file contains routines used for analyzing expressions and
89748 ** for generating VDBE code that evaluates expressions in SQLite.
89749 */
89750 /* #include "sqliteInt.h" */
89751 
89752 /* Forward declarations */
89753 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
89754 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
89755 
89756 /*
89757 ** Return the affinity character for a single column of a table.
89758 */
89759 SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
89760  assert( iCol<pTab->nCol );
89761  return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
89762 }
89763 
89764 /*
89765 ** Return the 'affinity' of the expression pExpr if any.
89766 **
89767 ** If pExpr is a column, a reference to a column via an 'AS' alias,
89768 ** or a sub-select with a column as the return value, then the
89769 ** affinity of that column is returned. Otherwise, 0x00 is returned,
89770 ** indicating no affinity for the expression.
89771 **
89772 ** i.e. the WHERE clause expressions in the following statements all
89773 ** have an affinity:
89774 **
89775 ** CREATE TABLE t1(a);
89776 ** SELECT * FROM t1 WHERE a;
89777 ** SELECT a AS b FROM t1 WHERE b;
89778 ** SELECT * FROM t1 WHERE (select a from t1);
89779 */
89780 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
89781  int op;
89782  pExpr = sqlite3ExprSkipCollate(pExpr);
89783  if( pExpr->flags & EP_Generic ) return 0;
89784  op = pExpr->op;
89785  if( op==TK_SELECT ){
89786  assert( pExpr->flags&EP_xIsSelect );
89787  return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
89788  }
89789  if( op==TK_REGISTER ) op = pExpr->op2;
89790 #ifndef SQLITE_OMIT_CAST
89791  if( op==TK_CAST ){
89792  assert( !ExprHasProperty(pExpr, EP_IntValue) );
89793  return sqlite3AffinityType(pExpr->u.zToken, 0);
89794  }
89795 #endif
89796  if( op==TK_AGG_COLUMN || op==TK_COLUMN ){
89797  return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
89798  }
89799  if( op==TK_SELECT_COLUMN ){
89800  assert( pExpr->pLeft->flags&EP_xIsSelect );
89801  return sqlite3ExprAffinity(
89802  pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
89803  );
89804  }
89805  return pExpr->affinity;
89806 }
89807 
89808 /*
89809 ** Set the collating sequence for expression pExpr to be the collating
89810 ** sequence named by pToken. Return a pointer to a new Expr node that
89811 ** implements the COLLATE operator.
89812 **
89813 ** If a memory allocation error occurs, that fact is recorded in pParse->db
89814 ** and the pExpr parameter is returned unchanged.
89815 */
89816 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
89817  Parse *pParse, /* Parsing context */
89818  Expr *pExpr, /* Add the "COLLATE" clause to this expression */
89819  const Token *pCollName, /* Name of collating sequence */
89820  int dequote /* True to dequote pCollName */
89821 ){
89822  if( pCollName->n>0 ){
89823  Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
89824  if( pNew ){
89825  pNew->pLeft = pExpr;
89826  pNew->flags |= EP_Collate|EP_Skip;
89827  pExpr = pNew;
89828  }
89829  }
89830  return pExpr;
89831 }
89832 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
89833  Token s;
89834  assert( zC!=0 );
89835  sqlite3TokenInit(&s, (char*)zC);
89836  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
89837 }
89838 
89839 /*
89840 ** Skip over any TK_COLLATE operators and any unlikely()
89841 ** or likelihood() function at the root of an expression.
89842 */
89843 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
89844  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
89845  if( ExprHasProperty(pExpr, EP_Unlikely) ){
89846  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89847  assert( pExpr->x.pList->nExpr>0 );
89848  assert( pExpr->op==TK_FUNCTION );
89849  pExpr = pExpr->x.pList->a[0].pExpr;
89850  }else{
89851  assert( pExpr->op==TK_COLLATE );
89852  pExpr = pExpr->pLeft;
89853  }
89854  }
89855  return pExpr;
89856 }
89857 
89858 /*
89859 ** Return the collation sequence for the expression pExpr. If
89860 ** there is no defined collating sequence, return NULL.
89861 **
89862 ** The collating sequence might be determined by a COLLATE operator
89863 ** or by the presence of a column with a defined collating sequence.
89864 ** COLLATE operators take first precedence. Left operands take
89865 ** precedence over right operands.
89866 */
89867 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
89868  sqlite3 *db = pParse->db;
89869  CollSeq *pColl = 0;
89870  Expr *p = pExpr;
89871  while( p ){
89872  int op = p->op;
89873  if( p->flags & EP_Generic ) break;
89874  if( op==TK_CAST || op==TK_UPLUS ){
89875  p = p->pLeft;
89876  continue;
89877  }
89878  if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
89879  pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
89880  break;
89881  }
89882  if( (op==TK_AGG_COLUMN || op==TK_COLUMN
89883  || op==TK_REGISTER || op==TK_TRIGGER)
89884  && p->pTab!=0
89885  ){
89886  /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
89887  ** a TK_COLUMN but was previously evaluated and cached in a register */
89888  int j = p->iColumn;
89889  if( j>=0 ){
89890  const char *zColl = p->pTab->aCol[j].zColl;
89891  pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
89892  }
89893  break;
89894  }
89895  if( p->flags & EP_Collate ){
89896  if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
89897  p = p->pLeft;
89898  }else{
89899  Expr *pNext = p->pRight;
89900  /* The Expr.x union is never used at the same time as Expr.pRight */
89901  assert( p->x.pList==0 || p->pRight==0 );
89902  /* p->flags holds EP_Collate and p->pLeft->flags does not. And
89903  ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
89904  ** least one EP_Collate. Thus the following two ALWAYS. */
89905  if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
89906  int i;
89907  for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
89908  if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
89909  pNext = p->x.pList->a[i].pExpr;
89910  break;
89911  }
89912  }
89913  }
89914  p = pNext;
89915  }
89916  }else{
89917  break;
89918  }
89919  }
89920  if( sqlite3CheckCollSeq(pParse, pColl) ){
89921  pColl = 0;
89922  }
89923  return pColl;
89924 }
89925 
89926 /*
89927 ** pExpr is an operand of a comparison operator. aff2 is the
89928 ** type affinity of the other operand. This routine returns the
89929 ** type affinity that should be used for the comparison operator.
89930 */
89931 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
89932  char aff1 = sqlite3ExprAffinity(pExpr);
89933  if( aff1 && aff2 ){
89934  /* Both sides of the comparison are columns. If one has numeric
89935  ** affinity, use that. Otherwise use no affinity.
89936  */
89937  if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
89938  return SQLITE_AFF_NUMERIC;
89939  }else{
89940  return SQLITE_AFF_BLOB;
89941  }
89942  }else if( !aff1 && !aff2 ){
89943  /* Neither side of the comparison is a column. Compare the
89944  ** results directly.
89945  */
89946  return SQLITE_AFF_BLOB;
89947  }else{
89948  /* One side is a column, the other is not. Use the columns affinity. */
89949  assert( aff1==0 || aff2==0 );
89950  return (aff1 + aff2);
89951  }
89952 }
89953 
89954 /*
89955 ** pExpr is a comparison operator. Return the type affinity that should
89956 ** be applied to both operands prior to doing the comparison.
89957 */
89958 static char comparisonAffinity(Expr *pExpr){
89959  char aff;
89960  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
89961  pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
89962  pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
89963  assert( pExpr->pLeft );
89964  aff = sqlite3ExprAffinity(pExpr->pLeft);
89965  if( pExpr->pRight ){
89966  aff = sqlite3CompareAffinity(pExpr->pRight, aff);
89967  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89968  aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
89969  }else if( NEVER(aff==0) ){
89970  aff = SQLITE_AFF_BLOB;
89971  }
89972  return aff;
89973 }
89974 
89975 /*
89976 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
89977 ** idx_affinity is the affinity of an indexed column. Return true
89978 ** if the index with affinity idx_affinity may be used to implement
89979 ** the comparison in pExpr.
89980 */
89981 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
89982  char aff = comparisonAffinity(pExpr);
89983  switch( aff ){
89984  case SQLITE_AFF_BLOB:
89985  return 1;
89986  case SQLITE_AFF_TEXT:
89987  return idx_affinity==SQLITE_AFF_TEXT;
89988  default:
89989  return sqlite3IsNumericAffinity(idx_affinity);
89990  }
89991 }
89992 
89993 /*
89994 ** Return the P5 value that should be used for a binary comparison
89995 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
89996 */
89997 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
89998  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
89999  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
90000  return aff;
90001 }
90002 
90003 /*
90004 ** Return a pointer to the collation sequence that should be used by
90005 ** a binary comparison operator comparing pLeft and pRight.
90006 **
90007 ** If the left hand expression has a collating sequence type, then it is
90008 ** used. Otherwise the collation sequence for the right hand expression
90009 ** is used, or the default (BINARY) if neither expression has a collating
90010 ** type.
90011 **
90012 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
90013 ** it is not considered.
90014 */
90015 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
90016  Parse *pParse,
90017  Expr *pLeft,
90018  Expr *pRight
90019 ){
90020  CollSeq *pColl;
90021  assert( pLeft );
90022  if( pLeft->flags & EP_Collate ){
90023  pColl = sqlite3ExprCollSeq(pParse, pLeft);
90024  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
90025  pColl = sqlite3ExprCollSeq(pParse, pRight);
90026  }else{
90027  pColl = sqlite3ExprCollSeq(pParse, pLeft);
90028  if( !pColl ){
90029  pColl = sqlite3ExprCollSeq(pParse, pRight);
90030  }
90031  }
90032  return pColl;
90033 }
90034 
90035 /*
90036 ** Generate code for a comparison operator.
90037 */
90038 static int codeCompare(
90039  Parse *pParse, /* The parsing (and code generating) context */
90040  Expr *pLeft, /* The left operand */
90041  Expr *pRight, /* The right operand */
90042  int opcode, /* The comparison opcode */
90043  int in1, int in2, /* Register holding operands */
90044  int dest, /* Jump here if true. */
90045  int jumpIfNull /* If true, jump if either operand is NULL */
90046 ){
90047  int p5;
90048  int addr;
90049  CollSeq *p4;
90050 
90051  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
90052  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
90053  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
90054  (void*)p4, P4_COLLSEQ);
90055  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
90056  return addr;
90057 }
90058 
90059 /*
90060 ** Return true if expression pExpr is a vector, or false otherwise.
90061 **
90062 ** A vector is defined as any expression that results in two or more
90063 ** columns of result. Every TK_VECTOR node is an vector because the
90064 ** parser will not generate a TK_VECTOR with fewer than two entries.
90065 ** But a TK_SELECT might be either a vector or a scalar. It is only
90066 ** considered a vector if it has two or more result columns.
90067 */
90068 SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
90069  return sqlite3ExprVectorSize(pExpr)>1;
90070 }
90071 
90072 /*
90073 ** If the expression passed as the only argument is of type TK_VECTOR
90074 ** return the number of expressions in the vector. Or, if the expression
90075 ** is a sub-select, return the number of columns in the sub-select. For
90076 ** any other type of expression, return 1.
90077 */
90078 SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
90079  u8 op = pExpr->op;
90080  if( op==TK_REGISTER ) op = pExpr->op2;
90081  if( op==TK_VECTOR ){
90082  return pExpr->x.pList->nExpr;
90083  }else if( op==TK_SELECT ){
90084  return pExpr->x.pSelect->pEList->nExpr;
90085  }else{
90086  return 1;
90087  }
90088 }
90089 
90090 #ifndef SQLITE_OMIT_SUBQUERY
90091 /*
90092 ** Return a pointer to a subexpression of pVector that is the i-th
90093 ** column of the vector (numbered starting with 0). The caller must
90094 ** ensure that i is within range.
90095 **
90096 ** If pVector is really a scalar (and "scalar" here includes subqueries
90097 ** that return a single column!) then return pVector unmodified.
90098 **
90099 ** pVector retains ownership of the returned subexpression.
90100 **
90101 ** If the vector is a (SELECT ...) then the expression returned is
90102 ** just the expression for the i-th term of the result set, and may
90103 ** not be ready for evaluation because the table cursor has not yet
90104 ** been positioned.
90105 */
90106 SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
90107  assert( i<sqlite3ExprVectorSize(pVector) );
90108  if( sqlite3ExprIsVector(pVector) ){
90109  assert( pVector->op2==0 || pVector->op==TK_REGISTER );
90110  if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
90111  return pVector->x.pSelect->pEList->a[i].pExpr;
90112  }else{
90113  return pVector->x.pList->a[i].pExpr;
90114  }
90115  }
90116  return pVector;
90117 }
90118 #endif /* !defined(SQLITE_OMIT_SUBQUERY) */
90119 
90120 #ifndef SQLITE_OMIT_SUBQUERY
90121 /*
90122 ** Compute and return a new Expr object which when passed to
90123 ** sqlite3ExprCode() will generate all necessary code to compute
90124 ** the iField-th column of the vector expression pVector.
90125 **
90126 ** It is ok for pVector to be a scalar (as long as iField==0).
90127 ** In that case, this routine works like sqlite3ExprDup().
90128 **
90129 ** The caller owns the returned Expr object and is responsible for
90130 ** ensuring that the returned value eventually gets freed.
90131 **
90132 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
90133 ** then the returned object will reference pVector and so pVector must remain
90134 ** valid for the life of the returned object. If pVector is a TK_VECTOR
90135 ** or a scalar expression, then it can be deleted as soon as this routine
90136 ** returns.
90137 **
90138 ** A trick to cause a TK_SELECT pVector to be deleted together with
90139 ** the returned Expr object is to attach the pVector to the pRight field
90140 ** of the returned TK_SELECT_COLUMN Expr object.
90141 */
90142 SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
90143  Parse *pParse, /* Parsing context */
90144  Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
90145  int iField /* Which column of the vector to return */
90146 ){
90147  Expr *pRet;
90148  if( pVector->op==TK_SELECT ){
90149  assert( pVector->flags & EP_xIsSelect );
90150  /* The TK_SELECT_COLUMN Expr node:
90151  **
90152  ** pLeft: pVector containing TK_SELECT
90153  ** pRight: not used. But recursively deleted.
90154  ** iColumn: Index of a column in pVector
90155  ** pLeft->iTable: First in an array of register holding result, or 0
90156  ** if the result is not yet computed.
90157  **
90158  ** sqlite3ExprDelete() specifically skips the recursive delete of
90159  ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
90160  ** can be attached to pRight to cause this node to take ownership of
90161  ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
90162  ** with the same pLeft pointer to the pVector, but only one of them
90163  ** will own the pVector.
90164  */
90165  pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0, 0);
90166  if( pRet ){
90167  pRet->iColumn = iField;
90168  pRet->pLeft = pVector;
90169  }
90170  assert( pRet==0 || pRet->iTable==0 );
90171  }else{
90172  if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
90173  pRet = sqlite3ExprDup(pParse->db, pVector, 0);
90174  }
90175  return pRet;
90176 }
90177 #endif /* !define(SQLITE_OMIT_SUBQUERY) */
90178 
90179 /*
90180 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
90181 ** it. Return the register in which the result is stored (or, if the
90182 ** sub-select returns more than one column, the first in an array
90183 ** of registers in which the result is stored).
90184 **
90185 ** If pExpr is not a TK_SELECT expression, return 0.
90186 */
90187 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
90188  int reg = 0;
90189 #ifndef SQLITE_OMIT_SUBQUERY
90190  if( pExpr->op==TK_SELECT ){
90191  reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
90192  }
90193 #endif
90194  return reg;
90195 }
90196 
90197 /*
90198 ** Argument pVector points to a vector expression - either a TK_VECTOR
90199 ** or TK_SELECT that returns more than one column. This function returns
90200 ** the register number of a register that contains the value of
90201 ** element iField of the vector.
90202 **
90203 ** If pVector is a TK_SELECT expression, then code for it must have
90204 ** already been generated using the exprCodeSubselect() routine. In this
90205 ** case parameter regSelect should be the first in an array of registers
90206 ** containing the results of the sub-select.
90207 **
90208 ** If pVector is of type TK_VECTOR, then code for the requested field
90209 ** is generated. In this case (*pRegFree) may be set to the number of
90210 ** a temporary register to be freed by the caller before returning.
90211 **
90212 ** Before returning, output parameter (*ppExpr) is set to point to the
90213 ** Expr object corresponding to element iElem of the vector.
90214 */
90215 static int exprVectorRegister(
90216  Parse *pParse, /* Parse context */
90217  Expr *pVector, /* Vector to extract element from */
90218  int iField, /* Field to extract from pVector */
90219  int regSelect, /* First in array of registers */
90220  Expr **ppExpr, /* OUT: Expression element */
90221  int *pRegFree /* OUT: Temp register to free */
90222 ){
90223  u8 op = pVector->op;
90224  assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
90225  if( op==TK_REGISTER ){
90226  *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
90227  return pVector->iTable+iField;
90228  }
90229  if( op==TK_SELECT ){
90230  *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
90231  return regSelect+iField;
90232  }
90233  *ppExpr = pVector->x.pList->a[iField].pExpr;
90234  return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
90235 }
90236 
90237 /*
90238 ** Expression pExpr is a comparison between two vector values. Compute
90239 ** the result of the comparison (1, 0, or NULL) and write that
90240 ** result into register dest.
90241 **
90242 ** The caller must satisfy the following preconditions:
90243 **
90244 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
90245 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
90246 ** otherwise: op==pExpr->op and p5==0
90247 */
90248 static void codeVectorCompare(
90249  Parse *pParse, /* Code generator context */
90250  Expr *pExpr, /* The comparison operation */
90251  int dest, /* Write results into this register */
90252  u8 op, /* Comparison operator */
90253  u8 p5 /* SQLITE_NULLEQ or zero */
90254 ){
90255  Vdbe *v = pParse->pVdbe;
90256  Expr *pLeft = pExpr->pLeft;
90257  Expr *pRight = pExpr->pRight;
90258  int nLeft = sqlite3ExprVectorSize(pLeft);
90259  int i;
90260  int regLeft = 0;
90261  int regRight = 0;
90262  u8 opx = op;
90263  int addrDone = sqlite3VdbeMakeLabel(v);
90264 
90265  assert( nLeft==sqlite3ExprVectorSize(pRight) );
90266  assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
90267  || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
90268  || pExpr->op==TK_LT || pExpr->op==TK_GT
90269  || pExpr->op==TK_LE || pExpr->op==TK_GE
90270  );
90271  assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
90272  || (pExpr->op==TK_ISNOT && op==TK_NE) );
90273  assert( p5==0 || pExpr->op!=op );
90274  assert( p5==SQLITE_NULLEQ || pExpr->op==op );
90275 
90276  p5 |= SQLITE_STOREP2;
90277  if( opx==TK_LE ) opx = TK_LT;
90278  if( opx==TK_GE ) opx = TK_GT;
90279 
90280  regLeft = exprCodeSubselect(pParse, pLeft);
90281  regRight = exprCodeSubselect(pParse, pRight);
90282 
90283  for(i=0; 1 /*Loop exits by "break"*/; i++){
90284  int regFree1 = 0, regFree2 = 0;
90285  Expr *pL, *pR;
90286  int r1, r2;
90287  assert( i>=0 && i<nLeft );
90288  if( i>0 ) sqlite3ExprCachePush(pParse);
90289  r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
90290  r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
90291  codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
90292  testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
90293  testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
90294  testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
90295  testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
90296  testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
90297  testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
90298  sqlite3ReleaseTempReg(pParse, regFree1);
90299  sqlite3ReleaseTempReg(pParse, regFree2);
90300  if( i>0 ) sqlite3ExprCachePop(pParse);
90301  if( i==nLeft-1 ){
90302  break;
90303  }
90304  if( opx==TK_EQ ){
90305  sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
90306  p5 |= SQLITE_KEEPNULL;
90307  }else if( opx==TK_NE ){
90308  sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
90309  p5 |= SQLITE_KEEPNULL;
90310  }else{
90311  assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
90312  sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
90313  VdbeCoverageIf(v, op==TK_LT);
90314  VdbeCoverageIf(v, op==TK_GT);
90315  VdbeCoverageIf(v, op==TK_LE);
90316  VdbeCoverageIf(v, op==TK_GE);
90317  if( i==nLeft-2 ) opx = op;
90318  }
90319  }
90320  sqlite3VdbeResolveLabel(v, addrDone);
90321 }
90322 
90323 #if SQLITE_MAX_EXPR_DEPTH>0
90324 /*
90325 ** Check that argument nHeight is less than or equal to the maximum
90326 ** expression depth allowed. If it is not, leave an error message in
90327 ** pParse.
90328 */
90329 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
90330  int rc = SQLITE_OK;
90331  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
90332  if( nHeight>mxHeight ){
90333  sqlite3ErrorMsg(pParse,
90334  "Expression tree is too large (maximum depth %d)", mxHeight
90335  );
90336  rc = SQLITE_ERROR;
90337  }
90338  return rc;
90339 }
90340 
90341 /* The following three functions, heightOfExpr(), heightOfExprList()
90342 ** and heightOfSelect(), are used to determine the maximum height
90343 ** of any expression tree referenced by the structure passed as the
90344 ** first argument.
90345 **
90346 ** If this maximum height is greater than the current value pointed
90347 ** to by pnHeight, the second parameter, then set *pnHeight to that
90348 ** value.
90349 */
90350 static void heightOfExpr(Expr *p, int *pnHeight){
90351  if( p ){
90352  if( p->nHeight>*pnHeight ){
90353  *pnHeight = p->nHeight;
90354  }
90355  }
90356 }
90357 static void heightOfExprList(ExprList *p, int *pnHeight){
90358  if( p ){
90359  int i;
90360  for(i=0; i<p->nExpr; i++){
90361  heightOfExpr(p->a[i].pExpr, pnHeight);
90362  }
90363  }
90364 }
90365 static void heightOfSelect(Select *p, int *pnHeight){
90366  if( p ){
90367  heightOfExpr(p->pWhere, pnHeight);
90368  heightOfExpr(p->pHaving, pnHeight);
90369  heightOfExpr(p->pLimit, pnHeight);
90370  heightOfExpr(p->pOffset, pnHeight);
90371  heightOfExprList(p->pEList, pnHeight);
90372  heightOfExprList(p->pGroupBy, pnHeight);
90373  heightOfExprList(p->pOrderBy, pnHeight);
90374  heightOfSelect(p->pPrior, pnHeight);
90375  }
90376 }
90377 
90378 /*
90379 ** Set the Expr.nHeight variable in the structure passed as an
90380 ** argument. An expression with no children, Expr.pList or
90381 ** Expr.pSelect member has a height of 1. Any other expression
90382 ** has a height equal to the maximum height of any other
90383 ** referenced Expr plus one.
90384 **
90385 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
90386 ** if appropriate.
90387 */
90388 static void exprSetHeight(Expr *p){
90389  int nHeight = 0;
90390  heightOfExpr(p->pLeft, &nHeight);
90391  heightOfExpr(p->pRight, &nHeight);
90392  if( ExprHasProperty(p, EP_xIsSelect) ){
90393  heightOfSelect(p->x.pSelect, &nHeight);
90394  }else if( p->x.pList ){
90395  heightOfExprList(p->x.pList, &nHeight);
90396  p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
90397  }
90398  p->nHeight = nHeight + 1;
90399 }
90400 
90401 /*
90402 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
90403 ** the height is greater than the maximum allowed expression depth,
90404 ** leave an error in pParse.
90405 **
90406 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
90407 ** Expr.flags.
90408 */
90409 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
90410  if( pParse->nErr ) return;
90411  exprSetHeight(p);
90412  sqlite3ExprCheckHeight(pParse, p->nHeight);
90413 }
90414 
90415 /*
90416 ** Return the maximum height of any expression tree referenced
90417 ** by the select statement passed as an argument.
90418 */
90419 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
90420  int nHeight = 0;
90421  heightOfSelect(p, &nHeight);
90422  return nHeight;
90423 }
90424 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
90425 /*
90426 ** Propagate all EP_Propagate flags from the Expr.x.pList into
90427 ** Expr.flags.
90428 */
90429 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
90430  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
90431  p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
90432  }
90433 }
90434 #define exprSetHeight(y)
90435 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
90436 
90437 /*
90438 ** This routine is the core allocator for Expr nodes.
90439 **
90440 ** Construct a new expression node and return a pointer to it. Memory
90441 ** for this node and for the pToken argument is a single allocation
90442 ** obtained from sqlite3DbMalloc(). The calling function
90443 ** is responsible for making sure the node eventually gets freed.
90444 **
90445 ** If dequote is true, then the token (if it exists) is dequoted.
90446 ** If dequote is false, no dequoting is performed. The deQuote
90447 ** parameter is ignored if pToken is NULL or if the token does not
90448 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
90449 ** then the EP_DblQuoted flag is set on the expression node.
90450 **
90451 ** Special case: If op==TK_INTEGER and pToken points to a string that
90452 ** can be translated into a 32-bit integer, then the token is not
90453 ** stored in u.zToken. Instead, the integer values is written
90454 ** into u.iValue and the EP_IntValue flag is set. No extra storage
90455 ** is allocated to hold the integer text and the dequote flag is ignored.
90456 */
90457 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
90458  sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
90459  int op, /* Expression opcode */
90460  const Token *pToken, /* Token argument. Might be NULL */
90461  int dequote /* True to dequote */
90462 ){
90463  Expr *pNew;
90464  int nExtra = 0;
90465  int iValue = 0;
90466 
90467  assert( db!=0 );
90468  if( pToken ){
90469  if( op!=TK_INTEGER || pToken->z==0
90470  || sqlite3GetInt32(pToken->z, &iValue)==0 ){
90471  nExtra = pToken->n+1;
90472  assert( iValue>=0 );
90473  }
90474  }
90475  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
90476  if( pNew ){
90477  memset(pNew, 0, sizeof(Expr));
90478  pNew->op = (u8)op;
90479  pNew->iAgg = -1;
90480  if( pToken ){
90481  if( nExtra==0 ){
90482  pNew->flags |= EP_IntValue;
90483  pNew->u.iValue = iValue;
90484  }else{
90485  pNew->u.zToken = (char*)&pNew[1];
90486  assert( pToken->z!=0 || pToken->n==0 );
90487  if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
90488  pNew->u.zToken[pToken->n] = 0;
90489  if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
90490  if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
90491  sqlite3Dequote(pNew->u.zToken);
90492  }
90493  }
90494  }
90495 #if SQLITE_MAX_EXPR_DEPTH>0
90496  pNew->nHeight = 1;
90497 #endif
90498  }
90499  return pNew;
90500 }
90501 
90502 /*
90503 ** Allocate a new expression node from a zero-terminated token that has
90504 ** already been dequoted.
90505 */
90506 SQLITE_PRIVATE Expr *sqlite3Expr(
90507  sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
90508  int op, /* Expression opcode */
90509  const char *zToken /* Token argument. Might be NULL */
90510 ){
90511  Token x;
90512  x.z = zToken;
90513  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
90514  return sqlite3ExprAlloc(db, op, &x, 0);
90515 }
90516 
90517 /*
90518 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
90519 **
90520 ** If pRoot==NULL that means that a memory allocation error has occurred.
90521 ** In that case, delete the subtrees pLeft and pRight.
90522 */
90523 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
90524  sqlite3 *db,
90525  Expr *pRoot,
90526  Expr *pLeft,
90527  Expr *pRight
90528 ){
90529  if( pRoot==0 ){
90530  assert( db->mallocFailed );
90531  sqlite3ExprDelete(db, pLeft);
90532  sqlite3ExprDelete(db, pRight);
90533  }else{
90534  if( pRight ){
90535  pRoot->pRight = pRight;
90536  pRoot->flags |= EP_Propagate & pRight->flags;
90537  }
90538  if( pLeft ){
90539  pRoot->pLeft = pLeft;
90540  pRoot->flags |= EP_Propagate & pLeft->flags;
90541  }
90542  exprSetHeight(pRoot);
90543  }
90544 }
90545 
90546 /*
90547 ** Allocate an Expr node which joins as many as two subtrees.
90548 **
90549 ** One or both of the subtrees can be NULL. Return a pointer to the new
90550 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
90551 ** free the subtrees and return NULL.
90552 */
90553 SQLITE_PRIVATE Expr *sqlite3PExpr(
90554  Parse *pParse, /* Parsing context */
90555  int op, /* Expression opcode */
90556  Expr *pLeft, /* Left operand */
90557  Expr *pRight, /* Right operand */
90558  const Token *pToken /* Argument token */
90559 ){
90560  Expr *p;
90561  if( op==TK_AND && pParse->nErr==0 ){
90562  /* Take advantage of short-circuit false optimization for AND */
90563  p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
90564  }else{
90565  p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
90566  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
90567  }
90568  if( p ) {
90569  sqlite3ExprCheckHeight(pParse, p->nHeight);
90570  }
90571  return p;
90572 }
90573 
90574 /*
90575 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
90576 ** do a memory allocation failure) then delete the pSelect object.
90577 */
90578 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
90579  if( pExpr ){
90580  pExpr->x.pSelect = pSelect;
90581  ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
90582  sqlite3ExprSetHeightAndFlags(pParse, pExpr);
90583  }else{
90584  assert( pParse->db->mallocFailed );
90585  sqlite3SelectDelete(pParse->db, pSelect);
90586  }
90587 }
90588 
90589 
90590 /*
90591 ** If the expression is always either TRUE or FALSE (respectively),
90592 ** then return 1. If one cannot determine the truth value of the
90593 ** expression at compile-time return 0.
90594 **
90595 ** This is an optimization. If is OK to return 0 here even if
90596 ** the expression really is always false or false (a false negative).
90597 ** But it is a bug to return 1 if the expression might have different
90598 ** boolean values in different circumstances (a false positive.)
90599 **
90600 ** Note that if the expression is part of conditional for a
90601 ** LEFT JOIN, then we cannot determine at compile-time whether or not
90602 ** is it true or false, so always return 0.
90603 */
90604 static int exprAlwaysTrue(Expr *p){
90605  int v = 0;
90606  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
90607  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
90608  return v!=0;
90609 }
90610 static int exprAlwaysFalse(Expr *p){
90611  int v = 0;
90612  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
90613  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
90614  return v==0;
90615 }
90616 
90617 /*
90618 ** Join two expressions using an AND operator. If either expression is
90619 ** NULL, then just return the other expression.
90620 **
90621 ** If one side or the other of the AND is known to be false, then instead
90622 ** of returning an AND expression, just return a constant expression with
90623 ** a value of false.
90624 */
90625 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
90626  if( pLeft==0 ){
90627  return pRight;
90628  }else if( pRight==0 ){
90629  return pLeft;
90630  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
90631  sqlite3ExprDelete(db, pLeft);
90632  sqlite3ExprDelete(db, pRight);
90633  return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
90634  }else{
90635  Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
90636  sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
90637  return pNew;
90638  }
90639 }
90640 
90641 /*
90642 ** Construct a new expression node for a function with multiple
90643 ** arguments.
90644 */
90645 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
90646  Expr *pNew;
90647  sqlite3 *db = pParse->db;
90648  assert( pToken );
90649  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
90650  if( pNew==0 ){
90651  sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
90652  return 0;
90653  }
90654  pNew->x.pList = pList;
90655  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
90656  sqlite3ExprSetHeightAndFlags(pParse, pNew);
90657  return pNew;
90658 }
90659 
90660 /*
90661 ** Assign a variable number to an expression that encodes a wildcard
90662 ** in the original SQL statement.
90663 **
90664 ** Wildcards consisting of a single "?" are assigned the next sequential
90665 ** variable number.
90666 **
90667 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
90668 ** sure "nnn" is not too be to avoid a denial of service attack when
90669 ** the SQL statement comes from an external source.
90670 **
90671 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
90672 ** as the previous instance of the same wildcard. Or if this is the first
90673 ** instance of the wildcard, the next sequential variable number is
90674 ** assigned.
90675 */
90676 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
90677  sqlite3 *db = pParse->db;
90678  const char *z;
90679 
90680  if( pExpr==0 ) return;
90681  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
90682  z = pExpr->u.zToken;
90683  assert( z!=0 );
90684  assert( z[0]!=0 );
90685  assert( n==sqlite3Strlen30(z) );
90686  if( z[1]==0 ){
90687  /* Wildcard of the form "?". Assign the next variable number */
90688  assert( z[0]=='?' );
90689  pExpr->iColumn = (ynVar)(++pParse->nVar);
90690  }else{
90691  ynVar x;
90692  if( z[0]=='?' ){
90693  /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
90694  ** use it as the variable number */
90695  i64 i;
90696  int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
90697  x = (ynVar)i;
90698  testcase( i==0 );
90699  testcase( i==1 );
90700  testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
90701  testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
90702  if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90703  sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
90704  db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
90705  return;
90706  }
90707  if( i>pParse->nVar ){
90708  pParse->nVar = (int)i;
90709  }
90710  }else{
90711  /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
90712  ** number as the prior appearance of the same name, or if the name
90713  ** has never appeared before, reuse the same variable number
90714  */
90715  ynVar i;
90716  for(i=x=0; i<pParse->nzVar; i++){
90717  if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
90718  x = (ynVar)i+1;
90719  break;
90720  }
90721  }
90722  if( x==0 ) x = (ynVar)(++pParse->nVar);
90723  }
90724  pExpr->iColumn = x;
90725  if( x>pParse->nzVar ){
90726  char **a;
90727  a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
90728  if( a==0 ){
90729  assert( db->mallocFailed ); /* Error reported through mallocFailed */
90730  return;
90731  }
90732  pParse->azVar = a;
90733  memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
90734  pParse->nzVar = x;
90735  }
90736  if( pParse->azVar[x-1]==0 ){
90737  pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
90738  }
90739  }
90740  if( pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90741  sqlite3ErrorMsg(pParse, "too many SQL variables");
90742  }
90743 }
90744 
90745 /*
90746 ** Recursively delete an expression tree.
90747 */
90748 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
90749  assert( p!=0 );
90750  /* Sanity check: Assert that the IntValue is non-negative if it exists */
90751  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
90752 #ifdef SQLITE_DEBUG
90753  if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
90754  assert( p->pLeft==0 );
90755  assert( p->pRight==0 );
90756  assert( p->x.pSelect==0 );
90757  }
90758 #endif
90759  if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
90760  /* The Expr.x union is never used at the same time as Expr.pRight */
90761  assert( p->x.pList==0 || p->pRight==0 );
90762  if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
90763  sqlite3ExprDelete(db, p->pRight);
90764  if( ExprHasProperty(p, EP_xIsSelect) ){
90765  sqlite3SelectDelete(db, p->x.pSelect);
90766  }else{
90767  sqlite3ExprListDelete(db, p->x.pList);
90768  }
90769  }
90770  if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
90771  if( !ExprHasProperty(p, EP_Static) ){
90772  sqlite3DbFree(db, p);
90773  }
90774 }
90775 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
90776  if( p ) sqlite3ExprDeleteNN(db, p);
90777 }
90778 
90779 /*
90780 ** Return the number of bytes allocated for the expression structure
90781 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
90782 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
90783 */
90784 static int exprStructSize(Expr *p){
90785  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
90786  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
90787  return EXPR_FULLSIZE;
90788 }
90789 
90790 /*
90791 ** The dupedExpr*Size() routines each return the number of bytes required
90792 ** to store a copy of an expression or expression tree. They differ in
90793 ** how much of the tree is measured.
90794 **
90795 ** dupedExprStructSize() Size of only the Expr structure
90796 ** dupedExprNodeSize() Size of Expr + space for token
90797 ** dupedExprSize() Expr + token + subtree components
90798 **
90799 ***************************************************************************
90800 **
90801 ** The dupedExprStructSize() function returns two values OR-ed together:
90802 ** (1) the space required for a copy of the Expr structure only and
90803 ** (2) the EP_xxx flags that indicate what the structure size should be.
90804 ** The return values is always one of:
90805 **
90806 ** EXPR_FULLSIZE
90807 ** EXPR_REDUCEDSIZE | EP_Reduced
90808 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
90809 **
90810 ** The size of the structure can be found by masking the return value
90811 ** of this routine with 0xfff. The flags can be found by masking the
90812 ** return value with EP_Reduced|EP_TokenOnly.
90813 **
90814 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
90815 ** (unreduced) Expr objects as they or originally constructed by the parser.
90816 ** During expression analysis, extra information is computed and moved into
90817 ** later parts of teh Expr object and that extra information might get chopped
90818 ** off if the expression is reduced. Note also that it does not work to
90819 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
90820 ** to reduce a pristine expression tree from the parser. The implementation
90821 ** of dupedExprStructSize() contain multiple assert() statements that attempt
90822 ** to enforce this constraint.
90823 */
90824 static int dupedExprStructSize(Expr *p, int flags){
90825  int nSize;
90826  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
90827  assert( EXPR_FULLSIZE<=0xfff );
90828  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
90829  if( 0==flags ){
90830  nSize = EXPR_FULLSIZE;
90831  }else{
90832  assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
90833  assert( !ExprHasProperty(p, EP_FromJoin) );
90834  assert( !ExprHasProperty(p, EP_MemToken) );
90835  assert( !ExprHasProperty(p, EP_NoReduce) );
90836  if( p->pLeft || p->x.pList ){
90837  nSize = EXPR_REDUCEDSIZE | EP_Reduced;
90838  }else{
90839  assert( p->pRight==0 );
90840  nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
90841  }
90842  }
90843  return nSize;
90844 }
90845 
90846 /*
90847 ** This function returns the space in bytes required to store the copy
90848 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
90849 ** string is defined.)
90850 */
90851 static int dupedExprNodeSize(Expr *p, int flags){
90852  int nByte = dupedExprStructSize(p, flags) & 0xfff;
90853  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90854  nByte += sqlite3Strlen30(p->u.zToken)+1;
90855  }
90856  return ROUND8(nByte);
90857 }
90858 
90859 /*
90860 ** Return the number of bytes required to create a duplicate of the
90861 ** expression passed as the first argument. The second argument is a
90862 ** mask containing EXPRDUP_XXX flags.
90863 **
90864 ** The value returned includes space to create a copy of the Expr struct
90865 ** itself and the buffer referred to by Expr.u.zToken, if any.
90866 **
90867 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
90868 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
90869 ** and Expr.pRight variables (but not for any structures pointed to or
90870 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
90871 */
90872 static int dupedExprSize(Expr *p, int flags){
90873  int nByte = 0;
90874  if( p ){
90875  nByte = dupedExprNodeSize(p, flags);
90876  if( flags&EXPRDUP_REDUCE ){
90877  nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
90878  }
90879  }
90880  return nByte;
90881 }
90882 
90883 /*
90884 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
90885 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
90886 ** to store the copy of expression p, the copies of p->u.zToken
90887 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
90888 ** if any. Before returning, *pzBuffer is set to the first byte past the
90889 ** portion of the buffer copied into by this function.
90890 */
90891 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
90892  Expr *pNew; /* Value to return */
90893  u8 *zAlloc; /* Memory space from which to build Expr object */
90894  u32 staticFlag; /* EP_Static if space not obtained from malloc */
90895 
90896  assert( db!=0 );
90897  assert( p );
90898  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
90899  assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
90900 
90901  /* Figure out where to write the new Expr structure. */
90902  if( pzBuffer ){
90903  zAlloc = *pzBuffer;
90904  staticFlag = EP_Static;
90905  }else{
90906  zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
90907  staticFlag = 0;
90908  }
90909  pNew = (Expr *)zAlloc;
90910 
90911  if( pNew ){
90912  /* Set nNewSize to the size allocated for the structure pointed to
90913  ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
90914  ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
90915  ** by the copy of the p->u.zToken string (if any).
90916  */
90917  const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
90918  const int nNewSize = nStructSize & 0xfff;
90919  int nToken;
90920  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90921  nToken = sqlite3Strlen30(p->u.zToken) + 1;
90922  }else{
90923  nToken = 0;
90924  }
90925  if( dupFlags ){
90926  assert( ExprHasProperty(p, EP_Reduced)==0 );
90927  memcpy(zAlloc, p, nNewSize);
90928  }else{
90929  u32 nSize = (u32)exprStructSize(p);
90930  memcpy(zAlloc, p, nSize);
90931  if( nSize<EXPR_FULLSIZE ){
90932  memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
90933  }
90934  }
90935 
90936  /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
90937  pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
90938  pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
90939  pNew->flags |= staticFlag;
90940 
90941  /* Copy the p->u.zToken string, if any. */
90942  if( nToken ){
90943  char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
90944  memcpy(zToken, p->u.zToken, nToken);
90945  }
90946 
90947  if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
90948  /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
90949  if( ExprHasProperty(p, EP_xIsSelect) ){
90950  pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
90951  }else{
90952  pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
90953  }
90954  }
90955 
90956  /* Fill in pNew->pLeft and pNew->pRight. */
90957  if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
90958  zAlloc += dupedExprNodeSize(p, dupFlags);
90959  if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
90960  pNew->pLeft = p->pLeft ?
90961  exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
90962  pNew->pRight = p->pRight ?
90963  exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
90964  }
90965  if( pzBuffer ){
90966  *pzBuffer = zAlloc;
90967  }
90968  }else{
90969  if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
90970  if( pNew->op==TK_SELECT_COLUMN ){
90971  pNew->pLeft = p->pLeft;
90972  }else{
90973  pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
90974  }
90975  pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
90976  }
90977  }
90978  }
90979  return pNew;
90980 }
90981 
90982 /*
90983 ** Create and return a deep copy of the object passed as the second
90984 ** argument. If an OOM condition is encountered, NULL is returned
90985 ** and the db->mallocFailed flag set.
90986 */
90987 #ifndef SQLITE_OMIT_CTE
90988 static With *withDup(sqlite3 *db, With *p){
90989  With *pRet = 0;
90990  if( p ){
90991  int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
90992  pRet = sqlite3DbMallocZero(db, nByte);
90993  if( pRet ){
90994  int i;
90995  pRet->nCte = p->nCte;
90996  for(i=0; i<p->nCte; i++){
90997  pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
90998  pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
90999  pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
91000  }
91001  }
91002  }
91003  return pRet;
91004 }
91005 #else
91006 # define withDup(x,y) 0
91007 #endif
91008 
91009 /*
91010 ** The following group of routines make deep copies of expressions,
91011 ** expression lists, ID lists, and select statements. The copies can
91012 ** be deleted (by being passed to their respective ...Delete() routines)
91013 ** without effecting the originals.
91014 **
91015 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
91016 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
91017 ** by subsequent calls to sqlite*ListAppend() routines.
91018 **
91019 ** Any tables that the SrcList might point to are not duplicated.
91020 **
91021 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
91022 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
91023 ** truncated version of the usual Expr structure that will be stored as
91024 ** part of the in-memory representation of the database schema.
91025 */
91026 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
91027  assert( flags==0 || flags==EXPRDUP_REDUCE );
91028  return p ? exprDup(db, p, flags, 0) : 0;
91029 }
91030 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
91031  ExprList *pNew;
91032  struct ExprList_item *pItem, *pOldItem;
91033  int i;
91034  assert( db!=0 );
91035  if( p==0 ) return 0;
91036  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
91037  if( pNew==0 ) return 0;
91038  pNew->nExpr = i = p->nExpr;
91039  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
91040  pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
91041  if( pItem==0 ){
91042  sqlite3DbFree(db, pNew);
91043  return 0;
91044  }
91045  pOldItem = p->a;
91046  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
91047  Expr *pOldExpr = pOldItem->pExpr;
91048  pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
91049  pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
91050  pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
91051  pItem->sortOrder = pOldItem->sortOrder;
91052  pItem->done = 0;
91053  pItem->bSpanIsTab = pOldItem->bSpanIsTab;
91054  pItem->u = pOldItem->u;
91055  }
91056  return pNew;
91057 }
91058 
91059 /*
91060 ** If cursors, triggers, views and subqueries are all omitted from
91061 ** the build, then none of the following routines, except for
91062 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
91063 ** called with a NULL argument.
91064 */
91065 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
91066  || !defined(SQLITE_OMIT_SUBQUERY)
91067 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
91068  SrcList *pNew;
91069  int i;
91070  int nByte;
91071  assert( db!=0 );
91072  if( p==0 ) return 0;
91073  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
91074  pNew = sqlite3DbMallocRawNN(db, nByte );
91075  if( pNew==0 ) return 0;
91076  pNew->nSrc = pNew->nAlloc = p->nSrc;
91077  for(i=0; i<p->nSrc; i++){
91078  struct SrcList_item *pNewItem = &pNew->a[i];
91079  struct SrcList_item *pOldItem = &p->a[i];
91080  Table *pTab;
91081  pNewItem->pSchema = pOldItem->pSchema;
91082  pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
91083  pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
91084  pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
91085  pNewItem->fg = pOldItem->fg;
91086  pNewItem->iCursor = pOldItem->iCursor;
91087  pNewItem->addrFillSub = pOldItem->addrFillSub;
91088  pNewItem->regReturn = pOldItem->regReturn;
91089  if( pNewItem->fg.isIndexedBy ){
91090  pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
91091  }
91092  pNewItem->pIBIndex = pOldItem->pIBIndex;
91093  if( pNewItem->fg.isTabFunc ){
91094  pNewItem->u1.pFuncArg =
91095  sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
91096  }
91097  pTab = pNewItem->pTab = pOldItem->pTab;
91098  if( pTab ){
91099  pTab->nRef++;
91100  }
91101  pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
91102  pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
91103  pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
91104  pNewItem->colUsed = pOldItem->colUsed;
91105  }
91106  return pNew;
91107 }
91108 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
91109  IdList *pNew;
91110  int i;
91111  assert( db!=0 );
91112  if( p==0 ) return 0;
91113  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
91114  if( pNew==0 ) return 0;
91115  pNew->nId = p->nId;
91116  pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
91117  if( pNew->a==0 ){
91118  sqlite3DbFree(db, pNew);
91119  return 0;
91120  }
91121  /* Note that because the size of the allocation for p->a[] is not
91122  ** necessarily a power of two, sqlite3IdListAppend() may not be called
91123  ** on the duplicate created by this function. */
91124  for(i=0; i<p->nId; i++){
91125  struct IdList_item *pNewItem = &pNew->a[i];
91126  struct IdList_item *pOldItem = &p->a[i];
91127  pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
91128  pNewItem->idx = pOldItem->idx;
91129  }
91130  return pNew;
91131 }
91132 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
91133  Select *pNew, *pPrior;
91134  assert( db!=0 );
91135  if( p==0 ) return 0;
91136  pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
91137  if( pNew==0 ) return 0;
91138  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
91139  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
91140  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
91141  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
91142  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
91143  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
91144  pNew->op = p->op;
91145  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
91146  if( pPrior ) pPrior->pNext = pNew;
91147  pNew->pNext = 0;
91148  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
91149  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
91150  pNew->iLimit = 0;
91151  pNew->iOffset = 0;
91152  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
91153  pNew->addrOpenEphm[0] = -1;
91154  pNew->addrOpenEphm[1] = -1;
91155  pNew->nSelectRow = p->nSelectRow;
91156  pNew->pWith = withDup(db, p->pWith);
91157  sqlite3SelectSetName(pNew, p->zSelName);
91158  return pNew;
91159 }
91160 #else
91161 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
91162  assert( p==0 );
91163  return 0;
91164 }
91165 #endif
91166 
91167 
91168 /*
91169 ** Add a new element to the end of an expression list. If pList is
91170 ** initially NULL, then create a new expression list.
91171 **
91172 ** If a memory allocation error occurs, the entire list is freed and
91173 ** NULL is returned. If non-NULL is returned, then it is guaranteed
91174 ** that the new entry was successfully appended.
91175 */
91176 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
91177  Parse *pParse, /* Parsing context */
91178  ExprList *pList, /* List to which to append. Might be NULL */
91179  Expr *pExpr /* Expression to be appended. Might be NULL */
91180 ){
91181  sqlite3 *db = pParse->db;
91182  assert( db!=0 );
91183  if( pList==0 ){
91184  pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
91185  if( pList==0 ){
91186  goto no_mem;
91187  }
91188  pList->nExpr = 0;
91189  pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
91190  if( pList->a==0 ) goto no_mem;
91191  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
91192  struct ExprList_item *a;
91193  assert( pList->nExpr>0 );
91194  a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
91195  if( a==0 ){
91196  goto no_mem;
91197  }
91198  pList->a = a;
91199  }
91200  assert( pList->a!=0 );
91201  if( 1 ){
91202  struct ExprList_item *pItem = &pList->a[pList->nExpr++];
91203  memset(pItem, 0, sizeof(*pItem));
91204  pItem->pExpr = pExpr;
91205  }
91206  return pList;
91207 
91208 no_mem:
91209  /* Avoid leaking memory if malloc has failed. */
91210  sqlite3ExprDelete(db, pExpr);
91211  sqlite3ExprListDelete(db, pList);
91212  return 0;
91213 }
91214 
91215 /*
91216 ** pColumns and pExpr form a vector assignment which is part of the SET
91217 ** clause of an UPDATE statement. Like this:
91218 **
91219 ** (a,b,c) = (expr1,expr2,expr3)
91220 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
91221 **
91222 ** For each term of the vector assignment, append new entries to the
91223 ** expression list pList. In the case of a subquery on the LHS, append
91224 ** TK_SELECT_COLUMN expressions.
91225 */
91226 SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
91227  Parse *pParse, /* Parsing context */
91228  ExprList *pList, /* List to which to append. Might be NULL */
91229  IdList *pColumns, /* List of names of LHS of the assignment */
91230  Expr *pExpr /* Vector expression to be appended. Might be NULL */
91231 ){
91232  sqlite3 *db = pParse->db;
91233  int n;
91234  int i;
91235  int iFirst = pList ? pList->nExpr : 0;
91236  /* pColumns can only be NULL due to an OOM but an OOM will cause an
91237  ** exit prior to this routine being invoked */
91238  if( NEVER(pColumns==0) ) goto vector_append_error;
91239  if( pExpr==0 ) goto vector_append_error;
91240  n = sqlite3ExprVectorSize(pExpr);
91241  if( pColumns->nId!=n ){
91242  sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
91243  pColumns->nId, n);
91244  goto vector_append_error;
91245  }
91246  for(i=0; i<n; i++){
91247  Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
91248  pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
91249  if( pList ){
91250  assert( pList->nExpr==iFirst+i+1 );
91251  pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
91252  pColumns->a[i].zName = 0;
91253  }
91254  }
91255  if( pExpr->op==TK_SELECT ){
91256  if( pList && pList->a[iFirst].pExpr ){
91257  assert( pList->a[iFirst].pExpr->op==TK_SELECT_COLUMN );
91258  pList->a[iFirst].pExpr->pRight = pExpr;
91259  pExpr = 0;
91260  }
91261  }
91262 
91263 vector_append_error:
91264  sqlite3ExprDelete(db, pExpr);
91265  sqlite3IdListDelete(db, pColumns);
91266  return pList;
91267 }
91268 
91269 /*
91270 ** Set the sort order for the last element on the given ExprList.
91271 */
91272 SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
91273  if( p==0 ) return;
91274  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
91275  assert( p->nExpr>0 );
91276  if( iSortOrder<0 ){
91277  assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
91278  return;
91279  }
91280  p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
91281 }
91282 
91283 /*
91284 ** Set the ExprList.a[].zName element of the most recently added item
91285 ** on the expression list.
91286 **
91287 ** pList might be NULL following an OOM error. But pName should never be
91288 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
91289 ** is set.
91290 */
91291 SQLITE_PRIVATE void sqlite3ExprListSetName(
91292  Parse *pParse, /* Parsing context */
91293  ExprList *pList, /* List to which to add the span. */
91294  Token *pName, /* Name to be added */
91295  int dequote /* True to cause the name to be dequoted */
91296 ){
91297  assert( pList!=0 || pParse->db->mallocFailed!=0 );
91298  if( pList ){
91299  struct ExprList_item *pItem;
91300  assert( pList->nExpr>0 );
91301  pItem = &pList->a[pList->nExpr-1];
91302  assert( pItem->zName==0 );
91303  pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
91304  if( dequote ) sqlite3Dequote(pItem->zName);
91305  }
91306 }
91307 
91308 /*
91309 ** Set the ExprList.a[].zSpan element of the most recently added item
91310 ** on the expression list.
91311 **
91312 ** pList might be NULL following an OOM error. But pSpan should never be
91313 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
91314 ** is set.
91315 */
91316 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
91317  Parse *pParse, /* Parsing context */
91318  ExprList *pList, /* List to which to add the span. */
91319  ExprSpan *pSpan /* The span to be added */
91320 ){
91321  sqlite3 *db = pParse->db;
91322  assert( pList!=0 || db->mallocFailed!=0 );
91323  if( pList ){
91324  struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
91325  assert( pList->nExpr>0 );
91326  assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
91327  sqlite3DbFree(db, pItem->zSpan);
91328  pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
91329  (int)(pSpan->zEnd - pSpan->zStart));
91330  }
91331 }
91332 
91333 /*
91334 ** If the expression list pEList contains more than iLimit elements,
91335 ** leave an error message in pParse.
91336 */
91337 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
91338  Parse *pParse,
91339  ExprList *pEList,
91340  const char *zObject
91341 ){
91342  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
91343  testcase( pEList && pEList->nExpr==mx );
91344  testcase( pEList && pEList->nExpr==mx+1 );
91345  if( pEList && pEList->nExpr>mx ){
91346  sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
91347  }
91348 }
91349 
91350 /*
91351 ** Delete an entire expression list.
91352 */
91353 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
91354  int i;
91355  struct ExprList_item *pItem;
91356  assert( pList->a!=0 || pList->nExpr==0 );
91357  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
91358  sqlite3ExprDelete(db, pItem->pExpr);
91359  sqlite3DbFree(db, pItem->zName);
91360  sqlite3DbFree(db, pItem->zSpan);
91361  }
91362  sqlite3DbFree(db, pList->a);
91363  sqlite3DbFree(db, pList);
91364 }
91365 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
91366  if( pList ) exprListDeleteNN(db, pList);
91367 }
91368 
91369 /*
91370 ** Return the bitwise-OR of all Expr.flags fields in the given
91371 ** ExprList.
91372 */
91373 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
91374  int i;
91375  u32 m = 0;
91376  if( pList ){
91377  for(i=0; i<pList->nExpr; i++){
91378  Expr *pExpr = pList->a[i].pExpr;
91379  assert( pExpr!=0 );
91380  m |= pExpr->flags;
91381  }
91382  }
91383  return m;
91384 }
91385 
91386 /*
91387 ** These routines are Walker callbacks used to check expressions to
91388 ** see if they are "constant" for some definition of constant. The
91389 ** Walker.eCode value determines the type of "constant" we are looking
91390 ** for.
91391 **
91392 ** These callback routines are used to implement the following:
91393 **
91394 ** sqlite3ExprIsConstant() pWalker->eCode==1
91395 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
91396 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
91397 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
91398 **
91399 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
91400 ** is found to not be a constant.
91401 **
91402 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
91403 ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
91404 ** an existing schema and 4 when processing a new statement. A bound
91405 ** parameter raises an error for new statements, but is silently converted
91406 ** to NULL for existing schemas. This allows sqlite_master tables that
91407 ** contain a bound parameter because they were generated by older versions
91408 ** of SQLite to be parsed by newer versions of SQLite without raising a
91409 ** malformed schema error.
91410 */
91411 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
91412 
91413  /* If pWalker->eCode is 2 then any term of the expression that comes from
91414  ** the ON or USING clauses of a left join disqualifies the expression
91415  ** from being considered constant. */
91416  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
91417  pWalker->eCode = 0;
91418  return WRC_Abort;
91419  }
91420 
91421  switch( pExpr->op ){
91422  /* Consider functions to be constant if all their arguments are constant
91423  ** and either pWalker->eCode==4 or 5 or the function has the
91424  ** SQLITE_FUNC_CONST flag. */
91425  case TK_FUNCTION:
91426  if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
91427  return WRC_Continue;
91428  }else{
91429  pWalker->eCode = 0;
91430  return WRC_Abort;
91431  }
91432  case TK_ID:
91433  case TK_COLUMN:
91434  case TK_AGG_FUNCTION:
91435  case TK_AGG_COLUMN:
91436  testcase( pExpr->op==TK_ID );
91437  testcase( pExpr->op==TK_COLUMN );
91438  testcase( pExpr->op==TK_AGG_FUNCTION );
91439  testcase( pExpr->op==TK_AGG_COLUMN );
91440  if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
91441  return WRC_Continue;
91442  }else{
91443  pWalker->eCode = 0;
91444  return WRC_Abort;
91445  }
91446  case TK_VARIABLE:
91447  if( pWalker->eCode==5 ){
91448  /* Silently convert bound parameters that appear inside of CREATE
91449  ** statements into a NULL when parsing the CREATE statement text out
91450  ** of the sqlite_master table */
91451  pExpr->op = TK_NULL;
91452  }else if( pWalker->eCode==4 ){
91453  /* A bound parameter in a CREATE statement that originates from
91454  ** sqlite3_prepare() causes an error */
91455  pWalker->eCode = 0;
91456  return WRC_Abort;
91457  }
91458  /* Fall through */
91459  default:
91460  testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
91461  testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
91462  return WRC_Continue;
91463  }
91464 }
91465 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
91466  UNUSED_PARAMETER(NotUsed);
91467  pWalker->eCode = 0;
91468  return WRC_Abort;
91469 }
91470 static int exprIsConst(Expr *p, int initFlag, int iCur){
91471  Walker w;
91472  memset(&w, 0, sizeof(w));
91473  w.eCode = initFlag;
91474  w.xExprCallback = exprNodeIsConstant;
91475  w.xSelectCallback = selectNodeIsConstant;
91476  w.u.iCur = iCur;
91477  sqlite3WalkExpr(&w, p);
91478  return w.eCode;
91479 }
91480 
91481 /*
91482 ** Walk an expression tree. Return non-zero if the expression is constant
91483 ** and 0 if it involves variables or function calls.
91484 **
91485 ** For the purposes of this function, a double-quoted string (ex: "abc")
91486 ** is considered a variable but a single-quoted string (ex: 'abc') is
91487 ** a constant.
91488 */
91489 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
91490  return exprIsConst(p, 1, 0);
91491 }
91492 
91493 /*
91494 ** Walk an expression tree. Return non-zero if the expression is constant
91495 ** that does no originate from the ON or USING clauses of a join.
91496 ** Return 0 if it involves variables or function calls or terms from
91497 ** an ON or USING clause.
91498 */
91499 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
91500  return exprIsConst(p, 2, 0);
91501 }
91502 
91503 /*
91504 ** Walk an expression tree. Return non-zero if the expression is constant
91505 ** for any single row of the table with cursor iCur. In other words, the
91506 ** expression must not refer to any non-deterministic function nor any
91507 ** table other than iCur.
91508 */
91509 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
91510  return exprIsConst(p, 3, iCur);
91511 }
91512 
91513 /*
91514 ** Walk an expression tree. Return non-zero if the expression is constant
91515 ** or a function call with constant arguments. Return and 0 if there
91516 ** are any variables.
91517 **
91518 ** For the purposes of this function, a double-quoted string (ex: "abc")
91519 ** is considered a variable but a single-quoted string (ex: 'abc') is
91520 ** a constant.
91521 */
91522 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
91523  assert( isInit==0 || isInit==1 );
91524  return exprIsConst(p, 4+isInit, 0);
91525 }
91526 
91527 #ifdef SQLITE_ENABLE_CURSOR_HINTS
91528 /*
91529 ** Walk an expression tree. Return 1 if the expression contains a
91530 ** subquery of some kind. Return 0 if there are no subqueries.
91531 */
91532 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
91533  Walker w;
91534  memset(&w, 0, sizeof(w));
91535  w.eCode = 1;
91536  w.xExprCallback = sqlite3ExprWalkNoop;
91537  w.xSelectCallback = selectNodeIsConstant;
91538  sqlite3WalkExpr(&w, p);
91539  return w.eCode==0;
91540 }
91541 #endif
91542 
91543 /*
91544 ** If the expression p codes a constant integer that is small enough
91545 ** to fit in a 32-bit integer, return 1 and put the value of the integer
91546 ** in *pValue. If the expression is not an integer or if it is too big
91547 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
91548 */
91549 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
91550  int rc = 0;
91551 
91552  /* If an expression is an integer literal that fits in a signed 32-bit
91553  ** integer, then the EP_IntValue flag will have already been set */
91554  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
91555  || sqlite3GetInt32(p->u.zToken, &rc)==0 );
91556 
91557  if( p->flags & EP_IntValue ){
91558  *pValue = p->u.iValue;
91559  return 1;
91560  }
91561  switch( p->op ){
91562  case TK_UPLUS: {
91563  rc = sqlite3ExprIsInteger(p->pLeft, pValue);
91564  break;
91565  }
91566  case TK_UMINUS: {
91567  int v;
91568  if( sqlite3ExprIsInteger(p->pLeft, &v) ){
91569  assert( v!=(-2147483647-1) );
91570  *pValue = -v;
91571  rc = 1;
91572  }
91573  break;
91574  }
91575  default: break;
91576  }
91577  return rc;
91578 }
91579 
91580 /*
91581 ** Return FALSE if there is no chance that the expression can be NULL.
91582 **
91583 ** If the expression might be NULL or if the expression is too complex
91584 ** to tell return TRUE.
91585 **
91586 ** This routine is used as an optimization, to skip OP_IsNull opcodes
91587 ** when we know that a value cannot be NULL. Hence, a false positive
91588 ** (returning TRUE when in fact the expression can never be NULL) might
91589 ** be a small performance hit but is otherwise harmless. On the other
91590 ** hand, a false negative (returning FALSE when the result could be NULL)
91591 ** will likely result in an incorrect answer. So when in doubt, return
91592 ** TRUE.
91593 */
91594 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
91595  u8 op;
91596  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
91597  op = p->op;
91598  if( op==TK_REGISTER ) op = p->op2;
91599  switch( op ){
91600  case TK_INTEGER:
91601  case TK_STRING:
91602  case TK_FLOAT:
91603  case TK_BLOB:
91604  return 0;
91605  case TK_COLUMN:
91606  assert( p->pTab!=0 );
91607  return ExprHasProperty(p, EP_CanBeNull) ||
91608  (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
91609  default:
91610  return 1;
91611  }
91612 }
91613 
91614 /*
91615 ** Return TRUE if the given expression is a constant which would be
91616 ** unchanged by OP_Affinity with the affinity given in the second
91617 ** argument.
91618 **
91619 ** This routine is used to determine if the OP_Affinity operation
91620 ** can be omitted. When in doubt return FALSE. A false negative
91621 ** is harmless. A false positive, however, can result in the wrong
91622 ** answer.
91623 */
91624 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
91625  u8 op;
91626  if( aff==SQLITE_AFF_BLOB ) return 1;
91627  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
91628  op = p->op;
91629  if( op==TK_REGISTER ) op = p->op2;
91630  switch( op ){
91631  case TK_INTEGER: {
91632  return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
91633  }
91634  case TK_FLOAT: {
91635  return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
91636  }
91637  case TK_STRING: {
91638  return aff==SQLITE_AFF_TEXT;
91639  }
91640  case TK_BLOB: {
91641  return 1;
91642  }
91643  case TK_COLUMN: {
91644  assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
91645  return p->iColumn<0
91646  && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
91647  }
91648  default: {
91649  return 0;
91650  }
91651  }
91652 }
91653 
91654 /*
91655 ** Return TRUE if the given string is a row-id column name.
91656 */
91657 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
91658  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
91659  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
91660  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
91661  return 0;
91662 }
91663 
91664 /*
91665 ** pX is the RHS of an IN operator. If pX is a SELECT statement
91666 ** that can be simplified to a direct table access, then return
91667 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
91668 ** or if the SELECT statement needs to be manifested into a transient
91669 ** table, then return NULL.
91670 */
91671 #ifndef SQLITE_OMIT_SUBQUERY
91672 static Select *isCandidateForInOpt(Expr *pX){
91673  Select *p;
91674  SrcList *pSrc;
91675  ExprList *pEList;
91676  Table *pTab;
91677  int i;
91678  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
91679  if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
91680  p = pX->x.pSelect;
91681  if( p->pPrior ) return 0; /* Not a compound SELECT */
91682  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
91683  testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
91684  testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
91685  return 0; /* No DISTINCT keyword and no aggregate functions */
91686  }
91687  assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
91688  if( p->pLimit ) return 0; /* Has no LIMIT clause */
91689  assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
91690  if( p->pWhere ) return 0; /* Has no WHERE clause */
91691  pSrc = p->pSrc;
91692  assert( pSrc!=0 );
91693  if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
91694  if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
91695  pTab = pSrc->a[0].pTab;
91696  assert( pTab!=0 );
91697  assert( pTab->pSelect==0 ); /* FROM clause is not a view */
91698  if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
91699  pEList = p->pEList;
91700  assert( pEList!=0 );
91701  /* All SELECT results must be columns. */
91702  for(i=0; i<pEList->nExpr; i++){
91703  Expr *pRes = pEList->a[i].pExpr;
91704  if( pRes->op!=TK_COLUMN ) return 0;
91705  assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
91706  }
91707  return p;
91708 }
91709 #endif /* SQLITE_OMIT_SUBQUERY */
91710 
91711 #ifndef SQLITE_OMIT_SUBQUERY
91712 /*
91713 ** Generate code that checks the left-most column of index table iCur to see if
91714 ** it contains any NULL entries. Cause the register at regHasNull to be set
91715 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
91716 ** to be set to NULL if iCur contains one or more NULL values.
91717 */
91718 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
91719  int addr1;
91720  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
91721  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
91722  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
91723  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
91724  VdbeComment((v, "first_entry_in(%d)", iCur));
91725  sqlite3VdbeJumpHere(v, addr1);
91726 }
91727 #endif
91728 
91729 
91730 #ifndef SQLITE_OMIT_SUBQUERY
91731 /*
91732 ** The argument is an IN operator with a list (not a subquery) on the
91733 ** right-hand side. Return TRUE if that list is constant.
91734 */
91735 static int sqlite3InRhsIsConstant(Expr *pIn){
91736  Expr *pLHS;
91737  int res;
91738  assert( !ExprHasProperty(pIn, EP_xIsSelect) );
91739  pLHS = pIn->pLeft;
91740  pIn->pLeft = 0;
91741  res = sqlite3ExprIsConstant(pIn);
91742  pIn->pLeft = pLHS;
91743  return res;
91744 }
91745 #endif
91746 
91747 /*
91748 ** This function is used by the implementation of the IN (...) operator.
91749 ** The pX parameter is the expression on the RHS of the IN operator, which
91750 ** might be either a list of expressions or a subquery.
91751 **
91752 ** The job of this routine is to find or create a b-tree object that can
91753 ** be used either to test for membership in the RHS set or to iterate through
91754 ** all members of the RHS set, skipping duplicates.
91755 **
91756 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
91757 ** and pX->iTable is set to the index of that cursor.
91758 **
91759 ** The returned value of this function indicates the b-tree type, as follows:
91760 **
91761 ** IN_INDEX_ROWID - The cursor was opened on a database table.
91762 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
91763 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
91764 ** IN_INDEX_EPH - The cursor was opened on a specially created and
91765 ** populated epheremal table.
91766 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
91767 ** implemented as a sequence of comparisons.
91768 **
91769 ** An existing b-tree might be used if the RHS expression pX is a simple
91770 ** subquery such as:
91771 **
91772 ** SELECT <column1>, <column2>... FROM <table>
91773 **
91774 ** If the RHS of the IN operator is a list or a more complex subquery, then
91775 ** an ephemeral table might need to be generated from the RHS and then
91776 ** pX->iTable made to point to the ephemeral table instead of an
91777 ** existing table.
91778 **
91779 ** The inFlags parameter must contain exactly one of the bits
91780 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
91781 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
91782 ** fast membership test. When the IN_INDEX_LOOP bit is set, the
91783 ** IN index will be used to loop over all values of the RHS of the
91784 ** IN operator.
91785 **
91786 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
91787 ** through the set members) then the b-tree must not contain duplicates.
91788 ** An epheremal table must be used unless the selected columns are guaranteed
91789 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
91790 ** a UNIQUE constraint or index.
91791 **
91792 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
91793 ** for fast set membership tests) then an epheremal table must
91794 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
91795 ** index can be found with the specified <columns> as its left-most.
91796 **
91797 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
91798 ** if the RHS of the IN operator is a list (not a subquery) then this
91799 ** routine might decide that creating an ephemeral b-tree for membership
91800 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
91801 ** calling routine should implement the IN operator using a sequence
91802 ** of Eq or Ne comparison operations.
91803 **
91804 ** When the b-tree is being used for membership tests, the calling function
91805 ** might need to know whether or not the RHS side of the IN operator
91806 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
91807 ** if there is any chance that the (...) might contain a NULL value at
91808 ** runtime, then a register is allocated and the register number written
91809 ** to *prRhsHasNull. If there is no chance that the (...) contains a
91810 ** NULL value, then *prRhsHasNull is left unchanged.
91811 **
91812 ** If a register is allocated and its location stored in *prRhsHasNull, then
91813 ** the value in that register will be NULL if the b-tree contains one or more
91814 ** NULL values, and it will be some non-NULL value if the b-tree contains no
91815 ** NULL values.
91816 **
91817 ** If the aiMap parameter is not NULL, it must point to an array containing
91818 ** one element for each column returned by the SELECT statement on the RHS
91819 ** of the IN(...) operator. The i'th entry of the array is populated with the
91820 ** offset of the index column that matches the i'th column returned by the
91821 ** SELECT. For example, if the expression and selected index are:
91822 **
91823 ** (?,?,?) IN (SELECT a, b, c FROM t1)
91824 ** CREATE INDEX i1 ON t1(b, c, a);
91825 **
91826 ** then aiMap[] is populated with {2, 0, 1}.
91827 */
91828 #ifndef SQLITE_OMIT_SUBQUERY
91829 SQLITE_PRIVATE int sqlite3FindInIndex(
91830  Parse *pParse, /* Parsing context */
91831  Expr *pX, /* The right-hand side (RHS) of the IN operator */
91832  u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
91833  int *prRhsHasNull, /* Register holding NULL status. See notes */
91834  int *aiMap /* Mapping from Index fields to RHS fields */
91835 ){
91836  Select *p; /* SELECT to the right of IN operator */
91837  int eType = 0; /* Type of RHS table. IN_INDEX_* */
91838  int iTab = pParse->nTab++; /* Cursor of the RHS table */
91839  int mustBeUnique; /* True if RHS must be unique */
91840  Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
91841 
91842  assert( pX->op==TK_IN );
91843  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
91844 
91845  /* If the RHS of this IN(...) operator is a SELECT, and if it matters
91846  ** whether or not the SELECT result contains NULL values, check whether
91847  ** or not NULL is actually possible (it may not be, for example, due
91848  ** to NOT NULL constraints in the schema). If no NULL values are possible,
91849  ** set prRhsHasNull to 0 before continuing. */
91850  if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
91851  int i;
91852  ExprList *pEList = pX->x.pSelect->pEList;
91853  for(i=0; i<pEList->nExpr; i++){
91854  if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
91855  }
91856  if( i==pEList->nExpr ){
91857  prRhsHasNull = 0;
91858  }
91859  }
91860 
91861  /* Check to see if an existing table or index can be used to
91862  ** satisfy the query. This is preferable to generating a new
91863  ** ephemeral table. */
91864  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
91865  sqlite3 *db = pParse->db; /* Database connection */
91866  Table *pTab; /* Table <table>. */
91867  i16 iDb; /* Database idx for pTab */
91868  ExprList *pEList = p->pEList;
91869  int nExpr = pEList->nExpr;
91870 
91871  assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
91872  assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
91873  assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
91874  pTab = p->pSrc->a[0].pTab;
91875 
91876  /* Code an OP_Transaction and OP_TableLock for <table>. */
91877  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91878  sqlite3CodeVerifySchema(pParse, iDb);
91879  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91880 
91881  assert(v); /* sqlite3GetVdbe() has always been previously called */
91882  if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
91883  /* The "x IN (SELECT rowid FROM table)" case */
91884  int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
91885  VdbeCoverage(v);
91886 
91887  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
91888  eType = IN_INDEX_ROWID;
91889 
91890  sqlite3VdbeJumpHere(v, iAddr);
91891  }else{
91892  Index *pIdx; /* Iterator variable */
91893  int affinity_ok = 1;
91894  int i;
91895 
91896  /* Check that the affinity that will be used to perform each
91897  ** comparison is the same as the affinity of each column in table
91898  ** on the RHS of the IN operator. If it not, it is not possible to
91899  ** use any index of the RHS table. */
91900  for(i=0; i<nExpr && affinity_ok; i++){
91901  Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
91902  int iCol = pEList->a[i].pExpr->iColumn;
91903  char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
91904  char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
91905  testcase( cmpaff==SQLITE_AFF_BLOB );
91906  testcase( cmpaff==SQLITE_AFF_TEXT );
91907  switch( cmpaff ){
91908  case SQLITE_AFF_BLOB:
91909  break;
91910  case SQLITE_AFF_TEXT:
91911  /* sqlite3CompareAffinity() only returns TEXT if one side or the
91912  ** other has no affinity and the other side is TEXT. Hence,
91913  ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
91914  ** and for the term on the LHS of the IN to have no affinity. */
91915  assert( idxaff==SQLITE_AFF_TEXT );
91916  break;
91917  default:
91918  affinity_ok = sqlite3IsNumericAffinity(idxaff);
91919  }
91920  }
91921 
91922  if( affinity_ok ){
91923  /* Search for an existing index that will work for this IN operator */
91924  for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
91925  Bitmask colUsed; /* Columns of the index used */
91926  Bitmask mCol; /* Mask for the current column */
91927  if( pIdx->nColumn<nExpr ) continue;
91928  /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
91929  ** BITMASK(nExpr) without overflowing */
91930  testcase( pIdx->nColumn==BMS-2 );
91931  testcase( pIdx->nColumn==BMS-1 );
91932  if( pIdx->nColumn>=BMS-1 ) continue;
91933  if( mustBeUnique ){
91934  if( pIdx->nKeyCol>nExpr
91935  ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
91936  ){
91937  continue; /* This index is not unique over the IN RHS columns */
91938  }
91939  }
91940 
91941  colUsed = 0; /* Columns of index used so far */
91942  for(i=0; i<nExpr; i++){
91943  Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
91944  Expr *pRhs = pEList->a[i].pExpr;
91945  CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
91946  int j;
91947 
91948  assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
91949  for(j=0; j<nExpr; j++){
91950  if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
91951  assert( pIdx->azColl[j] );
91952  if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
91953  continue;
91954  }
91955  break;
91956  }
91957  if( j==nExpr ) break;
91958  mCol = MASKBIT(j);
91959  if( mCol & colUsed ) break; /* Each column used only once */
91960  colUsed |= mCol;
91961  if( aiMap ) aiMap[i] = j;
91962  }
91963 
91964  assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
91965  if( colUsed==(MASKBIT(nExpr)-1) ){
91966  /* If we reach this point, that means the index pIdx is usable */
91967  int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
91968 #ifndef SQLITE_OMIT_EXPLAIN
91969  sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
91970  sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
91971  P4_DYNAMIC);
91972 #endif
91973  sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
91974  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
91975  VdbeComment((v, "%s", pIdx->zName));
91976  assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
91977  eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
91978 
91979  if( prRhsHasNull ){
91980 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
91981  i64 mask = (1<<nExpr)-1;
91982  sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
91983  iTab, 0, 0, (u8*)&mask, P4_INT64);
91984 #endif
91985  *prRhsHasNull = ++pParse->nMem;
91986  if( nExpr==1 ){
91987  sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
91988  }
91989  }
91990  sqlite3VdbeJumpHere(v, iAddr);
91991  }
91992  } /* End loop over indexes */
91993  } /* End if( affinity_ok ) */
91994  } /* End if not an rowid index */
91995  } /* End attempt to optimize using an index */
91996 
91997  /* If no preexisting index is available for the IN clause
91998  ** and IN_INDEX_NOOP is an allowed reply
91999  ** and the RHS of the IN operator is a list, not a subquery
92000  ** and the RHS is not constant or has two or fewer terms,
92001  ** then it is not worth creating an ephemeral table to evaluate
92002  ** the IN operator so return IN_INDEX_NOOP.
92003  */
92004  if( eType==0
92005  && (inFlags & IN_INDEX_NOOP_OK)
92006  && !ExprHasProperty(pX, EP_xIsSelect)
92007  && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
92008  ){
92009  eType = IN_INDEX_NOOP;
92010  }
92011 
92012  if( eType==0 ){
92013  /* Could not find an existing table or index to use as the RHS b-tree.
92014  ** We will have to generate an ephemeral table to do the job.
92015  */
92016  u32 savedNQueryLoop = pParse->nQueryLoop;
92017  int rMayHaveNull = 0;
92018  eType = IN_INDEX_EPH;
92019  if( inFlags & IN_INDEX_LOOP ){
92020  pParse->nQueryLoop = 0;
92021  if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
92022  eType = IN_INDEX_ROWID;
92023  }
92024  }else if( prRhsHasNull ){
92025  *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
92026  }
92027  sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
92028  pParse->nQueryLoop = savedNQueryLoop;
92029  }else{
92030  pX->iTable = iTab;
92031  }
92032 
92033  if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
92034  int i, n;
92035  n = sqlite3ExprVectorSize(pX->pLeft);
92036  for(i=0; i<n; i++) aiMap[i] = i;
92037  }
92038  return eType;
92039 }
92040 #endif
92041 
92042 #ifndef SQLITE_OMIT_SUBQUERY
92043 /*
92044 ** Argument pExpr is an (?, ?...) IN(...) expression. This
92045 ** function allocates and returns a nul-terminated string containing
92046 ** the affinities to be used for each column of the comparison.
92047 **
92048 ** It is the responsibility of the caller to ensure that the returned
92049 ** string is eventually freed using sqlite3DbFree().
92050 */
92051 static char *exprINAffinity(Parse *pParse, Expr *pExpr){
92052  Expr *pLeft = pExpr->pLeft;
92053  int nVal = sqlite3ExprVectorSize(pLeft);
92054  Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
92055  char *zRet;
92056 
92057  assert( pExpr->op==TK_IN );
92058  zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
92059  if( zRet ){
92060  int i;
92061  for(i=0; i<nVal; i++){
92062  Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
92063  char a = sqlite3ExprAffinity(pA);
92064  if( pSelect ){
92065  zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
92066  }else{
92067  zRet[i] = a;
92068  }
92069  }
92070  zRet[nVal] = '\0';
92071  }
92072  return zRet;
92073 }
92074 #endif
92075 
92076 #ifndef SQLITE_OMIT_SUBQUERY
92077 /*
92078 ** Load the Parse object passed as the first argument with an error
92079 ** message of the form:
92080 **
92081 ** "sub-select returns N columns - expected M"
92082 */
92083 SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
92084  const char *zFmt = "sub-select returns %d columns - expected %d";
92085  sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
92086 }
92087 #endif
92088 
92089 /*
92090 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
92091 ** or IN operators. Examples:
92092 **
92093 ** (SELECT a FROM b) -- subquery
92094 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
92095 ** x IN (4,5,11) -- IN operator with list on right-hand side
92096 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
92097 **
92098 ** The pExpr parameter describes the expression that contains the IN
92099 ** operator or subquery.
92100 **
92101 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
92102 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
92103 ** to some integer key column of a table B-Tree. In this case, use an
92104 ** intkey B-Tree to store the set of IN(...) values instead of the usual
92105 ** (slower) variable length keys B-Tree.
92106 **
92107 ** If rMayHaveNull is non-zero, that means that the operation is an IN
92108 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
92109 ** All this routine does is initialize the register given by rMayHaveNull
92110 ** to NULL. Calling routines will take care of changing this register
92111 ** value to non-NULL if the RHS is NULL-free.
92112 **
92113 ** For a SELECT or EXISTS operator, return the register that holds the
92114 ** result. For a multi-column SELECT, the result is stored in a contiguous
92115 ** array of registers and the return value is the register of the left-most
92116 ** result column. Return 0 for IN operators or if an error occurs.
92117 */
92118 #ifndef SQLITE_OMIT_SUBQUERY
92119 SQLITE_PRIVATE int sqlite3CodeSubselect(
92120  Parse *pParse, /* Parsing context */
92121  Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
92122  int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
92123  int isRowid /* If true, LHS of IN operator is a rowid */
92124 ){
92125  int jmpIfDynamic = -1; /* One-time test address */
92126  int rReg = 0; /* Register storing resulting */
92127  Vdbe *v = sqlite3GetVdbe(pParse);
92128  if( NEVER(v==0) ) return 0;
92129  sqlite3ExprCachePush(pParse);
92130 
92131  /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
92132  ** is encountered if any of the following is true:
92133  **
92134  ** * The right-hand side is a correlated subquery
92135  ** * The right-hand side is an expression list containing variables
92136  ** * We are inside a trigger
92137  **
92138  ** If all of the above are false, then we can run this code just once
92139  ** save the results, and reuse the same result on subsequent invocations.
92140  */
92141  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
92142  jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
92143  }
92144 
92145 #ifndef SQLITE_OMIT_EXPLAIN
92146  if( pParse->explain==2 ){
92147  char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
92148  jmpIfDynamic>=0?"":"CORRELATED ",
92149  pExpr->op==TK_IN?"LIST":"SCALAR",
92150  pParse->iNextSelectId
92151  );
92152  sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
92153  }
92154 #endif
92155 
92156  switch( pExpr->op ){
92157  case TK_IN: {
92158  int addr; /* Address of OP_OpenEphemeral instruction */
92159  Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
92160  KeyInfo *pKeyInfo = 0; /* Key information */
92161  int nVal; /* Size of vector pLeft */
92162 
92163  nVal = sqlite3ExprVectorSize(pLeft);
92164  assert( !isRowid || nVal==1 );
92165 
92166  /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
92167  ** expression it is handled the same way. An ephemeral table is
92168  ** filled with index keys representing the results from the
92169  ** SELECT or the <exprlist>.
92170  **
92171  ** If the 'x' expression is a column value, or the SELECT...
92172  ** statement returns a column value, then the affinity of that
92173  ** column is used to build the index keys. If both 'x' and the
92174  ** SELECT... statement are columns, then numeric affinity is used
92175  ** if either column has NUMERIC or INTEGER affinity. If neither
92176  ** 'x' nor the SELECT... statement are columns, then numeric affinity
92177  ** is used.
92178  */
92179  pExpr->iTable = pParse->nTab++;
92180  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
92181  pExpr->iTable, (isRowid?0:nVal));
92182  pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
92183 
92184  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92185  /* Case 1: expr IN (SELECT ...)
92186  **
92187  ** Generate code to write the results of the select into the temporary
92188  ** table allocated and opened above.
92189  */
92190  Select *pSelect = pExpr->x.pSelect;
92191  ExprList *pEList = pSelect->pEList;
92192 
92193  assert( !isRowid );
92194  /* If the LHS and RHS of the IN operator do not match, that
92195  ** error will have been caught long before we reach this point. */
92196  if( ALWAYS(pEList->nExpr==nVal) ){
92197  SelectDest dest;
92198  int i;
92199  sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
92200  dest.zAffSdst = exprINAffinity(pParse, pExpr);
92201  assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
92202  pSelect->iLimit = 0;
92203  testcase( pSelect->selFlags & SF_Distinct );
92204  testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
92205  if( sqlite3Select(pParse, pSelect, &dest) ){
92206  sqlite3DbFree(pParse->db, dest.zAffSdst);
92207  sqlite3KeyInfoUnref(pKeyInfo);
92208  return 0;
92209  }
92210  sqlite3DbFree(pParse->db, dest.zAffSdst);
92211  assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
92212  assert( pEList!=0 );
92213  assert( pEList->nExpr>0 );
92214  assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
92215  for(i=0; i<nVal; i++){
92216  Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
92217  pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
92218  pParse, p, pEList->a[i].pExpr
92219  );
92220  }
92221  }
92222  }else if( ALWAYS(pExpr->x.pList!=0) ){
92223  /* Case 2: expr IN (exprlist)
92224  **
92225  ** For each expression, build an index key from the evaluation and
92226  ** store it in the temporary table. If <expr> is a column, then use
92227  ** that columns affinity when building index keys. If <expr> is not
92228  ** a column, use numeric affinity.
92229  */
92230  char affinity; /* Affinity of the LHS of the IN */
92231  int i;
92232  ExprList *pList = pExpr->x.pList;
92233  struct ExprList_item *pItem;
92234  int r1, r2, r3;
92235 
92236  affinity = sqlite3ExprAffinity(pLeft);
92237  if( !affinity ){
92238  affinity = SQLITE_AFF_BLOB;
92239  }
92240  if( pKeyInfo ){
92241  assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
92242  pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
92243  }
92244 
92245  /* Loop through each expression in <exprlist>. */
92246  r1 = sqlite3GetTempReg(pParse);
92247  r2 = sqlite3GetTempReg(pParse);
92248  if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
92249  for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
92250  Expr *pE2 = pItem->pExpr;
92251  int iValToIns;
92252 
92253  /* If the expression is not constant then we will need to
92254  ** disable the test that was generated above that makes sure
92255  ** this code only executes once. Because for a non-constant
92256  ** expression we need to rerun this code each time.
92257  */
92258  if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
92259  sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
92260  jmpIfDynamic = -1;
92261  }
92262 
92263  /* Evaluate the expression and insert it into the temp table */
92264  if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
92265  sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
92266  }else{
92267  r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
92268  if( isRowid ){
92269  sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
92270  sqlite3VdbeCurrentAddr(v)+2);
92271  VdbeCoverage(v);
92272  sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
92273  }else{
92274  sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
92275  sqlite3ExprCacheAffinityChange(pParse, r3, 1);
92276  sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
92277  }
92278  }
92279  }
92280  sqlite3ReleaseTempReg(pParse, r1);
92281  sqlite3ReleaseTempReg(pParse, r2);
92282  }
92283  if( pKeyInfo ){
92284  sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
92285  }
92286  break;
92287  }
92288 
92289  case TK_EXISTS:
92290  case TK_SELECT:
92291  default: {
92292  /* Case 3: (SELECT ... FROM ...)
92293  ** or: EXISTS(SELECT ... FROM ...)
92294  **
92295  ** For a SELECT, generate code to put the values for all columns of
92296  ** the first row into an array of registers and return the index of
92297  ** the first register.
92298  **
92299  ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
92300  ** into a register and return that register number.
92301  **
92302  ** In both cases, the query is augmented with "LIMIT 1". Any
92303  ** preexisting limit is discarded in place of the new LIMIT 1.
92304  */
92305  Select *pSel; /* SELECT statement to encode */
92306  SelectDest dest; /* How to deal with SELECT result */
92307  int nReg; /* Registers to allocate */
92308 
92309  testcase( pExpr->op==TK_EXISTS );
92310  testcase( pExpr->op==TK_SELECT );
92311  assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
92312  assert( ExprHasProperty(pExpr, EP_xIsSelect) );
92313 
92314  pSel = pExpr->x.pSelect;
92315  nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
92316  sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
92317  pParse->nMem += nReg;
92318  if( pExpr->op==TK_SELECT ){
92319  dest.eDest = SRT_Mem;
92320  dest.iSdst = dest.iSDParm;
92321  dest.nSdst = nReg;
92322  sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
92323  VdbeComment((v, "Init subquery result"));
92324  }else{
92325  dest.eDest = SRT_Exists;
92326  sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
92327  VdbeComment((v, "Init EXISTS result"));
92328  }
92329  sqlite3ExprDelete(pParse->db, pSel->pLimit);
92330  pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
92331  &sqlite3IntTokens[1], 0);
92332  pSel->iLimit = 0;
92333  pSel->selFlags &= ~SF_MultiValue;
92334  if( sqlite3Select(pParse, pSel, &dest) ){
92335  return 0;
92336  }
92337  rReg = dest.iSDParm;
92338  ExprSetVVAProperty(pExpr, EP_NoReduce);
92339  break;
92340  }
92341  }
92342 
92343  if( rHasNullFlag ){
92344  sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
92345  }
92346 
92347  if( jmpIfDynamic>=0 ){
92348  sqlite3VdbeJumpHere(v, jmpIfDynamic);
92349  }
92350  sqlite3ExprCachePop(pParse);
92351 
92352  return rReg;
92353 }
92354 #endif /* SQLITE_OMIT_SUBQUERY */
92355 
92356 #ifndef SQLITE_OMIT_SUBQUERY
92357 /*
92358 ** Expr pIn is an IN(...) expression. This function checks that the
92359 ** sub-select on the RHS of the IN() operator has the same number of
92360 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
92361 ** a sub-query, that the LHS is a vector of size 1.
92362 */
92363 SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
92364  int nVector = sqlite3ExprVectorSize(pIn->pLeft);
92365  if( (pIn->flags & EP_xIsSelect) ){
92366  if( nVector!=pIn->x.pSelect->pEList->nExpr ){
92367  sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
92368  return 1;
92369  }
92370  }else if( nVector!=1 ){
92371  if( (pIn->pLeft->flags & EP_xIsSelect) ){
92372  sqlite3SubselectError(pParse, nVector, 1);
92373  }else{
92374  sqlite3ErrorMsg(pParse, "row value misused");
92375  }
92376  return 1;
92377  }
92378  return 0;
92379 }
92380 #endif
92381 
92382 #ifndef SQLITE_OMIT_SUBQUERY
92383 /*
92384 ** Generate code for an IN expression.
92385 **
92386 ** x IN (SELECT ...)
92387 ** x IN (value, value, ...)
92388 **
92389 ** The left-hand side (LHS) is a scalar or vector expression. The
92390 ** right-hand side (RHS) is an array of zero or more scalar values, or a
92391 ** subquery. If the RHS is a subquery, the number of result columns must
92392 ** match the number of columns in the vector on the LHS. If the RHS is
92393 ** a list of values, the LHS must be a scalar.
92394 **
92395 ** The IN operator is true if the LHS value is contained within the RHS.
92396 ** The result is false if the LHS is definitely not in the RHS. The
92397 ** result is NULL if the presence of the LHS in the RHS cannot be
92398 ** determined due to NULLs.
92399 **
92400 ** This routine generates code that jumps to destIfFalse if the LHS is not
92401 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
92402 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
92403 ** within the RHS then fall through.
92404 **
92405 ** See the separate in-operator.md documentation file in the canonical
92406 ** SQLite source tree for additional information.
92407 */
92408 static void sqlite3ExprCodeIN(
92409  Parse *pParse, /* Parsing and code generating context */
92410  Expr *pExpr, /* The IN expression */
92411  int destIfFalse, /* Jump here if LHS is not contained in the RHS */
92412  int destIfNull /* Jump here if the results are unknown due to NULLs */
92413 ){
92414  int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
92415  int eType; /* Type of the RHS */
92416  int rLhs; /* Register(s) holding the LHS values */
92417  int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
92418  Vdbe *v; /* Statement under construction */
92419  int *aiMap = 0; /* Map from vector field to index column */
92420  char *zAff = 0; /* Affinity string for comparisons */
92421  int nVector; /* Size of vectors for this IN operator */
92422  int iDummy; /* Dummy parameter to exprCodeVector() */
92423  Expr *pLeft; /* The LHS of the IN operator */
92424  int i; /* loop counter */
92425  int destStep2; /* Where to jump when NULLs seen in step 2 */
92426  int destStep6 = 0; /* Start of code for Step 6 */
92427  int addrTruthOp; /* Address of opcode that determines the IN is true */
92428  int destNotNull; /* Jump here if a comparison is not true in step 6 */
92429  int addrTop; /* Top of the step-6 loop */
92430 
92431  pLeft = pExpr->pLeft;
92432  if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
92433  zAff = exprINAffinity(pParse, pExpr);
92434  nVector = sqlite3ExprVectorSize(pExpr->pLeft);
92435  aiMap = (int*)sqlite3DbMallocZero(
92436  pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
92437  );
92438  if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
92439 
92440  /* Attempt to compute the RHS. After this step, if anything other than
92441  ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
92442  ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
92443  ** the RHS has not yet been coded. */
92444  v = pParse->pVdbe;
92445  assert( v!=0 ); /* OOM detected prior to this routine */
92446  VdbeNoopComment((v, "begin IN expr"));
92447  eType = sqlite3FindInIndex(pParse, pExpr,
92448  IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
92449  destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
92450 
92451  assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
92452  || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
92453  );
92454 #ifdef SQLITE_DEBUG
92455  /* Confirm that aiMap[] contains nVector integer values between 0 and
92456  ** nVector-1. */
92457  for(i=0; i<nVector; i++){
92458  int j, cnt;
92459  for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
92460  assert( cnt==1 );
92461  }
92462 #endif
92463 
92464  /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
92465  ** vector, then it is stored in an array of nVector registers starting
92466  ** at r1.
92467  **
92468  ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
92469  ** so that the fields are in the same order as an existing index. The
92470  ** aiMap[] array contains a mapping from the original LHS field order to
92471  ** the field order that matches the RHS index.
92472  */
92473  sqlite3ExprCachePush(pParse);
92474  rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
92475  for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
92476  if( i==nVector ){
92477  /* LHS fields are not reordered */
92478  rLhs = rLhsOrig;
92479  }else{
92480  /* Need to reorder the LHS fields according to aiMap */
92481  rLhs = sqlite3GetTempRange(pParse, nVector);
92482  for(i=0; i<nVector; i++){
92483  sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
92484  }
92485  }
92486 
92487  /* If sqlite3FindInIndex() did not find or create an index that is
92488  ** suitable for evaluating the IN operator, then evaluate using a
92489  ** sequence of comparisons.
92490  **
92491  ** This is step (1) in the in-operator.md optimized algorithm.
92492  */
92493  if( eType==IN_INDEX_NOOP ){
92494  ExprList *pList = pExpr->x.pList;
92495  CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
92496  int labelOk = sqlite3VdbeMakeLabel(v);
92497  int r2, regToFree;
92498  int regCkNull = 0;
92499  int ii;
92500  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92501  if( destIfNull!=destIfFalse ){
92502  regCkNull = sqlite3GetTempReg(pParse);
92503  sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
92504  }
92505  for(ii=0; ii<pList->nExpr; ii++){
92506  r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
92507  if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
92508  sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
92509  }
92510  if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
92511  sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
92512  (void*)pColl, P4_COLLSEQ);
92513  VdbeCoverageIf(v, ii<pList->nExpr-1);
92514  VdbeCoverageIf(v, ii==pList->nExpr-1);
92515  sqlite3VdbeChangeP5(v, zAff[0]);
92516  }else{
92517  assert( destIfNull==destIfFalse );
92518  sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
92519  (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
92520  sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
92521  }
92522  sqlite3ReleaseTempReg(pParse, regToFree);
92523  }
92524  if( regCkNull ){
92525  sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
92526  sqlite3VdbeGoto(v, destIfFalse);
92527  }
92528  sqlite3VdbeResolveLabel(v, labelOk);
92529  sqlite3ReleaseTempReg(pParse, regCkNull);
92530  goto sqlite3ExprCodeIN_finished;
92531  }
92532 
92533  /* Step 2: Check to see if the LHS contains any NULL columns. If the
92534  ** LHS does contain NULLs then the result must be either FALSE or NULL.
92535  ** We will then skip the binary search of the RHS.
92536  */
92537  if( destIfNull==destIfFalse ){
92538  destStep2 = destIfFalse;
92539  }else{
92540  destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
92541  }
92542  for(i=0; i<nVector; i++){
92543  Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
92544  if( sqlite3ExprCanBeNull(p) ){
92545  sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
92546  VdbeCoverage(v);
92547  }
92548  }
92549 
92550  /* Step 3. The LHS is now known to be non-NULL. Do the binary search
92551  ** of the RHS using the LHS as a probe. If found, the result is
92552  ** true.
92553  */
92554  if( eType==IN_INDEX_ROWID ){
92555  /* In this case, the RHS is the ROWID of table b-tree and so we also
92556  ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
92557  ** into a single opcode. */
92558  sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
92559  VdbeCoverage(v);
92560  addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
92561  }else{
92562  sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
92563  if( destIfFalse==destIfNull ){
92564  /* Combine Step 3 and Step 5 into a single opcode */
92565  sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
92566  rLhs, nVector); VdbeCoverage(v);
92567  goto sqlite3ExprCodeIN_finished;
92568  }
92569  /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
92570  addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
92571  rLhs, nVector); VdbeCoverage(v);
92572  }
92573 
92574  /* Step 4. If the RHS is known to be non-NULL and we did not find
92575  ** an match on the search above, then the result must be FALSE.
92576  */
92577  if( rRhsHasNull && nVector==1 ){
92578  sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
92579  VdbeCoverage(v);
92580  }
92581 
92582  /* Step 5. If we do not care about the difference between NULL and
92583  ** FALSE, then just return false.
92584  */
92585  if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
92586 
92587  /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
92588  ** If any comparison is NULL, then the result is NULL. If all
92589  ** comparisons are FALSE then the final result is FALSE.
92590  **
92591  ** For a scalar LHS, it is sufficient to check just the first row
92592  ** of the RHS.
92593  */
92594  if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
92595  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
92596  VdbeCoverage(v);
92597  if( nVector>1 ){
92598  destNotNull = sqlite3VdbeMakeLabel(v);
92599  }else{
92600  /* For nVector==1, combine steps 6 and 7 by immediately returning
92601  ** FALSE if the first comparison is not NULL */
92602  destNotNull = destIfFalse;
92603  }
92604  for(i=0; i<nVector; i++){
92605  Expr *p;
92606  CollSeq *pColl;
92607  int r3 = sqlite3GetTempReg(pParse);
92608  p = sqlite3VectorFieldSubexpr(pLeft, i);
92609  pColl = sqlite3ExprCollSeq(pParse, p);
92610  sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
92611  sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
92612  (void*)pColl, P4_COLLSEQ);
92613  VdbeCoverage(v);
92614  sqlite3ReleaseTempReg(pParse, r3);
92615  }
92616  sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
92617  if( nVector>1 ){
92618  sqlite3VdbeResolveLabel(v, destNotNull);
92619  sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
92620  VdbeCoverage(v);
92621 
92622  /* Step 7: If we reach this point, we know that the result must
92623  ** be false. */
92624  sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
92625  }
92626 
92627  /* Jumps here in order to return true. */
92628  sqlite3VdbeJumpHere(v, addrTruthOp);
92629 
92630 sqlite3ExprCodeIN_finished:
92631  if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
92632  sqlite3ExprCachePop(pParse);
92633  VdbeComment((v, "end IN expr"));
92634 sqlite3ExprCodeIN_oom_error:
92635  sqlite3DbFree(pParse->db, aiMap);
92636  sqlite3DbFree(pParse->db, zAff);
92637 }
92638 #endif /* SQLITE_OMIT_SUBQUERY */
92639 
92640 #ifndef SQLITE_OMIT_FLOATING_POINT
92641 /*
92642 ** Generate an instruction that will put the floating point
92643 ** value described by z[0..n-1] into register iMem.
92644 **
92645 ** The z[] string will probably not be zero-terminated. But the
92646 ** z[n] character is guaranteed to be something that does not look
92647 ** like the continuation of the number.
92648 */
92649 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
92650  if( ALWAYS(z!=0) ){
92651  double value;
92652  sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
92653  assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
92654  if( negateFlag ) value = -value;
92655  sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
92656  }
92657 }
92658 #endif
92659 
92660 
92661 /*
92662 ** Generate an instruction that will put the integer describe by
92663 ** text z[0..n-1] into register iMem.
92664 **
92665 ** Expr.u.zToken is always UTF8 and zero-terminated.
92666 */
92667 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
92668  Vdbe *v = pParse->pVdbe;
92669  if( pExpr->flags & EP_IntValue ){
92670  int i = pExpr->u.iValue;
92671  assert( i>=0 );
92672  if( negFlag ) i = -i;
92673  sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
92674  }else{
92675  int c;
92676  i64 value;
92677  const char *z = pExpr->u.zToken;
92678  assert( z!=0 );
92679  c = sqlite3DecOrHexToI64(z, &value);
92680  if( c==0 || (c==2 && negFlag) ){
92681  if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
92682  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
92683  }else{
92684 #ifdef SQLITE_OMIT_FLOATING_POINT
92685  sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
92686 #else
92687 #ifndef SQLITE_OMIT_HEX_INTEGER
92688  if( sqlite3_strnicmp(z,"0x",2)==0 ){
92689  sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
92690  }else
92691 #endif
92692  {
92693  codeReal(v, z, negFlag, iMem);
92694  }
92695 #endif
92696  }
92697  }
92698 }
92699 
92700 /*
92701 ** Erase column-cache entry number i
92702 */
92703 static void cacheEntryClear(Parse *pParse, int i){
92704  if( pParse->aColCache[i].tempReg ){
92705  if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
92706  pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
92707  }
92708  }
92709  pParse->nColCache--;
92710  if( i<pParse->nColCache ){
92711  pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
92712  }
92713 }
92714 
92715 
92716 /*
92717 ** Record in the column cache that a particular column from a
92718 ** particular table is stored in a particular register.
92719 */
92720 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
92721  int i;
92722  int minLru;
92723  int idxLru;
92724  struct yColCache *p;
92725 
92726  /* Unless an error has occurred, register numbers are always positive. */
92727  assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
92728  assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
92729 
92730  /* The SQLITE_ColumnCache flag disables the column cache. This is used
92731  ** for testing only - to verify that SQLite always gets the same answer
92732  ** with and without the column cache.
92733  */
92734  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
92735 
92736  /* First replace any existing entry.
92737  **
92738  ** Actually, the way the column cache is currently used, we are guaranteed
92739  ** that the object will never already be in cache. Verify this guarantee.
92740  */
92741 #ifndef NDEBUG
92742  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
92743  assert( p->iTable!=iTab || p->iColumn!=iCol );
92744  }
92745 #endif
92746 
92747  /* If the cache is already full, delete the least recently used entry */
92748  if( pParse->nColCache>=SQLITE_N_COLCACHE ){
92749  minLru = 0x7fffffff;
92750  idxLru = -1;
92751  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92752  if( p->lru<minLru ){
92753  idxLru = i;
92754  minLru = p->lru;
92755  }
92756  }
92757  p = &pParse->aColCache[idxLru];
92758  }else{
92759  p = &pParse->aColCache[pParse->nColCache++];
92760  }
92761 
92762  /* Add the new entry to the end of the cache */
92763  p->iLevel = pParse->iCacheLevel;
92764  p->iTable = iTab;
92765  p->iColumn = iCol;
92766  p->iReg = iReg;
92767  p->tempReg = 0;
92768  p->lru = pParse->iCacheCnt++;
92769 }
92770 
92771 /*
92772 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
92773 ** Purge the range of registers from the column cache.
92774 */
92775 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
92776  int i = 0;
92777  while( i<pParse->nColCache ){
92778  struct yColCache *p = &pParse->aColCache[i];
92779  if( p->iReg >= iReg && p->iReg < iReg+nReg ){
92780  cacheEntryClear(pParse, i);
92781  }else{
92782  i++;
92783  }
92784  }
92785 }
92786 
92787 /*
92788 ** Remember the current column cache context. Any new entries added
92789 ** added to the column cache after this call are removed when the
92790 ** corresponding pop occurs.
92791 */
92792 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
92793  pParse->iCacheLevel++;
92794 #ifdef SQLITE_DEBUG
92795  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
92796  printf("PUSH to %d\n", pParse->iCacheLevel);
92797  }
92798 #endif
92799 }
92800 
92801 /*
92802 ** Remove from the column cache any entries that were added since the
92803 ** the previous sqlite3ExprCachePush operation. In other words, restore
92804 ** the cache to the state it was in prior the most recent Push.
92805 */
92806 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
92807  int i = 0;
92808  assert( pParse->iCacheLevel>=1 );
92809  pParse->iCacheLevel--;
92810 #ifdef SQLITE_DEBUG
92811  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
92812  printf("POP to %d\n", pParse->iCacheLevel);
92813  }
92814 #endif
92815  while( i<pParse->nColCache ){
92816  if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
92817  cacheEntryClear(pParse, i);
92818  }else{
92819  i++;
92820  }
92821  }
92822 }
92823 
92824 /*
92825 ** When a cached column is reused, make sure that its register is
92826 ** no longer available as a temp register. ticket #3879: that same
92827 ** register might be in the cache in multiple places, so be sure to
92828 ** get them all.
92829 */
92830 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
92831  int i;
92832  struct yColCache *p;
92833  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
92834  if( p->iReg==iReg ){
92835  p->tempReg = 0;
92836  }
92837  }
92838 }
92839 
92840 /* Generate code that will load into register regOut a value that is
92841 ** appropriate for the iIdxCol-th column of index pIdx.
92842 */
92843 SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
92844  Parse *pParse, /* The parsing context */
92845  Index *pIdx, /* The index whose column is to be loaded */
92846  int iTabCur, /* Cursor pointing to a table row */
92847  int iIdxCol, /* The column of the index to be loaded */
92848  int regOut /* Store the index column value in this register */
92849 ){
92850  i16 iTabCol = pIdx->aiColumn[iIdxCol];
92851  if( iTabCol==XN_EXPR ){
92852  assert( pIdx->aColExpr );
92853  assert( pIdx->aColExpr->nExpr>iIdxCol );
92854  pParse->iSelfTab = iTabCur;
92855  sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
92856  }else{
92857  sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
92858  iTabCol, regOut);
92859  }
92860 }
92861 
92862 /*
92863 ** Generate code to extract the value of the iCol-th column of a table.
92864 */
92865 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
92866  Vdbe *v, /* The VDBE under construction */
92867  Table *pTab, /* The table containing the value */
92868  int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
92869  int iCol, /* Index of the column to extract */
92870  int regOut /* Extract the value into this register */
92871 ){
92872  if( iCol<0 || iCol==pTab->iPKey ){
92873  sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
92874  }else{
92875  int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
92876  int x = iCol;
92877  if( !HasRowid(pTab) && !IsVirtual(pTab) ){
92878  x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
92879  }
92880  sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
92881  }
92882  if( iCol>=0 ){
92883  sqlite3ColumnDefault(v, pTab, iCol, regOut);
92884  }
92885 }
92886 
92887 /*
92888 ** Generate code that will extract the iColumn-th column from
92889 ** table pTab and store the column value in a register.
92890 **
92891 ** An effort is made to store the column value in register iReg. This
92892 ** is not garanteeed for GetColumn() - the result can be stored in
92893 ** any register. But the result is guaranteed to land in register iReg
92894 ** for GetColumnToReg().
92895 **
92896 ** There must be an open cursor to pTab in iTable when this routine
92897 ** is called. If iColumn<0 then code is generated that extracts the rowid.
92898 */
92899 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
92900  Parse *pParse, /* Parsing and code generating context */
92901  Table *pTab, /* Description of the table we are reading from */
92902  int iColumn, /* Index of the table column */
92903  int iTable, /* The cursor pointing to the table */
92904  int iReg, /* Store results here */
92905  u8 p5 /* P5 value for OP_Column + FLAGS */
92906 ){
92907  Vdbe *v = pParse->pVdbe;
92908  int i;
92909  struct yColCache *p;
92910 
92911  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
92912  if( p->iTable==iTable && p->iColumn==iColumn ){
92913  p->lru = pParse->iCacheCnt++;
92914  sqlite3ExprCachePinRegister(pParse, p->iReg);
92915  return p->iReg;
92916  }
92917  }
92918  assert( v!=0 );
92919  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
92920  if( p5 ){
92921  sqlite3VdbeChangeP5(v, p5);
92922  }else{
92923  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
92924  }
92925  return iReg;
92926 }
92927 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
92928  Parse *pParse, /* Parsing and code generating context */
92929  Table *pTab, /* Description of the table we are reading from */
92930  int iColumn, /* Index of the table column */
92931  int iTable, /* The cursor pointing to the table */
92932  int iReg /* Store results here */
92933 ){
92934  int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
92935  if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
92936 }
92937 
92938 
92939 /*
92940 ** Clear all column cache entries.
92941 */
92942 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
92943  int i;
92944 
92945 #if SQLITE_DEBUG
92946  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
92947  printf("CLEAR\n");
92948  }
92949 #endif
92950  for(i=0; i<pParse->nColCache; i++){
92951  if( pParse->aColCache[i].tempReg
92952  && pParse->nTempReg<ArraySize(pParse->aTempReg)
92953  ){
92954  pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
92955  }
92956  }
92957  pParse->nColCache = 0;
92958 }
92959 
92960 /*
92961 ** Record the fact that an affinity change has occurred on iCount
92962 ** registers starting with iStart.
92963 */
92964 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
92965  sqlite3ExprCacheRemove(pParse, iStart, iCount);
92966 }
92967 
92968 /*
92969 ** Generate code to move content from registers iFrom...iFrom+nReg-1
92970 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
92971 */
92972 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
92973  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
92974  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
92975  sqlite3ExprCacheRemove(pParse, iFrom, nReg);
92976 }
92977 
92978 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
92979 /*
92980 ** Return true if any register in the range iFrom..iTo (inclusive)
92981 ** is used as part of the column cache.
92982 **
92983 ** This routine is used within assert() and testcase() macros only
92984 ** and does not appear in a normal build.
92985 */
92986 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
92987  int i;
92988  struct yColCache *p;
92989  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
92990  int r = p->iReg;
92991  if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
92992  }
92993  return 0;
92994 }
92995 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
92996 
92997 
92998 /*
92999 ** Convert a scalar expression node to a TK_REGISTER referencing
93000 ** register iReg. The caller must ensure that iReg already contains
93001 ** the correct value for the expression.
93002 */
93003 static void exprToRegister(Expr *p, int iReg){
93004  p->op2 = p->op;
93005  p->op = TK_REGISTER;
93006  p->iTable = iReg;
93007  ExprClearProperty(p, EP_Skip);
93008 }
93009 
93010 /*
93011 ** Evaluate an expression (either a vector or a scalar expression) and store
93012 ** the result in continguous temporary registers. Return the index of
93013 ** the first register used to store the result.
93014 **
93015 ** If the returned result register is a temporary scalar, then also write
93016 ** that register number into *piFreeable. If the returned result register
93017 ** is not a temporary or if the expression is a vector set *piFreeable
93018 ** to 0.
93019 */
93020 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
93021  int iResult;
93022  int nResult = sqlite3ExprVectorSize(p);
93023  if( nResult==1 ){
93024  iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
93025  }else{
93026  *piFreeable = 0;
93027  if( p->op==TK_SELECT ){
93028  iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
93029  }else{
93030  int i;
93031  iResult = pParse->nMem+1;
93032  pParse->nMem += nResult;
93033  for(i=0; i<nResult; i++){
93034  sqlite3ExprCode(pParse, p->x.pList->a[i].pExpr, i+iResult);
93035  }
93036  }
93037  }
93038  return iResult;
93039 }
93040 
93041 
93042 /*
93043 ** Generate code into the current Vdbe to evaluate the given
93044 ** expression. Attempt to store the results in register "target".
93045 ** Return the register where results are stored.
93046 **
93047 ** With this routine, there is no guarantee that results will
93048 ** be stored in target. The result might be stored in some other
93049 ** register if it is convenient to do so. The calling function
93050 ** must check the return code and move the results to the desired
93051 ** register.
93052 */
93053 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
93054  Vdbe *v = pParse->pVdbe; /* The VM under construction */
93055  int op; /* The opcode being coded */
93056  int inReg = target; /* Results stored in register inReg */
93057  int regFree1 = 0; /* If non-zero free this temporary register */
93058  int regFree2 = 0; /* If non-zero free this temporary register */
93059  int r1, r2; /* Various register numbers */
93060  Expr tempX; /* Temporary expression node */
93061  int p5 = 0;
93062 
93063  assert( target>0 && target<=pParse->nMem );
93064  if( v==0 ){
93065  assert( pParse->db->mallocFailed );
93066  return 0;
93067  }
93068 
93069  if( pExpr==0 ){
93070  op = TK_NULL;
93071  }else{
93072  op = pExpr->op;
93073  }
93074  switch( op ){
93075  case TK_AGG_COLUMN: {
93076  AggInfo *pAggInfo = pExpr->pAggInfo;
93077  struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
93078  if( !pAggInfo->directMode ){
93079  assert( pCol->iMem>0 );
93080  return pCol->iMem;
93081  }else if( pAggInfo->useSortingIdx ){
93082  sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
93083  pCol->iSorterColumn, target);
93084  return target;
93085  }
93086  /* Otherwise, fall thru into the TK_COLUMN case */
93087  }
93088  case TK_COLUMN: {
93089  int iTab = pExpr->iTable;
93090  if( iTab<0 ){
93091  if( pParse->ckBase>0 ){
93092  /* Generating CHECK constraints or inserting into partial index */
93093  return pExpr->iColumn + pParse->ckBase;
93094  }else{
93095  /* Coding an expression that is part of an index where column names
93096  ** in the index refer to the table to which the index belongs */
93097  iTab = pParse->iSelfTab;
93098  }
93099  }
93100  return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
93101  pExpr->iColumn, iTab, target,
93102  pExpr->op2);
93103  }
93104  case TK_INTEGER: {
93105  codeInteger(pParse, pExpr, 0, target);
93106  return target;
93107  }
93108 #ifndef SQLITE_OMIT_FLOATING_POINT
93109  case TK_FLOAT: {
93110  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93111  codeReal(v, pExpr->u.zToken, 0, target);
93112  return target;
93113  }
93114 #endif
93115  case TK_STRING: {
93116  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93117  sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
93118  return target;
93119  }
93120  case TK_NULL: {
93121  sqlite3VdbeAddOp2(v, OP_Null, 0, target);
93122  return target;
93123  }
93124 #ifndef SQLITE_OMIT_BLOB_LITERAL
93125  case TK_BLOB: {
93126  int n;
93127  const char *z;
93128  char *zBlob;
93129  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93130  assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
93131  assert( pExpr->u.zToken[1]=='\'' );
93132  z = &pExpr->u.zToken[2];
93133  n = sqlite3Strlen30(z) - 1;
93134  assert( z[n]=='\'' );
93135  zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
93136  sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
93137  return target;
93138  }
93139 #endif
93140  case TK_VARIABLE: {
93141  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93142  assert( pExpr->u.zToken!=0 );
93143  assert( pExpr->u.zToken[0]!=0 );
93144  sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
93145  if( pExpr->u.zToken[1]!=0 ){
93146  assert( pExpr->u.zToken[0]=='?'
93147  || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
93148  sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
93149  }
93150  return target;
93151  }
93152  case TK_REGISTER: {
93153  return pExpr->iTable;
93154  }
93155 #ifndef SQLITE_OMIT_CAST
93156  case TK_CAST: {
93157  /* Expressions of the form: CAST(pLeft AS token) */
93158  inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
93159  if( inReg!=target ){
93160  sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
93161  inReg = target;
93162  }
93163  sqlite3VdbeAddOp2(v, OP_Cast, target,
93164  sqlite3AffinityType(pExpr->u.zToken, 0));
93165  testcase( usedAsColumnCache(pParse, inReg, inReg) );
93166  sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
93167  return inReg;
93168  }
93169 #endif /* SQLITE_OMIT_CAST */
93170  case TK_IS:
93171  case TK_ISNOT:
93172  op = (op==TK_IS) ? TK_EQ : TK_NE;
93173  p5 = SQLITE_NULLEQ;
93174  /* fall-through */
93175  case TK_LT:
93176  case TK_LE:
93177  case TK_GT:
93178  case TK_GE:
93179  case TK_NE:
93180  case TK_EQ: {
93181  Expr *pLeft = pExpr->pLeft;
93182  if( sqlite3ExprIsVector(pLeft) ){
93183  codeVectorCompare(pParse, pExpr, target, op, p5);
93184  }else{
93185  r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
93186  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93187  codeCompare(pParse, pLeft, pExpr->pRight, op,
93188  r1, r2, inReg, SQLITE_STOREP2 | p5);
93189  assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93190  assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93191  assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93192  assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93193  assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
93194  assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
93195  testcase( regFree1==0 );
93196  testcase( regFree2==0 );
93197  }
93198  break;
93199  }
93200  case TK_AND:
93201  case TK_OR:
93202  case TK_PLUS:
93203  case TK_STAR:
93204  case TK_MINUS:
93205  case TK_REM:
93206  case TK_BITAND:
93207  case TK_BITOR:
93208  case TK_SLASH:
93209  case TK_LSHIFT:
93210  case TK_RSHIFT:
93211  case TK_CONCAT: {
93212  assert( TK_AND==OP_And ); testcase( op==TK_AND );
93213  assert( TK_OR==OP_Or ); testcase( op==TK_OR );
93214  assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
93215  assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
93216  assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
93217  assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
93218  assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
93219  assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
93220  assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
93221  assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
93222  assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
93223  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93224  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93225  sqlite3VdbeAddOp3(v, op, r2, r1, target);
93226  testcase( regFree1==0 );
93227  testcase( regFree2==0 );
93228  break;
93229  }
93230  case TK_UMINUS: {
93231  Expr *pLeft = pExpr->pLeft;
93232  assert( pLeft );
93233  if( pLeft->op==TK_INTEGER ){
93234  codeInteger(pParse, pLeft, 1, target);
93235  return target;
93236 #ifndef SQLITE_OMIT_FLOATING_POINT
93237  }else if( pLeft->op==TK_FLOAT ){
93238  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93239  codeReal(v, pLeft->u.zToken, 1, target);
93240  return target;
93241 #endif
93242  }else{
93243  tempX.op = TK_INTEGER;
93244  tempX.flags = EP_IntValue|EP_TokenOnly;
93245  tempX.u.iValue = 0;
93246  r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
93247  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
93248  sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
93249  testcase( regFree2==0 );
93250  }
93251  break;
93252  }
93253  case TK_BITNOT:
93254  case TK_NOT: {
93255  assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
93256  assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
93257  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93258  testcase( regFree1==0 );
93259  sqlite3VdbeAddOp2(v, op, r1, inReg);
93260  break;
93261  }
93262  case TK_ISNULL:
93263  case TK_NOTNULL: {
93264  int addr;
93265  assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
93266  assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
93267  sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
93268  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93269  testcase( regFree1==0 );
93270  addr = sqlite3VdbeAddOp1(v, op, r1);
93271  VdbeCoverageIf(v, op==TK_ISNULL);
93272  VdbeCoverageIf(v, op==TK_NOTNULL);
93273  sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
93274  sqlite3VdbeJumpHere(v, addr);
93275  break;
93276  }
93277  case TK_AGG_FUNCTION: {
93278  AggInfo *pInfo = pExpr->pAggInfo;
93279  if( pInfo==0 ){
93280  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93281  sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
93282  }else{
93283  return pInfo->aFunc[pExpr->iAgg].iMem;
93284  }
93285  break;
93286  }
93287  case TK_FUNCTION: {
93288  ExprList *pFarg; /* List of function arguments */
93289  int nFarg; /* Number of function arguments */
93290  FuncDef *pDef; /* The function definition object */
93291  const char *zId; /* The function name */
93292  u32 constMask = 0; /* Mask of function arguments that are constant */
93293  int i; /* Loop counter */
93294  sqlite3 *db = pParse->db; /* The database connection */
93295  u8 enc = ENC(db); /* The text encoding used by this database */
93296  CollSeq *pColl = 0; /* A collating sequence */
93297 
93298  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
93299  if( ExprHasProperty(pExpr, EP_TokenOnly) ){
93300  pFarg = 0;
93301  }else{
93302  pFarg = pExpr->x.pList;
93303  }
93304  nFarg = pFarg ? pFarg->nExpr : 0;
93305  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93306  zId = pExpr->u.zToken;
93307  pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
93308 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
93309  if( pDef==0 && pParse->explain ){
93310  pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
93311  }
93312 #endif
93313  if( pDef==0 || pDef->xFinalize!=0 ){
93314  sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
93315  break;
93316  }
93317 
93318  /* Attempt a direct implementation of the built-in COALESCE() and
93319  ** IFNULL() functions. This avoids unnecessary evaluation of
93320  ** arguments past the first non-NULL argument.
93321  */
93322  if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
93323  int endCoalesce = sqlite3VdbeMakeLabel(v);
93324  assert( nFarg>=2 );
93325  sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
93326  for(i=1; i<nFarg; i++){
93327  sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
93328  VdbeCoverage(v);
93329  sqlite3ExprCacheRemove(pParse, target, 1);
93330  sqlite3ExprCachePush(pParse);
93331  sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
93332  sqlite3ExprCachePop(pParse);
93333  }
93334  sqlite3VdbeResolveLabel(v, endCoalesce);
93335  break;
93336  }
93337 
93338  /* The UNLIKELY() function is a no-op. The result is the value
93339  ** of the first argument.
93340  */
93341  if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
93342  assert( nFarg>=1 );
93343  return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
93344  }
93345 
93346  for(i=0; i<nFarg; i++){
93347  if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
93348  testcase( i==31 );
93349  constMask |= MASKBIT32(i);
93350  }
93351  if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
93352  pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
93353  }
93354  }
93355  if( pFarg ){
93356  if( constMask ){
93357  r1 = pParse->nMem+1;
93358  pParse->nMem += nFarg;
93359  }else{
93360  r1 = sqlite3GetTempRange(pParse, nFarg);
93361  }
93362 
93363  /* For length() and typeof() functions with a column argument,
93364  ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
93365  ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
93366  ** loading.
93367  */
93368  if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
93369  u8 exprOp;
93370  assert( nFarg==1 );
93371  assert( pFarg->a[0].pExpr!=0 );
93372  exprOp = pFarg->a[0].pExpr->op;
93373  if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
93374  assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
93375  assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
93376  testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
93377  pFarg->a[0].pExpr->op2 =
93378  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
93379  }
93380  }
93381 
93382  sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
93383  sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
93384  SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
93385  sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
93386  }else{
93387  r1 = 0;
93388  }
93389 #ifndef SQLITE_OMIT_VIRTUALTABLE
93390  /* Possibly overload the function if the first argument is
93391  ** a virtual table column.
93392  **
93393  ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
93394  ** second argument, not the first, as the argument to test to
93395  ** see if it is a column in a virtual table. This is done because
93396  ** the left operand of infix functions (the operand we want to
93397  ** control overloading) ends up as the second argument to the
93398  ** function. The expression "A glob B" is equivalent to
93399  ** "glob(B,A). We want to use the A in "A glob B" to test
93400  ** for function overloading. But we use the B term in "glob(B,A)".
93401  */
93402  if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
93403  pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
93404  }else if( nFarg>0 ){
93405  pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
93406  }
93407 #endif
93408  if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
93409  if( !pColl ) pColl = db->pDfltColl;
93410  sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
93411  }
93412  sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
93413  (char*)pDef, P4_FUNCDEF);
93414  sqlite3VdbeChangeP5(v, (u8)nFarg);
93415  if( nFarg && constMask==0 ){
93416  sqlite3ReleaseTempRange(pParse, r1, nFarg);
93417  }
93418  return target;
93419  }
93420 #ifndef SQLITE_OMIT_SUBQUERY
93421  case TK_EXISTS:
93422  case TK_SELECT: {
93423  int nCol;
93424  testcase( op==TK_EXISTS );
93425  testcase( op==TK_SELECT );
93426  if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
93427  sqlite3SubselectError(pParse, nCol, 1);
93428  }else{
93429  return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
93430  }
93431  break;
93432  }
93433  case TK_SELECT_COLUMN: {
93434  if( pExpr->pLeft->iTable==0 ){
93435  pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
93436  }
93437  return pExpr->pLeft->iTable + pExpr->iColumn;
93438  }
93439  case TK_IN: {
93440  int destIfFalse = sqlite3VdbeMakeLabel(v);
93441  int destIfNull = sqlite3VdbeMakeLabel(v);
93442  sqlite3VdbeAddOp2(v, OP_Null, 0, target);
93443  sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
93444  sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
93445  sqlite3VdbeResolveLabel(v, destIfFalse);
93446  sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
93447  sqlite3VdbeResolveLabel(v, destIfNull);
93448  return target;
93449  }
93450 #endif /* SQLITE_OMIT_SUBQUERY */
93451 
93452 
93453  /*
93454  ** x BETWEEN y AND z
93455  **
93456  ** This is equivalent to
93457  **
93458  ** x>=y AND x<=z
93459  **
93460  ** X is stored in pExpr->pLeft.
93461  ** Y is stored in pExpr->pList->a[0].pExpr.
93462  ** Z is stored in pExpr->pList->a[1].pExpr.
93463  */
93464  case TK_BETWEEN: {
93465  exprCodeBetween(pParse, pExpr, target, 0, 0);
93466  return target;
93467  }
93468  case TK_SPAN:
93469  case TK_COLLATE:
93470  case TK_UPLUS: {
93471  return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
93472  }
93473 
93474  case TK_TRIGGER: {
93475  /* If the opcode is TK_TRIGGER, then the expression is a reference
93476  ** to a column in the new.* or old.* pseudo-tables available to
93477  ** trigger programs. In this case Expr.iTable is set to 1 for the
93478  ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
93479  ** is set to the column of the pseudo-table to read, or to -1 to
93480  ** read the rowid field.
93481  **
93482  ** The expression is implemented using an OP_Param opcode. The p1
93483  ** parameter is set to 0 for an old.rowid reference, or to (i+1)
93484  ** to reference another column of the old.* pseudo-table, where
93485  ** i is the index of the column. For a new.rowid reference, p1 is
93486  ** set to (n+1), where n is the number of columns in each pseudo-table.
93487  ** For a reference to any other column in the new.* pseudo-table, p1
93488  ** is set to (n+2+i), where n and i are as defined previously. For
93489  ** example, if the table on which triggers are being fired is
93490  ** declared as:
93491  **
93492  ** CREATE TABLE t1(a, b);
93493  **
93494  ** Then p1 is interpreted as follows:
93495  **
93496  ** p1==0 -> old.rowid p1==3 -> new.rowid
93497  ** p1==1 -> old.a p1==4 -> new.a
93498  ** p1==2 -> old.b p1==5 -> new.b
93499  */
93500  Table *pTab = pExpr->pTab;
93501  int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
93502 
93503  assert( pExpr->iTable==0 || pExpr->iTable==1 );
93504  assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
93505  assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
93506  assert( p1>=0 && p1<(pTab->nCol*2+2) );
93507 
93508  sqlite3VdbeAddOp2(v, OP_Param, p1, target);
93509  VdbeComment((v, "%s.%s -> $%d",
93510  (pExpr->iTable ? "new" : "old"),
93511  (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
93512  target
93513  ));
93514 
93515 #ifndef SQLITE_OMIT_FLOATING_POINT
93516  /* If the column has REAL affinity, it may currently be stored as an
93517  ** integer. Use OP_RealAffinity to make sure it is really real.
93518  **
93519  ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
93520  ** floating point when extracting it from the record. */
93521  if( pExpr->iColumn>=0
93522  && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
93523  ){
93524  sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
93525  }
93526 #endif
93527  break;
93528  }
93529 
93530  case TK_VECTOR: {
93531  sqlite3ErrorMsg(pParse, "row value misused");
93532  break;
93533  }
93534 
93535  /*
93536  ** Form A:
93537  ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
93538  **
93539  ** Form B:
93540  ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
93541  **
93542  ** Form A is can be transformed into the equivalent form B as follows:
93543  ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
93544  ** WHEN x=eN THEN rN ELSE y END
93545  **
93546  ** X (if it exists) is in pExpr->pLeft.
93547  ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
93548  ** odd. The Y is also optional. If the number of elements in x.pList
93549  ** is even, then Y is omitted and the "otherwise" result is NULL.
93550  ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
93551  **
93552  ** The result of the expression is the Ri for the first matching Ei,
93553  ** or if there is no matching Ei, the ELSE term Y, or if there is
93554  ** no ELSE term, NULL.
93555  */
93556  default: assert( op==TK_CASE ); {
93557  int endLabel; /* GOTO label for end of CASE stmt */
93558  int nextCase; /* GOTO label for next WHEN clause */
93559  int nExpr; /* 2x number of WHEN terms */
93560  int i; /* Loop counter */
93561  ExprList *pEList; /* List of WHEN terms */
93562  struct ExprList_item *aListelem; /* Array of WHEN terms */
93563  Expr opCompare; /* The X==Ei expression */
93564  Expr *pX; /* The X expression */
93565  Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
93566  VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
93567 
93568  assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
93569  assert(pExpr->x.pList->nExpr > 0);
93570  pEList = pExpr->x.pList;
93571  aListelem = pEList->a;
93572  nExpr = pEList->nExpr;
93573  endLabel = sqlite3VdbeMakeLabel(v);
93574  if( (pX = pExpr->pLeft)!=0 ){
93575  tempX = *pX;
93576  testcase( pX->op==TK_COLUMN );
93577  exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
93578  testcase( regFree1==0 );
93579  memset(&opCompare, 0, sizeof(opCompare));
93580  opCompare.op = TK_EQ;
93581  opCompare.pLeft = &tempX;
93582  pTest = &opCompare;
93583  /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
93584  ** The value in regFree1 might get SCopy-ed into the file result.
93585  ** So make sure that the regFree1 register is not reused for other
93586  ** purposes and possibly overwritten. */
93587  regFree1 = 0;
93588  }
93589  for(i=0; i<nExpr-1; i=i+2){
93590  sqlite3ExprCachePush(pParse);
93591  if( pX ){
93592  assert( pTest!=0 );
93593  opCompare.pRight = aListelem[i].pExpr;
93594  }else{
93595  pTest = aListelem[i].pExpr;
93596  }
93597  nextCase = sqlite3VdbeMakeLabel(v);
93598  testcase( pTest->op==TK_COLUMN );
93599  sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
93600  testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
93601  sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
93602  sqlite3VdbeGoto(v, endLabel);
93603  sqlite3ExprCachePop(pParse);
93604  sqlite3VdbeResolveLabel(v, nextCase);
93605  }
93606  if( (nExpr&1)!=0 ){
93607  sqlite3ExprCachePush(pParse);
93608  sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
93609  sqlite3ExprCachePop(pParse);
93610  }else{
93611  sqlite3VdbeAddOp2(v, OP_Null, 0, target);
93612  }
93613  assert( pParse->db->mallocFailed || pParse->nErr>0
93614  || pParse->iCacheLevel==iCacheLevel );
93615  sqlite3VdbeResolveLabel(v, endLabel);
93616  break;
93617  }
93618 #ifndef SQLITE_OMIT_TRIGGER
93619  case TK_RAISE: {
93620  assert( pExpr->affinity==OE_Rollback
93621  || pExpr->affinity==OE_Abort
93622  || pExpr->affinity==OE_Fail
93623  || pExpr->affinity==OE_Ignore
93624  );
93625  if( !pParse->pTriggerTab ){
93626  sqlite3ErrorMsg(pParse,
93627  "RAISE() may only be used within a trigger-program");
93628  return 0;
93629  }
93630  if( pExpr->affinity==OE_Abort ){
93631  sqlite3MayAbort(pParse);
93632  }
93633  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93634  if( pExpr->affinity==OE_Ignore ){
93635  sqlite3VdbeAddOp4(
93636  v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
93637  VdbeCoverage(v);
93638  }else{
93639  sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
93640  pExpr->affinity, pExpr->u.zToken, 0, 0);
93641  }
93642 
93643  break;
93644  }
93645 #endif
93646  }
93647  sqlite3ReleaseTempReg(pParse, regFree1);
93648  sqlite3ReleaseTempReg(pParse, regFree2);
93649  return inReg;
93650 }
93651 
93652 /*
93653 ** Factor out the code of the given expression to initialization time.
93654 */
93655 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
93656  Parse *pParse, /* Parsing context */
93657  Expr *pExpr, /* The expression to code when the VDBE initializes */
93658  int regDest, /* Store the value in this register */
93659  u8 reusable /* True if this expression is reusable */
93660 ){
93661  ExprList *p;
93662  assert( ConstFactorOk(pParse) );
93663  p = pParse->pConstExpr;
93664  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
93665  p = sqlite3ExprListAppend(pParse, p, pExpr);
93666  if( p ){
93667  struct ExprList_item *pItem = &p->a[p->nExpr-1];
93668  pItem->u.iConstExprReg = regDest;
93669  pItem->reusable = reusable;
93670  }
93671  pParse->pConstExpr = p;
93672 }
93673 
93674 /*
93675 ** Generate code to evaluate an expression and store the results
93676 ** into a register. Return the register number where the results
93677 ** are stored.
93678 **
93679 ** If the register is a temporary register that can be deallocated,
93680 ** then write its number into *pReg. If the result register is not
93681 ** a temporary, then set *pReg to zero.
93682 **
93683 ** If pExpr is a constant, then this routine might generate this
93684 ** code to fill the register in the initialization section of the
93685 ** VDBE program, in order to factor it out of the evaluation loop.
93686 */
93687 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
93688  int r2;
93689  pExpr = sqlite3ExprSkipCollate(pExpr);
93690  if( ConstFactorOk(pParse)
93691  && pExpr->op!=TK_REGISTER
93692  && sqlite3ExprIsConstantNotJoin(pExpr)
93693  ){
93694  ExprList *p = pParse->pConstExpr;
93695  int i;
93696  *pReg = 0;
93697  if( p ){
93698  struct ExprList_item *pItem;
93699  for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
93700  if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
93701  return pItem->u.iConstExprReg;
93702  }
93703  }
93704  }
93705  r2 = ++pParse->nMem;
93706  sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
93707  }else{
93708  int r1 = sqlite3GetTempReg(pParse);
93709  r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
93710  if( r2==r1 ){
93711  *pReg = r1;
93712  }else{
93713  sqlite3ReleaseTempReg(pParse, r1);
93714  *pReg = 0;
93715  }
93716  }
93717  return r2;
93718 }
93719 
93720 /*
93721 ** Generate code that will evaluate expression pExpr and store the
93722 ** results in register target. The results are guaranteed to appear
93723 ** in register target.
93724 */
93725 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
93726  int inReg;
93727 
93728  assert( target>0 && target<=pParse->nMem );
93729  if( pExpr && pExpr->op==TK_REGISTER ){
93730  sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
93731  }else{
93732  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
93733  assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
93734  if( inReg!=target && pParse->pVdbe ){
93735  sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
93736  }
93737  }
93738 }
93739 
93740 /*
93741 ** Make a transient copy of expression pExpr and then code it using
93742 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
93743 ** except that the input expression is guaranteed to be unchanged.
93744 */
93745 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
93746  sqlite3 *db = pParse->db;
93747  pExpr = sqlite3ExprDup(db, pExpr, 0);
93748  if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
93749  sqlite3ExprDelete(db, pExpr);
93750 }
93751 
93752 /*
93753 ** Generate code that will evaluate expression pExpr and store the
93754 ** results in register target. The results are guaranteed to appear
93755 ** in register target. If the expression is constant, then this routine
93756 ** might choose to code the expression at initialization time.
93757 */
93758 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
93759  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
93760  sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
93761  }else{
93762  sqlite3ExprCode(pParse, pExpr, target);
93763  }
93764 }
93765 
93766 /*
93767 ** Generate code that evaluates the given expression and puts the result
93768 ** in register target.
93769 **
93770 ** Also make a copy of the expression results into another "cache" register
93771 ** and modify the expression so that the next time it is evaluated,
93772 ** the result is a copy of the cache register.
93773 **
93774 ** This routine is used for expressions that are used multiple
93775 ** times. They are evaluated once and the results of the expression
93776 ** are reused.
93777 */
93778 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
93779  Vdbe *v = pParse->pVdbe;
93780  int iMem;
93781 
93782  assert( target>0 );
93783  assert( pExpr->op!=TK_REGISTER );
93784  sqlite3ExprCode(pParse, pExpr, target);
93785  iMem = ++pParse->nMem;
93786  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
93787  exprToRegister(pExpr, iMem);
93788 }
93789 
93790 /*
93791 ** Generate code that pushes the value of every element of the given
93792 ** expression list into a sequence of registers beginning at target.
93793 **
93794 ** Return the number of elements evaluated.
93795 **
93796 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
93797 ** filled using OP_SCopy. OP_Copy must be used instead.
93798 **
93799 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
93800 ** factored out into initialization code.
93801 **
93802 ** The SQLITE_ECEL_REF flag means that expressions in the list with
93803 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
93804 ** in registers at srcReg, and so the value can be copied from there.
93805 */
93806 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
93807  Parse *pParse, /* Parsing context */
93808  ExprList *pList, /* The expression list to be coded */
93809  int target, /* Where to write results */
93810  int srcReg, /* Source registers if SQLITE_ECEL_REF */
93811  u8 flags /* SQLITE_ECEL_* flags */
93812 ){
93813  struct ExprList_item *pItem;
93814  int i, j, n;
93815  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
93816  Vdbe *v = pParse->pVdbe;
93817  assert( pList!=0 );
93818  assert( target>0 );
93819  assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
93820  n = pList->nExpr;
93821  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
93822  for(pItem=pList->a, i=0; i<n; i++, pItem++){
93823  Expr *pExpr = pItem->pExpr;
93824  if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
93825  sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
93826  }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
93827  sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
93828  }else{
93829  int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
93830  if( inReg!=target+i ){
93831  VdbeOp *pOp;
93832  if( copyOp==OP_Copy
93833  && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
93834  && pOp->p1+pOp->p3+1==inReg
93835  && pOp->p2+pOp->p3+1==target+i
93836  ){
93837  pOp->p3++;
93838  }else{
93839  sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
93840  }
93841  }
93842  }
93843  }
93844  return n;
93845 }
93846 
93847 /*
93848 ** Generate code for a BETWEEN operator.
93849 **
93850 ** x BETWEEN y AND z
93851 **
93852 ** The above is equivalent to
93853 **
93854 ** x>=y AND x<=z
93855 **
93856 ** Code it as such, taking care to do the common subexpression
93857 ** elimination of x.
93858 **
93859 ** The xJumpIf parameter determines details:
93860 **
93861 ** NULL: Store the boolean result in reg[dest]
93862 ** sqlite3ExprIfTrue: Jump to dest if true
93863 ** sqlite3ExprIfFalse: Jump to dest if false
93864 **
93865 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
93866 */
93867 static void exprCodeBetween(
93868  Parse *pParse, /* Parsing and code generating context */
93869  Expr *pExpr, /* The BETWEEN expression */
93870  int dest, /* Jump destination or storage location */
93871  void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
93872  int jumpIfNull /* Take the jump if the BETWEEN is NULL */
93873 ){
93874  Expr exprAnd; /* The AND operator in x>=y AND x<=z */
93875  Expr compLeft; /* The x>=y term */
93876  Expr compRight; /* The x<=z term */
93877  Expr exprX; /* The x subexpression */
93878  int regFree1 = 0; /* Temporary use register */
93879 
93880 
93881  memset(&compLeft, 0, sizeof(Expr));
93882  memset(&compRight, 0, sizeof(Expr));
93883  memset(&exprAnd, 0, sizeof(Expr));
93884 
93885  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
93886  exprX = *pExpr->pLeft;
93887  exprAnd.op = TK_AND;
93888  exprAnd.pLeft = &compLeft;
93889  exprAnd.pRight = &compRight;
93890  compLeft.op = TK_GE;
93891  compLeft.pLeft = &exprX;
93892  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
93893  compRight.op = TK_LE;
93894  compRight.pLeft = &exprX;
93895  compRight.pRight = pExpr->x.pList->a[1].pExpr;
93896  exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
93897  if( xJump ){
93898  xJump(pParse, &exprAnd, dest, jumpIfNull);
93899  }else{
93900  exprX.flags |= EP_FromJoin;
93901  sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
93902  }
93903  sqlite3ReleaseTempReg(pParse, regFree1);
93904 
93905  /* Ensure adequate test coverage */
93906  testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
93907  testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
93908  testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
93909  testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
93910  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
93911  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
93912  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
93913  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
93914  testcase( xJump==0 );
93915 }
93916 
93917 /*
93918 ** Generate code for a boolean expression such that a jump is made
93919 ** to the label "dest" if the expression is true but execution
93920 ** continues straight thru if the expression is false.
93921 **
93922 ** If the expression evaluates to NULL (neither true nor false), then
93923 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
93924 **
93925 ** This code depends on the fact that certain token values (ex: TK_EQ)
93926 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
93927 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
93928 ** the make process cause these values to align. Assert()s in the code
93929 ** below verify that the numbers are aligned correctly.
93930 */
93931 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
93932  Vdbe *v = pParse->pVdbe;
93933  int op = 0;
93934  int regFree1 = 0;
93935  int regFree2 = 0;
93936  int r1, r2;
93937 
93938  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
93939  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
93940  if( NEVER(pExpr==0) ) return; /* No way this can happen */
93941  op = pExpr->op;
93942  switch( op ){
93943  case TK_AND: {
93944  int d2 = sqlite3VdbeMakeLabel(v);
93945  testcase( jumpIfNull==0 );
93946  sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
93947  sqlite3ExprCachePush(pParse);
93948  sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93949  sqlite3VdbeResolveLabel(v, d2);
93950  sqlite3ExprCachePop(pParse);
93951  break;
93952  }
93953  case TK_OR: {
93954  testcase( jumpIfNull==0 );
93955  sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
93956  sqlite3ExprCachePush(pParse);
93957  sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93958  sqlite3ExprCachePop(pParse);
93959  break;
93960  }
93961  case TK_NOT: {
93962  testcase( jumpIfNull==0 );
93963  sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
93964  break;
93965  }
93966  case TK_IS:
93967  case TK_ISNOT:
93968  testcase( op==TK_IS );
93969  testcase( op==TK_ISNOT );
93970  op = (op==TK_IS) ? TK_EQ : TK_NE;
93971  jumpIfNull = SQLITE_NULLEQ;
93972  /* Fall thru */
93973  case TK_LT:
93974  case TK_LE:
93975  case TK_GT:
93976  case TK_GE:
93977  case TK_NE:
93978  case TK_EQ: {
93979  if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
93980  testcase( jumpIfNull==0 );
93981  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93982  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93983  codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
93984  r1, r2, dest, jumpIfNull);
93985  assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93986  assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93987  assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93988  assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93989  assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
93990  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
93991  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
93992  assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
93993  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
93994  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
93995  testcase( regFree1==0 );
93996  testcase( regFree2==0 );
93997  break;
93998  }
93999  case TK_ISNULL:
94000  case TK_NOTNULL: {
94001  assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
94002  assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
94003  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
94004  sqlite3VdbeAddOp2(v, op, r1, dest);
94005  VdbeCoverageIf(v, op==TK_ISNULL);
94006  VdbeCoverageIf(v, op==TK_NOTNULL);
94007  testcase( regFree1==0 );
94008  break;
94009  }
94010  case TK_BETWEEN: {
94011  testcase( jumpIfNull==0 );
94012  exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
94013  break;
94014  }
94015 #ifndef SQLITE_OMIT_SUBQUERY
94016  case TK_IN: {
94017  int destIfFalse = sqlite3VdbeMakeLabel(v);
94018  int destIfNull = jumpIfNull ? dest : destIfFalse;
94019  sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
94020  sqlite3VdbeGoto(v, dest);
94021  sqlite3VdbeResolveLabel(v, destIfFalse);
94022  break;
94023  }
94024 #endif
94025  default: {
94026  default_expr:
94027  if( exprAlwaysTrue(pExpr) ){
94028  sqlite3VdbeGoto(v, dest);
94029  }else if( exprAlwaysFalse(pExpr) ){
94030  /* No-op */
94031  }else{
94032  r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
94033  sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
94034  VdbeCoverage(v);
94035  testcase( regFree1==0 );
94036  testcase( jumpIfNull==0 );
94037  }
94038  break;
94039  }
94040  }
94041  sqlite3ReleaseTempReg(pParse, regFree1);
94042  sqlite3ReleaseTempReg(pParse, regFree2);
94043 }
94044 
94045 /*
94046 ** Generate code for a boolean expression such that a jump is made
94047 ** to the label "dest" if the expression is false but execution
94048 ** continues straight thru if the expression is true.
94049 **
94050 ** If the expression evaluates to NULL (neither true nor false) then
94051 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
94052 ** is 0.
94053 */
94054 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
94055  Vdbe *v = pParse->pVdbe;
94056  int op = 0;
94057  int regFree1 = 0;
94058  int regFree2 = 0;
94059  int r1, r2;
94060 
94061  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
94062  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
94063  if( pExpr==0 ) return;
94064 
94065  /* The value of pExpr->op and op are related as follows:
94066  **
94067  ** pExpr->op op
94068  ** --------- ----------
94069  ** TK_ISNULL OP_NotNull
94070  ** TK_NOTNULL OP_IsNull
94071  ** TK_NE OP_Eq
94072  ** TK_EQ OP_Ne
94073  ** TK_GT OP_Le
94074  ** TK_LE OP_Gt
94075  ** TK_GE OP_Lt
94076  ** TK_LT OP_Ge
94077  **
94078  ** For other values of pExpr->op, op is undefined and unused.
94079  ** The value of TK_ and OP_ constants are arranged such that we
94080  ** can compute the mapping above using the following expression.
94081  ** Assert()s verify that the computation is correct.
94082  */
94083  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
94084 
94085  /* Verify correct alignment of TK_ and OP_ constants
94086  */
94087  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
94088  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
94089  assert( pExpr->op!=TK_NE || op==OP_Eq );
94090  assert( pExpr->op!=TK_EQ || op==OP_Ne );
94091  assert( pExpr->op!=TK_LT || op==OP_Ge );
94092  assert( pExpr->op!=TK_LE || op==OP_Gt );
94093  assert( pExpr->op!=TK_GT || op==OP_Le );
94094  assert( pExpr->op!=TK_GE || op==OP_Lt );
94095 
94096  switch( pExpr->op ){
94097  case TK_AND: {
94098  testcase( jumpIfNull==0 );
94099  sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
94100  sqlite3ExprCachePush(pParse);
94101  sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
94102  sqlite3ExprCachePop(pParse);
94103  break;
94104  }
94105  case TK_OR: {
94106  int d2 = sqlite3VdbeMakeLabel(v);
94107  testcase( jumpIfNull==0 );
94108  sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
94109  sqlite3ExprCachePush(pParse);
94110  sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
94111  sqlite3VdbeResolveLabel(v, d2);
94112  sqlite3ExprCachePop(pParse);
94113  break;
94114  }
94115  case TK_NOT: {
94116  testcase( jumpIfNull==0 );
94117  sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
94118  break;
94119  }
94120  case TK_IS:
94121  case TK_ISNOT:
94122  testcase( pExpr->op==TK_IS );
94123  testcase( pExpr->op==TK_ISNOT );
94124  op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
94125  jumpIfNull = SQLITE_NULLEQ;
94126  /* Fall thru */
94127  case TK_LT:
94128  case TK_LE:
94129  case TK_GT:
94130  case TK_GE:
94131  case TK_NE:
94132  case TK_EQ: {
94133  if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
94134  testcase( jumpIfNull==0 );
94135  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
94136  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
94137  codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
94138  r1, r2, dest, jumpIfNull);
94139  assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
94140  assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
94141  assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
94142  assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
94143  assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
94144  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
94145  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
94146  assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
94147  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
94148  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
94149  testcase( regFree1==0 );
94150  testcase( regFree2==0 );
94151  break;
94152  }
94153  case TK_ISNULL:
94154  case TK_NOTNULL: {
94155  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
94156  sqlite3VdbeAddOp2(v, op, r1, dest);
94157  testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
94158  testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
94159  testcase( regFree1==0 );
94160  break;
94161  }
94162  case TK_BETWEEN: {
94163  testcase( jumpIfNull==0 );
94164  exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
94165  break;
94166  }
94167 #ifndef SQLITE_OMIT_SUBQUERY
94168  case TK_IN: {
94169  if( jumpIfNull ){
94170  sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
94171  }else{
94172  int destIfNull = sqlite3VdbeMakeLabel(v);
94173  sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
94174  sqlite3VdbeResolveLabel(v, destIfNull);
94175  }
94176  break;
94177  }
94178 #endif
94179  default: {
94180  default_expr:
94181  if( exprAlwaysFalse(pExpr) ){
94182  sqlite3VdbeGoto(v, dest);
94183  }else if( exprAlwaysTrue(pExpr) ){
94184  /* no-op */
94185  }else{
94186  r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
94187  sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
94188  VdbeCoverage(v);
94189  testcase( regFree1==0 );
94190  testcase( jumpIfNull==0 );
94191  }
94192  break;
94193  }
94194  }
94195  sqlite3ReleaseTempReg(pParse, regFree1);
94196  sqlite3ReleaseTempReg(pParse, regFree2);
94197 }
94198 
94199 /*
94200 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
94201 ** code generation, and that copy is deleted after code generation. This
94202 ** ensures that the original pExpr is unchanged.
94203 */
94204 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
94205  sqlite3 *db = pParse->db;
94206  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
94207  if( db->mallocFailed==0 ){
94208  sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
94209  }
94210  sqlite3ExprDelete(db, pCopy);
94211 }
94212 
94213 
94214 /*
94215 ** Do a deep comparison of two expression trees. Return 0 if the two
94216 ** expressions are completely identical. Return 1 if they differ only
94217 ** by a COLLATE operator at the top level. Return 2 if there are differences
94218 ** other than the top-level COLLATE operator.
94219 **
94220 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
94221 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
94222 **
94223 ** The pA side might be using TK_REGISTER. If that is the case and pB is
94224 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
94225 **
94226 ** Sometimes this routine will return 2 even if the two expressions
94227 ** really are equivalent. If we cannot prove that the expressions are
94228 ** identical, we return 2 just to be safe. So if this routine
94229 ** returns 2, then you do not really know for certain if the two
94230 ** expressions are the same. But if you get a 0 or 1 return, then you
94231 ** can be sure the expressions are the same. In the places where
94232 ** this routine is used, it does not hurt to get an extra 2 - that
94233 ** just might result in some slightly slower code. But returning
94234 ** an incorrect 0 or 1 could lead to a malfunction.
94235 */
94236 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
94237  u32 combinedFlags;
94238  if( pA==0 || pB==0 ){
94239  return pB==pA ? 0 : 2;
94240  }
94241  combinedFlags = pA->flags | pB->flags;
94242  if( combinedFlags & EP_IntValue ){
94243  if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
94244  return 0;
94245  }
94246  return 2;
94247  }
94248  if( pA->op!=pB->op ){
94249  if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
94250  return 1;
94251  }
94252  if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
94253  return 1;
94254  }
94255  return 2;
94256  }
94257  if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
94258  if( pA->op==TK_FUNCTION ){
94259  if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
94260  }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
94261  return pA->op==TK_COLLATE ? 1 : 2;
94262  }
94263  }
94264  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
94265  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
94266  if( combinedFlags & EP_xIsSelect ) return 2;
94267  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
94268  if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
94269  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
94270  if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
94271  if( pA->iColumn!=pB->iColumn ) return 2;
94272  if( pA->iTable!=pB->iTable
94273  && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
94274  }
94275  }
94276  return 0;
94277 }
94278 
94279 /*
94280 ** Compare two ExprList objects. Return 0 if they are identical and
94281 ** non-zero if they differ in any way.
94282 **
94283 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
94284 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
94285 **
94286 ** This routine might return non-zero for equivalent ExprLists. The
94287 ** only consequence will be disabled optimizations. But this routine
94288 ** must never return 0 if the two ExprList objects are different, or
94289 ** a malfunction will result.
94290 **
94291 ** Two NULL pointers are considered to be the same. But a NULL pointer
94292 ** always differs from a non-NULL pointer.
94293 */
94294 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
94295  int i;
94296  if( pA==0 && pB==0 ) return 0;
94297  if( pA==0 || pB==0 ) return 1;
94298  if( pA->nExpr!=pB->nExpr ) return 1;
94299  for(i=0; i<pA->nExpr; i++){
94300  Expr *pExprA = pA->a[i].pExpr;
94301  Expr *pExprB = pB->a[i].pExpr;
94302  if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
94303  if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
94304  }
94305  return 0;
94306 }
94307 
94308 /*
94309 ** Return true if we can prove the pE2 will always be true if pE1 is
94310 ** true. Return false if we cannot complete the proof or if pE2 might
94311 ** be false. Examples:
94312 **
94313 ** pE1: x==5 pE2: x==5 Result: true
94314 ** pE1: x>0 pE2: x==5 Result: false
94315 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
94316 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
94317 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
94318 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
94319 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
94320 **
94321 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
94322 ** Expr.iTable<0 then assume a table number given by iTab.
94323 **
94324 ** When in doubt, return false. Returning true might give a performance
94325 ** improvement. Returning false might cause a performance reduction, but
94326 ** it will always give the correct answer and is hence always safe.
94327 */
94328 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
94329  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
94330  return 1;
94331  }
94332  if( pE2->op==TK_OR
94333  && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
94334  || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
94335  ){
94336  return 1;
94337  }
94338  if( pE2->op==TK_NOTNULL
94339  && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
94340  && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
94341  ){
94342  return 1;
94343  }
94344  return 0;
94345 }
94346 
94347 /*
94348 ** An instance of the following structure is used by the tree walker
94349 ** to determine if an expression can be evaluated by reference to the
94350 ** index only, without having to do a search for the corresponding
94351 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
94352 ** is the cursor for the table.
94353 */
94354 struct IdxCover {
94355  Index *pIdx; /* The index to be tested for coverage */
94356  int iCur; /* Cursor number for the table corresponding to the index */
94357 };
94358 
94359 /*
94360 ** Check to see if there are references to columns in table
94361 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
94362 ** pWalker->u.pIdxCover->pIdx.
94363 */
94364 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
94365  if( pExpr->op==TK_COLUMN
94366  && pExpr->iTable==pWalker->u.pIdxCover->iCur
94367  && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
94368  ){
94369  pWalker->eCode = 1;
94370  return WRC_Abort;
94371  }
94372  return WRC_Continue;
94373 }
94374 
94375 /*
94376 ** Determine if an index pIdx on table with cursor iCur contains will
94377 ** the expression pExpr. Return true if the index does cover the
94378 ** expression and false if the pExpr expression references table columns
94379 ** that are not found in the index pIdx.
94380 **
94381 ** An index covering an expression means that the expression can be
94382 ** evaluated using only the index and without having to lookup the
94383 ** corresponding table entry.
94384 */
94385 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
94386  Expr *pExpr, /* The index to be tested */
94387  int iCur, /* The cursor number for the corresponding table */
94388  Index *pIdx /* The index that might be used for coverage */
94389 ){
94390  Walker w;
94391  struct IdxCover xcov;
94392  memset(&w, 0, sizeof(w));
94393  xcov.iCur = iCur;
94394  xcov.pIdx = pIdx;
94395  w.xExprCallback = exprIdxCover;
94396  w.u.pIdxCover = &xcov;
94397  sqlite3WalkExpr(&w, pExpr);
94398  return !w.eCode;
94399 }
94400 
94401 
94402 /*
94403 ** An instance of the following structure is used by the tree walker
94404 ** to count references to table columns in the arguments of an
94405 ** aggregate function, in order to implement the
94406 ** sqlite3FunctionThisSrc() routine.
94407 */
94408 struct SrcCount {
94409  SrcList *pSrc; /* One particular FROM clause in a nested query */
94410  int nThis; /* Number of references to columns in pSrcList */
94411  int nOther; /* Number of references to columns in other FROM clauses */
94412 };
94413 
94414 /*
94415 ** Count the number of references to columns.
94416 */
94417 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
94418  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
94419  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
94420  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
94421  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
94422  ** NEVER() will need to be removed. */
94423  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
94424  int i;
94425  struct SrcCount *p = pWalker->u.pSrcCount;
94426  SrcList *pSrc = p->pSrc;
94427  int nSrc = pSrc ? pSrc->nSrc : 0;
94428  for(i=0; i<nSrc; i++){
94429  if( pExpr->iTable==pSrc->a[i].iCursor ) break;
94430  }
94431  if( i<nSrc ){
94432  p->nThis++;
94433  }else{
94434  p->nOther++;
94435  }
94436  }
94437  return WRC_Continue;
94438 }
94439 
94440 /*
94441 ** Determine if any of the arguments to the pExpr Function reference
94442 ** pSrcList. Return true if they do. Also return true if the function
94443 ** has no arguments or has only constant arguments. Return false if pExpr
94444 ** references columns but not columns of tables found in pSrcList.
94445 */
94446 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
94447  Walker w;
94448  struct SrcCount cnt;
94449  assert( pExpr->op==TK_AGG_FUNCTION );
94450  memset(&w, 0, sizeof(w));
94451  w.xExprCallback = exprSrcCount;
94452  w.u.pSrcCount = &cnt;
94453  cnt.pSrc = pSrcList;
94454  cnt.nThis = 0;
94455  cnt.nOther = 0;
94456  sqlite3WalkExprList(&w, pExpr->x.pList);
94457  return cnt.nThis>0 || cnt.nOther==0;
94458 }
94459 
94460 /*
94461 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
94462 ** the new element. Return a negative number if malloc fails.
94463 */
94464 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
94465  int i;
94466  pInfo->aCol = sqlite3ArrayAllocate(
94467  db,
94468  pInfo->aCol,
94469  sizeof(pInfo->aCol[0]),
94470  &pInfo->nColumn,
94471  &i
94472  );
94473  return i;
94474 }
94475 
94476 /*
94477 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
94478 ** the new element. Return a negative number if malloc fails.
94479 */
94480 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
94481  int i;
94482  pInfo->aFunc = sqlite3ArrayAllocate(
94483  db,
94484  pInfo->aFunc,
94485  sizeof(pInfo->aFunc[0]),
94486  &pInfo->nFunc,
94487  &i
94488  );
94489  return i;
94490 }
94491 
94492 /*
94493 ** This is the xExprCallback for a tree walker. It is used to
94494 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
94495 ** for additional information.
94496 */
94497 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
94498  int i;
94499  NameContext *pNC = pWalker->u.pNC;
94500  Parse *pParse = pNC->pParse;
94501  SrcList *pSrcList = pNC->pSrcList;
94502  AggInfo *pAggInfo = pNC->pAggInfo;
94503 
94504  switch( pExpr->op ){
94505  case TK_AGG_COLUMN:
94506  case TK_COLUMN: {
94507  testcase( pExpr->op==TK_AGG_COLUMN );
94508  testcase( pExpr->op==TK_COLUMN );
94509  /* Check to see if the column is in one of the tables in the FROM
94510  ** clause of the aggregate query */
94511  if( ALWAYS(pSrcList!=0) ){
94512  struct SrcList_item *pItem = pSrcList->a;
94513  for(i=0; i<pSrcList->nSrc; i++, pItem++){
94514  struct AggInfo_col *pCol;
94515  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
94516  if( pExpr->iTable==pItem->iCursor ){
94517  /* If we reach this point, it means that pExpr refers to a table
94518  ** that is in the FROM clause of the aggregate query.
94519  **
94520  ** Make an entry for the column in pAggInfo->aCol[] if there
94521  ** is not an entry there already.
94522  */
94523  int k;
94524  pCol = pAggInfo->aCol;
94525  for(k=0; k<pAggInfo->nColumn; k++, pCol++){
94526  if( pCol->iTable==pExpr->iTable &&
94527  pCol->iColumn==pExpr->iColumn ){
94528  break;
94529  }
94530  }
94531  if( (k>=pAggInfo->nColumn)
94532  && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
94533  ){
94534  pCol = &pAggInfo->aCol[k];
94535  pCol->pTab = pExpr->pTab;
94536  pCol->iTable = pExpr->iTable;
94537  pCol->iColumn = pExpr->iColumn;
94538  pCol->iMem = ++pParse->nMem;
94539  pCol->iSorterColumn = -1;
94540  pCol->pExpr = pExpr;
94541  if( pAggInfo->pGroupBy ){
94542  int j, n;
94543  ExprList *pGB = pAggInfo->pGroupBy;
94544  struct ExprList_item *pTerm = pGB->a;
94545  n = pGB->nExpr;
94546  for(j=0; j<n; j++, pTerm++){
94547  Expr *pE = pTerm->pExpr;
94548  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
94549  pE->iColumn==pExpr->iColumn ){
94550  pCol->iSorterColumn = j;
94551  break;
94552  }
94553  }
94554  }
94555  if( pCol->iSorterColumn<0 ){
94556  pCol->iSorterColumn = pAggInfo->nSortingColumn++;
94557  }
94558  }
94559  /* There is now an entry for pExpr in pAggInfo->aCol[] (either
94560  ** because it was there before or because we just created it).
94561  ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
94562  ** pAggInfo->aCol[] entry.
94563  */
94564  ExprSetVVAProperty(pExpr, EP_NoReduce);
94565  pExpr->pAggInfo = pAggInfo;
94566  pExpr->op = TK_AGG_COLUMN;
94567  pExpr->iAgg = (i16)k;
94568  break;
94569  } /* endif pExpr->iTable==pItem->iCursor */
94570  } /* end loop over pSrcList */
94571  }
94572  return WRC_Prune;
94573  }
94574  case TK_AGG_FUNCTION: {
94575  if( (pNC->ncFlags & NC_InAggFunc)==0
94576  && pWalker->walkerDepth==pExpr->op2
94577  ){
94578  /* Check to see if pExpr is a duplicate of another aggregate
94579  ** function that is already in the pAggInfo structure
94580  */
94581  struct AggInfo_func *pItem = pAggInfo->aFunc;
94582  for(i=0; i<pAggInfo->nFunc; i++, pItem++){
94583  if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
94584  break;
94585  }
94586  }
94587  if( i>=pAggInfo->nFunc ){
94588  /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
94589  */
94590  u8 enc = ENC(pParse->db);
94591  i = addAggInfoFunc(pParse->db, pAggInfo);
94592  if( i>=0 ){
94593  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
94594  pItem = &pAggInfo->aFunc[i];
94595  pItem->pExpr = pExpr;
94596  pItem->iMem = ++pParse->nMem;
94597  assert( !ExprHasProperty(pExpr, EP_IntValue) );
94598  pItem->pFunc = sqlite3FindFunction(pParse->db,
94599  pExpr->u.zToken,
94600  pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
94601  if( pExpr->flags & EP_Distinct ){
94602  pItem->iDistinct = pParse->nTab++;
94603  }else{
94604  pItem->iDistinct = -1;
94605  }
94606  }
94607  }
94608  /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
94609  */
94610  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
94611  ExprSetVVAProperty(pExpr, EP_NoReduce);
94612  pExpr->iAgg = (i16)i;
94613  pExpr->pAggInfo = pAggInfo;
94614  return WRC_Prune;
94615  }else{
94616  return WRC_Continue;
94617  }
94618  }
94619  }
94620  return WRC_Continue;
94621 }
94622 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
94623  UNUSED_PARAMETER(pWalker);
94624  UNUSED_PARAMETER(pSelect);
94625  return WRC_Continue;
94626 }
94627 
94628 /*
94629 ** Analyze the pExpr expression looking for aggregate functions and
94630 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
94631 ** points to. Additional entries are made on the AggInfo object as
94632 ** necessary.
94633 **
94634 ** This routine should only be called after the expression has been
94635 ** analyzed by sqlite3ResolveExprNames().
94636 */
94637 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
94638  Walker w;
94639  memset(&w, 0, sizeof(w));
94640  w.xExprCallback = analyzeAggregate;
94641  w.xSelectCallback = analyzeAggregatesInSelect;
94642  w.u.pNC = pNC;
94643  assert( pNC->pSrcList!=0 );
94644  sqlite3WalkExpr(&w, pExpr);
94645 }
94646 
94647 /*
94648 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
94649 ** expression list. Return the number of errors.
94650 **
94651 ** If an error is found, the analysis is cut short.
94652 */
94653 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
94654  struct ExprList_item *pItem;
94655  int i;
94656  if( pList ){
94657  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
94658  sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
94659  }
94660  }
94661 }
94662 
94663 /*
94664 ** Allocate a single new register for use to hold some intermediate result.
94665 */
94666 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
94667  if( pParse->nTempReg==0 ){
94668  return ++pParse->nMem;
94669  }
94670  return pParse->aTempReg[--pParse->nTempReg];
94671 }
94672 
94673 /*
94674 ** Deallocate a register, making available for reuse for some other
94675 ** purpose.
94676 **
94677 ** If a register is currently being used by the column cache, then
94678 ** the deallocation is deferred until the column cache line that uses
94679 ** the register becomes stale.
94680 */
94681 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
94682  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
94683  int i;
94684  struct yColCache *p;
94685  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
94686  if( p->iReg==iReg ){
94687  p->tempReg = 1;
94688  return;
94689  }
94690  }
94691  pParse->aTempReg[pParse->nTempReg++] = iReg;
94692  }
94693 }
94694 
94695 /*
94696 ** Allocate or deallocate a block of nReg consecutive registers.
94697 */
94698 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
94699  int i, n;
94700  if( nReg==1 ) return sqlite3GetTempReg(pParse);
94701  i = pParse->iRangeReg;
94702  n = pParse->nRangeReg;
94703  if( nReg<=n ){
94704  assert( !usedAsColumnCache(pParse, i, i+n-1) );
94705  pParse->iRangeReg += nReg;
94706  pParse->nRangeReg -= nReg;
94707  }else{
94708  i = pParse->nMem+1;
94709  pParse->nMem += nReg;
94710  }
94711  return i;
94712 }
94713 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
94714  if( nReg==1 ){
94715  sqlite3ReleaseTempReg(pParse, iReg);
94716  return;
94717  }
94718  sqlite3ExprCacheRemove(pParse, iReg, nReg);
94719  if( nReg>pParse->nRangeReg ){
94720  pParse->nRangeReg = nReg;
94721  pParse->iRangeReg = iReg;
94722  }
94723 }
94724 
94725 /*
94726 ** Mark all temporary registers as being unavailable for reuse.
94727 */
94728 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
94729  pParse->nTempReg = 0;
94730  pParse->nRangeReg = 0;
94731 }
94732 
94733 /*
94734 ** Validate that no temporary register falls within the range of
94735 ** iFirst..iLast, inclusive. This routine is only call from within assert()
94736 ** statements.
94737 */
94738 #ifdef SQLITE_DEBUG
94739 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
94740  int i;
94741  if( pParse->nRangeReg>0
94742  && pParse->iRangeReg+pParse->nRangeReg<iLast
94743  && pParse->iRangeReg>=iFirst
94744  ){
94745  return 0;
94746  }
94747  for(i=0; i<pParse->nTempReg; i++){
94748  if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
94749  return 0;
94750  }
94751  }
94752  return 1;
94753 }
94754 #endif /* SQLITE_DEBUG */
94755 
94756 /************** End of expr.c ************************************************/
94757 /************** Begin file alter.c *******************************************/
94758 /*
94759 ** 2005 February 15
94760 **
94761 ** The author disclaims copyright to this source code. In place of
94762 ** a legal notice, here is a blessing:
94763 **
94764 ** May you do good and not evil.
94765 ** May you find forgiveness for yourself and forgive others.
94766 ** May you share freely, never taking more than you give.
94767 **
94768 *************************************************************************
94769 ** This file contains C code routines that used to generate VDBE code
94770 ** that implements the ALTER TABLE command.
94771 */
94772 /* #include "sqliteInt.h" */
94773 
94774 /*
94775 ** The code in this file only exists if we are not omitting the
94776 ** ALTER TABLE logic from the build.
94777 */
94778 #ifndef SQLITE_OMIT_ALTERTABLE
94779 
94780 
94781 /*
94782 ** This function is used by SQL generated to implement the
94783 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
94784 ** CREATE INDEX command. The second is a table name. The table name in
94785 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
94786 ** argument and the result returned. Examples:
94787 **
94788 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
94789 ** -> 'CREATE TABLE def(a, b, c)'
94790 **
94791 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
94792 ** -> 'CREATE INDEX i ON def(a, b, c)'
94793 */
94794 static void renameTableFunc(
94795  sqlite3_context *context,
94796  int NotUsed,
94797  sqlite3_value **argv
94798 ){
94799  unsigned char const *zSql = sqlite3_value_text(argv[0]);
94800  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
94801 
94802  int token;
94803  Token tname;
94804  unsigned char const *zCsr = zSql;
94805  int len = 0;
94806  char *zRet;
94807 
94808  sqlite3 *db = sqlite3_context_db_handle(context);
94809 
94810  UNUSED_PARAMETER(NotUsed);
94811 
94812  /* The principle used to locate the table name in the CREATE TABLE
94813  ** statement is that the table name is the first non-space token that
94814  ** is immediately followed by a TK_LP or TK_USING token.
94815  */
94816  if( zSql ){
94817  do {
94818  if( !*zCsr ){
94819  /* Ran out of input before finding an opening bracket. Return NULL. */
94820  return;
94821  }
94822 
94823  /* Store the token that zCsr points to in tname. */
94824  tname.z = (char*)zCsr;
94825  tname.n = len;
94826 
94827  /* Advance zCsr to the next token. Store that token type in 'token',
94828  ** and its length in 'len' (to be used next iteration of this loop).
94829  */
94830  do {
94831  zCsr += len;
94832  len = sqlite3GetToken(zCsr, &token);
94833  } while( token==TK_SPACE );
94834  assert( len>0 );
94835  } while( token!=TK_LP && token!=TK_USING );
94836 
94837  zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
94838  zSql, zTableName, tname.z+tname.n);
94839  sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
94840  }
94841 }
94842 
94843 /*
94844 ** This C function implements an SQL user function that is used by SQL code
94845 ** generated by the ALTER TABLE ... RENAME command to modify the definition
94846 ** of any foreign key constraints that use the table being renamed as the
94847 ** parent table. It is passed three arguments:
94848 **
94849 ** 1) The complete text of the CREATE TABLE statement being modified,
94850 ** 2) The old name of the table being renamed, and
94851 ** 3) The new name of the table being renamed.
94852 **
94853 ** It returns the new CREATE TABLE statement. For example:
94854 **
94855 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
94856 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
94857 */
94858 #ifndef SQLITE_OMIT_FOREIGN_KEY
94859 static void renameParentFunc(
94860  sqlite3_context *context,
94861  int NotUsed,
94862  sqlite3_value **argv
94863 ){
94864  sqlite3 *db = sqlite3_context_db_handle(context);
94865  char *zOutput = 0;
94866  char *zResult;
94867  unsigned char const *zInput = sqlite3_value_text(argv[0]);
94868  unsigned char const *zOld = sqlite3_value_text(argv[1]);
94869  unsigned char const *zNew = sqlite3_value_text(argv[2]);
94870 
94871  unsigned const char *z; /* Pointer to token */
94872  int n; /* Length of token z */
94873  int token; /* Type of token */
94874 
94875  UNUSED_PARAMETER(NotUsed);
94876  if( zInput==0 || zOld==0 ) return;
94877  for(z=zInput; *z; z=z+n){
94878  n = sqlite3GetToken(z, &token);
94879  if( token==TK_REFERENCES ){
94880  char *zParent;
94881  do {
94882  z += n;
94883  n = sqlite3GetToken(z, &token);
94884  }while( token==TK_SPACE );
94885 
94886  if( token==TK_ILLEGAL ) break;
94887  zParent = sqlite3DbStrNDup(db, (const char *)z, n);
94888  if( zParent==0 ) break;
94889  sqlite3Dequote(zParent);
94890  if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
94891  char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
94892  (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
94893  );
94894  sqlite3DbFree(db, zOutput);
94895  zOutput = zOut;
94896  zInput = &z[n];
94897  }
94898  sqlite3DbFree(db, zParent);
94899  }
94900  }
94901 
94902  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
94903  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
94904  sqlite3DbFree(db, zOutput);
94905 }
94906 #endif
94907 
94908 #ifndef SQLITE_OMIT_TRIGGER
94909 /* This function is used by SQL generated to implement the
94910 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
94911 ** statement. The second is a table name. The table name in the CREATE
94912 ** TRIGGER statement is replaced with the third argument and the result
94913 ** returned. This is analagous to renameTableFunc() above, except for CREATE
94914 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
94915 */
94916 static void renameTriggerFunc(
94917  sqlite3_context *context,
94918  int NotUsed,
94919  sqlite3_value **argv
94920 ){
94921  unsigned char const *zSql = sqlite3_value_text(argv[0]);
94922  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
94923 
94924  int token;
94925  Token tname;
94926  int dist = 3;
94927  unsigned char const *zCsr = zSql;
94928  int len = 0;
94929  char *zRet;
94930  sqlite3 *db = sqlite3_context_db_handle(context);
94931 
94932  UNUSED_PARAMETER(NotUsed);
94933 
94934  /* The principle used to locate the table name in the CREATE TRIGGER
94935  ** statement is that the table name is the first token that is immediately
94936  ** preceded by either TK_ON or TK_DOT and immediately followed by one
94937  ** of TK_WHEN, TK_BEGIN or TK_FOR.
94938  */
94939  if( zSql ){
94940  do {
94941 
94942  if( !*zCsr ){
94943  /* Ran out of input before finding the table name. Return NULL. */
94944  return;
94945  }
94946 
94947  /* Store the token that zCsr points to in tname. */
94948  tname.z = (char*)zCsr;
94949  tname.n = len;
94950 
94951  /* Advance zCsr to the next token. Store that token type in 'token',
94952  ** and its length in 'len' (to be used next iteration of this loop).
94953  */
94954  do {
94955  zCsr += len;
94956  len = sqlite3GetToken(zCsr, &token);
94957  }while( token==TK_SPACE );
94958  assert( len>0 );
94959 
94960  /* Variable 'dist' stores the number of tokens read since the most
94961  ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
94962  ** token is read and 'dist' equals 2, the condition stated above
94963  ** to be met.
94964  **
94965  ** Note that ON cannot be a database, table or column name, so
94966  ** there is no need to worry about syntax like
94967  ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
94968  */
94969  dist++;
94970  if( token==TK_DOT || token==TK_ON ){
94971  dist = 0;
94972  }
94973  } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
94974 
94975  /* Variable tname now contains the token that is the old table-name
94976  ** in the CREATE TRIGGER statement.
94977  */
94978  zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
94979  zSql, zTableName, tname.z+tname.n);
94980  sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
94981  }
94982 }
94983 #endif /* !SQLITE_OMIT_TRIGGER */
94984 
94985 /*
94986 ** Register built-in functions used to help implement ALTER TABLE
94987 */
94988 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
94989  static FuncDef aAlterTableFuncs[] = {
94990  FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
94991 #ifndef SQLITE_OMIT_TRIGGER
94992  FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
94993 #endif
94994 #ifndef SQLITE_OMIT_FOREIGN_KEY
94995  FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
94996 #endif
94997  };
94998  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
94999 }
95000 
95001 /*
95002 ** This function is used to create the text of expressions of the form:
95003 **
95004 ** name=<constant1> OR name=<constant2> OR ...
95005 **
95006 ** If argument zWhere is NULL, then a pointer string containing the text
95007 ** "name=<constant>" is returned, where <constant> is the quoted version
95008 ** of the string passed as argument zConstant. The returned buffer is
95009 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
95010 ** caller to ensure that it is eventually freed.
95011 **
95012 ** If argument zWhere is not NULL, then the string returned is
95013 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
95014 ** In this case zWhere is passed to sqlite3DbFree() before returning.
95015 **
95016 */
95017 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
95018  char *zNew;
95019  if( !zWhere ){
95020  zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
95021  }else{
95022  zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
95023  sqlite3DbFree(db, zWhere);
95024  }
95025  return zNew;
95026 }
95027 
95028 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
95029 /*
95030 ** Generate the text of a WHERE expression which can be used to select all
95031 ** tables that have foreign key constraints that refer to table pTab (i.e.
95032 ** constraints for which pTab is the parent table) from the sqlite_master
95033 ** table.
95034 */
95035 static char *whereForeignKeys(Parse *pParse, Table *pTab){
95036  FKey *p;
95037  char *zWhere = 0;
95038  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
95039  zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
95040  }
95041  return zWhere;
95042 }
95043 #endif
95044 
95045 /*
95046 ** Generate the text of a WHERE expression which can be used to select all
95047 ** temporary triggers on table pTab from the sqlite_temp_master table. If
95048 ** table pTab has no temporary triggers, or is itself stored in the
95049 ** temporary database, NULL is returned.
95050 */
95051 static char *whereTempTriggers(Parse *pParse, Table *pTab){
95052  Trigger *pTrig;
95053  char *zWhere = 0;
95054  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
95055 
95056  /* If the table is not located in the temp-db (in which case NULL is
95057  ** returned, loop through the tables list of triggers. For each trigger
95058  ** that is not part of the temp-db schema, add a clause to the WHERE
95059  ** expression being built up in zWhere.
95060  */
95061  if( pTab->pSchema!=pTempSchema ){
95062  sqlite3 *db = pParse->db;
95063  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
95064  if( pTrig->pSchema==pTempSchema ){
95065  zWhere = whereOrName(db, zWhere, pTrig->zName);
95066  }
95067  }
95068  }
95069  if( zWhere ){
95070  char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
95071  sqlite3DbFree(pParse->db, zWhere);
95072  zWhere = zNew;
95073  }
95074  return zWhere;
95075 }
95076 
95077 /*
95078 ** Generate code to drop and reload the internal representation of table
95079 ** pTab from the database, including triggers and temporary triggers.
95080 ** Argument zName is the name of the table in the database schema at
95081 ** the time the generated code is executed. This can be different from
95082 ** pTab->zName if this function is being called to code part of an
95083 ** "ALTER TABLE RENAME TO" statement.
95084 */
95085 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
95086  Vdbe *v;
95087  char *zWhere;
95088  int iDb; /* Index of database containing pTab */
95089 #ifndef SQLITE_OMIT_TRIGGER
95090  Trigger *pTrig;
95091 #endif
95092 
95093  v = sqlite3GetVdbe(pParse);
95094  if( NEVER(v==0) ) return;
95095  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95096  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95097  assert( iDb>=0 );
95098 
95099 #ifndef SQLITE_OMIT_TRIGGER
95100  /* Drop any table triggers from the internal schema. */
95101  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
95102  int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
95103  assert( iTrigDb==iDb || iTrigDb==1 );
95104  sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
95105  }
95106 #endif
95107 
95108  /* Drop the table and index from the internal schema. */
95109  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
95110 
95111  /* Reload the table, index and permanent trigger schemas. */
95112  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
95113  if( !zWhere ) return;
95114  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
95115 
95116 #ifndef SQLITE_OMIT_TRIGGER
95117  /* Now, if the table is not stored in the temp database, reload any temp
95118  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
95119  */
95120  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
95121  sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
95122  }
95123 #endif
95124 }
95125 
95126 /*
95127 ** Parameter zName is the name of a table that is about to be altered
95128 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
95129 ** If the table is a system table, this function leaves an error message
95130 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
95131 **
95132 ** Or, if zName is not a system table, zero is returned.
95133 */
95134 static int isSystemTable(Parse *pParse, const char *zName){
95135  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
95136  sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
95137  return 1;
95138  }
95139  return 0;
95140 }
95141 
95142 /*
95143 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
95144 ** command.
95145 */
95146 SQLITE_PRIVATE void sqlite3AlterRenameTable(
95147  Parse *pParse, /* Parser context. */
95148  SrcList *pSrc, /* The table to rename. */
95149  Token *pName /* The new table name. */
95150 ){
95151  int iDb; /* Database that contains the table */
95152  char *zDb; /* Name of database iDb */
95153  Table *pTab; /* Table being renamed */
95154  char *zName = 0; /* NULL-terminated version of pName */
95155  sqlite3 *db = pParse->db; /* Database connection */
95156  int nTabName; /* Number of UTF-8 characters in zTabName */
95157  const char *zTabName; /* Original name of the table */
95158  Vdbe *v;
95159 #ifndef SQLITE_OMIT_TRIGGER
95160  char *zWhere = 0; /* Where clause to locate temp triggers */
95161 #endif
95162  VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
95163  int savedDbFlags; /* Saved value of db->flags */
95164 
95165  savedDbFlags = db->flags;
95166  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
95167  assert( pSrc->nSrc==1 );
95168  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95169 
95170  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
95171  if( !pTab ) goto exit_rename_table;
95172  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95173  zDb = db->aDb[iDb].zDbSName;
95174  db->flags |= SQLITE_PreferBuiltin;
95175 
95176  /* Get a NULL terminated version of the new table name. */
95177  zName = sqlite3NameFromToken(db, pName);
95178  if( !zName ) goto exit_rename_table;
95179 
95180  /* Check that a table or index named 'zName' does not already exist
95181  ** in database iDb. If so, this is an error.
95182  */
95183  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
95184  sqlite3ErrorMsg(pParse,
95185  "there is already another table or index with this name: %s", zName);
95186  goto exit_rename_table;
95187  }
95188 
95189  /* Make sure it is not a system table being altered, or a reserved name
95190  ** that the table is being renamed to.
95191  */
95192  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
95193  goto exit_rename_table;
95194  }
95195  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
95196  exit_rename_table;
95197  }
95198 
95199 #ifndef SQLITE_OMIT_VIEW
95200  if( pTab->pSelect ){
95201  sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
95202  goto exit_rename_table;
95203  }
95204 #endif
95205 
95206 #ifndef SQLITE_OMIT_AUTHORIZATION
95207  /* Invoke the authorization callback. */
95208  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
95209  goto exit_rename_table;
95210  }
95211 #endif
95212 
95213 #ifndef SQLITE_OMIT_VIRTUALTABLE
95214  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
95215  goto exit_rename_table;
95216  }
95217  if( IsVirtual(pTab) ){
95218  pVTab = sqlite3GetVTable(db, pTab);
95219  if( pVTab->pVtab->pModule->xRename==0 ){
95220  pVTab = 0;
95221  }
95222  }
95223 #endif
95224 
95225  /* Begin a transaction for database iDb.
95226  ** Then modify the schema cookie (since the ALTER TABLE modifies the
95227  ** schema). Open a statement transaction if the table is a virtual
95228  ** table.
95229  */
95230  v = sqlite3GetVdbe(pParse);
95231  if( v==0 ){
95232  goto exit_rename_table;
95233  }
95234  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
95235  sqlite3ChangeCookie(pParse, iDb);
95236 
95237  /* If this is a virtual table, invoke the xRename() function if
95238  ** one is defined. The xRename() callback will modify the names
95239  ** of any resources used by the v-table implementation (including other
95240  ** SQLite tables) that are identified by the name of the virtual table.
95241  */
95242 #ifndef SQLITE_OMIT_VIRTUALTABLE
95243  if( pVTab ){
95244  int i = ++pParse->nMem;
95245  sqlite3VdbeLoadString(v, i, zName);
95246  sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
95247  sqlite3MayAbort(pParse);
95248  }
95249 #endif
95250 
95251  /* figure out how many UTF-8 characters are in zName */
95252  zTabName = pTab->zName;
95253  nTabName = sqlite3Utf8CharLen(zTabName, -1);
95254 
95255 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
95256  if( db->flags&SQLITE_ForeignKeys ){
95257  /* If foreign-key support is enabled, rewrite the CREATE TABLE
95258  ** statements corresponding to all child tables of foreign key constraints
95259  ** for which the renamed table is the parent table. */
95260  if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
95261  sqlite3NestedParse(pParse,
95262  "UPDATE \"%w\".%s SET "
95263  "sql = sqlite_rename_parent(sql, %Q, %Q) "
95264  "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
95265  sqlite3DbFree(db, zWhere);
95266  }
95267  }
95268 #endif
95269 
95270  /* Modify the sqlite_master table to use the new table name. */
95271  sqlite3NestedParse(pParse,
95272  "UPDATE %Q.%s SET "
95273 #ifdef SQLITE_OMIT_TRIGGER
95274  "sql = sqlite_rename_table(sql, %Q), "
95275 #else
95276  "sql = CASE "
95277  "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
95278  "ELSE sqlite_rename_table(sql, %Q) END, "
95279 #endif
95280  "tbl_name = %Q, "
95281  "name = CASE "
95282  "WHEN type='table' THEN %Q "
95283  "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
95284  "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
95285  "ELSE name END "
95286  "WHERE tbl_name=%Q COLLATE nocase AND "
95287  "(type='table' OR type='index' OR type='trigger');",
95288  zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
95289 #ifndef SQLITE_OMIT_TRIGGER
95290  zName,
95291 #endif
95292  zName, nTabName, zTabName
95293  );
95294 
95295 #ifndef SQLITE_OMIT_AUTOINCREMENT
95296  /* If the sqlite_sequence table exists in this database, then update
95297  ** it with the new table name.
95298  */
95299  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
95300  sqlite3NestedParse(pParse,
95301  "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
95302  zDb, zName, pTab->zName);
95303  }
95304 #endif
95305 
95306 #ifndef SQLITE_OMIT_TRIGGER
95307  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
95308  ** table. Don't do this if the table being ALTERed is itself located in
95309  ** the temp database.
95310  */
95311  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
95312  sqlite3NestedParse(pParse,
95313  "UPDATE sqlite_temp_master SET "
95314  "sql = sqlite_rename_trigger(sql, %Q), "
95315  "tbl_name = %Q "
95316  "WHERE %s;", zName, zName, zWhere);
95317  sqlite3DbFree(db, zWhere);
95318  }
95319 #endif
95320 
95321 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
95322  if( db->flags&SQLITE_ForeignKeys ){
95323  FKey *p;
95324  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
95325  Table *pFrom = p->pFrom;
95326  if( pFrom!=pTab ){
95327  reloadTableSchema(pParse, p->pFrom, pFrom->zName);
95328  }
95329  }
95330  }
95331 #endif
95332 
95333  /* Drop and reload the internal table schema. */
95334  reloadTableSchema(pParse, pTab, zName);
95335 
95336 exit_rename_table:
95337  sqlite3SrcListDelete(db, pSrc);
95338  sqlite3DbFree(db, zName);
95339  db->flags = savedDbFlags;
95340 }
95341 
95342 /*
95343 ** This function is called after an "ALTER TABLE ... ADD" statement
95344 ** has been parsed. Argument pColDef contains the text of the new
95345 ** column definition.
95346 **
95347 ** The Table structure pParse->pNewTable was extended to include
95348 ** the new column during parsing.
95349 */
95350 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
95351  Table *pNew; /* Copy of pParse->pNewTable */
95352  Table *pTab; /* Table being altered */
95353  int iDb; /* Database number */
95354  const char *zDb; /* Database name */
95355  const char *zTab; /* Table name */
95356  char *zCol; /* Null-terminated column definition */
95357  Column *pCol; /* The new column */
95358  Expr *pDflt; /* Default value for the new column */
95359  sqlite3 *db; /* The database connection; */
95360  Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
95361  int r1; /* Temporary registers */
95362 
95363  db = pParse->db;
95364  if( pParse->nErr || db->mallocFailed ) return;
95365  assert( v!=0 );
95366  pNew = pParse->pNewTable;
95367  assert( pNew );
95368 
95369  assert( sqlite3BtreeHoldsAllMutexes(db) );
95370  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
95371  zDb = db->aDb[iDb].zDbSName;
95372  zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
95373  pCol = &pNew->aCol[pNew->nCol-1];
95374  pDflt = pCol->pDflt;
95375  pTab = sqlite3FindTable(db, zTab, zDb);
95376  assert( pTab );
95377 
95378 #ifndef SQLITE_OMIT_AUTHORIZATION
95379  /* Invoke the authorization callback. */
95380  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
95381  return;
95382  }
95383 #endif
95384 
95385  /* If the default value for the new column was specified with a
95386  ** literal NULL, then set pDflt to 0. This simplifies checking
95387  ** for an SQL NULL default below.
95388  */
95389  assert( pDflt==0 || pDflt->op==TK_SPAN );
95390  if( pDflt && pDflt->pLeft->op==TK_NULL ){
95391  pDflt = 0;
95392  }
95393 
95394  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
95395  ** If there is a NOT NULL constraint, then the default value for the
95396  ** column must not be NULL.
95397  */
95398  if( pCol->colFlags & COLFLAG_PRIMKEY ){
95399  sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
95400  return;
95401  }
95402  if( pNew->pIndex ){
95403  sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
95404  return;
95405  }
95406  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
95407  sqlite3ErrorMsg(pParse,
95408  "Cannot add a REFERENCES column with non-NULL default value");
95409  return;
95410  }
95411  if( pCol->notNull && !pDflt ){
95412  sqlite3ErrorMsg(pParse,
95413  "Cannot add a NOT NULL column with default value NULL");
95414  return;
95415  }
95416 
95417  /* Ensure the default expression is something that sqlite3ValueFromExpr()
95418  ** can handle (i.e. not CURRENT_TIME etc.)
95419  */
95420  if( pDflt ){
95421  sqlite3_value *pVal = 0;
95422  int rc;
95423  rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
95424  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
95425  if( rc!=SQLITE_OK ){
95426  assert( db->mallocFailed == 1 );
95427  return;
95428  }
95429  if( !pVal ){
95430  sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
95431  return;
95432  }
95433  sqlite3ValueFree(pVal);
95434  }
95435 
95436  /* Modify the CREATE TABLE statement. */
95437  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
95438  if( zCol ){
95439  char *zEnd = &zCol[pColDef->n-1];
95440  int savedDbFlags = db->flags;
95441  while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
95442  *zEnd-- = '\0';
95443  }
95444  db->flags |= SQLITE_PreferBuiltin;
95445  sqlite3NestedParse(pParse,
95446  "UPDATE \"%w\".%s SET "
95447  "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
95448  "WHERE type = 'table' AND name = %Q",
95449  zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
95450  zTab
95451  );
95452  sqlite3DbFree(db, zCol);
95453  db->flags = savedDbFlags;
95454  }
95455 
95456  /* Make sure the schema version is at least 3. But do not upgrade
95457  ** from less than 3 to 4, as that will corrupt any preexisting DESC
95458  ** index.
95459  */
95460  r1 = sqlite3GetTempReg(pParse);
95461  sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
95462  sqlite3VdbeUsesBtree(v, iDb);
95463  sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
95464  sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
95465  VdbeCoverage(v);
95466  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
95467  sqlite3ReleaseTempReg(pParse, r1);
95468 
95469  /* Reload the schema of the modified table. */
95470  reloadTableSchema(pParse, pTab, pTab->zName);
95471 }
95472 
95473 /*
95474 ** This function is called by the parser after the table-name in
95475 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
95476 ** pSrc is the full-name of the table being altered.
95477 **
95478 ** This routine makes a (partial) copy of the Table structure
95479 ** for the table being altered and sets Parse.pNewTable to point
95480 ** to it. Routines called by the parser as the column definition
95481 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
95482 ** the copy. The copy of the Table structure is deleted by tokenize.c
95483 ** after parsing is finished.
95484 **
95485 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
95486 ** coding the "ALTER TABLE ... ADD" statement.
95487 */
95488 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
95489  Table *pNew;
95490  Table *pTab;
95491  Vdbe *v;
95492  int iDb;
95493  int i;
95494  int nAlloc;
95495  sqlite3 *db = pParse->db;
95496 
95497  /* Look up the table being altered. */
95498  assert( pParse->pNewTable==0 );
95499  assert( sqlite3BtreeHoldsAllMutexes(db) );
95500  if( db->mallocFailed ) goto exit_begin_add_column;
95501  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
95502  if( !pTab ) goto exit_begin_add_column;
95503 
95504 #ifndef SQLITE_OMIT_VIRTUALTABLE
95505  if( IsVirtual(pTab) ){
95506  sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
95507  goto exit_begin_add_column;
95508  }
95509 #endif
95510 
95511  /* Make sure this is not an attempt to ALTER a view. */
95512  if( pTab->pSelect ){
95513  sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
95514  goto exit_begin_add_column;
95515  }
95516  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
95517  goto exit_begin_add_column;
95518  }
95519 
95520  assert( pTab->addColOffset>0 );
95521  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95522 
95523  /* Put a copy of the Table struct in Parse.pNewTable for the
95524  ** sqlite3AddColumn() function and friends to modify. But modify
95525  ** the name by adding an "sqlite_altertab_" prefix. By adding this
95526  ** prefix, we insure that the name will not collide with an existing
95527  ** table because user table are not allowed to have the "sqlite_"
95528  ** prefix on their name.
95529  */
95530  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
95531  if( !pNew ) goto exit_begin_add_column;
95532  pParse->pNewTable = pNew;
95533  pNew->nRef = 1;
95534  pNew->nCol = pTab->nCol;
95535  assert( pNew->nCol>0 );
95536  nAlloc = (((pNew->nCol-1)/8)*8)+8;
95537  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
95538  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
95539  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
95540  if( !pNew->aCol || !pNew->zName ){
95541  assert( db->mallocFailed );
95542  goto exit_begin_add_column;
95543  }
95544  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
95545  for(i=0; i<pNew->nCol; i++){
95546  Column *pCol = &pNew->aCol[i];
95547  pCol->zName = sqlite3DbStrDup(db, pCol->zName);
95548  pCol->zColl = 0;
95549  pCol->pDflt = 0;
95550  }
95551  pNew->pSchema = db->aDb[iDb].pSchema;
95552  pNew->addColOffset = pTab->addColOffset;
95553  pNew->nRef = 1;
95554 
95555  /* Begin a transaction and increment the schema cookie. */
95556  sqlite3BeginWriteOperation(pParse, 0, iDb);
95557  v = sqlite3GetVdbe(pParse);
95558  if( !v ) goto exit_begin_add_column;
95559  sqlite3ChangeCookie(pParse, iDb);
95560 
95561 exit_begin_add_column:
95562  sqlite3SrcListDelete(db, pSrc);
95563  return;
95564 }
95565 #endif /* SQLITE_ALTER_TABLE */
95566 
95567 /************** End of alter.c ***********************************************/
95568 /************** Begin file analyze.c *****************************************/
95569 /*
95570 ** 2005-07-08
95571 **
95572 ** The author disclaims copyright to this source code. In place of
95573 ** a legal notice, here is a blessing:
95574 **
95575 ** May you do good and not evil.
95576 ** May you find forgiveness for yourself and forgive others.
95577 ** May you share freely, never taking more than you give.
95578 **
95579 *************************************************************************
95580 ** This file contains code associated with the ANALYZE command.
95581 **
95582 ** The ANALYZE command gather statistics about the content of tables
95583 ** and indices. These statistics are made available to the query planner
95584 ** to help it make better decisions about how to perform queries.
95585 **
95586 ** The following system tables are or have been supported:
95587 **
95588 ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
95589 ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
95590 ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
95591 ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
95592 **
95593 ** Additional tables might be added in future releases of SQLite.
95594 ** The sqlite_stat2 table is not created or used unless the SQLite version
95595 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
95596 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
95597 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
95598 ** created and used by SQLite versions 3.7.9 and later and with
95599 ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
95600 ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
95601 ** version of sqlite_stat3 and is only available when compiled with
95602 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
95603 ** not possible to enable both STAT3 and STAT4 at the same time. If they
95604 ** are both enabled, then STAT4 takes precedence.
95605 **
95606 ** For most applications, sqlite_stat1 provides all the statistics required
95607 ** for the query planner to make good choices.
95608 **
95609 ** Format of sqlite_stat1:
95610 **
95611 ** There is normally one row per index, with the index identified by the
95612 ** name in the idx column. The tbl column is the name of the table to
95613 ** which the index belongs. In each such row, the stat column will be
95614 ** a string consisting of a list of integers. The first integer in this
95615 ** list is the number of rows in the index. (This is the same as the
95616 ** number of rows in the table, except for partial indices.) The second
95617 ** integer is the average number of rows in the index that have the same
95618 ** value in the first column of the index. The third integer is the average
95619 ** number of rows in the index that have the same value for the first two
95620 ** columns. The N-th integer (for N>1) is the average number of rows in
95621 ** the index which have the same value for the first N-1 columns. For
95622 ** a K-column index, there will be K+1 integers in the stat column. If
95623 ** the index is unique, then the last integer will be 1.
95624 **
95625 ** The list of integers in the stat column can optionally be followed
95626 ** by the keyword "unordered". The "unordered" keyword, if it is present,
95627 ** must be separated from the last integer by a single space. If the
95628 ** "unordered" keyword is present, then the query planner assumes that
95629 ** the index is unordered and will not use the index for a range query.
95630 **
95631 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
95632 ** column contains a single integer which is the (estimated) number of
95633 ** rows in the table identified by sqlite_stat1.tbl.
95634 **
95635 ** Format of sqlite_stat2:
95636 **
95637 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
95638 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
95639 ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
95640 ** about the distribution of keys within an index. The index is identified by
95641 ** the "idx" column and the "tbl" column is the name of the table to which
95642 ** the index belongs. There are usually 10 rows in the sqlite_stat2
95643 ** table for each index.
95644 **
95645 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
95646 ** inclusive are samples of the left-most key value in the index taken at
95647 ** evenly spaced points along the index. Let the number of samples be S
95648 ** (10 in the standard build) and let C be the number of rows in the index.
95649 ** Then the sampled rows are given by:
95650 **
95651 ** rownumber = (i*C*2 + C)/(S*2)
95652 **
95653 ** For i between 0 and S-1. Conceptually, the index space is divided into
95654 ** S uniform buckets and the samples are the middle row from each bucket.
95655 **
95656 ** The format for sqlite_stat2 is recorded here for legacy reference. This
95657 ** version of SQLite does not support sqlite_stat2. It neither reads nor
95658 ** writes the sqlite_stat2 table. This version of SQLite only supports
95659 ** sqlite_stat3.
95660 **
95661 ** Format for sqlite_stat3:
95662 **
95663 ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
95664 ** sqlite_stat4 format will be described first. Further information
95665 ** about sqlite_stat3 follows the sqlite_stat4 description.
95666 **
95667 ** Format for sqlite_stat4:
95668 **
95669 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
95670 ** to aid the query planner in choosing good indices based on the values
95671 ** that indexed columns are compared against in the WHERE clauses of
95672 ** queries.
95673 **
95674 ** The sqlite_stat4 table contains multiple entries for each index.
95675 ** The idx column names the index and the tbl column is the table of the
95676 ** index. If the idx and tbl columns are the same, then the sample is
95677 ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
95678 ** binary encoding of a key from the index. The nEq column is a
95679 ** list of integers. The first integer is the approximate number
95680 ** of entries in the index whose left-most column exactly matches
95681 ** the left-most column of the sample. The second integer in nEq
95682 ** is the approximate number of entries in the index where the
95683 ** first two columns match the first two columns of the sample.
95684 ** And so forth. nLt is another list of integers that show the approximate
95685 ** number of entries that are strictly less than the sample. The first
95686 ** integer in nLt contains the number of entries in the index where the
95687 ** left-most column is less than the left-most column of the sample.
95688 ** The K-th integer in the nLt entry is the number of index entries
95689 ** where the first K columns are less than the first K columns of the
95690 ** sample. The nDLt column is like nLt except that it contains the
95691 ** number of distinct entries in the index that are less than the
95692 ** sample.
95693 **
95694 ** There can be an arbitrary number of sqlite_stat4 entries per index.
95695 ** The ANALYZE command will typically generate sqlite_stat4 tables
95696 ** that contain between 10 and 40 samples which are distributed across
95697 ** the key space, though not uniformly, and which include samples with
95698 ** large nEq values.
95699 **
95700 ** Format for sqlite_stat3 redux:
95701 **
95702 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
95703 ** looks at the left-most column of the index. The sqlite_stat3.sample
95704 ** column contains the actual value of the left-most column instead
95705 ** of a blob encoding of the complete index key as is found in
95706 ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
95707 ** all contain just a single integer which is the same as the first
95708 ** integer in the equivalent columns in sqlite_stat4.
95709 */
95710 #ifndef SQLITE_OMIT_ANALYZE
95711 /* #include "sqliteInt.h" */
95712 
95713 #if defined(SQLITE_ENABLE_STAT4)
95714 # define IsStat4 1
95715 # define IsStat3 0
95716 #elif defined(SQLITE_ENABLE_STAT3)
95717 # define IsStat4 0
95718 # define IsStat3 1
95719 #else
95720 # define IsStat4 0
95721 # define IsStat3 0
95722 # undef SQLITE_STAT4_SAMPLES
95723 # define SQLITE_STAT4_SAMPLES 1
95724 #endif
95725 #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
95726 
95727 /*
95728 ** This routine generates code that opens the sqlite_statN tables.
95729 ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
95730 ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
95731 ** appropriate compile-time options are provided.
95732 **
95733 ** If the sqlite_statN tables do not previously exist, it is created.
95734 **
95735 ** Argument zWhere may be a pointer to a buffer containing a table name,
95736 ** or it may be a NULL pointer. If it is not NULL, then all entries in
95737 ** the sqlite_statN tables associated with the named table are deleted.
95738 ** If zWhere==0, then code is generated to delete all stat table entries.
95739 */
95740 static void openStatTable(
95741  Parse *pParse, /* Parsing context */
95742  int iDb, /* The database we are looking in */
95743  int iStatCur, /* Open the sqlite_stat1 table on this cursor */
95744  const char *zWhere, /* Delete entries for this table or index */
95745  const char *zWhereType /* Either "tbl" or "idx" */
95746 ){
95747  static const struct {
95748  const char *zName;
95749  const char *zCols;
95750  } aTable[] = {
95751  { "sqlite_stat1", "tbl,idx,stat" },
95752 #if defined(SQLITE_ENABLE_STAT4)
95753  { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
95754  { "sqlite_stat3", 0 },
95755 #elif defined(SQLITE_ENABLE_STAT3)
95756  { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
95757  { "sqlite_stat4", 0 },
95758 #else
95759  { "sqlite_stat3", 0 },
95760  { "sqlite_stat4", 0 },
95761 #endif
95762  };
95763  int i;
95764  sqlite3 *db = pParse->db;
95765  Db *pDb;
95766  Vdbe *v = sqlite3GetVdbe(pParse);
95767  int aRoot[ArraySize(aTable)];
95768  u8 aCreateTbl[ArraySize(aTable)];
95769 
95770  if( v==0 ) return;
95771  assert( sqlite3BtreeHoldsAllMutexes(db) );
95772  assert( sqlite3VdbeDb(v)==db );
95773  pDb = &db->aDb[iDb];
95774 
95775  /* Create new statistic tables if they do not exist, or clear them
95776  ** if they do already exist.
95777  */
95778  for(i=0; i<ArraySize(aTable); i++){
95779  const char *zTab = aTable[i].zName;
95780  Table *pStat;
95781  if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
95782  if( aTable[i].zCols ){
95783  /* The sqlite_statN table does not exist. Create it. Note that a
95784  ** side-effect of the CREATE TABLE statement is to leave the rootpage
95785  ** of the new table in register pParse->regRoot. This is important
95786  ** because the OpenWrite opcode below will be needing it. */
95787  sqlite3NestedParse(pParse,
95788  "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
95789  );
95790  aRoot[i] = pParse->regRoot;
95791  aCreateTbl[i] = OPFLAG_P2ISREG;
95792  }
95793  }else{
95794  /* The table already exists. If zWhere is not NULL, delete all entries
95795  ** associated with the table zWhere. If zWhere is NULL, delete the
95796  ** entire contents of the table. */
95797  aRoot[i] = pStat->tnum;
95798  aCreateTbl[i] = 0;
95799  sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
95800  if( zWhere ){
95801  sqlite3NestedParse(pParse,
95802  "DELETE FROM %Q.%s WHERE %s=%Q",
95803  pDb->zDbSName, zTab, zWhereType, zWhere
95804  );
95805  }else{
95806  /* The sqlite_stat[134] table already exists. Delete all rows. */
95807  sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
95808  }
95809  }
95810  }
95811 
95812  /* Open the sqlite_stat[134] tables for writing. */
95813  for(i=0; aTable[i].zCols; i++){
95814  assert( i<ArraySize(aTable) );
95815  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
95816  sqlite3VdbeChangeP5(v, aCreateTbl[i]);
95817  VdbeComment((v, aTable[i].zName));
95818  }
95819 }
95820 
95821 /*
95822 ** Recommended number of samples for sqlite_stat4
95823 */
95824 #ifndef SQLITE_STAT4_SAMPLES
95825 # define SQLITE_STAT4_SAMPLES 24
95826 #endif
95827 
95828 /*
95829 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
95830 ** share an instance of the following structure to hold their state
95831 ** information.
95832 */
95833 typedef struct Stat4Accum Stat4Accum;
95834 typedef struct Stat4Sample Stat4Sample;
95835 struct Stat4Sample {
95836  tRowcnt *anEq; /* sqlite_stat4.nEq */
95837  tRowcnt *anDLt; /* sqlite_stat4.nDLt */
95838 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95839  tRowcnt *anLt; /* sqlite_stat4.nLt */
95840  union {
95841  i64 iRowid; /* Rowid in main table of the key */
95842  u8 *aRowid; /* Key for WITHOUT ROWID tables */
95843  } u;
95844  u32 nRowid; /* Sizeof aRowid[] */
95845  u8 isPSample; /* True if a periodic sample */
95846  int iCol; /* If !isPSample, the reason for inclusion */
95847  u32 iHash; /* Tiebreaker hash */
95848 #endif
95849 };
95850 struct Stat4Accum {
95851  tRowcnt nRow; /* Number of rows in the entire table */
95852  tRowcnt nPSample; /* How often to do a periodic sample */
95853  int nCol; /* Number of columns in index + pk/rowid */
95854  int nKeyCol; /* Number of index columns w/o the pk/rowid */
95855  int mxSample; /* Maximum number of samples to accumulate */
95856  Stat4Sample current; /* Current row as a Stat4Sample */
95857  u32 iPrn; /* Pseudo-random number used for sampling */
95858  Stat4Sample *aBest; /* Array of nCol best samples */
95859  int iMin; /* Index in a[] of entry with minimum score */
95860  int nSample; /* Current number of samples */
95861  int iGet; /* Index of current sample accessed by stat_get() */
95862  Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
95863  sqlite3 *db; /* Database connection, for malloc() */
95864 };
95865 
95866 /* Reclaim memory used by a Stat4Sample
95867 */
95868 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95869 static void sampleClear(sqlite3 *db, Stat4Sample *p){
95870  assert( db!=0 );
95871  if( p->nRowid ){
95872  sqlite3DbFree(db, p->u.aRowid);
95873  p->nRowid = 0;
95874  }
95875 }
95876 #endif
95877 
95878 /* Initialize the BLOB value of a ROWID
95879 */
95880 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95881 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
95882  assert( db!=0 );
95883  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
95884  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
95885  if( p->u.aRowid ){
95886  p->nRowid = n;
95887  memcpy(p->u.aRowid, pData, n);
95888  }else{
95889  p->nRowid = 0;
95890  }
95891 }
95892 #endif
95893 
95894 /* Initialize the INTEGER value of a ROWID.
95895 */
95896 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95897 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
95898  assert( db!=0 );
95899  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
95900  p->nRowid = 0;
95901  p->u.iRowid = iRowid;
95902 }
95903 #endif
95904 
95905 
95906 /*
95907 ** Copy the contents of object (*pFrom) into (*pTo).
95908 */
95909 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95910 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
95911  pTo->isPSample = pFrom->isPSample;
95912  pTo->iCol = pFrom->iCol;
95913  pTo->iHash = pFrom->iHash;
95914  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
95915  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
95916  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
95917  if( pFrom->nRowid ){
95918  sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
95919  }else{
95920  sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
95921  }
95922 }
95923 #endif
95924 
95925 /*
95926 ** Reclaim all memory of a Stat4Accum structure.
95927 */
95928 static void stat4Destructor(void *pOld){
95929  Stat4Accum *p = (Stat4Accum*)pOld;
95930 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95931  int i;
95932  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
95933  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
95934  sampleClear(p->db, &p->current);
95935 #endif
95936  sqlite3DbFree(p->db, p);
95937 }
95938 
95939 /*
95940 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
95941 ** are:
95942 ** N: The number of columns in the index including the rowid/pk (note 1)
95943 ** K: The number of columns in the index excluding the rowid/pk.
95944 ** C: The number of rows in the index (note 2)
95945 **
95946 ** Note 1: In the special case of the covering index that implements a
95947 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
95948 ** total number of columns in the table.
95949 **
95950 ** Note 2: C is only used for STAT3 and STAT4.
95951 **
95952 ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
95953 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
95954 ** PRIMARY KEY of the table. The covering index that implements the
95955 ** original WITHOUT ROWID table as N==K as a special case.
95956 **
95957 ** This routine allocates the Stat4Accum object in heap memory. The return
95958 ** value is a pointer to the Stat4Accum object. The datatype of the
95959 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
95960 ** object.
95961 */
95962 static void statInit(
95963  sqlite3_context *context,
95964  int argc,
95965  sqlite3_value **argv
95966 ){
95967  Stat4Accum *p;
95968  int nCol; /* Number of columns in index being sampled */
95969  int nKeyCol; /* Number of key columns */
95970  int nColUp; /* nCol rounded up for alignment */
95971  int n; /* Bytes of space to allocate */
95972  sqlite3 *db; /* Database connection */
95973 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95974  int mxSample = SQLITE_STAT4_SAMPLES;
95975 #endif
95976 
95977  /* Decode the three function arguments */
95978  UNUSED_PARAMETER(argc);
95979  nCol = sqlite3_value_int(argv[0]);
95980  assert( nCol>0 );
95981  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
95982  nKeyCol = sqlite3_value_int(argv[1]);
95983  assert( nKeyCol<=nCol );
95984  assert( nKeyCol>0 );
95985 
95986  /* Allocate the space required for the Stat4Accum object */
95987  n = sizeof(*p)
95988  + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
95989  + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
95990 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95991  + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
95992  + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
95993  + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
95994 #endif
95995  ;
95996  db = sqlite3_context_db_handle(context);
95997  p = sqlite3DbMallocZero(db, n);
95998  if( p==0 ){
95999  sqlite3_result_error_nomem(context);
96000  return;
96001  }
96002 
96003  p->db = db;
96004  p->nRow = 0;
96005  p->nCol = nCol;
96006  p->nKeyCol = nKeyCol;
96007  p->current.anDLt = (tRowcnt*)&p[1];
96008  p->current.anEq = &p->current.anDLt[nColUp];
96009 
96010 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96011  {
96012  u8 *pSpace; /* Allocated space not yet assigned */
96013  int i; /* Used to iterate through p->aSample[] */
96014 
96015  p->iGet = -1;
96016  p->mxSample = mxSample;
96017  p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
96018  p->current.anLt = &p->current.anEq[nColUp];
96019  p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
96020 
96021  /* Set up the Stat4Accum.a[] and aBest[] arrays */
96022  p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
96023  p->aBest = &p->a[mxSample];
96024  pSpace = (u8*)(&p->a[mxSample+nCol]);
96025  for(i=0; i<(mxSample+nCol); i++){
96026  p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
96027  p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
96028  p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
96029  }
96030  assert( (pSpace - (u8*)p)==n );
96031 
96032  for(i=0; i<nCol; i++){
96033  p->aBest[i].iCol = i;
96034  }
96035  }
96036 #endif
96037 
96038  /* Return a pointer to the allocated object to the caller. Note that
96039  ** only the pointer (the 2nd parameter) matters. The size of the object
96040  ** (given by the 3rd parameter) is never used and can be any positive
96041  ** value. */
96042  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
96043 }
96044 static const FuncDef statInitFuncdef = {
96045  2+IsStat34, /* nArg */
96046  SQLITE_UTF8, /* funcFlags */
96047  0, /* pUserData */
96048  0, /* pNext */
96049  statInit, /* xSFunc */
96050  0, /* xFinalize */
96051  "stat_init", /* zName */
96052  {0}
96053 };
96054 
96055 #ifdef SQLITE_ENABLE_STAT4
96056 /*
96057 ** pNew and pOld are both candidate non-periodic samples selected for
96058 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
96059 ** considering only any trailing columns and the sample hash value, this
96060 ** function returns true if sample pNew is to be preferred over pOld.
96061 ** In other words, if we assume that the cardinalities of the selected
96062 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
96063 **
96064 ** This function assumes that for each argument sample, the contents of
96065 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
96066 */
96067 static int sampleIsBetterPost(
96068  Stat4Accum *pAccum,
96069  Stat4Sample *pNew,
96070  Stat4Sample *pOld
96071 ){
96072  int nCol = pAccum->nCol;
96073  int i;
96074  assert( pNew->iCol==pOld->iCol );
96075  for(i=pNew->iCol+1; i<nCol; i++){
96076  if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
96077  if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
96078  }
96079  if( pNew->iHash>pOld->iHash ) return 1;
96080  return 0;
96081 }
96082 #endif
96083 
96084 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96085 /*
96086 ** Return true if pNew is to be preferred over pOld.
96087 **
96088 ** This function assumes that for each argument sample, the contents of
96089 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
96090 */
96091 static int sampleIsBetter(
96092  Stat4Accum *pAccum,
96093  Stat4Sample *pNew,
96094  Stat4Sample *pOld
96095 ){
96096  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
96097  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
96098 
96099  assert( pOld->isPSample==0 && pNew->isPSample==0 );
96100  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
96101 
96102  if( (nEqNew>nEqOld) ) return 1;
96103 #ifdef SQLITE_ENABLE_STAT4
96104  if( nEqNew==nEqOld ){
96105  if( pNew->iCol<pOld->iCol ) return 1;
96106  return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
96107  }
96108  return 0;
96109 #else
96110  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
96111 #endif
96112 }
96113 
96114 /*
96115 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
96116 ** remove the least desirable sample from p->a[] to make room.
96117 */
96118 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
96119  Stat4Sample *pSample = 0;
96120  int i;
96121 
96122  assert( IsStat4 || nEqZero==0 );
96123 
96124 #ifdef SQLITE_ENABLE_STAT4
96125  if( pNew->isPSample==0 ){
96126  Stat4Sample *pUpgrade = 0;
96127  assert( pNew->anEq[pNew->iCol]>0 );
96128 
96129  /* This sample is being added because the prefix that ends in column
96130  ** iCol occurs many times in the table. However, if we have already
96131  ** added a sample that shares this prefix, there is no need to add
96132  ** this one. Instead, upgrade the priority of the highest priority
96133  ** existing sample that shares this prefix. */
96134  for(i=p->nSample-1; i>=0; i--){
96135  Stat4Sample *pOld = &p->a[i];
96136  if( pOld->anEq[pNew->iCol]==0 ){
96137  if( pOld->isPSample ) return;
96138  assert( pOld->iCol>pNew->iCol );
96139  assert( sampleIsBetter(p, pNew, pOld) );
96140  if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
96141  pUpgrade = pOld;
96142  }
96143  }
96144  }
96145  if( pUpgrade ){
96146  pUpgrade->iCol = pNew->iCol;
96147  pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
96148  goto find_new_min;
96149  }
96150  }
96151 #endif
96152 
96153  /* If necessary, remove sample iMin to make room for the new sample. */
96154  if( p->nSample>=p->mxSample ){
96155  Stat4Sample *pMin = &p->a[p->iMin];
96156  tRowcnt *anEq = pMin->anEq;
96157  tRowcnt *anLt = pMin->anLt;
96158  tRowcnt *anDLt = pMin->anDLt;
96159  sampleClear(p->db, pMin);
96160  memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
96161  pSample = &p->a[p->nSample-1];
96162  pSample->nRowid = 0;
96163  pSample->anEq = anEq;
96164  pSample->anDLt = anDLt;
96165  pSample->anLt = anLt;
96166  p->nSample = p->mxSample-1;
96167  }
96168 
96169  /* The "rows less-than" for the rowid column must be greater than that
96170  ** for the last sample in the p->a[] array. Otherwise, the samples would
96171  ** be out of order. */
96172 #ifdef SQLITE_ENABLE_STAT4
96173  assert( p->nSample==0
96174  || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
96175 #endif
96176 
96177  /* Insert the new sample */
96178  pSample = &p->a[p->nSample];
96179  sampleCopy(p, pSample, pNew);
96180  p->nSample++;
96181 
96182  /* Zero the first nEqZero entries in the anEq[] array. */
96183  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
96184 
96185 #ifdef SQLITE_ENABLE_STAT4
96186  find_new_min:
96187 #endif
96188  if( p->nSample>=p->mxSample ){
96189  int iMin = -1;
96190  for(i=0; i<p->mxSample; i++){
96191  if( p->a[i].isPSample ) continue;
96192  if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
96193  iMin = i;
96194  }
96195  }
96196  assert( iMin>=0 );
96197  p->iMin = iMin;
96198  }
96199 }
96200 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96201 
96202 /*
96203 ** Field iChng of the index being scanned has changed. So at this point
96204 ** p->current contains a sample that reflects the previous row of the
96205 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
96206 ** correct at this point.
96207 */
96208 static void samplePushPrevious(Stat4Accum *p, int iChng){
96209 #ifdef SQLITE_ENABLE_STAT4
96210  int i;
96211 
96212  /* Check if any samples from the aBest[] array should be pushed
96213  ** into IndexSample.a[] at this point. */
96214  for(i=(p->nCol-2); i>=iChng; i--){
96215  Stat4Sample *pBest = &p->aBest[i];
96216  pBest->anEq[i] = p->current.anEq[i];
96217  if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
96218  sampleInsert(p, pBest, i);
96219  }
96220  }
96221 
96222  /* Update the anEq[] fields of any samples already collected. */
96223  for(i=p->nSample-1; i>=0; i--){
96224  int j;
96225  for(j=iChng; j<p->nCol; j++){
96226  if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
96227  }
96228  }
96229 #endif
96230 
96231 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
96232  if( iChng==0 ){
96233  tRowcnt nLt = p->current.anLt[0];
96234  tRowcnt nEq = p->current.anEq[0];
96235 
96236  /* Check if this is to be a periodic sample. If so, add it. */
96237  if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
96238  p->current.isPSample = 1;
96239  sampleInsert(p, &p->current, 0);
96240  p->current.isPSample = 0;
96241  }else
96242 
96243  /* Or if it is a non-periodic sample. Add it in this case too. */
96244  if( p->nSample<p->mxSample
96245  || sampleIsBetter(p, &p->current, &p->a[p->iMin])
96246  ){
96247  sampleInsert(p, &p->current, 0);
96248  }
96249  }
96250 #endif
96251 
96252 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
96253  UNUSED_PARAMETER( p );
96254  UNUSED_PARAMETER( iChng );
96255 #endif
96256 }
96257 
96258 /*
96259 ** Implementation of the stat_push SQL function: stat_push(P,C,R)
96260 ** Arguments:
96261 **
96262 ** P Pointer to the Stat4Accum object created by stat_init()
96263 ** C Index of left-most column to differ from previous row
96264 ** R Rowid for the current row. Might be a key record for
96265 ** WITHOUT ROWID tables.
96266 **
96267 ** This SQL function always returns NULL. It's purpose it to accumulate
96268 ** statistical data and/or samples in the Stat4Accum object about the
96269 ** index being analyzed. The stat_get() SQL function will later be used to
96270 ** extract relevant information for constructing the sqlite_statN tables.
96271 **
96272 ** The R parameter is only used for STAT3 and STAT4
96273 */
96274 static void statPush(
96275  sqlite3_context *context,
96276  int argc,
96277  sqlite3_value **argv
96278 ){
96279  int i;
96280 
96281  /* The three function arguments */
96282  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
96283  int iChng = sqlite3_value_int(argv[1]);
96284 
96285  UNUSED_PARAMETER( argc );
96286  UNUSED_PARAMETER( context );
96287  assert( p->nCol>0 );
96288  assert( iChng<p->nCol );
96289 
96290  if( p->nRow==0 ){
96291  /* This is the first call to this function. Do initialization. */
96292  for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
96293  }else{
96294  /* Second and subsequent calls get processed here */
96295  samplePushPrevious(p, iChng);
96296 
96297  /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
96298  ** to the current row of the index. */
96299  for(i=0; i<iChng; i++){
96300  p->current.anEq[i]++;
96301  }
96302  for(i=iChng; i<p->nCol; i++){
96303  p->current.anDLt[i]++;
96304 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96305  p->current.anLt[i] += p->current.anEq[i];
96306 #endif
96307  p->current.anEq[i] = 1;
96308  }
96309  }
96310  p->nRow++;
96311 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96312  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
96313  sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
96314  }else{
96315  sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
96316  sqlite3_value_blob(argv[2]));
96317  }
96318  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
96319 #endif
96320 
96321 #ifdef SQLITE_ENABLE_STAT4
96322  {
96323  tRowcnt nLt = p->current.anLt[p->nCol-1];
96324 
96325  /* Check if this is to be a periodic sample. If so, add it. */
96326  if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
96327  p->current.isPSample = 1;
96328  p->current.iCol = 0;
96329  sampleInsert(p, &p->current, p->nCol-1);
96330  p->current.isPSample = 0;
96331  }
96332 
96333  /* Update the aBest[] array. */
96334  for(i=0; i<(p->nCol-1); i++){
96335  p->current.iCol = i;
96336  if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
96337  sampleCopy(p, &p->aBest[i], &p->current);
96338  }
96339  }
96340  }
96341 #endif
96342 }
96343 static const FuncDef statPushFuncdef = {
96344  2+IsStat34, /* nArg */
96345  SQLITE_UTF8, /* funcFlags */
96346  0, /* pUserData */
96347  0, /* pNext */
96348  statPush, /* xSFunc */
96349  0, /* xFinalize */
96350  "stat_push", /* zName */
96351  {0}
96352 };
96353 
96354 #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
96355 #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
96356 #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
96357 #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
96358 #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
96359 
96360 /*
96361 ** Implementation of the stat_get(P,J) SQL function. This routine is
96362 ** used to query statistical information that has been gathered into
96363 ** the Stat4Accum object by prior calls to stat_push(). The P parameter
96364 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
96365 ** The content to returned is determined by the parameter J
96366 ** which is one of the STAT_GET_xxxx values defined above.
96367 **
96368 ** If neither STAT3 nor STAT4 are enabled, then J is always
96369 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
96370 ** a one-parameter function, stat_get(P), that always returns the
96371 ** stat1 table entry information.
96372 */
96373 static void statGet(
96374  sqlite3_context *context,
96375  int argc,
96376  sqlite3_value **argv
96377 ){
96378  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
96379 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96380  /* STAT3 and STAT4 have a parameter on this routine. */
96381  int eCall = sqlite3_value_int(argv[1]);
96382  assert( argc==2 );
96383  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
96384  || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
96385  || eCall==STAT_GET_NDLT
96386  );
96387  if( eCall==STAT_GET_STAT1 )
96388 #else
96389  assert( argc==1 );
96390 #endif
96391  {
96392  /* Return the value to store in the "stat" column of the sqlite_stat1
96393  ** table for this index.
96394  **
96395  ** The value is a string composed of a list of integers describing
96396  ** the index. The first integer in the list is the total number of
96397  ** entries in the index. There is one additional integer in the list
96398  ** for each indexed column. This additional integer is an estimate of
96399  ** the number of rows matched by a stabbing query on the index using
96400  ** a key with the corresponding number of fields. In other words,
96401  ** if the index is on columns (a,b) and the sqlite_stat1 value is
96402  ** "100 10 2", then SQLite estimates that:
96403  **
96404  ** * the index contains 100 rows,
96405  ** * "WHERE a=?" matches 10 rows, and
96406  ** * "WHERE a=? AND b=?" matches 2 rows.
96407  **
96408  ** If D is the count of distinct values and K is the total number of
96409  ** rows, then each estimate is computed as:
96410  **
96411  ** I = (K+D-1)/D
96412  */
96413  char *z;
96414  int i;
96415 
96416  char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
96417  if( zRet==0 ){
96418  sqlite3_result_error_nomem(context);
96419  return;
96420  }
96421 
96422  sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
96423  z = zRet + sqlite3Strlen30(zRet);
96424  for(i=0; i<p->nKeyCol; i++){
96425  u64 nDistinct = p->current.anDLt[i] + 1;
96426  u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
96427  sqlite3_snprintf(24, z, " %llu", iVal);
96428  z += sqlite3Strlen30(z);
96429  assert( p->current.anEq[i] );
96430  }
96431  assert( z[0]=='\0' && z>zRet );
96432 
96433  sqlite3_result_text(context, zRet, -1, sqlite3_free);
96434  }
96435 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96436  else if( eCall==STAT_GET_ROWID ){
96437  if( p->iGet<0 ){
96438  samplePushPrevious(p, 0);
96439  p->iGet = 0;
96440  }
96441  if( p->iGet<p->nSample ){
96442  Stat4Sample *pS = p->a + p->iGet;
96443  if( pS->nRowid==0 ){
96444  sqlite3_result_int64(context, pS->u.iRowid);
96445  }else{
96446  sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
96447  SQLITE_TRANSIENT);
96448  }
96449  }
96450  }else{
96451  tRowcnt *aCnt = 0;
96452 
96453  assert( p->iGet<p->nSample );
96454  switch( eCall ){
96455  case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
96456  case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
96457  default: {
96458  aCnt = p->a[p->iGet].anDLt;
96459  p->iGet++;
96460  break;
96461  }
96462  }
96463 
96464  if( IsStat3 ){
96465  sqlite3_result_int64(context, (i64)aCnt[0]);
96466  }else{
96467  char *zRet = sqlite3MallocZero(p->nCol * 25);
96468  if( zRet==0 ){
96469  sqlite3_result_error_nomem(context);
96470  }else{
96471  int i;
96472  char *z = zRet;
96473  for(i=0; i<p->nCol; i++){
96474  sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
96475  z += sqlite3Strlen30(z);
96476  }
96477  assert( z[0]=='\0' && z>zRet );
96478  z[-1] = '\0';
96479  sqlite3_result_text(context, zRet, -1, sqlite3_free);
96480  }
96481  }
96482  }
96483 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96484 #ifndef SQLITE_DEBUG
96485  UNUSED_PARAMETER( argc );
96486 #endif
96487 }
96488 static const FuncDef statGetFuncdef = {
96489  1+IsStat34, /* nArg */
96490  SQLITE_UTF8, /* funcFlags */
96491  0, /* pUserData */
96492  0, /* pNext */
96493  statGet, /* xSFunc */
96494  0, /* xFinalize */
96495  "stat_get", /* zName */
96496  {0}
96497 };
96498 
96499 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
96500  assert( regOut!=regStat4 && regOut!=regStat4+1 );
96501 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96502  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
96503 #elif SQLITE_DEBUG
96504  assert( iParam==STAT_GET_STAT1 );
96505 #else
96506  UNUSED_PARAMETER( iParam );
96507 #endif
96508  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
96509  (char*)&statGetFuncdef, P4_FUNCDEF);
96510  sqlite3VdbeChangeP5(v, 1 + IsStat34);
96511 }
96512 
96513 /*
96514 ** Generate code to do an analysis of all indices associated with
96515 ** a single table.
96516 */
96517 static void analyzeOneTable(
96518  Parse *pParse, /* Parser context */
96519  Table *pTab, /* Table whose indices are to be analyzed */
96520  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
96521  int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
96522  int iMem, /* Available memory locations begin here */
96523  int iTab /* Next available cursor */
96524 ){
96525  sqlite3 *db = pParse->db; /* Database handle */
96526  Index *pIdx; /* An index to being analyzed */
96527  int iIdxCur; /* Cursor open on index being analyzed */
96528  int iTabCur; /* Table cursor */
96529  Vdbe *v; /* The virtual machine being built up */
96530  int i; /* Loop counter */
96531  int jZeroRows = -1; /* Jump from here if number of rows is zero */
96532  int iDb; /* Index of database containing pTab */
96533  u8 needTableCnt = 1; /* True to count the table */
96534  int regNewRowid = iMem++; /* Rowid for the inserted record */
96535  int regStat4 = iMem++; /* Register to hold Stat4Accum object */
96536  int regChng = iMem++; /* Index of changed index field */
96537 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96538  int regRowid = iMem++; /* Rowid argument passed to stat_push() */
96539 #endif
96540  int regTemp = iMem++; /* Temporary use register */
96541  int regTabname = iMem++; /* Register containing table name */
96542  int regIdxname = iMem++; /* Register containing index name */
96543  int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
96544  int regPrev = iMem; /* MUST BE LAST (see below) */
96545 
96546  pParse->nMem = MAX(pParse->nMem, iMem);
96547  v = sqlite3GetVdbe(pParse);
96548  if( v==0 || NEVER(pTab==0) ){
96549  return;
96550  }
96551  if( pTab->tnum==0 ){
96552  /* Do not gather statistics on views or virtual tables */
96553  return;
96554  }
96555  if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
96556  /* Do not gather statistics on system tables */
96557  return;
96558  }
96559  assert( sqlite3BtreeHoldsAllMutexes(db) );
96560  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
96561  assert( iDb>=0 );
96562  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96563 #ifndef SQLITE_OMIT_AUTHORIZATION
96564  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
96565  db->aDb[iDb].zDbSName ) ){
96566  return;
96567  }
96568 #endif
96569 
96570  /* Establish a read-lock on the table at the shared-cache level.
96571  ** Open a read-only cursor on the table. Also allocate a cursor number
96572  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
96573  ** this time though. */
96574  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
96575  iTabCur = iTab++;
96576  iIdxCur = iTab++;
96577  pParse->nTab = MAX(pParse->nTab, iTab);
96578  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
96579  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
96580 
96581  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96582  int nCol; /* Number of columns in pIdx. "N" */
96583  int addrRewind; /* Address of "OP_Rewind iIdxCur" */
96584  int addrNextRow; /* Address of "next_row:" */
96585  const char *zIdxName; /* Name of the index */
96586  int nColTest; /* Number of columns to test for changes */
96587 
96588  if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
96589  if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
96590  if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
96591  nCol = pIdx->nKeyCol;
96592  zIdxName = pTab->zName;
96593  nColTest = nCol - 1;
96594  }else{
96595  nCol = pIdx->nColumn;
96596  zIdxName = pIdx->zName;
96597  nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
96598  }
96599 
96600  /* Populate the register containing the index name. */
96601  sqlite3VdbeLoadString(v, regIdxname, zIdxName);
96602  VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
96603 
96604  /*
96605  ** Pseudo-code for loop that calls stat_push():
96606  **
96607  ** Rewind csr
96608  ** if eof(csr) goto end_of_scan;
96609  ** regChng = 0
96610  ** goto chng_addr_0;
96611  **
96612  ** next_row:
96613  ** regChng = 0
96614  ** if( idx(0) != regPrev(0) ) goto chng_addr_0
96615  ** regChng = 1
96616  ** if( idx(1) != regPrev(1) ) goto chng_addr_1
96617  ** ...
96618  ** regChng = N
96619  ** goto chng_addr_N
96620  **
96621  ** chng_addr_0:
96622  ** regPrev(0) = idx(0)
96623  ** chng_addr_1:
96624  ** regPrev(1) = idx(1)
96625  ** ...
96626  **
96627  ** endDistinctTest:
96628  ** regRowid = idx(rowid)
96629  ** stat_push(P, regChng, regRowid)
96630  ** Next csr
96631  ** if !eof(csr) goto next_row;
96632  **
96633  ** end_of_scan:
96634  */
96635 
96636  /* Make sure there are enough memory cells allocated to accommodate
96637  ** the regPrev array and a trailing rowid (the rowid slot is required
96638  ** when building a record to insert into the sample column of
96639  ** the sqlite_stat4 table. */
96640  pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
96641 
96642  /* Open a read-only cursor on the index being analyzed. */
96643  assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
96644  sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
96645  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
96646  VdbeComment((v, "%s", pIdx->zName));
96647 
96648  /* Invoke the stat_init() function. The arguments are:
96649  **
96650  ** (1) the number of columns in the index including the rowid
96651  ** (or for a WITHOUT ROWID table, the number of PK columns),
96652  ** (2) the number of columns in the key without the rowid/pk
96653  ** (3) the number of rows in the index,
96654  **
96655  **
96656  ** The third argument is only used for STAT3 and STAT4
96657  */
96658 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96659  sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
96660 #endif
96661  sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
96662  sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
96663  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
96664  (char*)&statInitFuncdef, P4_FUNCDEF);
96665  sqlite3VdbeChangeP5(v, 2+IsStat34);
96666 
96667  /* Implementation of the following:
96668  **
96669  ** Rewind csr
96670  ** if eof(csr) goto end_of_scan;
96671  ** regChng = 0
96672  ** goto next_push_0;
96673  **
96674  */
96675  addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
96676  VdbeCoverage(v);
96677  sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
96678  addrNextRow = sqlite3VdbeCurrentAddr(v);
96679 
96680  if( nColTest>0 ){
96681  int endDistinctTest = sqlite3VdbeMakeLabel(v);
96682  int *aGotoChng; /* Array of jump instruction addresses */
96683  aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
96684  if( aGotoChng==0 ) continue;
96685 
96686  /*
96687  ** next_row:
96688  ** regChng = 0
96689  ** if( idx(0) != regPrev(0) ) goto chng_addr_0
96690  ** regChng = 1
96691  ** if( idx(1) != regPrev(1) ) goto chng_addr_1
96692  ** ...
96693  ** regChng = N
96694  ** goto endDistinctTest
96695  */
96696  sqlite3VdbeAddOp0(v, OP_Goto);
96697  addrNextRow = sqlite3VdbeCurrentAddr(v);
96698  if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
96699  /* For a single-column UNIQUE index, once we have found a non-NULL
96700  ** row, we know that all the rest will be distinct, so skip
96701  ** subsequent distinctness tests. */
96702  sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
96703  VdbeCoverage(v);
96704  }
96705  for(i=0; i<nColTest; i++){
96706  char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
96707  sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
96708  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
96709  aGotoChng[i] =
96710  sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
96711  sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
96712  VdbeCoverage(v);
96713  }
96714  sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
96715  sqlite3VdbeGoto(v, endDistinctTest);
96716 
96717 
96718  /*
96719  ** chng_addr_0:
96720  ** regPrev(0) = idx(0)
96721  ** chng_addr_1:
96722  ** regPrev(1) = idx(1)
96723  ** ...
96724  */
96725  sqlite3VdbeJumpHere(v, addrNextRow-1);
96726  for(i=0; i<nColTest; i++){
96727  sqlite3VdbeJumpHere(v, aGotoChng[i]);
96728  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
96729  }
96730  sqlite3VdbeResolveLabel(v, endDistinctTest);
96731  sqlite3DbFree(db, aGotoChng);
96732  }
96733 
96734  /*
96735  ** chng_addr_N:
96736  ** regRowid = idx(rowid) // STAT34 only
96737  ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
96738  ** Next csr
96739  ** if !eof(csr) goto next_row;
96740  */
96741 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96742  assert( regRowid==(regStat4+2) );
96743  if( HasRowid(pTab) ){
96744  sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
96745  }else{
96746  Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
96747  int j, k, regKey;
96748  regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
96749  for(j=0; j<pPk->nKeyCol; j++){
96750  k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
96751  assert( k>=0 && k<pTab->nCol );
96752  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
96753  VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
96754  }
96755  sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
96756  sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
96757  }
96758 #endif
96759  assert( regChng==(regStat4+1) );
96760  sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
96761  (char*)&statPushFuncdef, P4_FUNCDEF);
96762  sqlite3VdbeChangeP5(v, 2+IsStat34);
96763  sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
96764 
96765  /* Add the entry to the stat1 table. */
96766  callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
96767  assert( "BBB"[0]==SQLITE_AFF_TEXT );
96768  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
96769  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
96770  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
96771  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96772 
96773  /* Add the entries to the stat3 or stat4 table. */
96774 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96775  {
96776  int regEq = regStat1;
96777  int regLt = regStat1+1;
96778  int regDLt = regStat1+2;
96779  int regSample = regStat1+3;
96780  int regCol = regStat1+4;
96781  int regSampleRowid = regCol + nCol;
96782  int addrNext;
96783  int addrIsNull;
96784  u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
96785 
96786  pParse->nMem = MAX(pParse->nMem, regCol+nCol);
96787 
96788  addrNext = sqlite3VdbeCurrentAddr(v);
96789  callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
96790  addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
96791  VdbeCoverage(v);
96792  callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
96793  callStatGet(v, regStat4, STAT_GET_NLT, regLt);
96794  callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
96795  sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
96796  /* We know that the regSampleRowid row exists because it was read by
96797  ** the previous loop. Thus the not-found jump of seekOp will never
96798  ** be taken */
96799  VdbeCoverageNeverTaken(v);
96800 #ifdef SQLITE_ENABLE_STAT3
96801  sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
96802 #else
96803  for(i=0; i<nCol; i++){
96804  sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
96805  }
96806  sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
96807 #endif
96808  sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
96809  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
96810  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
96811  sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
96812  sqlite3VdbeJumpHere(v, addrIsNull);
96813  }
96814 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96815 
96816  /* End of analysis */
96817  sqlite3VdbeJumpHere(v, addrRewind);
96818  }
96819 
96820 
96821  /* Create a single sqlite_stat1 entry containing NULL as the index
96822  ** name and the row count as the content.
96823  */
96824  if( pOnlyIdx==0 && needTableCnt ){
96825  VdbeComment((v, "%s", pTab->zName));
96826  sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
96827  jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
96828  sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
96829  assert( "BBB"[0]==SQLITE_AFF_TEXT );
96830  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
96831  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
96832  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
96833  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96834  sqlite3VdbeJumpHere(v, jZeroRows);
96835  }
96836 }
96837 
96838 
96839 /*
96840 ** Generate code that will cause the most recent index analysis to
96841 ** be loaded into internal hash tables where is can be used.
96842 */
96843 static void loadAnalysis(Parse *pParse, int iDb){
96844  Vdbe *v = sqlite3GetVdbe(pParse);
96845  if( v ){
96846  sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
96847  }
96848 }
96849 
96850 /*
96851 ** Generate code that will do an analysis of an entire database
96852 */
96853 static void analyzeDatabase(Parse *pParse, int iDb){
96854  sqlite3 *db = pParse->db;
96855  Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
96856  HashElem *k;
96857  int iStatCur;
96858  int iMem;
96859  int iTab;
96860 
96861  sqlite3BeginWriteOperation(pParse, 0, iDb);
96862  iStatCur = pParse->nTab;
96863  pParse->nTab += 3;
96864  openStatTable(pParse, iDb, iStatCur, 0, 0);
96865  iMem = pParse->nMem+1;
96866  iTab = pParse->nTab;
96867  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96868  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
96869  Table *pTab = (Table*)sqliteHashData(k);
96870  analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
96871  }
96872  loadAnalysis(pParse, iDb);
96873 }
96874 
96875 /*
96876 ** Generate code that will do an analysis of a single table in
96877 ** a database. If pOnlyIdx is not NULL then it is a single index
96878 ** in pTab that should be analyzed.
96879 */
96880 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
96881  int iDb;
96882  int iStatCur;
96883 
96884  assert( pTab!=0 );
96885  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
96886  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
96887  sqlite3BeginWriteOperation(pParse, 0, iDb);
96888  iStatCur = pParse->nTab;
96889  pParse->nTab += 3;
96890  if( pOnlyIdx ){
96891  openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
96892  }else{
96893  openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
96894  }
96895  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
96896  loadAnalysis(pParse, iDb);
96897 }
96898 
96899 /*
96900 ** Generate code for the ANALYZE command. The parser calls this routine
96901 ** when it recognizes an ANALYZE command.
96902 **
96903 ** ANALYZE -- 1
96904 ** ANALYZE <database> -- 2
96905 ** ANALYZE ?<database>.?<tablename> -- 3
96906 **
96907 ** Form 1 causes all indices in all attached databases to be analyzed.
96908 ** Form 2 analyzes all indices the single database named.
96909 ** Form 3 analyzes all indices associated with the named table.
96910 */
96911 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
96912  sqlite3 *db = pParse->db;
96913  int iDb;
96914  int i;
96915  char *z, *zDb;
96916  Table *pTab;
96917  Index *pIdx;
96918  Token *pTableName;
96919  Vdbe *v;
96920 
96921  /* Read the database schema. If an error occurs, leave an error message
96922  ** and code in pParse and return NULL. */
96923  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
96924  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
96925  return;
96926  }
96927 
96928  assert( pName2!=0 || pName1==0 );
96929  if( pName1==0 ){
96930  /* Form 1: Analyze everything */
96931  for(i=0; i<db->nDb; i++){
96932  if( i==1 ) continue; /* Do not analyze the TEMP database */
96933  analyzeDatabase(pParse, i);
96934  }
96935  }else if( pName2->n==0 ){
96936  /* Form 2: Analyze the database or table named */
96937  iDb = sqlite3FindDb(db, pName1);
96938  if( iDb>=0 ){
96939  analyzeDatabase(pParse, iDb);
96940  }else{
96941  z = sqlite3NameFromToken(db, pName1);
96942  if( z ){
96943  if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
96944  analyzeTable(pParse, pIdx->pTable, pIdx);
96945  }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
96946  analyzeTable(pParse, pTab, 0);
96947  }
96948  sqlite3DbFree(db, z);
96949  }
96950  }
96951  }else{
96952  /* Form 3: Analyze the fully qualified table name */
96953  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
96954  if( iDb>=0 ){
96955  zDb = db->aDb[iDb].zDbSName;
96956  z = sqlite3NameFromToken(db, pTableName);
96957  if( z ){
96958  if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
96959  analyzeTable(pParse, pIdx->pTable, pIdx);
96960  }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
96961  analyzeTable(pParse, pTab, 0);
96962  }
96963  sqlite3DbFree(db, z);
96964  }
96965  }
96966  }
96967  v = sqlite3GetVdbe(pParse);
96968  if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
96969 }
96970 
96971 /*
96972 ** Used to pass information from the analyzer reader through to the
96973 ** callback routine.
96974 */
96975 typedef struct analysisInfo analysisInfo;
96976 struct analysisInfo {
96977  sqlite3 *db;
96978  const char *zDatabase;
96979 };
96980 
96981 /*
96982 ** The first argument points to a nul-terminated string containing a
96983 ** list of space separated integers. Read the first nOut of these into
96984 ** the array aOut[].
96985 */
96986 static void decodeIntArray(
96987  char *zIntArray, /* String containing int array to decode */
96988  int nOut, /* Number of slots in aOut[] */
96989  tRowcnt *aOut, /* Store integers here */
96990  LogEst *aLog, /* Or, if aOut==0, here */
96991  Index *pIndex /* Handle extra flags for this index, if not NULL */
96992 ){
96993  char *z = zIntArray;
96994  int c;
96995  int i;
96996  tRowcnt v;
96997 
96998 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96999  if( z==0 ) z = "";
97000 #else
97001  assert( z!=0 );
97002 #endif
97003  for(i=0; *z && i<nOut; i++){
97004  v = 0;
97005  while( (c=z[0])>='0' && c<='9' ){
97006  v = v*10 + c - '0';
97007  z++;
97008  }
97009 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97010  if( aOut ) aOut[i] = v;
97011  if( aLog ) aLog[i] = sqlite3LogEst(v);
97012 #else
97013  assert( aOut==0 );
97014  UNUSED_PARAMETER(aOut);
97015  assert( aLog!=0 );
97016  aLog[i] = sqlite3LogEst(v);
97017 #endif
97018  if( *z==' ' ) z++;
97019  }
97020 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
97021  assert( pIndex!=0 ); {
97022 #else
97023  if( pIndex ){
97024 #endif
97025  pIndex->bUnordered = 0;
97026  pIndex->noSkipScan = 0;
97027  while( z[0] ){
97028  if( sqlite3_strglob("unordered*", z)==0 ){
97029  pIndex->bUnordered = 1;
97030  }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
97031  pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
97032  }else if( sqlite3_strglob("noskipscan*", z)==0 ){
97033  pIndex->noSkipScan = 1;
97034  }
97035 #ifdef SQLITE_ENABLE_COSTMULT
97036  else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
97037  pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
97038  }
97039 #endif
97040  while( z[0]!=0 && z[0]!=' ' ) z++;
97041  while( z[0]==' ' ) z++;
97042  }
97043  }
97044 }
97045 
97046 /*
97047 ** This callback is invoked once for each index when reading the
97048 ** sqlite_stat1 table.
97049 **
97050 ** argv[0] = name of the table
97051 ** argv[1] = name of the index (might be NULL)
97052 ** argv[2] = results of analysis - on integer for each column
97053 **
97054 ** Entries for which argv[1]==NULL simply record the number of rows in
97055 ** the table.
97056 */
97057 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
97058  analysisInfo *pInfo = (analysisInfo*)pData;
97059  Index *pIndex;
97060  Table *pTable;
97061  const char *z;
97062 
97063  assert( argc==3 );
97064  UNUSED_PARAMETER2(NotUsed, argc);
97065 
97066  if( argv==0 || argv[0]==0 || argv[2]==0 ){
97067  return 0;
97068  }
97069  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
97070  if( pTable==0 ){
97071  return 0;
97072  }
97073  if( argv[1]==0 ){
97074  pIndex = 0;
97075  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
97076  pIndex = sqlite3PrimaryKeyIndex(pTable);
97077  }else{
97078  pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
97079  }
97080  z = argv[2];
97081 
97082  if( pIndex ){
97083  tRowcnt *aiRowEst = 0;
97084  int nCol = pIndex->nKeyCol+1;
97085 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97086  /* Index.aiRowEst may already be set here if there are duplicate
97087  ** sqlite_stat1 entries for this index. In that case just clobber
97088  ** the old data with the new instead of allocating a new array. */
97089  if( pIndex->aiRowEst==0 ){
97090  pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
97091  if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
97092  }
97093  aiRowEst = pIndex->aiRowEst;
97094 #endif
97095  pIndex->bUnordered = 0;
97096  decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
97097  if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
97098  }else{
97099  Index fakeIdx;
97100  fakeIdx.szIdxRow = pTable->szTabRow;
97101 #ifdef SQLITE_ENABLE_COSTMULT
97102  fakeIdx.pTable = pTable;
97103 #endif
97104  decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
97105  pTable->szTabRow = fakeIdx.szIdxRow;
97106  }
97107 
97108  return 0;
97109 }
97110 
97111 /*
97112 ** If the Index.aSample variable is not NULL, delete the aSample[] array
97113 ** and its contents.
97114 */
97115 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
97116 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97117  if( pIdx->aSample ){
97118  int j;
97119  for(j=0; j<pIdx->nSample; j++){
97120  IndexSample *p = &pIdx->aSample[j];
97121  sqlite3DbFree(db, p->p);
97122  }
97123  sqlite3DbFree(db, pIdx->aSample);
97124  }
97125  if( db && db->pnBytesFreed==0 ){
97126  pIdx->nSample = 0;
97127  pIdx->aSample = 0;
97128  }
97129 #else
97130  UNUSED_PARAMETER(db);
97131  UNUSED_PARAMETER(pIdx);
97132 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
97133 }
97134 
97135 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97136 /*
97137 ** Populate the pIdx->aAvgEq[] array based on the samples currently
97138 ** stored in pIdx->aSample[].
97139 */
97140 static void initAvgEq(Index *pIdx){
97141  if( pIdx ){
97142  IndexSample *aSample = pIdx->aSample;
97143  IndexSample *pFinal = &aSample[pIdx->nSample-1];
97144  int iCol;
97145  int nCol = 1;
97146  if( pIdx->nSampleCol>1 ){
97147  /* If this is stat4 data, then calculate aAvgEq[] values for all
97148  ** sample columns except the last. The last is always set to 1, as
97149  ** once the trailing PK fields are considered all index keys are
97150  ** unique. */
97151  nCol = pIdx->nSampleCol-1;
97152  pIdx->aAvgEq[nCol] = 1;
97153  }
97154  for(iCol=0; iCol<nCol; iCol++){
97155  int nSample = pIdx->nSample;
97156  int i; /* Used to iterate through samples */
97157  tRowcnt sumEq = 0; /* Sum of the nEq values */
97158  tRowcnt avgEq = 0;
97159  tRowcnt nRow; /* Number of rows in index */
97160  i64 nSum100 = 0; /* Number of terms contributing to sumEq */
97161  i64 nDist100; /* Number of distinct values in index */
97162 
97163  if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
97164  nRow = pFinal->anLt[iCol];
97165  nDist100 = (i64)100 * pFinal->anDLt[iCol];
97166  nSample--;
97167  }else{
97168  nRow = pIdx->aiRowEst[0];
97169  nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
97170  }
97171  pIdx->nRowEst0 = nRow;
97172 
97173  /* Set nSum to the number of distinct (iCol+1) field prefixes that
97174  ** occur in the stat4 table for this index. Set sumEq to the sum of
97175  ** the nEq values for column iCol for the same set (adding the value
97176  ** only once where there exist duplicate prefixes). */
97177  for(i=0; i<nSample; i++){
97178  if( i==(pIdx->nSample-1)
97179  || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
97180  ){
97181  sumEq += aSample[i].anEq[iCol];
97182  nSum100 += 100;
97183  }
97184  }
97185 
97186  if( nDist100>nSum100 ){
97187  avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
97188  }
97189  if( avgEq==0 ) avgEq = 1;
97190  pIdx->aAvgEq[iCol] = avgEq;
97191  }
97192  }
97193 }
97194 
97195 /*
97196 ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
97197 ** is supplied instead, find the PRIMARY KEY index for that table.
97198 */
97199 static Index *findIndexOrPrimaryKey(
97200  sqlite3 *db,
97201  const char *zName,
97202  const char *zDb
97203 ){
97204  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
97205  if( pIdx==0 ){
97206  Table *pTab = sqlite3FindTable(db, zName, zDb);
97207  if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
97208  }
97209  return pIdx;
97210 }
97211 
97212 /*
97213 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
97214 ** into the relevant Index.aSample[] arrays.
97215 **
97216 ** Arguments zSql1 and zSql2 must point to SQL statements that return
97217 ** data equivalent to the following (statements are different for stat3,
97218 ** see the caller of this function for details):
97219 **
97220 ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
97221 ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
97222 **
97223 ** where %Q is replaced with the database name before the SQL is executed.
97224 */
97225 static int loadStatTbl(
97226  sqlite3 *db, /* Database handle */
97227  int bStat3, /* Assume single column records only */
97228  const char *zSql1, /* SQL statement 1 (see above) */
97229  const char *zSql2, /* SQL statement 2 (see above) */
97230  const char *zDb /* Database name (e.g. "main") */
97231 ){
97232  int rc; /* Result codes from subroutines */
97233  sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
97234  char *zSql; /* Text of the SQL statement */
97235  Index *pPrevIdx = 0; /* Previous index in the loop */
97236  IndexSample *pSample; /* A slot in pIdx->aSample[] */
97237 
97238  assert( db->lookaside.bDisable );
97239  zSql = sqlite3MPrintf(db, zSql1, zDb);
97240  if( !zSql ){
97241  return SQLITE_NOMEM_BKPT;
97242  }
97243  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
97244  sqlite3DbFree(db, zSql);
97245  if( rc ) return rc;
97246 
97247  while( sqlite3_step(pStmt)==SQLITE_ROW ){
97248  int nIdxCol = 1; /* Number of columns in stat4 records */
97249 
97250  char *zIndex; /* Index name */
97251  Index *pIdx; /* Pointer to the index object */
97252  int nSample; /* Number of samples */
97253  int nByte; /* Bytes of space required */
97254  int i; /* Bytes of space required */
97255  tRowcnt *pSpace;
97256 
97257  zIndex = (char *)sqlite3_column_text(pStmt, 0);
97258  if( zIndex==0 ) continue;
97259  nSample = sqlite3_column_int(pStmt, 1);
97260  pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
97261  assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
97262  /* Index.nSample is non-zero at this point if data has already been
97263  ** loaded from the stat4 table. In this case ignore stat3 data. */
97264  if( pIdx==0 || pIdx->nSample ) continue;
97265  if( bStat3==0 ){
97266  assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
97267  if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
97268  nIdxCol = pIdx->nKeyCol;
97269  }else{
97270  nIdxCol = pIdx->nColumn;
97271  }
97272  }
97273  pIdx->nSampleCol = nIdxCol;
97274  nByte = sizeof(IndexSample) * nSample;
97275  nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
97276  nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
97277 
97278  pIdx->aSample = sqlite3DbMallocZero(db, nByte);
97279  if( pIdx->aSample==0 ){
97280  sqlite3_finalize(pStmt);
97281  return SQLITE_NOMEM_BKPT;
97282  }
97283  pSpace = (tRowcnt*)&pIdx->aSample[nSample];
97284  pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
97285  for(i=0; i<nSample; i++){
97286  pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
97287  pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
97288  pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
97289  }
97290  assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
97291  }
97292  rc = sqlite3_finalize(pStmt);
97293  if( rc ) return rc;
97294 
97295  zSql = sqlite3MPrintf(db, zSql2, zDb);
97296  if( !zSql ){
97297  return SQLITE_NOMEM_BKPT;
97298  }
97299  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
97300  sqlite3DbFree(db, zSql);
97301  if( rc ) return rc;
97302 
97303  while( sqlite3_step(pStmt)==SQLITE_ROW ){
97304  char *zIndex; /* Index name */
97305  Index *pIdx; /* Pointer to the index object */
97306  int nCol = 1; /* Number of columns in index */
97307 
97308  zIndex = (char *)sqlite3_column_text(pStmt, 0);
97309  if( zIndex==0 ) continue;
97310  pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
97311  if( pIdx==0 ) continue;
97312  /* This next condition is true if data has already been loaded from
97313  ** the sqlite_stat4 table. In this case ignore stat3 data. */
97314  nCol = pIdx->nSampleCol;
97315  if( bStat3 && nCol>1 ) continue;
97316  if( pIdx!=pPrevIdx ){
97317  initAvgEq(pPrevIdx);
97318  pPrevIdx = pIdx;
97319  }
97320  pSample = &pIdx->aSample[pIdx->nSample];
97321  decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
97322  decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
97323  decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
97324 
97325  /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
97326  ** This is in case the sample record is corrupted. In that case, the
97327  ** sqlite3VdbeRecordCompare() may read up to two varints past the
97328  ** end of the allocated buffer before it realizes it is dealing with
97329  ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
97330  ** a buffer overread. */
97331  pSample->n = sqlite3_column_bytes(pStmt, 4);
97332  pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
97333  if( pSample->p==0 ){
97334  sqlite3_finalize(pStmt);
97335  return SQLITE_NOMEM_BKPT;
97336  }
97337  memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
97338  pIdx->nSample++;
97339  }
97340  rc = sqlite3_finalize(pStmt);
97341  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
97342  return rc;
97343 }
97344 
97345 /*
97346 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
97347 ** the Index.aSample[] arrays of all indices.
97348 */
97349 static int loadStat4(sqlite3 *db, const char *zDb){
97350  int rc = SQLITE_OK; /* Result codes from subroutines */
97351 
97352  assert( db->lookaside.bDisable );
97353  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
97354  rc = loadStatTbl(db, 0,
97355  "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
97356  "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
97357  zDb
97358  );
97359  }
97360 
97361  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
97362  rc = loadStatTbl(db, 1,
97363  "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
97364  "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
97365  zDb
97366  );
97367  }
97368 
97369  return rc;
97370 }
97371 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
97372 
97373 /*
97374 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
97375 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
97376 ** arrays. The contents of sqlite_stat3/4 are used to populate the
97377 ** Index.aSample[] arrays.
97378 **
97379 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
97380 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
97381 ** during compilation and the sqlite_stat3/4 table is present, no data is
97382 ** read from it.
97383 **
97384 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
97385 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
97386 ** returned. However, in this case, data is read from the sqlite_stat1
97387 ** table (if it is present) before returning.
97388 **
97389 ** If an OOM error occurs, this function always sets db->mallocFailed.
97390 ** This means if the caller does not care about other errors, the return
97391 ** code may be ignored.
97392 */
97393 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
97394  analysisInfo sInfo;
97395  HashElem *i;
97396  char *zSql;
97397  int rc = SQLITE_OK;
97398 
97399  assert( iDb>=0 && iDb<db->nDb );
97400  assert( db->aDb[iDb].pBt!=0 );
97401 
97402  /* Clear any prior statistics */
97403  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97404  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
97405  Index *pIdx = sqliteHashData(i);
97406  pIdx->aiRowLogEst[0] = 0;
97407 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97408  sqlite3DeleteIndexSamples(db, pIdx);
97409  pIdx->aSample = 0;
97410 #endif
97411  }
97412 
97413  /* Load new statistics out of the sqlite_stat1 table */
97414  sInfo.db = db;
97415  sInfo.zDatabase = db->aDb[iDb].zDbSName;
97416  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
97417  zSql = sqlite3MPrintf(db,
97418  "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
97419  if( zSql==0 ){
97420  rc = SQLITE_NOMEM_BKPT;
97421  }else{
97422  rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
97423  sqlite3DbFree(db, zSql);
97424  }
97425  }
97426 
97427  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
97428  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97429  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
97430  Index *pIdx = sqliteHashData(i);
97431  if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx);
97432  }
97433 
97434  /* Load the statistics from the sqlite_stat4 table. */
97435 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97436  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
97437  db->lookaside.bDisable++;
97438  rc = loadStat4(db, sInfo.zDatabase);
97439  db->lookaside.bDisable--;
97440  }
97441  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
97442  Index *pIdx = sqliteHashData(i);
97443  sqlite3_free(pIdx->aiRowEst);
97444  pIdx->aiRowEst = 0;
97445  }
97446 #endif
97447 
97448  if( rc==SQLITE_NOMEM ){
97449  sqlite3OomFault(db);
97450  }
97451  return rc;
97452 }
97453 
97454 
97455 #endif /* SQLITE_OMIT_ANALYZE */
97456 
97457 /************** End of analyze.c *********************************************/
97458 /************** Begin file attach.c ******************************************/
97459 /*
97460 ** 2003 April 6
97461 **
97462 ** The author disclaims copyright to this source code. In place of
97463 ** a legal notice, here is a blessing:
97464 **
97465 ** May you do good and not evil.
97466 ** May you find forgiveness for yourself and forgive others.
97467 ** May you share freely, never taking more than you give.
97468 **
97469 *************************************************************************
97470 ** This file contains code used to implement the ATTACH and DETACH commands.
97471 */
97472 /* #include "sqliteInt.h" */
97473 
97474 #ifndef SQLITE_OMIT_ATTACH
97475 /*
97476 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
97477 ** is slightly different from resolving a normal SQL expression, because simple
97478 ** identifiers are treated as strings, not possible column names or aliases.
97479 **
97480 ** i.e. if the parser sees:
97481 **
97482 ** ATTACH DATABASE abc AS def
97483 **
97484 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
97485 ** looking for columns of the same name.
97486 **
97487 ** This only applies to the root node of pExpr, so the statement:
97488 **
97489 ** ATTACH DATABASE abc||def AS 'db2'
97490 **
97491 ** will fail because neither abc or def can be resolved.
97492 */
97493 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
97494 {
97495  int rc = SQLITE_OK;
97496  if( pExpr ){
97497  if( pExpr->op!=TK_ID ){
97498  rc = sqlite3ResolveExprNames(pName, pExpr);
97499  }else{
97500  pExpr->op = TK_STRING;
97501  }
97502  }
97503  return rc;
97504 }
97505 
97506 /*
97507 ** An SQL user-function registered to do the work of an ATTACH statement. The
97508 ** three arguments to the function come directly from an attach statement:
97509 **
97510 ** ATTACH DATABASE x AS y KEY z
97511 **
97512 ** SELECT sqlite_attach(x, y, z)
97513 **
97514 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
97515 ** third argument.
97516 */
97517 static void attachFunc(
97518  sqlite3_context *context,
97519  int NotUsed,
97520  sqlite3_value **argv
97521 ){
97522  int i;
97523  int rc = 0;
97524  sqlite3 *db = sqlite3_context_db_handle(context);
97525  const char *zName;
97526  const char *zFile;
97527  char *zPath = 0;
97528  char *zErr = 0;
97529  unsigned int flags;
97530  Db *aNew;
97531  char *zErrDyn = 0;
97532  sqlite3_vfs *pVfs;
97533 
97534  UNUSED_PARAMETER(NotUsed);
97535 
97536  zFile = (const char *)sqlite3_value_text(argv[0]);
97537  zName = (const char *)sqlite3_value_text(argv[1]);
97538  if( zFile==0 ) zFile = "";
97539  if( zName==0 ) zName = "";
97540 
97541  /* Check for the following errors:
97542  **
97543  ** * Too many attached databases,
97544  ** * Transaction currently open
97545  ** * Specified database name already being used.
97546  */
97547  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
97548  zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
97549  db->aLimit[SQLITE_LIMIT_ATTACHED]
97550  );
97551  goto attach_error;
97552  }
97553  if( !db->autoCommit ){
97554  zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
97555  goto attach_error;
97556  }
97557  for(i=0; i<db->nDb; i++){
97558  char *z = db->aDb[i].zDbSName;
97559  assert( z && zName );
97560  if( sqlite3StrICmp(z, zName)==0 ){
97561  zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
97562  goto attach_error;
97563  }
97564  }
97565 
97566  /* Allocate the new entry in the db->aDb[] array and initialize the schema
97567  ** hash tables.
97568  */
97569  if( db->aDb==db->aDbStatic ){
97570  aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
97571  if( aNew==0 ) return;
97572  memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
97573  }else{
97574  aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
97575  if( aNew==0 ) return;
97576  }
97577  db->aDb = aNew;
97578  aNew = &db->aDb[db->nDb];
97579  memset(aNew, 0, sizeof(*aNew));
97580 
97581  /* Open the database file. If the btree is successfully opened, use
97582  ** it to obtain the database schema. At this point the schema may
97583  ** or may not be initialized.
97584  */
97585  flags = db->openFlags;
97586  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
97587  if( rc!=SQLITE_OK ){
97588  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
97589  sqlite3_result_error(context, zErr, -1);
97590  sqlite3_free(zErr);
97591  return;
97592  }
97593  assert( pVfs );
97594  flags |= SQLITE_OPEN_MAIN_DB;
97595  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
97596  sqlite3_free( zPath );
97597  db->nDb++;
97598  if( rc==SQLITE_CONSTRAINT ){
97599  rc = SQLITE_ERROR;
97600  zErrDyn = sqlite3MPrintf(db, "database is already attached");
97601  }else if( rc==SQLITE_OK ){
97602  Pager *pPager;
97603  aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
97604  if( !aNew->pSchema ){
97605  rc = SQLITE_NOMEM_BKPT;
97606  }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
97607  zErrDyn = sqlite3MPrintf(db,
97608  "attached databases must use the same text encoding as main database");
97609  rc = SQLITE_ERROR;
97610  }
97611  sqlite3BtreeEnter(aNew->pBt);
97612  pPager = sqlite3BtreePager(aNew->pBt);
97613  sqlite3PagerLockingMode(pPager, db->dfltLockMode);
97614  sqlite3BtreeSecureDelete(aNew->pBt,
97615  sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
97616 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
97617  sqlite3BtreeSetPagerFlags(aNew->pBt,
97618  PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
97619 #endif
97620  sqlite3BtreeLeave(aNew->pBt);
97621  }
97622  aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
97623  aNew->zDbSName = sqlite3DbStrDup(db, zName);
97624  if( rc==SQLITE_OK && aNew->zDbSName==0 ){
97625  rc = SQLITE_NOMEM_BKPT;
97626  }
97627 
97628 
97629 #ifdef SQLITE_HAS_CODEC
97630  if( rc==SQLITE_OK ){
97631  extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
97632  extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
97633  int nKey;
97634  char *zKey;
97635  int t = sqlite3_value_type(argv[2]);
97636  switch( t ){
97637  case SQLITE_INTEGER:
97638  case SQLITE_FLOAT:
97639  zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
97640  rc = SQLITE_ERROR;
97641  break;
97642 
97643  case SQLITE_TEXT:
97644  case SQLITE_BLOB:
97645  nKey = sqlite3_value_bytes(argv[2]);
97646  zKey = (char *)sqlite3_value_blob(argv[2]);
97647  rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
97648  break;
97649 
97650  case SQLITE_NULL:
97651  /* No key specified. Use the key from the main database */
97652  sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
97653  if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
97654  rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
97655  }
97656  break;
97657  }
97658  }
97659 #endif
97660 
97661  /* If the file was opened successfully, read the schema for the new database.
97662  ** If this fails, or if opening the file failed, then close the file and
97663  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
97664  ** we found it.
97665  */
97666  if( rc==SQLITE_OK ){
97667  sqlite3BtreeEnterAll(db);
97668  rc = sqlite3Init(db, &zErrDyn);
97669  sqlite3BtreeLeaveAll(db);
97670  }
97671 #ifdef SQLITE_USER_AUTHENTICATION
97672  if( rc==SQLITE_OK ){
97673  u8 newAuth = 0;
97674  rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
97675  if( newAuth<db->auth.authLevel ){
97676  rc = SQLITE_AUTH_USER;
97677  }
97678  }
97679 #endif
97680  if( rc ){
97681  int iDb = db->nDb - 1;
97682  assert( iDb>=2 );
97683  if( db->aDb[iDb].pBt ){
97684  sqlite3BtreeClose(db->aDb[iDb].pBt);
97685  db->aDb[iDb].pBt = 0;
97686  db->aDb[iDb].pSchema = 0;
97687  }
97688  sqlite3ResetAllSchemasOfConnection(db);
97689  db->nDb = iDb;
97690  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
97691  sqlite3OomFault(db);
97692  sqlite3DbFree(db, zErrDyn);
97693  zErrDyn = sqlite3MPrintf(db, "out of memory");
97694  }else if( zErrDyn==0 ){
97695  zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
97696  }
97697  goto attach_error;
97698  }
97699 
97700  return;
97701 
97702 attach_error:
97703  /* Return an error if we get here */
97704  if( zErrDyn ){
97705  sqlite3_result_error(context, zErrDyn, -1);
97706  sqlite3DbFree(db, zErrDyn);
97707  }
97708  if( rc ) sqlite3_result_error_code(context, rc);
97709 }
97710 
97711 /*
97712 ** An SQL user-function registered to do the work of an DETACH statement. The
97713 ** three arguments to the function come directly from a detach statement:
97714 **
97715 ** DETACH DATABASE x
97716 **
97717 ** SELECT sqlite_detach(x)
97718 */
97719 static void detachFunc(
97720  sqlite3_context *context,
97721  int NotUsed,
97722  sqlite3_value **argv
97723 ){
97724  const char *zName = (const char *)sqlite3_value_text(argv[0]);
97725  sqlite3 *db = sqlite3_context_db_handle(context);
97726  int i;
97727  Db *pDb = 0;
97728  char zErr[128];
97729 
97730  UNUSED_PARAMETER(NotUsed);
97731 
97732  if( zName==0 ) zName = "";
97733  for(i=0; i<db->nDb; i++){
97734  pDb = &db->aDb[i];
97735  if( pDb->pBt==0 ) continue;
97736  if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
97737  }
97738 
97739  if( i>=db->nDb ){
97740  sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
97741  goto detach_error;
97742  }
97743  if( i<2 ){
97744  sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
97745  goto detach_error;
97746  }
97747  if( !db->autoCommit ){
97748  sqlite3_snprintf(sizeof(zErr), zErr,
97749  "cannot DETACH database within transaction");
97750  goto detach_error;
97751  }
97752  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
97753  sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
97754  goto detach_error;
97755  }
97756 
97757  sqlite3BtreeClose(pDb->pBt);
97758  pDb->pBt = 0;
97759  pDb->pSchema = 0;
97760  sqlite3CollapseDatabaseArray(db);
97761  return;
97762 
97763 detach_error:
97764  sqlite3_result_error(context, zErr, -1);
97765 }
97766 
97767 /*
97768 ** This procedure generates VDBE code for a single invocation of either the
97769 ** sqlite_detach() or sqlite_attach() SQL user functions.
97770 */
97771 static void codeAttach(
97772  Parse *pParse, /* The parser context */
97773  int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
97774  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
97775  Expr *pAuthArg, /* Expression to pass to authorization callback */
97776  Expr *pFilename, /* Name of database file */
97777  Expr *pDbname, /* Name of the database to use internally */
97778  Expr *pKey /* Database key for encryption extension */
97779 ){
97780  int rc;
97781  NameContext sName;
97782  Vdbe *v;
97783  sqlite3* db = pParse->db;
97784  int regArgs;
97785 
97786  memset(&sName, 0, sizeof(NameContext));
97787  sName.pParse = pParse;
97788 
97789  if(
97790  SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
97791  SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
97792  SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
97793  ){
97794  goto attach_end;
97795  }
97796 
97797 #ifndef SQLITE_OMIT_AUTHORIZATION
97798  if( pAuthArg ){
97799  char *zAuthArg;
97800  if( pAuthArg->op==TK_STRING ){
97801  zAuthArg = pAuthArg->u.zToken;
97802  }else{
97803  zAuthArg = 0;
97804  }
97805  rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
97806  if(rc!=SQLITE_OK ){
97807  goto attach_end;
97808  }
97809  }
97810 #endif /* SQLITE_OMIT_AUTHORIZATION */
97811 
97812 
97813  v = sqlite3GetVdbe(pParse);
97814  regArgs = sqlite3GetTempRange(pParse, 4);
97815  sqlite3ExprCode(pParse, pFilename, regArgs);
97816  sqlite3ExprCode(pParse, pDbname, regArgs+1);
97817  sqlite3ExprCode(pParse, pKey, regArgs+2);
97818 
97819  assert( v || db->mallocFailed );
97820  if( v ){
97821  sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
97822  (char *)pFunc, P4_FUNCDEF);
97823  assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
97824  sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
97825 
97826  /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
97827  ** statement only). For DETACH, set it to false (expire all existing
97828  ** statements).
97829  */
97830  sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
97831  }
97832 
97833 attach_end:
97834  sqlite3ExprDelete(db, pFilename);
97835  sqlite3ExprDelete(db, pDbname);
97836  sqlite3ExprDelete(db, pKey);
97837 }
97838 
97839 /*
97840 ** Called by the parser to compile a DETACH statement.
97841 **
97842 ** DETACH pDbname
97843 */
97844 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
97845  static const FuncDef detach_func = {
97846  1, /* nArg */
97847  SQLITE_UTF8, /* funcFlags */
97848  0, /* pUserData */
97849  0, /* pNext */
97850  detachFunc, /* xSFunc */
97851  0, /* xFinalize */
97852  "sqlite_detach", /* zName */
97853  {0}
97854  };
97855  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
97856 }
97857 
97858 /*
97859 ** Called by the parser to compile an ATTACH statement.
97860 **
97861 ** ATTACH p AS pDbname KEY pKey
97862 */
97863 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
97864  static const FuncDef attach_func = {
97865  3, /* nArg */
97866  SQLITE_UTF8, /* funcFlags */
97867  0, /* pUserData */
97868  0, /* pNext */
97869  attachFunc, /* xSFunc */
97870  0, /* xFinalize */
97871  "sqlite_attach", /* zName */
97872  {0}
97873  };
97874  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
97875 }
97876 #endif /* SQLITE_OMIT_ATTACH */
97877 
97878 /*
97879 ** Initialize a DbFixer structure. This routine must be called prior
97880 ** to passing the structure to one of the sqliteFixAAAA() routines below.
97881 */
97882 SQLITE_PRIVATE void sqlite3FixInit(
97883  DbFixer *pFix, /* The fixer to be initialized */
97884  Parse *pParse, /* Error messages will be written here */
97885  int iDb, /* This is the database that must be used */
97886  const char *zType, /* "view", "trigger", or "index" */
97887  const Token *pName /* Name of the view, trigger, or index */
97888 ){
97889  sqlite3 *db;
97890 
97891  db = pParse->db;
97892  assert( db->nDb>iDb );
97893  pFix->pParse = pParse;
97894  pFix->zDb = db->aDb[iDb].zDbSName;
97895  pFix->pSchema = db->aDb[iDb].pSchema;
97896  pFix->zType = zType;
97897  pFix->pName = pName;
97898  pFix->bVarOnly = (iDb==1);
97899 }
97900 
97901 /*
97902 ** The following set of routines walk through the parse tree and assign
97903 ** a specific database to all table references where the database name
97904 ** was left unspecified in the original SQL statement. The pFix structure
97905 ** must have been initialized by a prior call to sqlite3FixInit().
97906 **
97907 ** These routines are used to make sure that an index, trigger, or
97908 ** view in one database does not refer to objects in a different database.
97909 ** (Exception: indices, triggers, and views in the TEMP database are
97910 ** allowed to refer to anything.) If a reference is explicitly made
97911 ** to an object in a different database, an error message is added to
97912 ** pParse->zErrMsg and these routines return non-zero. If everything
97913 ** checks out, these routines return 0.
97914 */
97915 SQLITE_PRIVATE int sqlite3FixSrcList(
97916  DbFixer *pFix, /* Context of the fixation */
97917  SrcList *pList /* The Source list to check and modify */
97918 ){
97919  int i;
97920  const char *zDb;
97921  struct SrcList_item *pItem;
97922 
97923  if( NEVER(pList==0) ) return 0;
97924  zDb = pFix->zDb;
97925  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
97926  if( pFix->bVarOnly==0 ){
97927  if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
97928  sqlite3ErrorMsg(pFix->pParse,
97929  "%s %T cannot reference objects in database %s",
97930  pFix->zType, pFix->pName, pItem->zDatabase);
97931  return 1;
97932  }
97933  sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
97934  pItem->zDatabase = 0;
97935  pItem->pSchema = pFix->pSchema;
97936  }
97937 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
97938  if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
97939  if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
97940 #endif
97941  }
97942  return 0;
97943 }
97944 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
97945 SQLITE_PRIVATE int sqlite3FixSelect(
97946  DbFixer *pFix, /* Context of the fixation */
97947  Select *pSelect /* The SELECT statement to be fixed to one database */
97948 ){
97949  while( pSelect ){
97950  if( sqlite3FixExprList(pFix, pSelect->pEList) ){
97951  return 1;
97952  }
97953  if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
97954  return 1;
97955  }
97956  if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
97957  return 1;
97958  }
97959  if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
97960  return 1;
97961  }
97962  if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
97963  return 1;
97964  }
97965  if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
97966  return 1;
97967  }
97968  if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
97969  return 1;
97970  }
97971  if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
97972  return 1;
97973  }
97974  pSelect = pSelect->pPrior;
97975  }
97976  return 0;
97977 }
97978 SQLITE_PRIVATE int sqlite3FixExpr(
97979  DbFixer *pFix, /* Context of the fixation */
97980  Expr *pExpr /* The expression to be fixed to one database */
97981 ){
97982  while( pExpr ){
97983  if( pExpr->op==TK_VARIABLE ){
97984  if( pFix->pParse->db->init.busy ){
97985  pExpr->op = TK_NULL;
97986  }else{
97987  sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
97988  return 1;
97989  }
97990  }
97991  if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
97992  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97993  if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
97994  }else{
97995  if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
97996  }
97997  if( sqlite3FixExpr(pFix, pExpr->pRight) ){
97998  return 1;
97999  }
98000  pExpr = pExpr->pLeft;
98001  }
98002  return 0;
98003 }
98004 SQLITE_PRIVATE int sqlite3FixExprList(
98005  DbFixer *pFix, /* Context of the fixation */
98006  ExprList *pList /* The expression to be fixed to one database */
98007 ){
98008  int i;
98009  struct ExprList_item *pItem;
98010  if( pList==0 ) return 0;
98011  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
98012  if( sqlite3FixExpr(pFix, pItem->pExpr) ){
98013  return 1;
98014  }
98015  }
98016  return 0;
98017 }
98018 #endif
98019 
98020 #ifndef SQLITE_OMIT_TRIGGER
98021 SQLITE_PRIVATE int sqlite3FixTriggerStep(
98022  DbFixer *pFix, /* Context of the fixation */
98023  TriggerStep *pStep /* The trigger step be fixed to one database */
98024 ){
98025  while( pStep ){
98026  if( sqlite3FixSelect(pFix, pStep->pSelect) ){
98027  return 1;
98028  }
98029  if( sqlite3FixExpr(pFix, pStep->pWhere) ){
98030  return 1;
98031  }
98032  if( sqlite3FixExprList(pFix, pStep->pExprList) ){
98033  return 1;
98034  }
98035  pStep = pStep->pNext;
98036  }
98037  return 0;
98038 }
98039 #endif
98040 
98041 /************** End of attach.c **********************************************/
98042 /************** Begin file auth.c ********************************************/
98043 /*
98044 ** 2003 January 11
98045 **
98046 ** The author disclaims copyright to this source code. In place of
98047 ** a legal notice, here is a blessing:
98048 **
98049 ** May you do good and not evil.
98050 ** May you find forgiveness for yourself and forgive others.
98051 ** May you share freely, never taking more than you give.
98052 **
98053 *************************************************************************
98054 ** This file contains code used to implement the sqlite3_set_authorizer()
98055 ** API. This facility is an optional feature of the library. Embedded
98056 ** systems that do not need this facility may omit it by recompiling
98057 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
98058 */
98059 /* #include "sqliteInt.h" */
98060 
98061 /*
98062 ** All of the code in this file may be omitted by defining a single
98063 ** macro.
98064 */
98065 #ifndef SQLITE_OMIT_AUTHORIZATION
98066 
98067 /*
98068 ** Set or clear the access authorization function.
98069 **
98070 ** The access authorization function is be called during the compilation
98071 ** phase to verify that the user has read and/or write access permission on
98072 ** various fields of the database. The first argument to the auth function
98073 ** is a copy of the 3rd argument to this routine. The second argument
98074 ** to the auth function is one of these constants:
98075 **
98076 ** SQLITE_CREATE_INDEX
98077 ** SQLITE_CREATE_TABLE
98078 ** SQLITE_CREATE_TEMP_INDEX
98079 ** SQLITE_CREATE_TEMP_TABLE
98080 ** SQLITE_CREATE_TEMP_TRIGGER
98081 ** SQLITE_CREATE_TEMP_VIEW
98082 ** SQLITE_CREATE_TRIGGER
98083 ** SQLITE_CREATE_VIEW
98084 ** SQLITE_DELETE
98085 ** SQLITE_DROP_INDEX
98086 ** SQLITE_DROP_TABLE
98087 ** SQLITE_DROP_TEMP_INDEX
98088 ** SQLITE_DROP_TEMP_TABLE
98089 ** SQLITE_DROP_TEMP_TRIGGER
98090 ** SQLITE_DROP_TEMP_VIEW
98091 ** SQLITE_DROP_TRIGGER
98092 ** SQLITE_DROP_VIEW
98093 ** SQLITE_INSERT
98094 ** SQLITE_PRAGMA
98095 ** SQLITE_READ
98096 ** SQLITE_SELECT
98097 ** SQLITE_TRANSACTION
98098 ** SQLITE_UPDATE
98099 **
98100 ** The third and fourth arguments to the auth function are the name of
98101 ** the table and the column that are being accessed. The auth function
98102 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
98103 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
98104 ** means that the SQL statement will never-run - the sqlite3_exec() call
98105 ** will return with an error. SQLITE_IGNORE means that the SQL statement
98106 ** should run but attempts to read the specified column will return NULL
98107 ** and attempts to write the column will be ignored.
98108 **
98109 ** Setting the auth function to NULL disables this hook. The default
98110 ** setting of the auth function is NULL.
98111 */
98112 SQLITE_API int sqlite3_set_authorizer(
98113  sqlite3 *db,
98114  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
98115  void *pArg
98116 ){
98117 #ifdef SQLITE_ENABLE_API_ARMOR
98118  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
98119 #endif
98120  sqlite3_mutex_enter(db->mutex);
98121  db->xAuth = (sqlite3_xauth)xAuth;
98122  db->pAuthArg = pArg;
98123  sqlite3ExpirePreparedStatements(db);
98124  sqlite3_mutex_leave(db->mutex);
98125  return SQLITE_OK;
98126 }
98127 
98128 /*
98129 ** Write an error message into pParse->zErrMsg that explains that the
98130 ** user-supplied authorization function returned an illegal value.
98131 */
98132 static void sqliteAuthBadReturnCode(Parse *pParse){
98133  sqlite3ErrorMsg(pParse, "authorizer malfunction");
98134  pParse->rc = SQLITE_ERROR;
98135 }
98136 
98137 /*
98138 ** Invoke the authorization callback for permission to read column zCol from
98139 ** table zTab in database zDb. This function assumes that an authorization
98140 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
98141 **
98142 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
98143 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
98144 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
98145 */
98146 SQLITE_PRIVATE int sqlite3AuthReadCol(
98147  Parse *pParse, /* The parser context */
98148  const char *zTab, /* Table name */
98149  const char *zCol, /* Column name */
98150  int iDb /* Index of containing database. */
98151 ){
98152  sqlite3 *db = pParse->db; /* Database handle */
98153  char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
98154  int rc; /* Auth callback return code */
98155 
98156  if( db->init.busy ) return SQLITE_OK;
98157  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
98158 #ifdef SQLITE_USER_AUTHENTICATION
98159  ,db->auth.zAuthUser
98160 #endif
98161  );
98162  if( rc==SQLITE_DENY ){
98163  if( db->nDb>2 || iDb!=0 ){
98164  sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
98165  }else{
98166  sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
98167  }
98168  pParse->rc = SQLITE_AUTH;
98169  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
98170  sqliteAuthBadReturnCode(pParse);
98171  }
98172  return rc;
98173 }
98174 
98175 /*
98176 ** The pExpr should be a TK_COLUMN expression. The table referred to
98177 ** is in pTabList or else it is the NEW or OLD table of a trigger.
98178 ** Check to see if it is OK to read this particular column.
98179 **
98180 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
98181 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
98182 ** then generate an error.
98183 */
98184 SQLITE_PRIVATE void sqlite3AuthRead(
98185  Parse *pParse, /* The parser context */
98186  Expr *pExpr, /* The expression to check authorization on */
98187  Schema *pSchema, /* The schema of the expression */
98188  SrcList *pTabList /* All table that pExpr might refer to */
98189 ){
98190  sqlite3 *db = pParse->db;
98191  Table *pTab = 0; /* The table being read */
98192  const char *zCol; /* Name of the column of the table */
98193  int iSrc; /* Index in pTabList->a[] of table being read */
98194  int iDb; /* The index of the database the expression refers to */
98195  int iCol; /* Index of column in table */
98196 
98197  if( db->xAuth==0 ) return;
98198  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
98199  if( iDb<0 ){
98200  /* An attempt to read a column out of a subquery or other
98201  ** temporary table. */
98202  return;
98203  }
98204 
98205  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
98206  if( pExpr->op==TK_TRIGGER ){
98207  pTab = pParse->pTriggerTab;
98208  }else{
98209  assert( pTabList );
98210  for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
98211  if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
98212  pTab = pTabList->a[iSrc].pTab;
98213  break;
98214  }
98215  }
98216  }
98217  iCol = pExpr->iColumn;
98218  if( NEVER(pTab==0) ) return;
98219 
98220  if( iCol>=0 ){
98221  assert( iCol<pTab->nCol );
98222  zCol = pTab->aCol[iCol].zName;
98223  }else if( pTab->iPKey>=0 ){
98224  assert( pTab->iPKey<pTab->nCol );
98225  zCol = pTab->aCol[pTab->iPKey].zName;
98226  }else{
98227  zCol = "ROWID";
98228  }
98229  assert( iDb>=0 && iDb<db->nDb );
98230  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
98231  pExpr->op = TK_NULL;
98232  }
98233 }
98234 
98235 /*
98236 ** Do an authorization check using the code and arguments given. Return
98237 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
98238 ** is returned, then the error count and error message in pParse are
98239 ** modified appropriately.
98240 */
98241 SQLITE_PRIVATE int sqlite3AuthCheck(
98242  Parse *pParse,
98243  int code,
98244  const char *zArg1,
98245  const char *zArg2,
98246  const char *zArg3
98247 ){
98248  sqlite3 *db = pParse->db;
98249  int rc;
98250 
98251  /* Don't do any authorization checks if the database is initialising
98252  ** or if the parser is being invoked from within sqlite3_declare_vtab.
98253  */
98254  if( db->init.busy || IN_DECLARE_VTAB ){
98255  return SQLITE_OK;
98256  }
98257 
98258  if( db->xAuth==0 ){
98259  return SQLITE_OK;
98260  }
98261  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
98262 #ifdef SQLITE_USER_AUTHENTICATION
98263  ,db->auth.zAuthUser
98264 #endif
98265  );
98266  if( rc==SQLITE_DENY ){
98267  sqlite3ErrorMsg(pParse, "not authorized");
98268  pParse->rc = SQLITE_AUTH;
98269  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
98270  rc = SQLITE_DENY;
98271  sqliteAuthBadReturnCode(pParse);
98272  }
98273  return rc;
98274 }
98275 
98276 /*
98277 ** Push an authorization context. After this routine is called, the
98278 ** zArg3 argument to authorization callbacks will be zContext until
98279 ** popped. Or if pParse==0, this routine is a no-op.
98280 */
98281 SQLITE_PRIVATE void sqlite3AuthContextPush(
98282  Parse *pParse,
98283  AuthContext *pContext,
98284  const char *zContext
98285 ){
98286  assert( pParse );
98287  pContext->pParse = pParse;
98288  pContext->zAuthContext = pParse->zAuthContext;
98289  pParse->zAuthContext = zContext;
98290 }
98291 
98292 /*
98293 ** Pop an authorization context that was previously pushed
98294 ** by sqlite3AuthContextPush
98295 */
98296 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
98297  if( pContext->pParse ){
98298  pContext->pParse->zAuthContext = pContext->zAuthContext;
98299  pContext->pParse = 0;
98300  }
98301 }
98302 
98303 #endif /* SQLITE_OMIT_AUTHORIZATION */
98304 
98305 /************** End of auth.c ************************************************/
98306 /************** Begin file build.c *******************************************/
98307 /*
98308 ** 2001 September 15
98309 **
98310 ** The author disclaims copyright to this source code. In place of
98311 ** a legal notice, here is a blessing:
98312 **
98313 ** May you do good and not evil.
98314 ** May you find forgiveness for yourself and forgive others.
98315 ** May you share freely, never taking more than you give.
98316 **
98317 *************************************************************************
98318 ** This file contains C code routines that are called by the SQLite parser
98319 ** when syntax rules are reduced. The routines in this file handle the
98320 ** following kinds of SQL syntax:
98321 **
98322 ** CREATE TABLE
98323 ** DROP TABLE
98324 ** CREATE INDEX
98325 ** DROP INDEX
98326 ** creating ID lists
98327 ** BEGIN TRANSACTION
98328 ** COMMIT
98329 ** ROLLBACK
98330 */
98331 /* #include "sqliteInt.h" */
98332 
98333 #ifndef SQLITE_OMIT_SHARED_CACHE
98334 /*
98335 ** The TableLock structure is only used by the sqlite3TableLock() and
98336 ** codeTableLocks() functions.
98337 */
98338 struct TableLock {
98339  int iDb; /* The database containing the table to be locked */
98340  int iTab; /* The root page of the table to be locked */
98341  u8 isWriteLock; /* True for write lock. False for a read lock */
98342  const char *zName; /* Name of the table */
98343 };
98344 
98345 /*
98346 ** Record the fact that we want to lock a table at run-time.
98347 **
98348 ** The table to be locked has root page iTab and is found in database iDb.
98349 ** A read or a write lock can be taken depending on isWritelock.
98350 **
98351 ** This routine just records the fact that the lock is desired. The
98352 ** code to make the lock occur is generated by a later call to
98353 ** codeTableLocks() which occurs during sqlite3FinishCoding().
98354 */
98355 SQLITE_PRIVATE void sqlite3TableLock(
98356  Parse *pParse, /* Parsing context */
98357  int iDb, /* Index of the database containing the table to lock */
98358  int iTab, /* Root page number of the table to be locked */
98359  u8 isWriteLock, /* True for a write lock */
98360  const char *zName /* Name of the table to be locked */
98361 ){
98362  Parse *pToplevel = sqlite3ParseToplevel(pParse);
98363  int i;
98364  int nBytes;
98365  TableLock *p;
98366  assert( iDb>=0 );
98367 
98368  for(i=0; i<pToplevel->nTableLock; i++){
98369  p = &pToplevel->aTableLock[i];
98370  if( p->iDb==iDb && p->iTab==iTab ){
98371  p->isWriteLock = (p->isWriteLock || isWriteLock);
98372  return;
98373  }
98374  }
98375 
98376  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
98377  pToplevel->aTableLock =
98378  sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
98379  if( pToplevel->aTableLock ){
98380  p = &pToplevel->aTableLock[pToplevel->nTableLock++];
98381  p->iDb = iDb;
98382  p->iTab = iTab;
98383  p->isWriteLock = isWriteLock;
98384  p->zName = zName;
98385  }else{
98386  pToplevel->nTableLock = 0;
98387  sqlite3OomFault(pToplevel->db);
98388  }
98389 }
98390 
98391 /*
98392 ** Code an OP_TableLock instruction for each table locked by the
98393 ** statement (configured by calls to sqlite3TableLock()).
98394 */
98395 static void codeTableLocks(Parse *pParse){
98396  int i;
98397  Vdbe *pVdbe;
98398 
98399  pVdbe = sqlite3GetVdbe(pParse);
98400  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
98401 
98402  for(i=0; i<pParse->nTableLock; i++){
98403  TableLock *p = &pParse->aTableLock[i];
98404  int p1 = p->iDb;
98405  sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
98406  p->zName, P4_STATIC);
98407  }
98408 }
98409 #else
98410  #define codeTableLocks(x)
98411 #endif
98412 
98413 /*
98414 ** Return TRUE if the given yDbMask object is empty - if it contains no
98415 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
98416 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
98417 */
98418 #if SQLITE_MAX_ATTACHED>30
98419 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
98420  int i;
98421  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
98422  return 1;
98423 }
98424 #endif
98425 
98426 /*
98427 ** This routine is called after a single SQL statement has been
98428 ** parsed and a VDBE program to execute that statement has been
98429 ** prepared. This routine puts the finishing touches on the
98430 ** VDBE program and resets the pParse structure for the next
98431 ** parse.
98432 **
98433 ** Note that if an error occurred, it might be the case that
98434 ** no VDBE code was generated.
98435 */
98436 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
98437  sqlite3 *db;
98438  Vdbe *v;
98439 
98440  assert( pParse->pToplevel==0 );
98441  db = pParse->db;
98442  if( pParse->nested ) return;
98443  if( db->mallocFailed || pParse->nErr ){
98444  if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
98445  return;
98446  }
98447 
98448  /* Begin by generating some termination code at the end of the
98449  ** vdbe program
98450  */
98451  v = sqlite3GetVdbe(pParse);
98452  assert( !pParse->isMultiWrite
98453  || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
98454  if( v ){
98455  sqlite3VdbeAddOp0(v, OP_Halt);
98456 
98457 #if SQLITE_USER_AUTHENTICATION
98458  if( pParse->nTableLock>0 && db->init.busy==0 ){
98459  sqlite3UserAuthInit(db);
98460  if( db->auth.authLevel<UAUTH_User ){
98461  sqlite3ErrorMsg(pParse, "user not authenticated");
98462  pParse->rc = SQLITE_AUTH_USER;
98463  return;
98464  }
98465  }
98466 #endif
98467 
98468  /* The cookie mask contains one bit for each database file open.
98469  ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
98470  ** set for each database that is used. Generate code to start a
98471  ** transaction on each used database and to verify the schema cookie
98472  ** on each used database.
98473  */
98474  if( db->mallocFailed==0
98475  && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
98476  ){
98477  int iDb, i;
98478  assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
98479  sqlite3VdbeJumpHere(v, 0);
98480  for(iDb=0; iDb<db->nDb; iDb++){
98481  Schema *pSchema;
98482  if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
98483  sqlite3VdbeUsesBtree(v, iDb);
98484  pSchema = db->aDb[iDb].pSchema;
98485  sqlite3VdbeAddOp4Int(v,
98486  OP_Transaction, /* Opcode */
98487  iDb, /* P1 */
98488  DbMaskTest(pParse->writeMask,iDb), /* P2 */
98489  pSchema->schema_cookie, /* P3 */
98490  pSchema->iGeneration /* P4 */
98491  );
98492  if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
98493  VdbeComment((v,
98494  "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
98495  }
98496 #ifndef SQLITE_OMIT_VIRTUALTABLE
98497  for(i=0; i<pParse->nVtabLock; i++){
98498  char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
98499  sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
98500  }
98501  pParse->nVtabLock = 0;
98502 #endif
98503 
98504  /* Once all the cookies have been verified and transactions opened,
98505  ** obtain the required table-locks. This is a no-op unless the
98506  ** shared-cache feature is enabled.
98507  */
98508  codeTableLocks(pParse);
98509 
98510  /* Initialize any AUTOINCREMENT data structures required.
98511  */
98512  sqlite3AutoincrementBegin(pParse);
98513 
98514  /* Code constant expressions that where factored out of inner loops */
98515  if( pParse->pConstExpr ){
98516  ExprList *pEL = pParse->pConstExpr;
98517  pParse->okConstFactor = 0;
98518  for(i=0; i<pEL->nExpr; i++){
98519  sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
98520  }
98521  }
98522 
98523  /* Finally, jump back to the beginning of the executable code. */
98524  sqlite3VdbeGoto(v, 1);
98525  }
98526  }
98527 
98528 
98529  /* Get the VDBE program ready for execution
98530  */
98531  if( v && pParse->nErr==0 && !db->mallocFailed ){
98532  assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
98533  /* A minimum of one cursor is required if autoincrement is used
98534  * See ticket [a696379c1f08866] */
98535  if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
98536  sqlite3VdbeMakeReady(v, pParse);
98537  pParse->rc = SQLITE_DONE;
98538  }else{
98539  pParse->rc = SQLITE_ERROR;
98540  }
98541 }
98542 
98543 /*
98544 ** Run the parser and code generator recursively in order to generate
98545 ** code for the SQL statement given onto the end of the pParse context
98546 ** currently under construction. When the parser is run recursively
98547 ** this way, the final OP_Halt is not appended and other initialization
98548 ** and finalization steps are omitted because those are handling by the
98549 ** outermost parser.
98550 **
98551 ** Not everything is nestable. This facility is designed to permit
98552 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
98553 ** care if you decide to try to use this routine for some other purposes.
98554 */
98555 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
98556  va_list ap;
98557  char *zSql;
98558  char *zErrMsg = 0;
98559  sqlite3 *db = pParse->db;
98560  char saveBuf[PARSE_TAIL_SZ];
98561 
98562  if( pParse->nErr ) return;
98563  assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
98564  va_start(ap, zFormat);
98565  zSql = sqlite3VMPrintf(db, zFormat, ap);
98566  va_end(ap);
98567  if( zSql==0 ){
98568  return; /* A malloc must have failed */
98569  }
98570  pParse->nested++;
98571  memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
98572  memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
98573  sqlite3RunParser(pParse, zSql, &zErrMsg);
98574  sqlite3DbFree(db, zErrMsg);
98575  sqlite3DbFree(db, zSql);
98576  memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
98577  pParse->nested--;
98578 }
98579 
98580 #if SQLITE_USER_AUTHENTICATION
98581 /*
98582 ** Return TRUE if zTable is the name of the system table that stores the
98583 ** list of users and their access credentials.
98584 */
98585 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
98586  return sqlite3_stricmp(zTable, "sqlite_user")==0;
98587 }
98588 #endif
98589 
98590 /*
98591 ** Locate the in-memory structure that describes a particular database
98592 ** table given the name of that table and (optionally) the name of the
98593 ** database containing the table. Return NULL if not found.
98594 **
98595 ** If zDatabase is 0, all databases are searched for the table and the
98596 ** first matching table is returned. (No checking for duplicate table
98597 ** names is done.) The search order is TEMP first, then MAIN, then any
98598 ** auxiliary databases added using the ATTACH command.
98599 **
98600 ** See also sqlite3LocateTable().
98601 */
98602 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
98603  Table *p = 0;
98604  int i;
98605 
98606  /* All mutexes are required for schema access. Make sure we hold them. */
98607  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
98608 #if SQLITE_USER_AUTHENTICATION
98609  /* Only the admin user is allowed to know that the sqlite_user table
98610  ** exists */
98611  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
98612  return 0;
98613  }
98614 #endif
98615  for(i=OMIT_TEMPDB; i<db->nDb; i++){
98616  int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
98617  if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
98618  assert( sqlite3SchemaMutexHeld(db, j, 0) );
98619  p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
98620  if( p ) break;
98621  }
98622  }
98623  return p;
98624 }
98625 
98626 /*
98627 ** Locate the in-memory structure that describes a particular database
98628 ** table given the name of that table and (optionally) the name of the
98629 ** database containing the table. Return NULL if not found. Also leave an
98630 ** error message in pParse->zErrMsg.
98631 **
98632 ** The difference between this routine and sqlite3FindTable() is that this
98633 ** routine leaves an error message in pParse->zErrMsg where
98634 ** sqlite3FindTable() does not.
98635 */
98636 SQLITE_PRIVATE Table *sqlite3LocateTable(
98637  Parse *pParse, /* context in which to report errors */
98638  u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
98639  const char *zName, /* Name of the table we are looking for */
98640  const char *zDbase /* Name of the database. Might be NULL */
98641 ){
98642  Table *p;
98643 
98644  /* Read the database schema. If an error occurs, leave an error message
98645  ** and code in pParse and return NULL. */
98646  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
98647  return 0;
98648  }
98649 
98650  p = sqlite3FindTable(pParse->db, zName, zDbase);
98651  if( p==0 ){
98652  const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
98653 #ifndef SQLITE_OMIT_VIRTUALTABLE
98654  if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
98655  /* If zName is the not the name of a table in the schema created using
98656  ** CREATE, then check to see if it is the name of an virtual table that
98657  ** can be an eponymous virtual table. */
98658  Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
98659  if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
98660  return pMod->pEpoTab;
98661  }
98662  }
98663 #endif
98664  if( (flags & LOCATE_NOERR)==0 ){
98665  if( zDbase ){
98666  sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
98667  }else{
98668  sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
98669  }
98670  pParse->checkSchema = 1;
98671  }
98672  }
98673 
98674  return p;
98675 }
98676 
98677 /*
98678 ** Locate the table identified by *p.
98679 **
98680 ** This is a wrapper around sqlite3LocateTable(). The difference between
98681 ** sqlite3LocateTable() and this function is that this function restricts
98682 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
98683 ** non-NULL if it is part of a view or trigger program definition. See
98684 ** sqlite3FixSrcList() for details.
98685 */
98686 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
98687  Parse *pParse,
98688  u32 flags,
98689  struct SrcList_item *p
98690 ){
98691  const char *zDb;
98692  assert( p->pSchema==0 || p->zDatabase==0 );
98693  if( p->pSchema ){
98694  int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
98695  zDb = pParse->db->aDb[iDb].zDbSName;
98696  }else{
98697  zDb = p->zDatabase;
98698  }
98699  return sqlite3LocateTable(pParse, flags, p->zName, zDb);
98700 }
98701 
98702 /*
98703 ** Locate the in-memory structure that describes
98704 ** a particular index given the name of that index
98705 ** and the name of the database that contains the index.
98706 ** Return NULL if not found.
98707 **
98708 ** If zDatabase is 0, all databases are searched for the
98709 ** table and the first matching index is returned. (No checking
98710 ** for duplicate index names is done.) The search order is
98711 ** TEMP first, then MAIN, then any auxiliary databases added
98712 ** using the ATTACH command.
98713 */
98714 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
98715  Index *p = 0;
98716  int i;
98717  /* All mutexes are required for schema access. Make sure we hold them. */
98718  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
98719  for(i=OMIT_TEMPDB; i<db->nDb; i++){
98720  int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
98721  Schema *pSchema = db->aDb[j].pSchema;
98722  assert( pSchema );
98723  if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
98724  assert( sqlite3SchemaMutexHeld(db, j, 0) );
98725  p = sqlite3HashFind(&pSchema->idxHash, zName);
98726  if( p ) break;
98727  }
98728  return p;
98729 }
98730 
98731 /*
98732 ** Reclaim the memory used by an index
98733 */
98734 static void freeIndex(sqlite3 *db, Index *p){
98735 #ifndef SQLITE_OMIT_ANALYZE
98736  sqlite3DeleteIndexSamples(db, p);
98737 #endif
98738  sqlite3ExprDelete(db, p->pPartIdxWhere);
98739  sqlite3ExprListDelete(db, p->aColExpr);
98740  sqlite3DbFree(db, p->zColAff);
98741  if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
98742 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98743  sqlite3_free(p->aiRowEst);
98744 #endif
98745  sqlite3DbFree(db, p);
98746 }
98747 
98748 /*
98749 ** For the index called zIdxName which is found in the database iDb,
98750 ** unlike that index from its Table then remove the index from
98751 ** the index hash table and free all memory structures associated
98752 ** with the index.
98753 */
98754 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
98755  Index *pIndex;
98756  Hash *pHash;
98757 
98758  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98759  pHash = &db->aDb[iDb].pSchema->idxHash;
98760  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
98761  if( ALWAYS(pIndex) ){
98762  if( pIndex->pTable->pIndex==pIndex ){
98763  pIndex->pTable->pIndex = pIndex->pNext;
98764  }else{
98765  Index *p;
98766  /* Justification of ALWAYS(); The index must be on the list of
98767  ** indices. */
98768  p = pIndex->pTable->pIndex;
98769  while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
98770  if( ALWAYS(p && p->pNext==pIndex) ){
98771  p->pNext = pIndex->pNext;
98772  }
98773  }
98774  freeIndex(db, pIndex);
98775  }
98776  db->flags |= SQLITE_InternChanges;
98777 }
98778 
98779 /*
98780 ** Look through the list of open database files in db->aDb[] and if
98781 ** any have been closed, remove them from the list. Reallocate the
98782 ** db->aDb[] structure to a smaller size, if possible.
98783 **
98784 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
98785 ** are never candidates for being collapsed.
98786 */
98787 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
98788  int i, j;
98789  for(i=j=2; i<db->nDb; i++){
98790  struct Db *pDb = &db->aDb[i];
98791  if( pDb->pBt==0 ){
98792  sqlite3DbFree(db, pDb->zDbSName);
98793  pDb->zDbSName = 0;
98794  continue;
98795  }
98796  if( j<i ){
98797  db->aDb[j] = db->aDb[i];
98798  }
98799  j++;
98800  }
98801  db->nDb = j;
98802  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
98803  memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
98804  sqlite3DbFree(db, db->aDb);
98805  db->aDb = db->aDbStatic;
98806  }
98807 }
98808 
98809 /*
98810 ** Reset the schema for the database at index iDb. Also reset the
98811 ** TEMP schema.
98812 */
98813 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
98814  Db *pDb;
98815  assert( iDb<db->nDb );
98816 
98817  /* Case 1: Reset the single schema identified by iDb */
98818  pDb = &db->aDb[iDb];
98819  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98820  assert( pDb->pSchema!=0 );
98821  sqlite3SchemaClear(pDb->pSchema);
98822 
98823  /* If any database other than TEMP is reset, then also reset TEMP
98824  ** since TEMP might be holding triggers that reference tables in the
98825  ** other database.
98826  */
98827  if( iDb!=1 ){
98828  pDb = &db->aDb[1];
98829  assert( pDb->pSchema!=0 );
98830  sqlite3SchemaClear(pDb->pSchema);
98831  }
98832  return;
98833 }
98834 
98835 /*
98836 ** Erase all schema information from all attached databases (including
98837 ** "main" and "temp") for a single database connection.
98838 */
98839 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
98840  int i;
98841  sqlite3BtreeEnterAll(db);
98842  for(i=0; i<db->nDb; i++){
98843  Db *pDb = &db->aDb[i];
98844  if( pDb->pSchema ){
98845  sqlite3SchemaClear(pDb->pSchema);
98846  }
98847  }
98848  db->flags &= ~SQLITE_InternChanges;
98849  sqlite3VtabUnlockList(db);
98850  sqlite3BtreeLeaveAll(db);
98851  sqlite3CollapseDatabaseArray(db);
98852 }
98853 
98854 /*
98855 ** This routine is called when a commit occurs.
98856 */
98857 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
98858  db->flags &= ~SQLITE_InternChanges;
98859 }
98860 
98861 /*
98862 ** Delete memory allocated for the column names of a table or view (the
98863 ** Table.aCol[] array).
98864 */
98865 SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
98866  int i;
98867  Column *pCol;
98868  assert( pTable!=0 );
98869  if( (pCol = pTable->aCol)!=0 ){
98870  for(i=0; i<pTable->nCol; i++, pCol++){
98871  sqlite3DbFree(db, pCol->zName);
98872  sqlite3ExprDelete(db, pCol->pDflt);
98873  sqlite3DbFree(db, pCol->zColl);
98874  }
98875  sqlite3DbFree(db, pTable->aCol);
98876  }
98877 }
98878 
98879 /*
98880 ** Remove the memory data structures associated with the given
98881 ** Table. No changes are made to disk by this routine.
98882 **
98883 ** This routine just deletes the data structure. It does not unlink
98884 ** the table data structure from the hash table. But it does destroy
98885 ** memory structures of the indices and foreign keys associated with
98886 ** the table.
98887 **
98888 ** The db parameter is optional. It is needed if the Table object
98889 ** contains lookaside memory. (Table objects in the schema do not use
98890 ** lookaside memory, but some ephemeral Table objects do.) Or the
98891 ** db parameter can be used with db->pnBytesFreed to measure the memory
98892 ** used by the Table object.
98893 */
98894 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
98895  Index *pIndex, *pNext;
98896  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
98897 
98898  /* Record the number of outstanding lookaside allocations in schema Tables
98899  ** prior to doing any free() operations. Since schema Tables do not use
98900  ** lookaside, this number should not change. */
98901  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
98902  db->lookaside.nOut : 0 );
98903 
98904  /* Delete all indices associated with this table. */
98905  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
98906  pNext = pIndex->pNext;
98907  assert( pIndex->pSchema==pTable->pSchema
98908  || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
98909  if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
98910  char *zName = pIndex->zName;
98911  TESTONLY ( Index *pOld = ) sqlite3HashInsert(
98912  &pIndex->pSchema->idxHash, zName, 0
98913  );
98914  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
98915  assert( pOld==pIndex || pOld==0 );
98916  }
98917  freeIndex(db, pIndex);
98918  }
98919 
98920  /* Delete any foreign keys attached to this table. */
98921  sqlite3FkDelete(db, pTable);
98922 
98923  /* Delete the Table structure itself.
98924  */
98925  sqlite3DeleteColumnNames(db, pTable);
98926  sqlite3DbFree(db, pTable->zName);
98927  sqlite3DbFree(db, pTable->zColAff);
98928  sqlite3SelectDelete(db, pTable->pSelect);
98929  sqlite3ExprListDelete(db, pTable->pCheck);
98930 #ifndef SQLITE_OMIT_VIRTUALTABLE
98931  sqlite3VtabClear(db, pTable);
98932 #endif
98933  sqlite3DbFree(db, pTable);
98934 
98935  /* Verify that no lookaside memory was used by schema tables */
98936  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
98937 }
98938 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
98939  /* Do not delete the table until the reference count reaches zero. */
98940  if( !pTable ) return;
98941  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
98942  deleteTable(db, pTable);
98943 }
98944 
98945 
98946 /*
98947 ** Unlink the given table from the hash tables and the delete the
98948 ** table structure with all its indices and foreign keys.
98949 */
98950 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
98951  Table *p;
98952  Db *pDb;
98953 
98954  assert( db!=0 );
98955  assert( iDb>=0 && iDb<db->nDb );
98956  assert( zTabName );
98957  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98958  testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
98959  pDb = &db->aDb[iDb];
98960  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
98961  sqlite3DeleteTable(db, p);
98962  db->flags |= SQLITE_InternChanges;
98963 }
98964 
98965 /*
98966 ** Given a token, return a string that consists of the text of that
98967 ** token. Space to hold the returned string
98968 ** is obtained from sqliteMalloc() and must be freed by the calling
98969 ** function.
98970 **
98971 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
98972 ** surround the body of the token are removed.
98973 **
98974 ** Tokens are often just pointers into the original SQL text and so
98975 ** are not \000 terminated and are not persistent. The returned string
98976 ** is \000 terminated and is persistent.
98977 */
98978 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
98979  char *zName;
98980  if( pName ){
98981  zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
98982  sqlite3Dequote(zName);
98983  }else{
98984  zName = 0;
98985  }
98986  return zName;
98987 }
98988 
98989 /*
98990 ** Open the sqlite_master table stored in database number iDb for
98991 ** writing. The table is opened using cursor 0.
98992 */
98993 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
98994  Vdbe *v = sqlite3GetVdbe(p);
98995  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
98996  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
98997  if( p->nTab==0 ){
98998  p->nTab = 1;
98999  }
99000 }
99001 
99002 /*
99003 ** Parameter zName points to a nul-terminated buffer containing the name
99004 ** of a database ("main", "temp" or the name of an attached db). This
99005 ** function returns the index of the named database in db->aDb[], or
99006 ** -1 if the named db cannot be found.
99007 */
99008 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
99009  int i = -1; /* Database number */
99010  if( zName ){
99011  Db *pDb;
99012  for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
99013  if( 0==sqlite3StrICmp(pDb->zDbSName, zName) ) break;
99014  }
99015  }
99016  return i;
99017 }
99018 
99019 /*
99020 ** The token *pName contains the name of a database (either "main" or
99021 ** "temp" or the name of an attached db). This routine returns the
99022 ** index of the named database in db->aDb[], or -1 if the named db
99023 ** does not exist.
99024 */
99025 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
99026  int i; /* Database number */
99027  char *zName; /* Name we are searching for */
99028  zName = sqlite3NameFromToken(db, pName);
99029  i = sqlite3FindDbName(db, zName);
99030  sqlite3DbFree(db, zName);
99031  return i;
99032 }
99033 
99034 /* The table or view or trigger name is passed to this routine via tokens
99035 ** pName1 and pName2. If the table name was fully qualified, for example:
99036 **
99037 ** CREATE TABLE xxx.yyy (...);
99038 **
99039 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
99040 ** the table name is not fully qualified, i.e.:
99041 **
99042 ** CREATE TABLE yyy(...);
99043 **
99044 ** Then pName1 is set to "yyy" and pName2 is "".
99045 **
99046 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
99047 ** pName2) that stores the unqualified table name. The index of the
99048 ** database "xxx" is returned.
99049 */
99050 SQLITE_PRIVATE int sqlite3TwoPartName(
99051  Parse *pParse, /* Parsing and code generating context */
99052  Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
99053  Token *pName2, /* The "yyy" in the name "xxx.yyy" */
99054  Token **pUnqual /* Write the unqualified object name here */
99055 ){
99056  int iDb; /* Database holding the object */
99057  sqlite3 *db = pParse->db;
99058 
99059  assert( pName2!=0 );
99060  if( pName2->n>0 ){
99061  if( db->init.busy ) {
99062  sqlite3ErrorMsg(pParse, "corrupt database");
99063  return -1;
99064  }
99065  *pUnqual = pName2;
99066  iDb = sqlite3FindDb(db, pName1);
99067  if( iDb<0 ){
99068  sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
99069  return -1;
99070  }
99071  }else{
99072  assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0);
99073  iDb = db->init.iDb;
99074  *pUnqual = pName1;
99075  }
99076  return iDb;
99077 }
99078 
99079 /*
99080 ** This routine is used to check if the UTF-8 string zName is a legal
99081 ** unqualified name for a new schema object (table, index, view or
99082 ** trigger). All names are legal except those that begin with the string
99083 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
99084 ** is reserved for internal use.
99085 */
99086 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
99087  if( !pParse->db->init.busy && pParse->nested==0
99088  && (pParse->db->flags & SQLITE_WriteSchema)==0
99089  && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
99090  sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
99091  return SQLITE_ERROR;
99092  }
99093  return SQLITE_OK;
99094 }
99095 
99096 /*
99097 ** Return the PRIMARY KEY index of a table
99098 */
99099 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
99100  Index *p;
99101  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
99102  return p;
99103 }
99104 
99105 /*
99106 ** Return the column of index pIdx that corresponds to table
99107 ** column iCol. Return -1 if not found.
99108 */
99109 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
99110  int i;
99111  for(i=0; i<pIdx->nColumn; i++){
99112  if( iCol==pIdx->aiColumn[i] ) return i;
99113  }
99114  return -1;
99115 }
99116 
99117 /*
99118 ** Begin constructing a new table representation in memory. This is
99119 ** the first of several action routines that get called in response
99120 ** to a CREATE TABLE statement. In particular, this routine is called
99121 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
99122 ** flag is true if the table should be stored in the auxiliary database
99123 ** file instead of in the main database file. This is normally the case
99124 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
99125 ** CREATE and TABLE.
99126 **
99127 ** The new table record is initialized and put in pParse->pNewTable.
99128 ** As more of the CREATE TABLE statement is parsed, additional action
99129 ** routines will be called to add more information to this record.
99130 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
99131 ** is called to complete the construction of the new table record.
99132 */
99133 SQLITE_PRIVATE void sqlite3StartTable(
99134  Parse *pParse, /* Parser context */
99135  Token *pName1, /* First part of the name of the table or view */
99136  Token *pName2, /* Second part of the name of the table or view */
99137  int isTemp, /* True if this is a TEMP table */
99138  int isView, /* True if this is a VIEW */
99139  int isVirtual, /* True if this is a VIRTUAL table */
99140  int noErr /* Do nothing if table already exists */
99141 ){
99142  Table *pTable;
99143  char *zName = 0; /* The name of the new table */
99144  sqlite3 *db = pParse->db;
99145  Vdbe *v;
99146  int iDb; /* Database number to create the table in */
99147  Token *pName; /* Unqualified name of the table to create */
99148 
99149  if( db->init.busy && db->init.newTnum==1 ){
99150  /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
99151  iDb = db->init.iDb;
99152  zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
99153  pName = pName1;
99154  }else{
99155  /* The common case */
99156  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99157  if( iDb<0 ) return;
99158  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
99159  /* If creating a temp table, the name may not be qualified. Unless
99160  ** the database name is "temp" anyway. */
99161  sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
99162  return;
99163  }
99164  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
99165  zName = sqlite3NameFromToken(db, pName);
99166  }
99167  pParse->sNameToken = *pName;
99168  if( zName==0 ) return;
99169  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
99170  goto begin_table_error;
99171  }
99172  if( db->init.iDb==1 ) isTemp = 1;
99173 #ifndef SQLITE_OMIT_AUTHORIZATION
99174  assert( isTemp==0 || isTemp==1 );
99175  assert( isView==0 || isView==1 );
99176  {
99177  static const u8 aCode[] = {
99178  SQLITE_CREATE_TABLE,
99179  SQLITE_CREATE_TEMP_TABLE,
99180  SQLITE_CREATE_VIEW,
99181  SQLITE_CREATE_TEMP_VIEW
99182  };
99183  char *zDb = db->aDb[iDb].zDbSName;
99184  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
99185  goto begin_table_error;
99186  }
99187  if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
99188  zName, 0, zDb) ){
99189  goto begin_table_error;
99190  }
99191  }
99192 #endif
99193 
99194  /* Make sure the new table name does not collide with an existing
99195  ** index or table name in the same database. Issue an error message if
99196  ** it does. The exception is if the statement being parsed was passed
99197  ** to an sqlite3_declare_vtab() call. In that case only the column names
99198  ** and types will be used, so there is no need to test for namespace
99199  ** collisions.
99200  */
99201  if( !IN_DECLARE_VTAB ){
99202  char *zDb = db->aDb[iDb].zDbSName;
99203  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
99204  goto begin_table_error;
99205  }
99206  pTable = sqlite3FindTable(db, zName, zDb);
99207  if( pTable ){
99208  if( !noErr ){
99209  sqlite3ErrorMsg(pParse, "table %T already exists", pName);
99210  }else{
99211  assert( !db->init.busy || CORRUPT_DB );
99212  sqlite3CodeVerifySchema(pParse, iDb);
99213  }
99214  goto begin_table_error;
99215  }
99216  if( sqlite3FindIndex(db, zName, zDb)!=0 ){
99217  sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
99218  goto begin_table_error;
99219  }
99220  }
99221 
99222  pTable = sqlite3DbMallocZero(db, sizeof(Table));
99223  if( pTable==0 ){
99224  assert( db->mallocFailed );
99225  pParse->rc = SQLITE_NOMEM_BKPT;
99226  pParse->nErr++;
99227  goto begin_table_error;
99228  }
99229  pTable->zName = zName;
99230  pTable->iPKey = -1;
99231  pTable->pSchema = db->aDb[iDb].pSchema;
99232  pTable->nRef = 1;
99233  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
99234  assert( pParse->pNewTable==0 );
99235  pParse->pNewTable = pTable;
99236 
99237  /* If this is the magic sqlite_sequence table used by autoincrement,
99238  ** then record a pointer to this table in the main database structure
99239  ** so that INSERT can find the table easily.
99240  */
99241 #ifndef SQLITE_OMIT_AUTOINCREMENT
99242  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
99243  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99244  pTable->pSchema->pSeqTab = pTable;
99245  }
99246 #endif
99247 
99248  /* Begin generating the code that will insert the table record into
99249  ** the SQLITE_MASTER table. Note in particular that we must go ahead
99250  ** and allocate the record number for the table entry now. Before any
99251  ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
99252  ** indices to be created and the table record must come before the
99253  ** indices. Hence, the record number for the table must be allocated
99254  ** now.
99255  */
99256  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
99257  int addr1;
99258  int fileFormat;
99259  int reg1, reg2, reg3;
99260  /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
99261  static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
99262  sqlite3BeginWriteOperation(pParse, 1, iDb);
99263 
99264 #ifndef SQLITE_OMIT_VIRTUALTABLE
99265  if( isVirtual ){
99266  sqlite3VdbeAddOp0(v, OP_VBegin);
99267  }
99268 #endif
99269 
99270  /* If the file format and encoding in the database have not been set,
99271  ** set them now.
99272  */
99273  reg1 = pParse->regRowid = ++pParse->nMem;
99274  reg2 = pParse->regRoot = ++pParse->nMem;
99275  reg3 = ++pParse->nMem;
99276  sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
99277  sqlite3VdbeUsesBtree(v, iDb);
99278  addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
99279  fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
99280  1 : SQLITE_MAX_FILE_FORMAT;
99281  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
99282  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
99283  sqlite3VdbeJumpHere(v, addr1);
99284 
99285  /* This just creates a place-holder record in the sqlite_master table.
99286  ** The record created does not contain anything yet. It will be replaced
99287  ** by the real entry in code generated at sqlite3EndTable().
99288  **
99289  ** The rowid for the new entry is left in register pParse->regRowid.
99290  ** The root page number of the new table is left in reg pParse->regRoot.
99291  ** The rowid and root page number values are needed by the code that
99292  ** sqlite3EndTable will generate.
99293  */
99294 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
99295  if( isView || isVirtual ){
99296  sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
99297  }else
99298 #endif
99299  {
99300  pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
99301  }
99302  sqlite3OpenMasterTable(pParse, iDb);
99303  sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
99304  sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
99305  sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
99306  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
99307  sqlite3VdbeAddOp0(v, OP_Close);
99308  }
99309 
99310  /* Normal (non-error) return. */
99311  return;
99312 
99313  /* If an error occurs, we jump here */
99314 begin_table_error:
99315  sqlite3DbFree(db, zName);
99316  return;
99317 }
99318 
99319 /* Set properties of a table column based on the (magical)
99320 ** name of the column.
99321 */
99322 #if SQLITE_ENABLE_HIDDEN_COLUMNS
99323 SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
99324  if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
99325  pCol->colFlags |= COLFLAG_HIDDEN;
99326  }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
99327  pTab->tabFlags |= TF_OOOHidden;
99328  }
99329 }
99330 #endif
99331 
99332 
99333 /*
99334 ** Add a new column to the table currently being constructed.
99335 **
99336 ** The parser calls this routine once for each column declaration
99337 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
99338 ** first to get things going. Then this routine is called for each
99339 ** column.
99340 */
99341 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
99342  Table *p;
99343  int i;
99344  char *z;
99345  char *zType;
99346  Column *pCol;
99347  sqlite3 *db = pParse->db;
99348  if( (p = pParse->pNewTable)==0 ) return;
99349 #if SQLITE_MAX_COLUMN
99350  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
99351  sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
99352  return;
99353  }
99354 #endif
99355  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
99356  if( z==0 ) return;
99357  memcpy(z, pName->z, pName->n);
99358  z[pName->n] = 0;
99359  sqlite3Dequote(z);
99360  for(i=0; i<p->nCol; i++){
99361  if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
99362  sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
99363  sqlite3DbFree(db, z);
99364  return;
99365  }
99366  }
99367  if( (p->nCol & 0x7)==0 ){
99368  Column *aNew;
99369  aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
99370  if( aNew==0 ){
99371  sqlite3DbFree(db, z);
99372  return;
99373  }
99374  p->aCol = aNew;
99375  }
99376  pCol = &p->aCol[p->nCol];
99377  memset(pCol, 0, sizeof(p->aCol[0]));
99378  pCol->zName = z;
99379  sqlite3ColumnPropertiesFromName(p, pCol);
99380 
99381  if( pType->n==0 ){
99382  /* If there is no type specified, columns have the default affinity
99383  ** 'BLOB'. */
99384  pCol->affinity = SQLITE_AFF_BLOB;
99385  pCol->szEst = 1;
99386  }else{
99387  zType = z + sqlite3Strlen30(z) + 1;
99388  memcpy(zType, pType->z, pType->n);
99389  zType[pType->n] = 0;
99390  sqlite3Dequote(zType);
99391  pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
99392  pCol->colFlags |= COLFLAG_HASTYPE;
99393  }
99394  p->nCol++;
99395  pParse->constraintName.n = 0;
99396 }
99397 
99398 /*
99399 ** This routine is called by the parser while in the middle of
99400 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
99401 ** been seen on a column. This routine sets the notNull flag on
99402 ** the column currently under construction.
99403 */
99404 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
99405  Table *p;
99406  p = pParse->pNewTable;
99407  if( p==0 || NEVER(p->nCol<1) ) return;
99408  p->aCol[p->nCol-1].notNull = (u8)onError;
99409 }
99410 
99411 /*
99412 ** Scan the column type name zType (length nType) and return the
99413 ** associated affinity type.
99414 **
99415 ** This routine does a case-independent search of zType for the
99416 ** substrings in the following table. If one of the substrings is
99417 ** found, the corresponding affinity is returned. If zType contains
99418 ** more than one of the substrings, entries toward the top of
99419 ** the table take priority. For example, if zType is 'BLOBINT',
99420 ** SQLITE_AFF_INTEGER is returned.
99421 **
99422 ** Substring | Affinity
99423 ** --------------------------------
99424 ** 'INT' | SQLITE_AFF_INTEGER
99425 ** 'CHAR' | SQLITE_AFF_TEXT
99426 ** 'CLOB' | SQLITE_AFF_TEXT
99427 ** 'TEXT' | SQLITE_AFF_TEXT
99428 ** 'BLOB' | SQLITE_AFF_BLOB
99429 ** 'REAL' | SQLITE_AFF_REAL
99430 ** 'FLOA' | SQLITE_AFF_REAL
99431 ** 'DOUB' | SQLITE_AFF_REAL
99432 **
99433 ** If none of the substrings in the above table are found,
99434 ** SQLITE_AFF_NUMERIC is returned.
99435 */
99436 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
99437  u32 h = 0;
99438  char aff = SQLITE_AFF_NUMERIC;
99439  const char *zChar = 0;
99440 
99441  assert( zIn!=0 );
99442  while( zIn[0] ){
99443  h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
99444  zIn++;
99445  if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
99446  aff = SQLITE_AFF_TEXT;
99447  zChar = zIn;
99448  }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
99449  aff = SQLITE_AFF_TEXT;
99450  }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
99451  aff = SQLITE_AFF_TEXT;
99452  }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
99453  && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
99454  aff = SQLITE_AFF_BLOB;
99455  if( zIn[0]=='(' ) zChar = zIn;
99456 #ifndef SQLITE_OMIT_FLOATING_POINT
99457  }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
99458  && aff==SQLITE_AFF_NUMERIC ){
99459  aff = SQLITE_AFF_REAL;
99460  }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
99461  && aff==SQLITE_AFF_NUMERIC ){
99462  aff = SQLITE_AFF_REAL;
99463  }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
99464  && aff==SQLITE_AFF_NUMERIC ){
99465  aff = SQLITE_AFF_REAL;
99466 #endif
99467  }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
99468  aff = SQLITE_AFF_INTEGER;
99469  break;
99470  }
99471  }
99472 
99473  /* If pszEst is not NULL, store an estimate of the field size. The
99474  ** estimate is scaled so that the size of an integer is 1. */
99475  if( pszEst ){
99476  *pszEst = 1; /* default size is approx 4 bytes */
99477  if( aff<SQLITE_AFF_NUMERIC ){
99478  if( zChar ){
99479  while( zChar[0] ){
99480  if( sqlite3Isdigit(zChar[0]) ){
99481  int v = 0;
99482  sqlite3GetInt32(zChar, &v);
99483  v = v/4 + 1;
99484  if( v>255 ) v = 255;
99485  *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
99486  break;
99487  }
99488  zChar++;
99489  }
99490  }else{
99491  *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
99492  }
99493  }
99494  }
99495  return aff;
99496 }
99497 
99498 /*
99499 ** The expression is the default value for the most recently added column
99500 ** of the table currently under construction.
99501 **
99502 ** Default value expressions must be constant. Raise an exception if this
99503 ** is not the case.
99504 **
99505 ** This routine is called by the parser while in the middle of
99506 ** parsing a CREATE TABLE statement.
99507 */
99508 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
99509  Table *p;
99510  Column *pCol;
99511  sqlite3 *db = pParse->db;
99512  p = pParse->pNewTable;
99513  if( p!=0 ){
99514  pCol = &(p->aCol[p->nCol-1]);
99515  if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
99516  sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
99517  pCol->zName);
99518  }else{
99519  /* A copy of pExpr is used instead of the original, as pExpr contains
99520  ** tokens that point to volatile memory. The 'span' of the expression
99521  ** is required by pragma table_info.
99522  */
99523  Expr x;
99524  sqlite3ExprDelete(db, pCol->pDflt);
99525  memset(&x, 0, sizeof(x));
99526  x.op = TK_SPAN;
99527  x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
99528  (int)(pSpan->zEnd - pSpan->zStart));
99529  x.pLeft = pSpan->pExpr;
99530  x.flags = EP_Skip;
99531  pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
99532  sqlite3DbFree(db, x.u.zToken);
99533  }
99534  }
99535  sqlite3ExprDelete(db, pSpan->pExpr);
99536 }
99537 
99538 /*
99539 ** Backwards Compatibility Hack:
99540 **
99541 ** Historical versions of SQLite accepted strings as column names in
99542 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
99543 **
99544 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
99545 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
99546 **
99547 ** This is goofy. But to preserve backwards compatibility we continue to
99548 ** accept it. This routine does the necessary conversion. It converts
99549 ** the expression given in its argument from a TK_STRING into a TK_ID
99550 ** if the expression is just a TK_STRING with an optional COLLATE clause.
99551 ** If the epxression is anything other than TK_STRING, the expression is
99552 ** unchanged.
99553 */
99554 static void sqlite3StringToId(Expr *p){
99555  if( p->op==TK_STRING ){
99556  p->op = TK_ID;
99557  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
99558  p->pLeft->op = TK_ID;
99559  }
99560 }
99561 
99562 /*
99563 ** Designate the PRIMARY KEY for the table. pList is a list of names
99564 ** of columns that form the primary key. If pList is NULL, then the
99565 ** most recently added column of the table is the primary key.
99566 **
99567 ** A table can have at most one primary key. If the table already has
99568 ** a primary key (and this is the second primary key) then create an
99569 ** error.
99570 **
99571 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
99572 ** then we will try to use that column as the rowid. Set the Table.iPKey
99573 ** field of the table under construction to be the index of the
99574 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
99575 ** no INTEGER PRIMARY KEY.
99576 **
99577 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
99578 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
99579 */
99580 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
99581  Parse *pParse, /* Parsing context */
99582  ExprList *pList, /* List of field names to be indexed */
99583  int onError, /* What to do with a uniqueness conflict */
99584  int autoInc, /* True if the AUTOINCREMENT keyword is present */
99585  int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
99586 ){
99587  Table *pTab = pParse->pNewTable;
99588  Column *pCol = 0;
99589  int iCol = -1, i;
99590  int nTerm;
99591  if( pTab==0 ) goto primary_key_exit;
99592  if( pTab->tabFlags & TF_HasPrimaryKey ){
99593  sqlite3ErrorMsg(pParse,
99594  "table \"%s\" has more than one primary key", pTab->zName);
99595  goto primary_key_exit;
99596  }
99597  pTab->tabFlags |= TF_HasPrimaryKey;
99598  if( pList==0 ){
99599  iCol = pTab->nCol - 1;
99600  pCol = &pTab->aCol[iCol];
99601  pCol->colFlags |= COLFLAG_PRIMKEY;
99602  nTerm = 1;
99603  }else{
99604  nTerm = pList->nExpr;
99605  for(i=0; i<nTerm; i++){
99606  Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
99607  assert( pCExpr!=0 );
99608  sqlite3StringToId(pCExpr);
99609  if( pCExpr->op==TK_ID ){
99610  const char *zCName = pCExpr->u.zToken;
99611  for(iCol=0; iCol<pTab->nCol; iCol++){
99612  if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
99613  pCol = &pTab->aCol[iCol];
99614  pCol->colFlags |= COLFLAG_PRIMKEY;
99615  break;
99616  }
99617  }
99618  }
99619  }
99620  }
99621  if( nTerm==1
99622  && pCol
99623  && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
99624  && sortOrder!=SQLITE_SO_DESC
99625  ){
99626  pTab->iPKey = iCol;
99627  pTab->keyConf = (u8)onError;
99628  assert( autoInc==0 || autoInc==1 );
99629  pTab->tabFlags |= autoInc*TF_Autoincrement;
99630  if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
99631  }else if( autoInc ){
99632 #ifndef SQLITE_OMIT_AUTOINCREMENT
99633  sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
99634  "INTEGER PRIMARY KEY");
99635 #endif
99636  }else{
99637  sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
99638  0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
99639  pList = 0;
99640  }
99641 
99642 primary_key_exit:
99643  sqlite3ExprListDelete(pParse->db, pList);
99644  return;
99645 }
99646 
99647 /*
99648 ** Add a new CHECK constraint to the table currently under construction.
99649 */
99650 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
99651  Parse *pParse, /* Parsing context */
99652  Expr *pCheckExpr /* The check expression */
99653 ){
99654 #ifndef SQLITE_OMIT_CHECK
99655  Table *pTab = pParse->pNewTable;
99656  sqlite3 *db = pParse->db;
99657  if( pTab && !IN_DECLARE_VTAB
99658  && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
99659  ){
99660  pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
99661  if( pParse->constraintName.n ){
99662  sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
99663  }
99664  }else
99665 #endif
99666  {
99667  sqlite3ExprDelete(pParse->db, pCheckExpr);
99668  }
99669 }
99670 
99671 /*
99672 ** Set the collation function of the most recently parsed table column
99673 ** to the CollSeq given.
99674 */
99675 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
99676  Table *p;
99677  int i;
99678  char *zColl; /* Dequoted name of collation sequence */
99679  sqlite3 *db;
99680 
99681  if( (p = pParse->pNewTable)==0 ) return;
99682  i = p->nCol-1;
99683  db = pParse->db;
99684  zColl = sqlite3NameFromToken(db, pToken);
99685  if( !zColl ) return;
99686 
99687  if( sqlite3LocateCollSeq(pParse, zColl) ){
99688  Index *pIdx;
99689  sqlite3DbFree(db, p->aCol[i].zColl);
99690  p->aCol[i].zColl = zColl;
99691 
99692  /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
99693  ** then an index may have been created on this column before the
99694  ** collation type was added. Correct this if it is the case.
99695  */
99696  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
99697  assert( pIdx->nKeyCol==1 );
99698  if( pIdx->aiColumn[0]==i ){
99699  pIdx->azColl[0] = p->aCol[i].zColl;
99700  }
99701  }
99702  }else{
99703  sqlite3DbFree(db, zColl);
99704  }
99705 }
99706 
99707 /*
99708 ** This function returns the collation sequence for database native text
99709 ** encoding identified by the string zName, length nName.
99710 **
99711 ** If the requested collation sequence is not available, or not available
99712 ** in the database native encoding, the collation factory is invoked to
99713 ** request it. If the collation factory does not supply such a sequence,
99714 ** and the sequence is available in another text encoding, then that is
99715 ** returned instead.
99716 **
99717 ** If no versions of the requested collations sequence are available, or
99718 ** another error occurs, NULL is returned and an error message written into
99719 ** pParse.
99720 **
99721 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
99722 ** invokes the collation factory if the named collation cannot be found
99723 ** and generates an error message.
99724 **
99725 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
99726 */
99727 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
99728  sqlite3 *db = pParse->db;
99729  u8 enc = ENC(db);
99730  u8 initbusy = db->init.busy;
99731  CollSeq *pColl;
99732 
99733  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
99734  if( !initbusy && (!pColl || !pColl->xCmp) ){
99735  pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
99736  }
99737 
99738  return pColl;
99739 }
99740 
99741 
99742 /*
99743 ** Generate code that will increment the schema cookie.
99744 **
99745 ** The schema cookie is used to determine when the schema for the
99746 ** database changes. After each schema change, the cookie value
99747 ** changes. When a process first reads the schema it records the
99748 ** cookie. Thereafter, whenever it goes to access the database,
99749 ** it checks the cookie to make sure the schema has not changed
99750 ** since it was last read.
99751 **
99752 ** This plan is not completely bullet-proof. It is possible for
99753 ** the schema to change multiple times and for the cookie to be
99754 ** set back to prior value. But schema changes are infrequent
99755 ** and the probability of hitting the same cookie value is only
99756 ** 1 chance in 2^32. So we're safe enough.
99757 **
99758 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
99759 ** the schema-version whenever the schema changes.
99760 */
99761 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
99762  sqlite3 *db = pParse->db;
99763  Vdbe *v = pParse->pVdbe;
99764  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99765  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
99766  db->aDb[iDb].pSchema->schema_cookie+1);
99767 }
99768 
99769 /*
99770 ** Measure the number of characters needed to output the given
99771 ** identifier. The number returned includes any quotes used
99772 ** but does not include the null terminator.
99773 **
99774 ** The estimate is conservative. It might be larger that what is
99775 ** really needed.
99776 */
99777 static int identLength(const char *z){
99778  int n;
99779  for(n=0; *z; n++, z++){
99780  if( *z=='"' ){ n++; }
99781  }
99782  return n + 2;
99783 }
99784 
99785 /*
99786 ** The first parameter is a pointer to an output buffer. The second
99787 ** parameter is a pointer to an integer that contains the offset at
99788 ** which to write into the output buffer. This function copies the
99789 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
99790 ** to the specified offset in the buffer and updates *pIdx to refer
99791 ** to the first byte after the last byte written before returning.
99792 **
99793 ** If the string zSignedIdent consists entirely of alpha-numeric
99794 ** characters, does not begin with a digit and is not an SQL keyword,
99795 ** then it is copied to the output buffer exactly as it is. Otherwise,
99796 ** it is quoted using double-quotes.
99797 */
99798 static void identPut(char *z, int *pIdx, char *zSignedIdent){
99799  unsigned char *zIdent = (unsigned char*)zSignedIdent;
99800  int i, j, needQuote;
99801  i = *pIdx;
99802 
99803  for(j=0; zIdent[j]; j++){
99804  if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
99805  }
99806  needQuote = sqlite3Isdigit(zIdent[0])
99807  || sqlite3KeywordCode(zIdent, j)!=TK_ID
99808  || zIdent[j]!=0
99809  || j==0;
99810 
99811  if( needQuote ) z[i++] = '"';
99812  for(j=0; zIdent[j]; j++){
99813  z[i++] = zIdent[j];
99814  if( zIdent[j]=='"' ) z[i++] = '"';
99815  }
99816  if( needQuote ) z[i++] = '"';
99817  z[i] = 0;
99818  *pIdx = i;
99819 }
99820 
99821 /*
99822 ** Generate a CREATE TABLE statement appropriate for the given
99823 ** table. Memory to hold the text of the statement is obtained
99824 ** from sqliteMalloc() and must be freed by the calling function.
99825 */
99826 static char *createTableStmt(sqlite3 *db, Table *p){
99827  int i, k, n;
99828  char *zStmt;
99829  char *zSep, *zSep2, *zEnd;
99830  Column *pCol;
99831  n = 0;
99832  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
99833  n += identLength(pCol->zName) + 5;
99834  }
99835  n += identLength(p->zName);
99836  if( n<50 ){
99837  zSep = "";
99838  zSep2 = ",";
99839  zEnd = ")";
99840  }else{
99841  zSep = "\n ";
99842  zSep2 = ",\n ";
99843  zEnd = "\n)";
99844  }
99845  n += 35 + 6*p->nCol;
99846  zStmt = sqlite3DbMallocRaw(0, n);
99847  if( zStmt==0 ){
99848  sqlite3OomFault(db);
99849  return 0;
99850  }
99851  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
99852  k = sqlite3Strlen30(zStmt);
99853  identPut(zStmt, &k, p->zName);
99854  zStmt[k++] = '(';
99855  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
99856  static const char * const azType[] = {
99857  /* SQLITE_AFF_BLOB */ "",
99858  /* SQLITE_AFF_TEXT */ " TEXT",
99859  /* SQLITE_AFF_NUMERIC */ " NUM",
99860  /* SQLITE_AFF_INTEGER */ " INT",
99861  /* SQLITE_AFF_REAL */ " REAL"
99862  };
99863  int len;
99864  const char *zType;
99865 
99866  sqlite3_snprintf(n-k, &zStmt[k], zSep);
99867  k += sqlite3Strlen30(&zStmt[k]);
99868  zSep = zSep2;
99869  identPut(zStmt, &k, pCol->zName);
99870  assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
99871  assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
99872  testcase( pCol->affinity==SQLITE_AFF_BLOB );
99873  testcase( pCol->affinity==SQLITE_AFF_TEXT );
99874  testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
99875  testcase( pCol->affinity==SQLITE_AFF_INTEGER );
99876  testcase( pCol->affinity==SQLITE_AFF_REAL );
99877 
99878  zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
99879  len = sqlite3Strlen30(zType);
99880  assert( pCol->affinity==SQLITE_AFF_BLOB
99881  || pCol->affinity==sqlite3AffinityType(zType, 0) );
99882  memcpy(&zStmt[k], zType, len);
99883  k += len;
99884  assert( k<=n );
99885  }
99886  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
99887  return zStmt;
99888 }
99889 
99890 /*
99891 ** Resize an Index object to hold N columns total. Return SQLITE_OK
99892 ** on success and SQLITE_NOMEM on an OOM error.
99893 */
99894 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
99895  char *zExtra;
99896  int nByte;
99897  if( pIdx->nColumn>=N ) return SQLITE_OK;
99898  assert( pIdx->isResized==0 );
99899  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
99900  zExtra = sqlite3DbMallocZero(db, nByte);
99901  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
99902  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
99903  pIdx->azColl = (const char**)zExtra;
99904  zExtra += sizeof(char*)*N;
99905  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
99906  pIdx->aiColumn = (i16*)zExtra;
99907  zExtra += sizeof(i16)*N;
99908  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
99909  pIdx->aSortOrder = (u8*)zExtra;
99910  pIdx->nColumn = N;
99911  pIdx->isResized = 1;
99912  return SQLITE_OK;
99913 }
99914 
99915 /*
99916 ** Estimate the total row width for a table.
99917 */
99918 static void estimateTableWidth(Table *pTab){
99919  unsigned wTable = 0;
99920  const Column *pTabCol;
99921  int i;
99922  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
99923  wTable += pTabCol->szEst;
99924  }
99925  if( pTab->iPKey<0 ) wTable++;
99926  pTab->szTabRow = sqlite3LogEst(wTable*4);
99927 }
99928 
99929 /*
99930 ** Estimate the average size of a row for an index.
99931 */
99932 static void estimateIndexWidth(Index *pIdx){
99933  unsigned wIndex = 0;
99934  int i;
99935  const Column *aCol = pIdx->pTable->aCol;
99936  for(i=0; i<pIdx->nColumn; i++){
99937  i16 x = pIdx->aiColumn[i];
99938  assert( x<pIdx->pTable->nCol );
99939  wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
99940  }
99941  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
99942 }
99943 
99944 /* Return true if value x is found any of the first nCol entries of aiCol[]
99945 */
99946 static int hasColumn(const i16 *aiCol, int nCol, int x){
99947  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
99948  return 0;
99949 }
99950 
99951 /*
99952 ** This routine runs at the end of parsing a CREATE TABLE statement that
99953 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
99954 ** internal schema data structures and the generated VDBE code so that they
99955 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
99956 ** Changes include:
99957 **
99958 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
99959 ** (2) Convert the OP_CreateTable into an OP_CreateIndex. There is
99960 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
99961 ** data storage is a covering index btree.
99962 ** (3) Bypass the creation of the sqlite_master table entry
99963 ** for the PRIMARY KEY as the primary key index is now
99964 ** identified by the sqlite_master table entry of the table itself.
99965 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
99966 ** schema to the rootpage from the main table.
99967 ** (5) Add all table columns to the PRIMARY KEY Index object
99968 ** so that the PRIMARY KEY is a covering index. The surplus
99969 ** columns are part of KeyInfo.nXField and are not used for
99970 ** sorting or lookup or uniqueness checks.
99971 ** (6) Replace the rowid tail on all automatically generated UNIQUE
99972 ** indices with the PRIMARY KEY columns.
99973 **
99974 ** For virtual tables, only (1) is performed.
99975 */
99976 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
99977  Index *pIdx;
99978  Index *pPk;
99979  int nPk;
99980  int i, j;
99981  sqlite3 *db = pParse->db;
99982  Vdbe *v = pParse->pVdbe;
99983 
99984  /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
99985  */
99986  if( !db->init.imposterTable ){
99987  for(i=0; i<pTab->nCol; i++){
99988  if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
99989  pTab->aCol[i].notNull = OE_Abort;
99990  }
99991  }
99992  }
99993 
99994  /* The remaining transformations only apply to b-tree tables, not to
99995  ** virtual tables */
99996  if( IN_DECLARE_VTAB ) return;
99997 
99998  /* Convert the OP_CreateTable opcode that would normally create the
99999  ** root-page for the table into an OP_CreateIndex opcode. The index
100000  ** created will become the PRIMARY KEY index.
100001  */
100002  if( pParse->addrCrTab ){
100003  assert( v );
100004  sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
100005  }
100006 
100007  /* Locate the PRIMARY KEY index. Or, if this table was originally
100008  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
100009  */
100010  if( pTab->iPKey>=0 ){
100011  ExprList *pList;
100012  Token ipkToken;
100013  sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
100014  pList = sqlite3ExprListAppend(pParse, 0,
100015  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
100016  if( pList==0 ) return;
100017  pList->a[0].sortOrder = pParse->iPkSortOrder;
100018  assert( pParse->pNewTable==pTab );
100019  sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
100020  SQLITE_IDXTYPE_PRIMARYKEY);
100021  if( db->mallocFailed ) return;
100022  pPk = sqlite3PrimaryKeyIndex(pTab);
100023  pTab->iPKey = -1;
100024  }else{
100025  pPk = sqlite3PrimaryKeyIndex(pTab);
100026 
100027  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
100028  ** table entry. This is only required if currently generating VDBE
100029  ** code for a CREATE TABLE (not when parsing one as part of reading
100030  ** a database schema). */
100031  if( v ){
100032  assert( db->init.busy==0 );
100033  sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
100034  }
100035 
100036  /*
100037  ** Remove all redundant columns from the PRIMARY KEY. For example, change
100038  ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
100039  ** code assumes the PRIMARY KEY contains no repeated columns.
100040  */
100041  for(i=j=1; i<pPk->nKeyCol; i++){
100042  if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
100043  pPk->nColumn--;
100044  }else{
100045  pPk->aiColumn[j++] = pPk->aiColumn[i];
100046  }
100047  }
100048  pPk->nKeyCol = j;
100049  }
100050  assert( pPk!=0 );
100051  pPk->isCovering = 1;
100052  if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
100053  nPk = pPk->nKeyCol;
100054 
100055  /* The root page of the PRIMARY KEY is the table root page */
100056  pPk->tnum = pTab->tnum;
100057 
100058  /* Update the in-memory representation of all UNIQUE indices by converting
100059  ** the final rowid column into one or more columns of the PRIMARY KEY.
100060  */
100061  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100062  int n;
100063  if( IsPrimaryKeyIndex(pIdx) ) continue;
100064  for(i=n=0; i<nPk; i++){
100065  if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
100066  }
100067  if( n==0 ){
100068  /* This index is a superset of the primary key */
100069  pIdx->nColumn = pIdx->nKeyCol;
100070  continue;
100071  }
100072  if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
100073  for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
100074  if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
100075  pIdx->aiColumn[j] = pPk->aiColumn[i];
100076  pIdx->azColl[j] = pPk->azColl[i];
100077  j++;
100078  }
100079  }
100080  assert( pIdx->nColumn>=pIdx->nKeyCol+n );
100081  assert( pIdx->nColumn>=j );
100082  }
100083 
100084  /* Add all table columns to the PRIMARY KEY index
100085  */
100086  if( nPk<pTab->nCol ){
100087  if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
100088  for(i=0, j=nPk; i<pTab->nCol; i++){
100089  if( !hasColumn(pPk->aiColumn, j, i) ){
100090  assert( j<pPk->nColumn );
100091  pPk->aiColumn[j] = i;
100092  pPk->azColl[j] = sqlite3StrBINARY;
100093  j++;
100094  }
100095  }
100096  assert( pPk->nColumn==j );
100097  assert( pTab->nCol==j );
100098  }else{
100099  pPk->nColumn = pTab->nCol;
100100  }
100101 }
100102 
100103 /*
100104 ** This routine is called to report the final ")" that terminates
100105 ** a CREATE TABLE statement.
100106 **
100107 ** The table structure that other action routines have been building
100108 ** is added to the internal hash tables, assuming no errors have
100109 ** occurred.
100110 **
100111 ** An entry for the table is made in the master table on disk, unless
100112 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
100113 ** it means we are reading the sqlite_master table because we just
100114 ** connected to the database or because the sqlite_master table has
100115 ** recently changed, so the entry for this table already exists in
100116 ** the sqlite_master table. We do not want to create it again.
100117 **
100118 ** If the pSelect argument is not NULL, it means that this routine
100119 ** was called to create a table generated from a
100120 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
100121 ** the new table will match the result set of the SELECT.
100122 */
100123 SQLITE_PRIVATE void sqlite3EndTable(
100124  Parse *pParse, /* Parse context */
100125  Token *pCons, /* The ',' token after the last column defn. */
100126  Token *pEnd, /* The ')' before options in the CREATE TABLE */
100127  u8 tabOpts, /* Extra table options. Usually 0. */
100128  Select *pSelect /* Select from a "CREATE ... AS SELECT" */
100129 ){
100130  Table *p; /* The new table */
100131  sqlite3 *db = pParse->db; /* The database connection */
100132  int iDb; /* Database in which the table lives */
100133  Index *pIdx; /* An implied index of the table */
100134 
100135  if( pEnd==0 && pSelect==0 ){
100136  return;
100137  }
100138  assert( !db->mallocFailed );
100139  p = pParse->pNewTable;
100140  if( p==0 ) return;
100141 
100142  assert( !db->init.busy || !pSelect );
100143 
100144  /* If the db->init.busy is 1 it means we are reading the SQL off the
100145  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
100146  ** So do not write to the disk again. Extract the root page number
100147  ** for the table from the db->init.newTnum field. (The page number
100148  ** should have been put there by the sqliteOpenCb routine.)
100149  **
100150  ** If the root page number is 1, that means this is the sqlite_master
100151  ** table itself. So mark it read-only.
100152  */
100153  if( db->init.busy ){
100154  p->tnum = db->init.newTnum;
100155  if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
100156  }
100157 
100158  /* Special processing for WITHOUT ROWID Tables */
100159  if( tabOpts & TF_WithoutRowid ){
100160  if( (p->tabFlags & TF_Autoincrement) ){
100161  sqlite3ErrorMsg(pParse,
100162  "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
100163  return;
100164  }
100165  if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
100166  sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
100167  }else{
100168  p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
100169  convertToWithoutRowidTable(pParse, p);
100170  }
100171  }
100172 
100173  iDb = sqlite3SchemaToIndex(db, p->pSchema);
100174 
100175 #ifndef SQLITE_OMIT_CHECK
100176  /* Resolve names in all CHECK constraint expressions.
100177  */
100178  if( p->pCheck ){
100179  sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
100180  }
100181 #endif /* !defined(SQLITE_OMIT_CHECK) */
100182 
100183  /* Estimate the average row size for the table and for all implied indices */
100184  estimateTableWidth(p);
100185  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
100186  estimateIndexWidth(pIdx);
100187  }
100188 
100189  /* If not initializing, then create a record for the new table
100190  ** in the SQLITE_MASTER table of the database.
100191  **
100192  ** If this is a TEMPORARY table, write the entry into the auxiliary
100193  ** file instead of into the main database file.
100194  */
100195  if( !db->init.busy ){
100196  int n;
100197  Vdbe *v;
100198  char *zType; /* "view" or "table" */
100199  char *zType2; /* "VIEW" or "TABLE" */
100200  char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
100201 
100202  v = sqlite3GetVdbe(pParse);
100203  if( NEVER(v==0) ) return;
100204 
100205  sqlite3VdbeAddOp1(v, OP_Close, 0);
100206 
100207  /*
100208  ** Initialize zType for the new view or table.
100209  */
100210  if( p->pSelect==0 ){
100211  /* A regular table */
100212  zType = "table";
100213  zType2 = "TABLE";
100214 #ifndef SQLITE_OMIT_VIEW
100215  }else{
100216  /* A view */
100217  zType = "view";
100218  zType2 = "VIEW";
100219 #endif
100220  }
100221 
100222  /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
100223  ** statement to populate the new table. The root-page number for the
100224  ** new table is in register pParse->regRoot.
100225  **
100226  ** Once the SELECT has been coded by sqlite3Select(), it is in a
100227  ** suitable state to query for the column names and types to be used
100228  ** by the new table.
100229  **
100230  ** A shared-cache write-lock is not required to write to the new table,
100231  ** as a schema-lock must have already been obtained to create it. Since
100232  ** a schema-lock excludes all other database users, the write-lock would
100233  ** be redundant.
100234  */
100235  if( pSelect ){
100236  SelectDest dest; /* Where the SELECT should store results */
100237  int regYield; /* Register holding co-routine entry-point */
100238  int addrTop; /* Top of the co-routine */
100239  int regRec; /* A record to be insert into the new table */
100240  int regRowid; /* Rowid of the next row to insert */
100241  int addrInsLoop; /* Top of the loop for inserting rows */
100242  Table *pSelTab; /* A table that describes the SELECT results */
100243 
100244  regYield = ++pParse->nMem;
100245  regRec = ++pParse->nMem;
100246  regRowid = ++pParse->nMem;
100247  assert(pParse->nTab==1);
100248  sqlite3MayAbort(pParse);
100249  sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
100250  sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
100251  pParse->nTab = 2;
100252  addrTop = sqlite3VdbeCurrentAddr(v) + 1;
100253  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
100254  sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
100255  sqlite3Select(pParse, pSelect, &dest);
100256  sqlite3VdbeEndCoroutine(v, regYield);
100257  sqlite3VdbeJumpHere(v, addrTop - 1);
100258  if( pParse->nErr ) return;
100259  pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
100260  if( pSelTab==0 ) return;
100261  assert( p->aCol==0 );
100262  p->nCol = pSelTab->nCol;
100263  p->aCol = pSelTab->aCol;
100264  pSelTab->nCol = 0;
100265  pSelTab->aCol = 0;
100266  sqlite3DeleteTable(db, pSelTab);
100267  addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
100268  VdbeCoverage(v);
100269  sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
100270  sqlite3TableAffinity(v, p, 0);
100271  sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
100272  sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
100273  sqlite3VdbeGoto(v, addrInsLoop);
100274  sqlite3VdbeJumpHere(v, addrInsLoop);
100275  sqlite3VdbeAddOp1(v, OP_Close, 1);
100276  }
100277 
100278  /* Compute the complete text of the CREATE statement */
100279  if( pSelect ){
100280  zStmt = createTableStmt(db, p);
100281  }else{
100282  Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
100283  n = (int)(pEnd2->z - pParse->sNameToken.z);
100284  if( pEnd2->z[0]!=';' ) n += pEnd2->n;
100285  zStmt = sqlite3MPrintf(db,
100286  "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
100287  );
100288  }
100289 
100290  /* A slot for the record has already been allocated in the
100291  ** SQLITE_MASTER table. We just need to update that slot with all
100292  ** the information we've collected.
100293  */
100294  sqlite3NestedParse(pParse,
100295  "UPDATE %Q.%s "
100296  "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
100297  "WHERE rowid=#%d",
100298  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb),
100299  zType,
100300  p->zName,
100301  p->zName,
100302  pParse->regRoot,
100303  zStmt,
100304  pParse->regRowid
100305  );
100306  sqlite3DbFree(db, zStmt);
100307  sqlite3ChangeCookie(pParse, iDb);
100308 
100309 #ifndef SQLITE_OMIT_AUTOINCREMENT
100310  /* Check to see if we need to create an sqlite_sequence table for
100311  ** keeping track of autoincrement keys.
100312  */
100313  if( (p->tabFlags & TF_Autoincrement)!=0 ){
100314  Db *pDb = &db->aDb[iDb];
100315  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100316  if( pDb->pSchema->pSeqTab==0 ){
100317  sqlite3NestedParse(pParse,
100318  "CREATE TABLE %Q.sqlite_sequence(name,seq)",
100319  pDb->zDbSName
100320  );
100321  }
100322  }
100323 #endif
100324 
100325  /* Reparse everything to update our internal data structures */
100326  sqlite3VdbeAddParseSchemaOp(v, iDb,
100327  sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
100328  }
100329 
100330 
100331  /* Add the table to the in-memory representation of the database.
100332  */
100333  if( db->init.busy ){
100334  Table *pOld;
100335  Schema *pSchema = p->pSchema;
100336  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100337  pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
100338  if( pOld ){
100339  assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
100340  sqlite3OomFault(db);
100341  return;
100342  }
100343  pParse->pNewTable = 0;
100344  db->flags |= SQLITE_InternChanges;
100345 
100346 #ifndef SQLITE_OMIT_ALTERTABLE
100347  if( !p->pSelect ){
100348  const char *zName = (const char *)pParse->sNameToken.z;
100349  int nName;
100350  assert( !pSelect && pCons && pEnd );
100351  if( pCons->z==0 ){
100352  pCons = pEnd;
100353  }
100354  nName = (int)((const char *)pCons->z - zName);
100355  p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
100356  }
100357 #endif
100358  }
100359 }
100360 
100361 #ifndef SQLITE_OMIT_VIEW
100362 /*
100363 ** The parser calls this routine in order to create a new VIEW
100364 */
100365 SQLITE_PRIVATE void sqlite3CreateView(
100366  Parse *pParse, /* The parsing context */
100367  Token *pBegin, /* The CREATE token that begins the statement */
100368  Token *pName1, /* The token that holds the name of the view */
100369  Token *pName2, /* The token that holds the name of the view */
100370  ExprList *pCNames, /* Optional list of view column names */
100371  Select *pSelect, /* A SELECT statement that will become the new view */
100372  int isTemp, /* TRUE for a TEMPORARY view */
100373  int noErr /* Suppress error messages if VIEW already exists */
100374 ){
100375  Table *p;
100376  int n;
100377  const char *z;
100378  Token sEnd;
100379  DbFixer sFix;
100380  Token *pName = 0;
100381  int iDb;
100382  sqlite3 *db = pParse->db;
100383 
100384  if( pParse->nVar>0 ){
100385  sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
100386  goto create_view_fail;
100387  }
100388  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
100389  p = pParse->pNewTable;
100390  if( p==0 || pParse->nErr ) goto create_view_fail;
100391  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
100392  iDb = sqlite3SchemaToIndex(db, p->pSchema);
100393  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
100394  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
100395 
100396  /* Make a copy of the entire SELECT statement that defines the view.
100397  ** This will force all the Expr.token.z values to be dynamically
100398  ** allocated rather than point to the input string - which means that
100399  ** they will persist after the current sqlite3_exec() call returns.
100400  */
100401  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
100402  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
100403  if( db->mallocFailed ) goto create_view_fail;
100404 
100405  /* Locate the end of the CREATE VIEW statement. Make sEnd point to
100406  ** the end.
100407  */
100408  sEnd = pParse->sLastToken;
100409  assert( sEnd.z[0]!=0 );
100410  if( sEnd.z[0]!=';' ){
100411  sEnd.z += sEnd.n;
100412  }
100413  sEnd.n = 0;
100414  n = (int)(sEnd.z - pBegin->z);
100415  assert( n>0 );
100416  z = pBegin->z;
100417  while( sqlite3Isspace(z[n-1]) ){ n--; }
100418  sEnd.z = &z[n-1];
100419  sEnd.n = 1;
100420 
100421  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
100422  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
100423 
100424 create_view_fail:
100425  sqlite3SelectDelete(db, pSelect);
100426  sqlite3ExprListDelete(db, pCNames);
100427  return;
100428 }
100429 #endif /* SQLITE_OMIT_VIEW */
100430 
100431 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
100432 /*
100433 ** The Table structure pTable is really a VIEW. Fill in the names of
100434 ** the columns of the view in the pTable structure. Return the number
100435 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
100436 */
100437 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
100438  Table *pSelTab; /* A fake table from which we get the result set */
100439  Select *pSel; /* Copy of the SELECT that implements the view */
100440  int nErr = 0; /* Number of errors encountered */
100441  int n; /* Temporarily holds the number of cursors assigned */
100442  sqlite3 *db = pParse->db; /* Database connection for malloc errors */
100443 #ifndef SQLITE_OMIT_AUTHORIZATION
100444  sqlite3_xauth xAuth; /* Saved xAuth pointer */
100445 #endif
100446 
100447  assert( pTable );
100448 
100449 #ifndef SQLITE_OMIT_VIRTUALTABLE
100450  if( sqlite3VtabCallConnect(pParse, pTable) ){
100451  return SQLITE_ERROR;
100452  }
100453  if( IsVirtual(pTable) ) return 0;
100454 #endif
100455 
100456 #ifndef SQLITE_OMIT_VIEW
100457  /* A positive nCol means the columns names for this view are
100458  ** already known.
100459  */
100460  if( pTable->nCol>0 ) return 0;
100461 
100462  /* A negative nCol is a special marker meaning that we are currently
100463  ** trying to compute the column names. If we enter this routine with
100464  ** a negative nCol, it means two or more views form a loop, like this:
100465  **
100466  ** CREATE VIEW one AS SELECT * FROM two;
100467  ** CREATE VIEW two AS SELECT * FROM one;
100468  **
100469  ** Actually, the error above is now caught prior to reaching this point.
100470  ** But the following test is still important as it does come up
100471  ** in the following:
100472  **
100473  ** CREATE TABLE main.ex1(a);
100474  ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
100475  ** SELECT * FROM temp.ex1;
100476  */
100477  if( pTable->nCol<0 ){
100478  sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
100479  return 1;
100480  }
100481  assert( pTable->nCol>=0 );
100482 
100483  /* If we get this far, it means we need to compute the table names.
100484  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
100485  ** "*" elements in the results set of the view and will assign cursors
100486  ** to the elements of the FROM clause. But we do not want these changes
100487  ** to be permanent. So the computation is done on a copy of the SELECT
100488  ** statement that defines the view.
100489  */
100490  assert( pTable->pSelect );
100491  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
100492  if( pSel ){
100493  n = pParse->nTab;
100494  sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
100495  pTable->nCol = -1;
100496  db->lookaside.bDisable++;
100497 #ifndef SQLITE_OMIT_AUTHORIZATION
100498  xAuth = db->xAuth;
100499  db->xAuth = 0;
100500  pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
100501  db->xAuth = xAuth;
100502 #else
100503  pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
100504 #endif
100505  pParse->nTab = n;
100506  if( pTable->pCheck ){
100507  /* CREATE VIEW name(arglist) AS ...
100508  ** The names of the columns in the table are taken from
100509  ** arglist which is stored in pTable->pCheck. The pCheck field
100510  ** normally holds CHECK constraints on an ordinary table, but for
100511  ** a VIEW it holds the list of column names.
100512  */
100513  sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
100514  &pTable->nCol, &pTable->aCol);
100515  if( db->mallocFailed==0
100516  && pParse->nErr==0
100517  && pTable->nCol==pSel->pEList->nExpr
100518  ){
100519  sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
100520  }
100521  }else if( pSelTab ){
100522  /* CREATE VIEW name AS... without an argument list. Construct
100523  ** the column names from the SELECT statement that defines the view.
100524  */
100525  assert( pTable->aCol==0 );
100526  pTable->nCol = pSelTab->nCol;
100527  pTable->aCol = pSelTab->aCol;
100528  pSelTab->nCol = 0;
100529  pSelTab->aCol = 0;
100530  assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
100531  }else{
100532  pTable->nCol = 0;
100533  nErr++;
100534  }
100535  sqlite3DeleteTable(db, pSelTab);
100536  sqlite3SelectDelete(db, pSel);
100537  db->lookaside.bDisable--;
100538  } else {
100539  nErr++;
100540  }
100541  pTable->pSchema->schemaFlags |= DB_UnresetViews;
100542 #endif /* SQLITE_OMIT_VIEW */
100543  return nErr;
100544 }
100545 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
100546 
100547 #ifndef SQLITE_OMIT_VIEW
100548 /*
100549 ** Clear the column names from every VIEW in database idx.
100550 */
100551 static void sqliteViewResetAll(sqlite3 *db, int idx){
100552  HashElem *i;
100553  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
100554  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
100555  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
100556  Table *pTab = sqliteHashData(i);
100557  if( pTab->pSelect ){
100558  sqlite3DeleteColumnNames(db, pTab);
100559  pTab->aCol = 0;
100560  pTab->nCol = 0;
100561  }
100562  }
100563  DbClearProperty(db, idx, DB_UnresetViews);
100564 }
100565 #else
100566 # define sqliteViewResetAll(A,B)
100567 #endif /* SQLITE_OMIT_VIEW */
100568 
100569 /*
100570 ** This function is called by the VDBE to adjust the internal schema
100571 ** used by SQLite when the btree layer moves a table root page. The
100572 ** root-page of a table or index in database iDb has changed from iFrom
100573 ** to iTo.
100574 **
100575 ** Ticket #1728: The symbol table might still contain information
100576 ** on tables and/or indices that are the process of being deleted.
100577 ** If you are unlucky, one of those deleted indices or tables might
100578 ** have the same rootpage number as the real table or index that is
100579 ** being moved. So we cannot stop searching after the first match
100580 ** because the first match might be for one of the deleted indices
100581 ** or tables and not the table/index that is actually being moved.
100582 ** We must continue looping until all tables and indices with
100583 ** rootpage==iFrom have been converted to have a rootpage of iTo
100584 ** in order to be certain that we got the right one.
100585 */
100586 #ifndef SQLITE_OMIT_AUTOVACUUM
100587 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
100588  HashElem *pElem;
100589  Hash *pHash;
100590  Db *pDb;
100591 
100592  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100593  pDb = &db->aDb[iDb];
100594  pHash = &pDb->pSchema->tblHash;
100595  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
100596  Table *pTab = sqliteHashData(pElem);
100597  if( pTab->tnum==iFrom ){
100598  pTab->tnum = iTo;
100599  }
100600  }
100601  pHash = &pDb->pSchema->idxHash;
100602  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
100603  Index *pIdx = sqliteHashData(pElem);
100604  if( pIdx->tnum==iFrom ){
100605  pIdx->tnum = iTo;
100606  }
100607  }
100608 }
100609 #endif
100610 
100611 /*
100612 ** Write code to erase the table with root-page iTable from database iDb.
100613 ** Also write code to modify the sqlite_master table and internal schema
100614 ** if a root-page of another table is moved by the btree-layer whilst
100615 ** erasing iTable (this can happen with an auto-vacuum database).
100616 */
100617 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
100618  Vdbe *v = sqlite3GetVdbe(pParse);
100619  int r1 = sqlite3GetTempReg(pParse);
100620  assert( iTable>1 );
100621  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
100622  sqlite3MayAbort(pParse);
100623 #ifndef SQLITE_OMIT_AUTOVACUUM
100624  /* OP_Destroy stores an in integer r1. If this integer
100625  ** is non-zero, then it is the root page number of a table moved to
100626  ** location iTable. The following code modifies the sqlite_master table to
100627  ** reflect this.
100628  **
100629  ** The "#NNN" in the SQL is a special constant that means whatever value
100630  ** is in register NNN. See grammar rules associated with the TK_REGISTER
100631  ** token for additional information.
100632  */
100633  sqlite3NestedParse(pParse,
100634  "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
100635  pParse->db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), iTable, r1, r1);
100636 #endif
100637  sqlite3ReleaseTempReg(pParse, r1);
100638 }
100639 
100640 /*
100641 ** Write VDBE code to erase table pTab and all associated indices on disk.
100642 ** Code to update the sqlite_master tables and internal schema definitions
100643 ** in case a root-page belonging to another table is moved by the btree layer
100644 ** is also added (this can happen with an auto-vacuum database).
100645 */
100646 static void destroyTable(Parse *pParse, Table *pTab){
100647 #ifdef SQLITE_OMIT_AUTOVACUUM
100648  Index *pIdx;
100649  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100650  destroyRootPage(pParse, pTab->tnum, iDb);
100651  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100652  destroyRootPage(pParse, pIdx->tnum, iDb);
100653  }
100654 #else
100655  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
100656  ** is not defined), then it is important to call OP_Destroy on the
100657  ** table and index root-pages in order, starting with the numerically
100658  ** largest root-page number. This guarantees that none of the root-pages
100659  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
100660  ** following were coded:
100661  **
100662  ** OP_Destroy 4 0
100663  ** ...
100664  ** OP_Destroy 5 0
100665  **
100666  ** and root page 5 happened to be the largest root-page number in the
100667  ** database, then root page 5 would be moved to page 4 by the
100668  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
100669  ** a free-list page.
100670  */
100671  int iTab = pTab->tnum;
100672  int iDestroyed = 0;
100673 
100674  while( 1 ){
100675  Index *pIdx;
100676  int iLargest = 0;
100677 
100678  if( iDestroyed==0 || iTab<iDestroyed ){
100679  iLargest = iTab;
100680  }
100681  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100682  int iIdx = pIdx->tnum;
100683  assert( pIdx->pSchema==pTab->pSchema );
100684  if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
100685  iLargest = iIdx;
100686  }
100687  }
100688  if( iLargest==0 ){
100689  return;
100690  }else{
100691  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100692  assert( iDb>=0 && iDb<pParse->db->nDb );
100693  destroyRootPage(pParse, iLargest, iDb);
100694  iDestroyed = iLargest;
100695  }
100696  }
100697 #endif
100698 }
100699 
100700 /*
100701 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
100702 ** after a DROP INDEX or DROP TABLE command.
100703 */
100704 static void sqlite3ClearStatTables(
100705  Parse *pParse, /* The parsing context */
100706  int iDb, /* The database number */
100707  const char *zType, /* "idx" or "tbl" */
100708  const char *zName /* Name of index or table */
100709 ){
100710  int i;
100711  const char *zDbName = pParse->db->aDb[iDb].zDbSName;
100712  for(i=1; i<=4; i++){
100713  char zTab[24];
100714  sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
100715  if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
100716  sqlite3NestedParse(pParse,
100717  "DELETE FROM %Q.%s WHERE %s=%Q",
100718  zDbName, zTab, zType, zName
100719  );
100720  }
100721  }
100722 }
100723 
100724 /*
100725 ** Generate code to drop a table.
100726 */
100727 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
100728  Vdbe *v;
100729  sqlite3 *db = pParse->db;
100730  Trigger *pTrigger;
100731  Db *pDb = &db->aDb[iDb];
100732 
100733  v = sqlite3GetVdbe(pParse);
100734  assert( v!=0 );
100735  sqlite3BeginWriteOperation(pParse, 1, iDb);
100736 
100737 #ifndef SQLITE_OMIT_VIRTUALTABLE
100738  if( IsVirtual(pTab) ){
100739  sqlite3VdbeAddOp0(v, OP_VBegin);
100740  }
100741 #endif
100742 
100743  /* Drop all triggers associated with the table being dropped. Code
100744  ** is generated to remove entries from sqlite_master and/or
100745  ** sqlite_temp_master if required.
100746  */
100747  pTrigger = sqlite3TriggerList(pParse, pTab);
100748  while( pTrigger ){
100749  assert( pTrigger->pSchema==pTab->pSchema ||
100750  pTrigger->pSchema==db->aDb[1].pSchema );
100751  sqlite3DropTriggerPtr(pParse, pTrigger);
100752  pTrigger = pTrigger->pNext;
100753  }
100754 
100755 #ifndef SQLITE_OMIT_AUTOINCREMENT
100756  /* Remove any entries of the sqlite_sequence table associated with
100757  ** the table being dropped. This is done before the table is dropped
100758  ** at the btree level, in case the sqlite_sequence table needs to
100759  ** move as a result of the drop (can happen in auto-vacuum mode).
100760  */
100761  if( pTab->tabFlags & TF_Autoincrement ){
100762  sqlite3NestedParse(pParse,
100763  "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
100764  pDb->zDbSName, pTab->zName
100765  );
100766  }
100767 #endif
100768 
100769  /* Drop all SQLITE_MASTER table and index entries that refer to the
100770  ** table. The program name loops through the master table and deletes
100771  ** every row that refers to a table of the same name as the one being
100772  ** dropped. Triggers are handled separately because a trigger can be
100773  ** created in the temp database that refers to a table in another
100774  ** database.
100775  */
100776  sqlite3NestedParse(pParse,
100777  "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
100778  pDb->zDbSName, SCHEMA_TABLE(iDb), pTab->zName);
100779  if( !isView && !IsVirtual(pTab) ){
100780  destroyTable(pParse, pTab);
100781  }
100782 
100783  /* Remove the table entry from SQLite's internal schema and modify
100784  ** the schema cookie.
100785  */
100786  if( IsVirtual(pTab) ){
100787  sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
100788  }
100789  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
100790  sqlite3ChangeCookie(pParse, iDb);
100791  sqliteViewResetAll(db, iDb);
100792 }
100793 
100794 /*
100795 ** This routine is called to do the work of a DROP TABLE statement.
100796 ** pName is the name of the table to be dropped.
100797 */
100798 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
100799  Table *pTab;
100800  Vdbe *v;
100801  sqlite3 *db = pParse->db;
100802  int iDb;
100803 
100804  if( db->mallocFailed ){
100805  goto exit_drop_table;
100806  }
100807  assert( pParse->nErr==0 );
100808  assert( pName->nSrc==1 );
100809  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
100810  if( noErr ) db->suppressErr++;
100811  assert( isView==0 || isView==LOCATE_VIEW );
100812  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
100813  if( noErr ) db->suppressErr--;
100814 
100815  if( pTab==0 ){
100816  if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
100817  goto exit_drop_table;
100818  }
100819  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100820  assert( iDb>=0 && iDb<db->nDb );
100821 
100822  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
100823  ** it is initialized.
100824  */
100825  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
100826  goto exit_drop_table;
100827  }
100828 #ifndef SQLITE_OMIT_AUTHORIZATION
100829  {
100830  int code;
100831  const char *zTab = SCHEMA_TABLE(iDb);
100832  const char *zDb = db->aDb[iDb].zDbSName;
100833  const char *zArg2 = 0;
100834  if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
100835  goto exit_drop_table;
100836  }
100837  if( isView ){
100838  if( !OMIT_TEMPDB && iDb==1 ){
100839  code = SQLITE_DROP_TEMP_VIEW;
100840  }else{
100841  code = SQLITE_DROP_VIEW;
100842  }
100843 #ifndef SQLITE_OMIT_VIRTUALTABLE
100844  }else if( IsVirtual(pTab) ){
100845  code = SQLITE_DROP_VTABLE;
100846  zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
100847 #endif
100848  }else{
100849  if( !OMIT_TEMPDB && iDb==1 ){
100850  code = SQLITE_DROP_TEMP_TABLE;
100851  }else{
100852  code = SQLITE_DROP_TABLE;
100853  }
100854  }
100855  if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
100856  goto exit_drop_table;
100857  }
100858  if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
100859  goto exit_drop_table;
100860  }
100861  }
100862 #endif
100863  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
100864  && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
100865  sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
100866  goto exit_drop_table;
100867  }
100868 
100869 #ifndef SQLITE_OMIT_VIEW
100870  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
100871  ** on a table.
100872  */
100873  if( isView && pTab->pSelect==0 ){
100874  sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
100875  goto exit_drop_table;
100876  }
100877  if( !isView && pTab->pSelect ){
100878  sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
100879  goto exit_drop_table;
100880  }
100881 #endif
100882 
100883  /* Generate code to remove the table from the master table
100884  ** on disk.
100885  */
100886  v = sqlite3GetVdbe(pParse);
100887  if( v ){
100888  sqlite3BeginWriteOperation(pParse, 1, iDb);
100889  sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
100890  sqlite3FkDropTable(pParse, pName, pTab);
100891  sqlite3CodeDropTable(pParse, pTab, iDb, isView);
100892  }
100893 
100894 exit_drop_table:
100895  sqlite3SrcListDelete(db, pName);
100896 }
100897 
100898 /*
100899 ** This routine is called to create a new foreign key on the table
100900 ** currently under construction. pFromCol determines which columns
100901 ** in the current table point to the foreign key. If pFromCol==0 then
100902 ** connect the key to the last column inserted. pTo is the name of
100903 ** the table referred to (a.k.a the "parent" table). pToCol is a list
100904 ** of tables in the parent pTo table. flags contains all
100905 ** information about the conflict resolution algorithms specified
100906 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
100907 **
100908 ** An FKey structure is created and added to the table currently
100909 ** under construction in the pParse->pNewTable field.
100910 **
100911 ** The foreign key is set for IMMEDIATE processing. A subsequent call
100912 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
100913 */
100914 SQLITE_PRIVATE void sqlite3CreateForeignKey(
100915  Parse *pParse, /* Parsing context */
100916  ExprList *pFromCol, /* Columns in this table that point to other table */
100917  Token *pTo, /* Name of the other table */
100918  ExprList *pToCol, /* Columns in the other table */
100919  int flags /* Conflict resolution algorithms. */
100920 ){
100921  sqlite3 *db = pParse->db;
100922 #ifndef SQLITE_OMIT_FOREIGN_KEY
100923  FKey *pFKey = 0;
100924  FKey *pNextTo;
100925  Table *p = pParse->pNewTable;
100926  int nByte;
100927  int i;
100928  int nCol;
100929  char *z;
100930 
100931  assert( pTo!=0 );
100932  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
100933  if( pFromCol==0 ){
100934  int iCol = p->nCol-1;
100935  if( NEVER(iCol<0) ) goto fk_end;
100936  if( pToCol && pToCol->nExpr!=1 ){
100937  sqlite3ErrorMsg(pParse, "foreign key on %s"
100938  " should reference only one column of table %T",
100939  p->aCol[iCol].zName, pTo);
100940  goto fk_end;
100941  }
100942  nCol = 1;
100943  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
100944  sqlite3ErrorMsg(pParse,
100945  "number of columns in foreign key does not match the number of "
100946  "columns in the referenced table");
100947  goto fk_end;
100948  }else{
100949  nCol = pFromCol->nExpr;
100950  }
100951  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
100952  if( pToCol ){
100953  for(i=0; i<pToCol->nExpr; i++){
100954  nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
100955  }
100956  }
100957  pFKey = sqlite3DbMallocZero(db, nByte );
100958  if( pFKey==0 ){
100959  goto fk_end;
100960  }
100961  pFKey->pFrom = p;
100962  pFKey->pNextFrom = p->pFKey;
100963  z = (char*)&pFKey->aCol[nCol];
100964  pFKey->zTo = z;
100965  memcpy(z, pTo->z, pTo->n);
100966  z[pTo->n] = 0;
100967  sqlite3Dequote(z);
100968  z += pTo->n+1;
100969  pFKey->nCol = nCol;
100970  if( pFromCol==0 ){
100971  pFKey->aCol[0].iFrom = p->nCol-1;
100972  }else{
100973  for(i=0; i<nCol; i++){
100974  int j;
100975  for(j=0; j<p->nCol; j++){
100976  if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
100977  pFKey->aCol[i].iFrom = j;
100978  break;
100979  }
100980  }
100981  if( j>=p->nCol ){
100982  sqlite3ErrorMsg(pParse,
100983  "unknown column \"%s\" in foreign key definition",
100984  pFromCol->a[i].zName);
100985  goto fk_end;
100986  }
100987  }
100988  }
100989  if( pToCol ){
100990  for(i=0; i<nCol; i++){
100991  int n = sqlite3Strlen30(pToCol->a[i].zName);
100992  pFKey->aCol[i].zCol = z;
100993  memcpy(z, pToCol->a[i].zName, n);
100994  z[n] = 0;
100995  z += n+1;
100996  }
100997  }
100998  pFKey->isDeferred = 0;
100999  pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
101000  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
101001 
101002  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
101003  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
101004  pFKey->zTo, (void *)pFKey
101005  );
101006  if( pNextTo==pFKey ){
101007  sqlite3OomFault(db);
101008  goto fk_end;
101009  }
101010  if( pNextTo ){
101011  assert( pNextTo->pPrevTo==0 );
101012  pFKey->pNextTo = pNextTo;
101013  pNextTo->pPrevTo = pFKey;
101014  }
101015 
101016  /* Link the foreign key to the table as the last step.
101017  */
101018  p->pFKey = pFKey;
101019  pFKey = 0;
101020 
101021 fk_end:
101022  sqlite3DbFree(db, pFKey);
101023 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
101024  sqlite3ExprListDelete(db, pFromCol);
101025  sqlite3ExprListDelete(db, pToCol);
101026 }
101027 
101028 /*
101029 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
101030 ** clause is seen as part of a foreign key definition. The isDeferred
101031 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
101032 ** The behavior of the most recently created foreign key is adjusted
101033 ** accordingly.
101034 */
101035 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
101036 #ifndef SQLITE_OMIT_FOREIGN_KEY
101037  Table *pTab;
101038  FKey *pFKey;
101039  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
101040  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
101041  pFKey->isDeferred = (u8)isDeferred;
101042 #endif
101043 }
101044 
101045 /*
101046 ** Generate code that will erase and refill index *pIdx. This is
101047 ** used to initialize a newly created index or to recompute the
101048 ** content of an index in response to a REINDEX command.
101049 **
101050 ** if memRootPage is not negative, it means that the index is newly
101051 ** created. The register specified by memRootPage contains the
101052 ** root page number of the index. If memRootPage is negative, then
101053 ** the index already exists and must be cleared before being refilled and
101054 ** the root page number of the index is taken from pIndex->tnum.
101055 */
101056 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
101057  Table *pTab = pIndex->pTable; /* The table that is indexed */
101058  int iTab = pParse->nTab++; /* Btree cursor used for pTab */
101059  int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
101060  int iSorter; /* Cursor opened by OpenSorter (if in use) */
101061  int addr1; /* Address of top of loop */
101062  int addr2; /* Address to jump to for next iteration */
101063  int tnum; /* Root page of index */
101064  int iPartIdxLabel; /* Jump to this label to skip a row */
101065  Vdbe *v; /* Generate code into this virtual machine */
101066  KeyInfo *pKey; /* KeyInfo for index */
101067  int regRecord; /* Register holding assembled index record */
101068  sqlite3 *db = pParse->db; /* The database connection */
101069  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
101070 
101071 #ifndef SQLITE_OMIT_AUTHORIZATION
101072  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
101073  db->aDb[iDb].zDbSName ) ){
101074  return;
101075  }
101076 #endif
101077 
101078  /* Require a write-lock on the table to perform this operation */
101079  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
101080 
101081  v = sqlite3GetVdbe(pParse);
101082  if( v==0 ) return;
101083  if( memRootPage>=0 ){
101084  tnum = memRootPage;
101085  }else{
101086  tnum = pIndex->tnum;
101087  }
101088  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
101089  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
101090 
101091  /* Open the sorter cursor if we are to use one. */
101092  iSorter = pParse->nTab++;
101093  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
101094  sqlite3KeyInfoRef(pKey), P4_KEYINFO);
101095 
101096  /* Open the table. Loop through all rows of the table, inserting index
101097  ** records into the sorter. */
101098  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
101099  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
101100  regRecord = sqlite3GetTempReg(pParse);
101101 
101102  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
101103  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
101104  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
101105  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
101106  sqlite3VdbeJumpHere(v, addr1);
101107  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
101108  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
101109  (char *)pKey, P4_KEYINFO);
101110  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
101111 
101112  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
101113  if( IsUniqueIndex(pIndex) ){
101114  int j2 = sqlite3VdbeCurrentAddr(v) + 3;
101115  sqlite3VdbeGoto(v, j2);
101116  addr2 = sqlite3VdbeCurrentAddr(v);
101117  sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
101118  pIndex->nKeyCol); VdbeCoverage(v);
101119  sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
101120  }else{
101121  addr2 = sqlite3VdbeCurrentAddr(v);
101122  }
101123  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
101124  sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
101125  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
101126  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
101127  sqlite3ReleaseTempReg(pParse, regRecord);
101128  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
101129  sqlite3VdbeJumpHere(v, addr1);
101130 
101131  sqlite3VdbeAddOp1(v, OP_Close, iTab);
101132  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
101133  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
101134 }
101135 
101136 /*
101137 ** Allocate heap space to hold an Index object with nCol columns.
101138 **
101139 ** Increase the allocation size to provide an extra nExtra bytes
101140 ** of 8-byte aligned space after the Index object and return a
101141 ** pointer to this extra space in *ppExtra.
101142 */
101143 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
101144  sqlite3 *db, /* Database connection */
101145  i16 nCol, /* Total number of columns in the index */
101146  int nExtra, /* Number of bytes of extra space to alloc */
101147  char **ppExtra /* Pointer to the "extra" space */
101148 ){
101149  Index *p; /* Allocated index object */
101150  int nByte; /* Bytes of space for Index object + arrays */
101151 
101152  nByte = ROUND8(sizeof(Index)) + /* Index structure */
101153  ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
101154  ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
101155  sizeof(i16)*nCol + /* Index.aiColumn */
101156  sizeof(u8)*nCol); /* Index.aSortOrder */
101157  p = sqlite3DbMallocZero(db, nByte + nExtra);
101158  if( p ){
101159  char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
101160  p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
101161  p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
101162  p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
101163  p->aSortOrder = (u8*)pExtra;
101164  p->nColumn = nCol;
101165  p->nKeyCol = nCol - 1;
101166  *ppExtra = ((char*)p) + nByte;
101167  }
101168  return p;
101169 }
101170 
101171 /*
101172 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
101173 ** and pTblList is the name of the table that is to be indexed. Both will
101174 ** be NULL for a primary key or an index that is created to satisfy a
101175 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
101176 ** as the table to be indexed. pParse->pNewTable is a table that is
101177 ** currently being constructed by a CREATE TABLE statement.
101178 **
101179 ** pList is a list of columns to be indexed. pList will be NULL if this
101180 ** is a primary key or unique-constraint on the most recent column added
101181 ** to the table currently under construction.
101182 */
101183 SQLITE_PRIVATE void sqlite3CreateIndex(
101184  Parse *pParse, /* All information about this parse */
101185  Token *pName1, /* First part of index name. May be NULL */
101186  Token *pName2, /* Second part of index name. May be NULL */
101187  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
101188  ExprList *pList, /* A list of columns to be indexed */
101189  int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
101190  Token *pStart, /* The CREATE token that begins this statement */
101191  Expr *pPIWhere, /* WHERE clause for partial indices */
101192  int sortOrder, /* Sort order of primary key when pList==NULL */
101193  int ifNotExist, /* Omit error if index already exists */
101194  u8 idxType /* The index type */
101195 ){
101196  Table *pTab = 0; /* Table to be indexed */
101197  Index *pIndex = 0; /* The index to be created */
101198  char *zName = 0; /* Name of the index */
101199  int nName; /* Number of characters in zName */
101200  int i, j;
101201  DbFixer sFix; /* For assigning database names to pTable */
101202  int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
101203  sqlite3 *db = pParse->db;
101204  Db *pDb; /* The specific table containing the indexed database */
101205  int iDb; /* Index of the database that is being written */
101206  Token *pName = 0; /* Unqualified name of the index to create */
101207  struct ExprList_item *pListItem; /* For looping over pList */
101208  int nExtra = 0; /* Space allocated for zExtra[] */
101209  int nExtraCol; /* Number of extra columns needed */
101210  char *zExtra = 0; /* Extra space after the Index object */
101211  Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
101212 
101213  if( db->mallocFailed || pParse->nErr>0 ){
101214  goto exit_create_index;
101215  }
101216  if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
101217  goto exit_create_index;
101218  }
101219  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101220  goto exit_create_index;
101221  }
101222 
101223  /*
101224  ** Find the table that is to be indexed. Return early if not found.
101225  */
101226  if( pTblName!=0 ){
101227 
101228  /* Use the two-part index name to determine the database
101229  ** to search for the table. 'Fix' the table name to this db
101230  ** before looking up the table.
101231  */
101232  assert( pName1 && pName2 );
101233  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101234  if( iDb<0 ) goto exit_create_index;
101235  assert( pName && pName->z );
101236 
101237 #ifndef SQLITE_OMIT_TEMPDB
101238  /* If the index name was unqualified, check if the table
101239  ** is a temp table. If so, set the database to 1. Do not do this
101240  ** if initialising a database schema.
101241  */
101242  if( !db->init.busy ){
101243  pTab = sqlite3SrcListLookup(pParse, pTblName);
101244  if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
101245  iDb = 1;
101246  }
101247  }
101248 #endif
101249 
101250  sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
101251  if( sqlite3FixSrcList(&sFix, pTblName) ){
101252  /* Because the parser constructs pTblName from a single identifier,
101253  ** sqlite3FixSrcList can never fail. */
101254  assert(0);
101255  }
101256  pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
101257  assert( db->mallocFailed==0 || pTab==0 );
101258  if( pTab==0 ) goto exit_create_index;
101259  if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
101260  sqlite3ErrorMsg(pParse,
101261  "cannot create a TEMP index on non-TEMP table \"%s\"",
101262  pTab->zName);
101263  goto exit_create_index;
101264  }
101265  if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
101266  }else{
101267  assert( pName==0 );
101268  assert( pStart==0 );
101269  pTab = pParse->pNewTable;
101270  if( !pTab ) goto exit_create_index;
101271  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101272  }
101273  pDb = &db->aDb[iDb];
101274 
101275  assert( pTab!=0 );
101276  assert( pParse->nErr==0 );
101277  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
101278  && db->init.busy==0
101279 #if SQLITE_USER_AUTHENTICATION
101280  && sqlite3UserAuthTable(pTab->zName)==0
101281 #endif
101282  && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
101283  sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
101284  goto exit_create_index;
101285  }
101286 #ifndef SQLITE_OMIT_VIEW
101287  if( pTab->pSelect ){
101288  sqlite3ErrorMsg(pParse, "views may not be indexed");
101289  goto exit_create_index;
101290  }
101291 #endif
101292 #ifndef SQLITE_OMIT_VIRTUALTABLE
101293  if( IsVirtual(pTab) ){
101294  sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
101295  goto exit_create_index;
101296  }
101297 #endif
101298 
101299  /*
101300  ** Find the name of the index. Make sure there is not already another
101301  ** index or table with the same name.
101302  **
101303  ** Exception: If we are reading the names of permanent indices from the
101304  ** sqlite_master table (because some other process changed the schema) and
101305  ** one of the index names collides with the name of a temporary table or
101306  ** index, then we will continue to process this index.
101307  **
101308  ** If pName==0 it means that we are
101309  ** dealing with a primary key or UNIQUE constraint. We have to invent our
101310  ** own name.
101311  */
101312  if( pName ){
101313  zName = sqlite3NameFromToken(db, pName);
101314  if( zName==0 ) goto exit_create_index;
101315  assert( pName->z!=0 );
101316  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
101317  goto exit_create_index;
101318  }
101319  if( !db->init.busy ){
101320  if( sqlite3FindTable(db, zName, 0)!=0 ){
101321  sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
101322  goto exit_create_index;
101323  }
101324  }
101325  if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
101326  if( !ifNotExist ){
101327  sqlite3ErrorMsg(pParse, "index %s already exists", zName);
101328  }else{
101329  assert( !db->init.busy );
101330  sqlite3CodeVerifySchema(pParse, iDb);
101331  }
101332  goto exit_create_index;
101333  }
101334  }else{
101335  int n;
101336  Index *pLoop;
101337  for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
101338  zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
101339  if( zName==0 ){
101340  goto exit_create_index;
101341  }
101342 
101343  /* Automatic index names generated from within sqlite3_declare_vtab()
101344  ** must have names that are distinct from normal automatic index names.
101345  ** The following statement converts "sqlite3_autoindex..." into
101346  ** "sqlite3_butoindex..." in order to make the names distinct.
101347  ** The "vtab_err.test" test demonstrates the need of this statement. */
101348  if( IN_DECLARE_VTAB ) zName[7]++;
101349  }
101350 
101351  /* Check for authorization to create an index.
101352  */
101353 #ifndef SQLITE_OMIT_AUTHORIZATION
101354  {
101355  const char *zDb = pDb->zDbSName;
101356  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
101357  goto exit_create_index;
101358  }
101359  i = SQLITE_CREATE_INDEX;
101360  if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
101361  if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
101362  goto exit_create_index;
101363  }
101364  }
101365 #endif
101366 
101367  /* If pList==0, it means this routine was called to make a primary
101368  ** key out of the last column added to the table under construction.
101369  ** So create a fake list to simulate this.
101370  */
101371  if( pList==0 ){
101372  Token prevCol;
101373  sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
101374  pList = sqlite3ExprListAppend(pParse, 0,
101375  sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
101376  if( pList==0 ) goto exit_create_index;
101377  assert( pList->nExpr==1 );
101378  sqlite3ExprListSetSortOrder(pList, sortOrder);
101379  }else{
101380  sqlite3ExprListCheckLength(pParse, pList, "index");
101381  }
101382 
101383  /* Figure out how many bytes of space are required to store explicitly
101384  ** specified collation sequence names.
101385  */
101386  for(i=0; i<pList->nExpr; i++){
101387  Expr *pExpr = pList->a[i].pExpr;
101388  assert( pExpr!=0 );
101389  if( pExpr->op==TK_COLLATE ){
101390  nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
101391  }
101392  }
101393 
101394  /*
101395  ** Allocate the index structure.
101396  */
101397  nName = sqlite3Strlen30(zName);
101398  nExtraCol = pPk ? pPk->nKeyCol : 1;
101399  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
101400  nName + nExtra + 1, &zExtra);
101401  if( db->mallocFailed ){
101402  goto exit_create_index;
101403  }
101404  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
101405  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
101406  pIndex->zName = zExtra;
101407  zExtra += nName + 1;
101408  memcpy(pIndex->zName, zName, nName+1);
101409  pIndex->pTable = pTab;
101410  pIndex->onError = (u8)onError;
101411  pIndex->uniqNotNull = onError!=OE_None;
101412  pIndex->idxType = idxType;
101413  pIndex->pSchema = db->aDb[iDb].pSchema;
101414  pIndex->nKeyCol = pList->nExpr;
101415  if( pPIWhere ){
101416  sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
101417  pIndex->pPartIdxWhere = pPIWhere;
101418  pPIWhere = 0;
101419  }
101420  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101421 
101422  /* Check to see if we should honor DESC requests on index columns
101423  */
101424  if( pDb->pSchema->file_format>=4 ){
101425  sortOrderMask = -1; /* Honor DESC */
101426  }else{
101427  sortOrderMask = 0; /* Ignore DESC */
101428  }
101429 
101430  /* Analyze the list of expressions that form the terms of the index and
101431  ** report any errors. In the common case where the expression is exactly
101432  ** a table column, store that column in aiColumn[]. For general expressions,
101433  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
101434  **
101435  ** TODO: Issue a warning if two or more columns of the index are identical.
101436  ** TODO: Issue a warning if the table primary key is used as part of the
101437  ** index key.
101438  */
101439  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
101440  Expr *pCExpr; /* The i-th index expression */
101441  int requestedSortOrder; /* ASC or DESC on the i-th expression */
101442  const char *zColl; /* Collation sequence name */
101443 
101444  sqlite3StringToId(pListItem->pExpr);
101445  sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
101446  if( pParse->nErr ) goto exit_create_index;
101447  pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
101448  if( pCExpr->op!=TK_COLUMN ){
101449  if( pTab==pParse->pNewTable ){
101450  sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
101451  "UNIQUE constraints");
101452  goto exit_create_index;
101453  }
101454  if( pIndex->aColExpr==0 ){
101455  ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
101456  pIndex->aColExpr = pCopy;
101457  if( !db->mallocFailed ){
101458  assert( pCopy!=0 );
101459  pListItem = &pCopy->a[i];
101460  }
101461  }
101462  j = XN_EXPR;
101463  pIndex->aiColumn[i] = XN_EXPR;
101464  pIndex->uniqNotNull = 0;
101465  }else{
101466  j = pCExpr->iColumn;
101467  assert( j<=0x7fff );
101468  if( j<0 ){
101469  j = pTab->iPKey;
101470  }else if( pTab->aCol[j].notNull==0 ){
101471  pIndex->uniqNotNull = 0;
101472  }
101473  pIndex->aiColumn[i] = (i16)j;
101474  }
101475  zColl = 0;
101476  if( pListItem->pExpr->op==TK_COLLATE ){
101477  int nColl;
101478  zColl = pListItem->pExpr->u.zToken;
101479  nColl = sqlite3Strlen30(zColl) + 1;
101480  assert( nExtra>=nColl );
101481  memcpy(zExtra, zColl, nColl);
101482  zColl = zExtra;
101483  zExtra += nColl;
101484  nExtra -= nColl;
101485  }else if( j>=0 ){
101486  zColl = pTab->aCol[j].zColl;
101487  }
101488  if( !zColl ) zColl = sqlite3StrBINARY;
101489  if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
101490  goto exit_create_index;
101491  }
101492  pIndex->azColl[i] = zColl;
101493  requestedSortOrder = pListItem->sortOrder & sortOrderMask;
101494  pIndex->aSortOrder[i] = (u8)requestedSortOrder;
101495  }
101496 
101497  /* Append the table key to the end of the index. For WITHOUT ROWID
101498  ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
101499  ** normal tables (when pPk==0) this will be the rowid.
101500  */
101501  if( pPk ){
101502  for(j=0; j<pPk->nKeyCol; j++){
101503  int x = pPk->aiColumn[j];
101504  assert( x>=0 );
101505  if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
101506  pIndex->nColumn--;
101507  }else{
101508  pIndex->aiColumn[i] = x;
101509  pIndex->azColl[i] = pPk->azColl[j];
101510  pIndex->aSortOrder[i] = pPk->aSortOrder[j];
101511  i++;
101512  }
101513  }
101514  assert( i==pIndex->nColumn );
101515  }else{
101516  pIndex->aiColumn[i] = XN_ROWID;
101517  pIndex->azColl[i] = sqlite3StrBINARY;
101518  }
101519  sqlite3DefaultRowEst(pIndex);
101520  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
101521 
101522  /* If this index contains every column of its table, then mark
101523  ** it as a covering index */
101524  assert( HasRowid(pTab)
101525  || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
101526  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
101527  pIndex->isCovering = 1;
101528  for(j=0; j<pTab->nCol; j++){
101529  if( j==pTab->iPKey ) continue;
101530  if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
101531  pIndex->isCovering = 0;
101532  break;
101533  }
101534  }
101535 
101536  if( pTab==pParse->pNewTable ){
101537  /* This routine has been called to create an automatic index as a
101538  ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
101539  ** a PRIMARY KEY or UNIQUE clause following the column definitions.
101540  ** i.e. one of:
101541  **
101542  ** CREATE TABLE t(x PRIMARY KEY, y);
101543  ** CREATE TABLE t(x, y, UNIQUE(x, y));
101544  **
101545  ** Either way, check to see if the table already has such an index. If
101546  ** so, don't bother creating this one. This only applies to
101547  ** automatically created indices. Users can do as they wish with
101548  ** explicit indices.
101549  **
101550  ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
101551  ** (and thus suppressing the second one) even if they have different
101552  ** sort orders.
101553  **
101554  ** If there are different collating sequences or if the columns of
101555  ** the constraint occur in different orders, then the constraints are
101556  ** considered distinct and both result in separate indices.
101557  */
101558  Index *pIdx;
101559  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101560  int k;
101561  assert( IsUniqueIndex(pIdx) );
101562  assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
101563  assert( IsUniqueIndex(pIndex) );
101564 
101565  if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
101566  for(k=0; k<pIdx->nKeyCol; k++){
101567  const char *z1;
101568  const char *z2;
101569  assert( pIdx->aiColumn[k]>=0 );
101570  if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
101571  z1 = pIdx->azColl[k];
101572  z2 = pIndex->azColl[k];
101573  if( sqlite3StrICmp(z1, z2) ) break;
101574  }
101575  if( k==pIdx->nKeyCol ){
101576  if( pIdx->onError!=pIndex->onError ){
101577  /* This constraint creates the same index as a previous
101578  ** constraint specified somewhere in the CREATE TABLE statement.
101579  ** However the ON CONFLICT clauses are different. If both this
101580  ** constraint and the previous equivalent constraint have explicit
101581  ** ON CONFLICT clauses this is an error. Otherwise, use the
101582  ** explicitly specified behavior for the index.
101583  */
101584  if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
101585  sqlite3ErrorMsg(pParse,
101586  "conflicting ON CONFLICT clauses specified", 0);
101587  }
101588  if( pIdx->onError==OE_Default ){
101589  pIdx->onError = pIndex->onError;
101590  }
101591  }
101592  if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
101593  goto exit_create_index;
101594  }
101595  }
101596  }
101597 
101598  /* Link the new Index structure to its table and to the other
101599  ** in-memory database structures.
101600  */
101601  assert( pParse->nErr==0 );
101602  if( db->init.busy ){
101603  Index *p;
101604  assert( !IN_DECLARE_VTAB );
101605  assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
101606  p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
101607  pIndex->zName, pIndex);
101608  if( p ){
101609  assert( p==pIndex ); /* Malloc must have failed */
101610  sqlite3OomFault(db);
101611  goto exit_create_index;
101612  }
101613  db->flags |= SQLITE_InternChanges;
101614  if( pTblName!=0 ){
101615  pIndex->tnum = db->init.newTnum;
101616  }
101617  }
101618 
101619  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
101620  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
101621  ** emit code to allocate the index rootpage on disk and make an entry for
101622  ** the index in the sqlite_master table and populate the index with
101623  ** content. But, do not do this if we are simply reading the sqlite_master
101624  ** table to parse the schema, or if this index is the PRIMARY KEY index
101625  ** of a WITHOUT ROWID table.
101626  **
101627  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
101628  ** or UNIQUE index in a CREATE TABLE statement. Since the table
101629  ** has just been created, it contains no data and the index initialization
101630  ** step can be skipped.
101631  */
101632  else if( HasRowid(pTab) || pTblName!=0 ){
101633  Vdbe *v;
101634  char *zStmt;
101635  int iMem = ++pParse->nMem;
101636 
101637  v = sqlite3GetVdbe(pParse);
101638  if( v==0 ) goto exit_create_index;
101639 
101640  sqlite3BeginWriteOperation(pParse, 1, iDb);
101641 
101642  /* Create the rootpage for the index using CreateIndex. But before
101643  ** doing so, code a Noop instruction and store its address in
101644  ** Index.tnum. This is required in case this index is actually a
101645  ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
101646  ** that case the convertToWithoutRowidTable() routine will replace
101647  ** the Noop with a Goto to jump over the VDBE code generated below. */
101648  pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
101649  sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
101650 
101651  /* Gather the complete text of the CREATE INDEX statement into
101652  ** the zStmt variable
101653  */
101654  if( pStart ){
101655  int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
101656  if( pName->z[n-1]==';' ) n--;
101657  /* A named index with an explicit CREATE INDEX statement */
101658  zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
101659  onError==OE_None ? "" : " UNIQUE", n, pName->z);
101660  }else{
101661  /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
101662  /* zStmt = sqlite3MPrintf(""); */
101663  zStmt = 0;
101664  }
101665 
101666  /* Add an entry in sqlite_master for this index
101667  */
101668  sqlite3NestedParse(pParse,
101669  "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
101670  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb),
101671  pIndex->zName,
101672  pTab->zName,
101673  iMem,
101674  zStmt
101675  );
101676  sqlite3DbFree(db, zStmt);
101677 
101678  /* Fill the index with data and reparse the schema. Code an OP_Expire
101679  ** to invalidate all pre-compiled statements.
101680  */
101681  if( pTblName ){
101682  sqlite3RefillIndex(pParse, pIndex, iMem);
101683  sqlite3ChangeCookie(pParse, iDb);
101684  sqlite3VdbeAddParseSchemaOp(v, iDb,
101685  sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
101686  sqlite3VdbeAddOp0(v, OP_Expire);
101687  }
101688 
101689  sqlite3VdbeJumpHere(v, pIndex->tnum);
101690  }
101691 
101692  /* When adding an index to the list of indices for a table, make
101693  ** sure all indices labeled OE_Replace come after all those labeled
101694  ** OE_Ignore. This is necessary for the correct constraint check
101695  ** processing (in sqlite3GenerateConstraintChecks()) as part of
101696  ** UPDATE and INSERT statements.
101697  */
101698  if( db->init.busy || pTblName==0 ){
101699  if( onError!=OE_Replace || pTab->pIndex==0
101700  || pTab->pIndex->onError==OE_Replace){
101701  pIndex->pNext = pTab->pIndex;
101702  pTab->pIndex = pIndex;
101703  }else{
101704  Index *pOther = pTab->pIndex;
101705  while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
101706  pOther = pOther->pNext;
101707  }
101708  pIndex->pNext = pOther->pNext;
101709  pOther->pNext = pIndex;
101710  }
101711  pIndex = 0;
101712  }
101713 
101714  /* Clean up before exiting */
101715 exit_create_index:
101716  if( pIndex ) freeIndex(db, pIndex);
101717  sqlite3ExprDelete(db, pPIWhere);
101718  sqlite3ExprListDelete(db, pList);
101719  sqlite3SrcListDelete(db, pTblName);
101720  sqlite3DbFree(db, zName);
101721 }
101722 
101723 /*
101724 ** Fill the Index.aiRowEst[] array with default information - information
101725 ** to be used when we have not run the ANALYZE command.
101726 **
101727 ** aiRowEst[0] is supposed to contain the number of elements in the index.
101728 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
101729 ** number of rows in the table that match any particular value of the
101730 ** first column of the index. aiRowEst[2] is an estimate of the number
101731 ** of rows that match any particular combination of the first 2 columns
101732 ** of the index. And so forth. It must always be the case that
101733 *
101734 ** aiRowEst[N]<=aiRowEst[N-1]
101735 ** aiRowEst[N]>=1
101736 **
101737 ** Apart from that, we have little to go on besides intuition as to
101738 ** how aiRowEst[] should be initialized. The numbers generated here
101739 ** are based on typical values found in actual indices.
101740 */
101741 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
101742  /* 10, 9, 8, 7, 6 */
101743  LogEst aVal[] = { 33, 32, 30, 28, 26 };
101744  LogEst *a = pIdx->aiRowLogEst;
101745  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
101746  int i;
101747 
101748  /* Set the first entry (number of rows in the index) to the estimated
101749  ** number of rows in the table, or half the number of rows in the table
101750  ** for a partial index. But do not let the estimate drop below 10. */
101751  a[0] = pIdx->pTable->nRowLogEst;
101752  if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
101753  if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
101754 
101755  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
101756  ** 6 and each subsequent value (if any) is 5. */
101757  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
101758  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
101759  a[i] = 23; assert( 23==sqlite3LogEst(5) );
101760  }
101761 
101762  assert( 0==sqlite3LogEst(1) );
101763  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
101764 }
101765 
101766 /*
101767 ** This routine will drop an existing named index. This routine
101768 ** implements the DROP INDEX statement.
101769 */
101770 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
101771  Index *pIndex;
101772  Vdbe *v;
101773  sqlite3 *db = pParse->db;
101774  int iDb;
101775 
101776  assert( pParse->nErr==0 ); /* Never called with prior errors */
101777  if( db->mallocFailed ){
101778  goto exit_drop_index;
101779  }
101780  assert( pName->nSrc==1 );
101781  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101782  goto exit_drop_index;
101783  }
101784  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
101785  if( pIndex==0 ){
101786  if( !ifExists ){
101787  sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
101788  }else{
101789  sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
101790  }
101791  pParse->checkSchema = 1;
101792  goto exit_drop_index;
101793  }
101794  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
101795  sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
101796  "or PRIMARY KEY constraint cannot be dropped", 0);
101797  goto exit_drop_index;
101798  }
101799  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
101800 #ifndef SQLITE_OMIT_AUTHORIZATION
101801  {
101802  int code = SQLITE_DROP_INDEX;
101803  Table *pTab = pIndex->pTable;
101804  const char *zDb = db->aDb[iDb].zDbSName;
101805  const char *zTab = SCHEMA_TABLE(iDb);
101806  if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
101807  goto exit_drop_index;
101808  }
101809  if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
101810  if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
101811  goto exit_drop_index;
101812  }
101813  }
101814 #endif
101815 
101816  /* Generate code to remove the index and from the master table */
101817  v = sqlite3GetVdbe(pParse);
101818  if( v ){
101819  sqlite3BeginWriteOperation(pParse, 1, iDb);
101820  sqlite3NestedParse(pParse,
101821  "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
101822  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pIndex->zName
101823  );
101824  sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
101825  sqlite3ChangeCookie(pParse, iDb);
101826  destroyRootPage(pParse, pIndex->tnum, iDb);
101827  sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
101828  }
101829 
101830 exit_drop_index:
101831  sqlite3SrcListDelete(db, pName);
101832 }
101833 
101834 /*
101835 ** pArray is a pointer to an array of objects. Each object in the
101836 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
101837 ** to extend the array so that there is space for a new object at the end.
101838 **
101839 ** When this function is called, *pnEntry contains the current size of
101840 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
101841 ** in total).
101842 **
101843 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
101844 ** space allocated for the new object is zeroed, *pnEntry updated to
101845 ** reflect the new size of the array and a pointer to the new allocation
101846 ** returned. *pIdx is set to the index of the new array entry in this case.
101847 **
101848 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
101849 ** unchanged and a copy of pArray returned.
101850 */
101851 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
101852  sqlite3 *db, /* Connection to notify of malloc failures */
101853  void *pArray, /* Array of objects. Might be reallocated */
101854  int szEntry, /* Size of each object in the array */
101855  int *pnEntry, /* Number of objects currently in use */
101856  int *pIdx /* Write the index of a new slot here */
101857 ){
101858  char *z;
101859  int n = *pnEntry;
101860  if( (n & (n-1))==0 ){
101861  int sz = (n==0) ? 1 : 2*n;
101862  void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
101863  if( pNew==0 ){
101864  *pIdx = -1;
101865  return pArray;
101866  }
101867  pArray = pNew;
101868  }
101869  z = (char*)pArray;
101870  memset(&z[n * szEntry], 0, szEntry);
101871  *pIdx = n;
101872  ++*pnEntry;
101873  return pArray;
101874 }
101875 
101876 /*
101877 ** Append a new element to the given IdList. Create a new IdList if
101878 ** need be.
101879 **
101880 ** A new IdList is returned, or NULL if malloc() fails.
101881 */
101882 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
101883  int i;
101884  if( pList==0 ){
101885  pList = sqlite3DbMallocZero(db, sizeof(IdList) );
101886  if( pList==0 ) return 0;
101887  }
101888  pList->a = sqlite3ArrayAllocate(
101889  db,
101890  pList->a,
101891  sizeof(pList->a[0]),
101892  &pList->nId,
101893  &i
101894  );
101895  if( i<0 ){
101896  sqlite3IdListDelete(db, pList);
101897  return 0;
101898  }
101899  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
101900  return pList;
101901 }
101902 
101903 /*
101904 ** Delete an IdList.
101905 */
101906 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
101907  int i;
101908  if( pList==0 ) return;
101909  for(i=0; i<pList->nId; i++){
101910  sqlite3DbFree(db, pList->a[i].zName);
101911  }
101912  sqlite3DbFree(db, pList->a);
101913  sqlite3DbFree(db, pList);
101914 }
101915 
101916 /*
101917 ** Return the index in pList of the identifier named zId. Return -1
101918 ** if not found.
101919 */
101920 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
101921  int i;
101922  if( pList==0 ) return -1;
101923  for(i=0; i<pList->nId; i++){
101924  if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
101925  }
101926  return -1;
101927 }
101928 
101929 /*
101930 ** Expand the space allocated for the given SrcList object by
101931 ** creating nExtra new slots beginning at iStart. iStart is zero based.
101932 ** New slots are zeroed.
101933 **
101934 ** For example, suppose a SrcList initially contains two entries: A,B.
101935 ** To append 3 new entries onto the end, do this:
101936 **
101937 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
101938 **
101939 ** After the call above it would contain: A, B, nil, nil, nil.
101940 ** If the iStart argument had been 1 instead of 2, then the result
101941 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
101942 ** the iStart value would be 0. The result then would
101943 ** be: nil, nil, nil, A, B.
101944 **
101945 ** If a memory allocation fails the SrcList is unchanged. The
101946 ** db->mallocFailed flag will be set to true.
101947 */
101948 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
101949  sqlite3 *db, /* Database connection to notify of OOM errors */
101950  SrcList *pSrc, /* The SrcList to be enlarged */
101951  int nExtra, /* Number of new slots to add to pSrc->a[] */
101952  int iStart /* Index in pSrc->a[] of first new slot */
101953 ){
101954  int i;
101955 
101956  /* Sanity checking on calling parameters */
101957  assert( iStart>=0 );
101958  assert( nExtra>=1 );
101959  assert( pSrc!=0 );
101960  assert( iStart<=pSrc->nSrc );
101961 
101962  /* Allocate additional space if needed */
101963  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
101964  SrcList *pNew;
101965  int nAlloc = pSrc->nSrc+nExtra;
101966  int nGot;
101967  pNew = sqlite3DbRealloc(db, pSrc,
101968  sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
101969  if( pNew==0 ){
101970  assert( db->mallocFailed );
101971  return pSrc;
101972  }
101973  pSrc = pNew;
101974  nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
101975  pSrc->nAlloc = nGot;
101976  }
101977 
101978  /* Move existing slots that come after the newly inserted slots
101979  ** out of the way */
101980  for(i=pSrc->nSrc-1; i>=iStart; i--){
101981  pSrc->a[i+nExtra] = pSrc->a[i];
101982  }
101983  pSrc->nSrc += nExtra;
101984 
101985  /* Zero the newly allocated slots */
101986  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
101987  for(i=iStart; i<iStart+nExtra; i++){
101988  pSrc->a[i].iCursor = -1;
101989  }
101990 
101991  /* Return a pointer to the enlarged SrcList */
101992  return pSrc;
101993 }
101994 
101995 
101996 /*
101997 ** Append a new table name to the given SrcList. Create a new SrcList if
101998 ** need be. A new entry is created in the SrcList even if pTable is NULL.
101999 **
102000 ** A SrcList is returned, or NULL if there is an OOM error. The returned
102001 ** SrcList might be the same as the SrcList that was input or it might be
102002 ** a new one. If an OOM error does occurs, then the prior value of pList
102003 ** that is input to this routine is automatically freed.
102004 **
102005 ** If pDatabase is not null, it means that the table has an optional
102006 ** database name prefix. Like this: "database.table". The pDatabase
102007 ** points to the table name and the pTable points to the database name.
102008 ** The SrcList.a[].zName field is filled with the table name which might
102009 ** come from pTable (if pDatabase is NULL) or from pDatabase.
102010 ** SrcList.a[].zDatabase is filled with the database name from pTable,
102011 ** or with NULL if no database is specified.
102012 **
102013 ** In other words, if call like this:
102014 **
102015 ** sqlite3SrcListAppend(D,A,B,0);
102016 **
102017 ** Then B is a table name and the database name is unspecified. If called
102018 ** like this:
102019 **
102020 ** sqlite3SrcListAppend(D,A,B,C);
102021 **
102022 ** Then C is the table name and B is the database name. If C is defined
102023 ** then so is B. In other words, we never have a case where:
102024 **
102025 ** sqlite3SrcListAppend(D,A,0,C);
102026 **
102027 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
102028 ** before being added to the SrcList.
102029 */
102030 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
102031  sqlite3 *db, /* Connection to notify of malloc failures */
102032  SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
102033  Token *pTable, /* Table to append */
102034  Token *pDatabase /* Database of the table */
102035 ){
102036  struct SrcList_item *pItem;
102037  assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
102038  assert( db!=0 );
102039  if( pList==0 ){
102040  pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
102041  if( pList==0 ) return 0;
102042  pList->nAlloc = 1;
102043  pList->nSrc = 0;
102044  }
102045  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
102046  if( db->mallocFailed ){
102047  sqlite3SrcListDelete(db, pList);
102048  return 0;
102049  }
102050  pItem = &pList->a[pList->nSrc-1];
102051  if( pDatabase && pDatabase->z==0 ){
102052  pDatabase = 0;
102053  }
102054  if( pDatabase ){
102055  Token *pTemp = pDatabase;
102056  pDatabase = pTable;
102057  pTable = pTemp;
102058  }
102059  pItem->zName = sqlite3NameFromToken(db, pTable);
102060  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
102061  return pList;
102062 }
102063 
102064 /*
102065 ** Assign VdbeCursor index numbers to all tables in a SrcList
102066 */
102067 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
102068  int i;
102069  struct SrcList_item *pItem;
102070  assert(pList || pParse->db->mallocFailed );
102071  if( pList ){
102072  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
102073  if( pItem->iCursor>=0 ) break;
102074  pItem->iCursor = pParse->nTab++;
102075  if( pItem->pSelect ){
102076  sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
102077  }
102078  }
102079  }
102080 }
102081 
102082 /*
102083 ** Delete an entire SrcList including all its substructure.
102084 */
102085 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
102086  int i;
102087  struct SrcList_item *pItem;
102088  if( pList==0 ) return;
102089  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
102090  sqlite3DbFree(db, pItem->zDatabase);
102091  sqlite3DbFree(db, pItem->zName);
102092  sqlite3DbFree(db, pItem->zAlias);
102093  if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
102094  if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
102095  sqlite3DeleteTable(db, pItem->pTab);
102096  sqlite3SelectDelete(db, pItem->pSelect);
102097  sqlite3ExprDelete(db, pItem->pOn);
102098  sqlite3IdListDelete(db, pItem->pUsing);
102099  }
102100  sqlite3DbFree(db, pList);
102101 }
102102 
102103 /*
102104 ** This routine is called by the parser to add a new term to the
102105 ** end of a growing FROM clause. The "p" parameter is the part of
102106 ** the FROM clause that has already been constructed. "p" is NULL
102107 ** if this is the first term of the FROM clause. pTable and pDatabase
102108 ** are the name of the table and database named in the FROM clause term.
102109 ** pDatabase is NULL if the database name qualifier is missing - the
102110 ** usual case. If the term has an alias, then pAlias points to the
102111 ** alias token. If the term is a subquery, then pSubquery is the
102112 ** SELECT statement that the subquery encodes. The pTable and
102113 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
102114 ** parameters are the content of the ON and USING clauses.
102115 **
102116 ** Return a new SrcList which encodes is the FROM with the new
102117 ** term added.
102118 */
102119 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
102120  Parse *pParse, /* Parsing context */
102121  SrcList *p, /* The left part of the FROM clause already seen */
102122  Token *pTable, /* Name of the table to add to the FROM clause */
102123  Token *pDatabase, /* Name of the database containing pTable */
102124  Token *pAlias, /* The right-hand side of the AS subexpression */
102125  Select *pSubquery, /* A subquery used in place of a table name */
102126  Expr *pOn, /* The ON clause of a join */
102127  IdList *pUsing /* The USING clause of a join */
102128 ){
102129  struct SrcList_item *pItem;
102130  sqlite3 *db = pParse->db;
102131  if( !p && (pOn || pUsing) ){
102132  sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
102133  (pOn ? "ON" : "USING")
102134  );
102135  goto append_from_error;
102136  }
102137  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
102138  if( p==0 || NEVER(p->nSrc==0) ){
102139  goto append_from_error;
102140  }
102141  pItem = &p->a[p->nSrc-1];
102142  assert( pAlias!=0 );
102143  if( pAlias->n ){
102144  pItem->zAlias = sqlite3NameFromToken(db, pAlias);
102145  }
102146  pItem->pSelect = pSubquery;
102147  pItem->pOn = pOn;
102148  pItem->pUsing = pUsing;
102149  return p;
102150 
102151  append_from_error:
102152  assert( p==0 );
102153  sqlite3ExprDelete(db, pOn);
102154  sqlite3IdListDelete(db, pUsing);
102155  sqlite3SelectDelete(db, pSubquery);
102156  return 0;
102157 }
102158 
102159 /*
102160 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
102161 ** element of the source-list passed as the second argument.
102162 */
102163 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
102164  assert( pIndexedBy!=0 );
102165  if( p && ALWAYS(p->nSrc>0) ){
102166  struct SrcList_item *pItem = &p->a[p->nSrc-1];
102167  assert( pItem->fg.notIndexed==0 );
102168  assert( pItem->fg.isIndexedBy==0 );
102169  assert( pItem->fg.isTabFunc==0 );
102170  if( pIndexedBy->n==1 && !pIndexedBy->z ){
102171  /* A "NOT INDEXED" clause was supplied. See parse.y
102172  ** construct "indexed_opt" for details. */
102173  pItem->fg.notIndexed = 1;
102174  }else{
102175  pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
102176  pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
102177  }
102178  }
102179 }
102180 
102181 /*
102182 ** Add the list of function arguments to the SrcList entry for a
102183 ** table-valued-function.
102184 */
102185 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
102186  if( p ){
102187  struct SrcList_item *pItem = &p->a[p->nSrc-1];
102188  assert( pItem->fg.notIndexed==0 );
102189  assert( pItem->fg.isIndexedBy==0 );
102190  assert( pItem->fg.isTabFunc==0 );
102191  pItem->u1.pFuncArg = pList;
102192  pItem->fg.isTabFunc = 1;
102193  }else{
102194  sqlite3ExprListDelete(pParse->db, pList);
102195  }
102196 }
102197 
102198 /*
102199 ** When building up a FROM clause in the parser, the join operator
102200 ** is initially attached to the left operand. But the code generator
102201 ** expects the join operator to be on the right operand. This routine
102202 ** Shifts all join operators from left to right for an entire FROM
102203 ** clause.
102204 **
102205 ** Example: Suppose the join is like this:
102206 **
102207 ** A natural cross join B
102208 **
102209 ** The operator is "natural cross join". The A and B operands are stored
102210 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
102211 ** operator with A. This routine shifts that operator over to B.
102212 */
102213 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
102214  if( p ){
102215  int i;
102216  for(i=p->nSrc-1; i>0; i--){
102217  p->a[i].fg.jointype = p->a[i-1].fg.jointype;
102218  }
102219  p->a[0].fg.jointype = 0;
102220  }
102221 }
102222 
102223 /*
102224 ** Generate VDBE code for a BEGIN statement.
102225 */
102226 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
102227  sqlite3 *db;
102228  Vdbe *v;
102229  int i;
102230 
102231  assert( pParse!=0 );
102232  db = pParse->db;
102233  assert( db!=0 );
102234  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
102235  return;
102236  }
102237  v = sqlite3GetVdbe(pParse);
102238  if( !v ) return;
102239  if( type!=TK_DEFERRED ){
102240  for(i=0; i<db->nDb; i++){
102241  sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
102242  sqlite3VdbeUsesBtree(v, i);
102243  }
102244  }
102245  sqlite3VdbeAddOp0(v, OP_AutoCommit);
102246 }
102247 
102248 /*
102249 ** Generate VDBE code for a COMMIT statement.
102250 */
102251 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
102252  Vdbe *v;
102253 
102254  assert( pParse!=0 );
102255  assert( pParse->db!=0 );
102256  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
102257  return;
102258  }
102259  v = sqlite3GetVdbe(pParse);
102260  if( v ){
102261  sqlite3VdbeAddOp1(v, OP_AutoCommit, 1);
102262  }
102263 }
102264 
102265 /*
102266 ** Generate VDBE code for a ROLLBACK statement.
102267 */
102268 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
102269  Vdbe *v;
102270 
102271  assert( pParse!=0 );
102272  assert( pParse->db!=0 );
102273  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
102274  return;
102275  }
102276  v = sqlite3GetVdbe(pParse);
102277  if( v ){
102278  sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
102279  }
102280 }
102281 
102282 /*
102283 ** This function is called by the parser when it parses a command to create,
102284 ** release or rollback an SQL savepoint.
102285 */
102286 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
102287  char *zName = sqlite3NameFromToken(pParse->db, pName);
102288  if( zName ){
102289  Vdbe *v = sqlite3GetVdbe(pParse);
102290 #ifndef SQLITE_OMIT_AUTHORIZATION
102291  static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
102292  assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
102293 #endif
102294  if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
102295  sqlite3DbFree(pParse->db, zName);
102296  return;
102297  }
102298  sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
102299  }
102300 }
102301 
102302 /*
102303 ** Make sure the TEMP database is open and available for use. Return
102304 ** the number of errors. Leave any error messages in the pParse structure.
102305 */
102306 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
102307  sqlite3 *db = pParse->db;
102308  if( db->aDb[1].pBt==0 && !pParse->explain ){
102309  int rc;
102310  Btree *pBt;
102311  static const int flags =
102312  SQLITE_OPEN_READWRITE |
102313  SQLITE_OPEN_CREATE |
102314  SQLITE_OPEN_EXCLUSIVE |
102315  SQLITE_OPEN_DELETEONCLOSE |
102316  SQLITE_OPEN_TEMP_DB;
102317 
102318  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
102319  if( rc!=SQLITE_OK ){
102320  sqlite3ErrorMsg(pParse, "unable to open a temporary database "
102321  "file for storing temporary tables");
102322  pParse->rc = rc;
102323  return 1;
102324  }
102325  db->aDb[1].pBt = pBt;
102326  assert( db->aDb[1].pSchema );
102327  if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
102328  sqlite3OomFault(db);
102329  return 1;
102330  }
102331  }
102332  return 0;
102333 }
102334 
102335 /*
102336 ** Record the fact that the schema cookie will need to be verified
102337 ** for database iDb. The code to actually verify the schema cookie
102338 ** will occur at the end of the top-level VDBE and will be generated
102339 ** later, by sqlite3FinishCoding().
102340 */
102341 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
102342  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102343 
102344  assert( iDb>=0 && iDb<pParse->db->nDb );
102345  assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
102346  assert( iDb<SQLITE_MAX_ATTACHED+2 );
102347  assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
102348  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
102349  DbMaskSet(pToplevel->cookieMask, iDb);
102350  if( !OMIT_TEMPDB && iDb==1 ){
102351  sqlite3OpenTempDatabase(pToplevel);
102352  }
102353  }
102354 }
102355 
102356 /*
102357 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
102358 ** attached database. Otherwise, invoke it for the database named zDb only.
102359 */
102360 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
102361  sqlite3 *db = pParse->db;
102362  int i;
102363  for(i=0; i<db->nDb; i++){
102364  Db *pDb = &db->aDb[i];
102365  if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
102366  sqlite3CodeVerifySchema(pParse, i);
102367  }
102368  }
102369 }
102370 
102371 /*
102372 ** Generate VDBE code that prepares for doing an operation that
102373 ** might change the database.
102374 **
102375 ** This routine starts a new transaction if we are not already within
102376 ** a transaction. If we are already within a transaction, then a checkpoint
102377 ** is set if the setStatement parameter is true. A checkpoint should
102378 ** be set for operations that might fail (due to a constraint) part of
102379 ** the way through and which will need to undo some writes without having to
102380 ** rollback the whole transaction. For operations where all constraints
102381 ** can be checked before any changes are made to the database, it is never
102382 ** necessary to undo a write and the checkpoint should not be set.
102383 */
102384 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
102385  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102386  sqlite3CodeVerifySchema(pParse, iDb);
102387  DbMaskSet(pToplevel->writeMask, iDb);
102388  pToplevel->isMultiWrite |= setStatement;
102389 }
102390 
102391 /*
102392 ** Indicate that the statement currently under construction might write
102393 ** more than one entry (example: deleting one row then inserting another,
102394 ** inserting multiple rows in a table, or inserting a row and index entries.)
102395 ** If an abort occurs after some of these writes have completed, then it will
102396 ** be necessary to undo the completed writes.
102397 */
102398 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
102399  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102400  pToplevel->isMultiWrite = 1;
102401 }
102402 
102403 /*
102404 ** The code generator calls this routine if is discovers that it is
102405 ** possible to abort a statement prior to completion. In order to
102406 ** perform this abort without corrupting the database, we need to make
102407 ** sure that the statement is protected by a statement transaction.
102408 **
102409 ** Technically, we only need to set the mayAbort flag if the
102410 ** isMultiWrite flag was previously set. There is a time dependency
102411 ** such that the abort must occur after the multiwrite. This makes
102412 ** some statements involving the REPLACE conflict resolution algorithm
102413 ** go a little faster. But taking advantage of this time dependency
102414 ** makes it more difficult to prove that the code is correct (in
102415 ** particular, it prevents us from writing an effective
102416 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
102417 ** to take the safe route and skip the optimization.
102418 */
102419 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
102420  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102421  pToplevel->mayAbort = 1;
102422 }
102423 
102424 /*
102425 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
102426 ** error. The onError parameter determines which (if any) of the statement
102427 ** and/or current transaction is rolled back.
102428 */
102429 SQLITE_PRIVATE void sqlite3HaltConstraint(
102430  Parse *pParse, /* Parsing context */
102431  int errCode, /* extended error code */
102432  int onError, /* Constraint type */
102433  char *p4, /* Error message */
102434  i8 p4type, /* P4_STATIC or P4_TRANSIENT */
102435  u8 p5Errmsg /* P5_ErrMsg type */
102436 ){
102437  Vdbe *v = sqlite3GetVdbe(pParse);
102438  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
102439  if( onError==OE_Abort ){
102440  sqlite3MayAbort(pParse);
102441  }
102442  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
102443  sqlite3VdbeChangeP5(v, p5Errmsg);
102444 }
102445 
102446 /*
102447 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
102448 */
102449 SQLITE_PRIVATE void sqlite3UniqueConstraint(
102450  Parse *pParse, /* Parsing context */
102451  int onError, /* Constraint type */
102452  Index *pIdx /* The index that triggers the constraint */
102453 ){
102454  char *zErr;
102455  int j;
102456  StrAccum errMsg;
102457  Table *pTab = pIdx->pTable;
102458 
102459  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
102460  if( pIdx->aColExpr ){
102461  sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
102462  }else{
102463  for(j=0; j<pIdx->nKeyCol; j++){
102464  char *zCol;
102465  assert( pIdx->aiColumn[j]>=0 );
102466  zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
102467  if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
102468  sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
102469  }
102470  }
102471  zErr = sqlite3StrAccumFinish(&errMsg);
102472  sqlite3HaltConstraint(pParse,
102473  IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
102474  : SQLITE_CONSTRAINT_UNIQUE,
102475  onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
102476 }
102477 
102478 
102479 /*
102480 ** Code an OP_Halt due to non-unique rowid.
102481 */
102482 SQLITE_PRIVATE void sqlite3RowidConstraint(
102483  Parse *pParse, /* Parsing context */
102484  int onError, /* Conflict resolution algorithm */
102485  Table *pTab /* The table with the non-unique rowid */
102486 ){
102487  char *zMsg;
102488  int rc;
102489  if( pTab->iPKey>=0 ){
102490  zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
102491  pTab->aCol[pTab->iPKey].zName);
102492  rc = SQLITE_CONSTRAINT_PRIMARYKEY;
102493  }else{
102494  zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
102495  rc = SQLITE_CONSTRAINT_ROWID;
102496  }
102497  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
102498  P5_ConstraintUnique);
102499 }
102500 
102501 /*
102502 ** Check to see if pIndex uses the collating sequence pColl. Return
102503 ** true if it does and false if it does not.
102504 */
102505 #ifndef SQLITE_OMIT_REINDEX
102506 static int collationMatch(const char *zColl, Index *pIndex){
102507  int i;
102508  assert( zColl!=0 );
102509  for(i=0; i<pIndex->nColumn; i++){
102510  const char *z = pIndex->azColl[i];
102511  assert( z!=0 || pIndex->aiColumn[i]<0 );
102512  if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
102513  return 1;
102514  }
102515  }
102516  return 0;
102517 }
102518 #endif
102519 
102520 /*
102521 ** Recompute all indices of pTab that use the collating sequence pColl.
102522 ** If pColl==0 then recompute all indices of pTab.
102523 */
102524 #ifndef SQLITE_OMIT_REINDEX
102525 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
102526  Index *pIndex; /* An index associated with pTab */
102527 
102528  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
102529  if( zColl==0 || collationMatch(zColl, pIndex) ){
102530  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
102531  sqlite3BeginWriteOperation(pParse, 0, iDb);
102532  sqlite3RefillIndex(pParse, pIndex, -1);
102533  }
102534  }
102535 }
102536 #endif
102537 
102538 /*
102539 ** Recompute all indices of all tables in all databases where the
102540 ** indices use the collating sequence pColl. If pColl==0 then recompute
102541 ** all indices everywhere.
102542 */
102543 #ifndef SQLITE_OMIT_REINDEX
102544 static void reindexDatabases(Parse *pParse, char const *zColl){
102545  Db *pDb; /* A single database */
102546  int iDb; /* The database index number */
102547  sqlite3 *db = pParse->db; /* The database connection */
102548  HashElem *k; /* For looping over tables in pDb */
102549  Table *pTab; /* A table in the database */
102550 
102551  assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
102552  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
102553  assert( pDb!=0 );
102554  for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
102555  pTab = (Table*)sqliteHashData(k);
102556  reindexTable(pParse, pTab, zColl);
102557  }
102558  }
102559 }
102560 #endif
102561 
102562 /*
102563 ** Generate code for the REINDEX command.
102564 **
102565 ** REINDEX -- 1
102566 ** REINDEX <collation> -- 2
102567 ** REINDEX ?<database>.?<tablename> -- 3
102568 ** REINDEX ?<database>.?<indexname> -- 4
102569 **
102570 ** Form 1 causes all indices in all attached databases to be rebuilt.
102571 ** Form 2 rebuilds all indices in all databases that use the named
102572 ** collating function. Forms 3 and 4 rebuild the named index or all
102573 ** indices associated with the named table.
102574 */
102575 #ifndef SQLITE_OMIT_REINDEX
102576 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
102577  CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
102578  char *z; /* Name of a table or index */
102579  const char *zDb; /* Name of the database */
102580  Table *pTab; /* A table in the database */
102581  Index *pIndex; /* An index associated with pTab */
102582  int iDb; /* The database index number */
102583  sqlite3 *db = pParse->db; /* The database connection */
102584  Token *pObjName; /* Name of the table or index to be reindexed */
102585 
102586  /* Read the database schema. If an error occurs, leave an error message
102587  ** and code in pParse and return NULL. */
102588  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
102589  return;
102590  }
102591 
102592  if( pName1==0 ){
102593  reindexDatabases(pParse, 0);
102594  return;
102595  }else if( NEVER(pName2==0) || pName2->z==0 ){
102596  char *zColl;
102597  assert( pName1->z );
102598  zColl = sqlite3NameFromToken(pParse->db, pName1);
102599  if( !zColl ) return;
102600  pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
102601  if( pColl ){
102602  reindexDatabases(pParse, zColl);
102603  sqlite3DbFree(db, zColl);
102604  return;
102605  }
102606  sqlite3DbFree(db, zColl);
102607  }
102608  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
102609  if( iDb<0 ) return;
102610  z = sqlite3NameFromToken(db, pObjName);
102611  if( z==0 ) return;
102612  zDb = db->aDb[iDb].zDbSName;
102613  pTab = sqlite3FindTable(db, z, zDb);
102614  if( pTab ){
102615  reindexTable(pParse, pTab, 0);
102616  sqlite3DbFree(db, z);
102617  return;
102618  }
102619  pIndex = sqlite3FindIndex(db, z, zDb);
102620  sqlite3DbFree(db, z);
102621  if( pIndex ){
102622  sqlite3BeginWriteOperation(pParse, 0, iDb);
102623  sqlite3RefillIndex(pParse, pIndex, -1);
102624  return;
102625  }
102626  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
102627 }
102628 #endif
102629 
102630 /*
102631 ** Return a KeyInfo structure that is appropriate for the given Index.
102632 **
102633 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
102634 ** when it has finished using it.
102635 */
102636 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
102637  int i;
102638  int nCol = pIdx->nColumn;
102639  int nKey = pIdx->nKeyCol;
102640  KeyInfo *pKey;
102641  if( pParse->nErr ) return 0;
102642  if( pIdx->uniqNotNull ){
102643  pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
102644  }else{
102645  pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
102646  }
102647  if( pKey ){
102648  assert( sqlite3KeyInfoIsWriteable(pKey) );
102649  for(i=0; i<nCol; i++){
102650  const char *zColl = pIdx->azColl[i];
102651  pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
102652  sqlite3LocateCollSeq(pParse, zColl);
102653  pKey->aSortOrder[i] = pIdx->aSortOrder[i];
102654  }
102655  if( pParse->nErr ){
102656  sqlite3KeyInfoUnref(pKey);
102657  pKey = 0;
102658  }
102659  }
102660  return pKey;
102661 }
102662 
102663 #ifndef SQLITE_OMIT_CTE
102664 /*
102665 ** This routine is invoked once per CTE by the parser while parsing a
102666 ** WITH clause.
102667 */
102668 SQLITE_PRIVATE With *sqlite3WithAdd(
102669  Parse *pParse, /* Parsing context */
102670  With *pWith, /* Existing WITH clause, or NULL */
102671  Token *pName, /* Name of the common-table */
102672  ExprList *pArglist, /* Optional column name list for the table */
102673  Select *pQuery /* Query used to initialize the table */
102674 ){
102675  sqlite3 *db = pParse->db;
102676  With *pNew;
102677  char *zName;
102678 
102679  /* Check that the CTE name is unique within this WITH clause. If
102680  ** not, store an error in the Parse structure. */
102681  zName = sqlite3NameFromToken(pParse->db, pName);
102682  if( zName && pWith ){
102683  int i;
102684  for(i=0; i<pWith->nCte; i++){
102685  if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
102686  sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
102687  }
102688  }
102689  }
102690 
102691  if( pWith ){
102692  int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
102693  pNew = sqlite3DbRealloc(db, pWith, nByte);
102694  }else{
102695  pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
102696  }
102697  assert( (pNew!=0 && zName!=0) || db->mallocFailed );
102698 
102699  if( db->mallocFailed ){
102700  sqlite3ExprListDelete(db, pArglist);
102701  sqlite3SelectDelete(db, pQuery);
102702  sqlite3DbFree(db, zName);
102703  pNew = pWith;
102704  }else{
102705  pNew->a[pNew->nCte].pSelect = pQuery;
102706  pNew->a[pNew->nCte].pCols = pArglist;
102707  pNew->a[pNew->nCte].zName = zName;
102708  pNew->a[pNew->nCte].zCteErr = 0;
102709  pNew->nCte++;
102710  }
102711 
102712  return pNew;
102713 }
102714 
102715 /*
102716 ** Free the contents of the With object passed as the second argument.
102717 */
102718 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
102719  if( pWith ){
102720  int i;
102721  for(i=0; i<pWith->nCte; i++){
102722  struct Cte *pCte = &pWith->a[i];
102723  sqlite3ExprListDelete(db, pCte->pCols);
102724  sqlite3SelectDelete(db, pCte->pSelect);
102725  sqlite3DbFree(db, pCte->zName);
102726  }
102727  sqlite3DbFree(db, pWith);
102728  }
102729 }
102730 #endif /* !defined(SQLITE_OMIT_CTE) */
102731 
102732 /************** End of build.c ***********************************************/
102733 /************** Begin file callback.c ****************************************/
102734 /*
102735 ** 2005 May 23
102736 **
102737 ** The author disclaims copyright to this source code. In place of
102738 ** a legal notice, here is a blessing:
102739 **
102740 ** May you do good and not evil.
102741 ** May you find forgiveness for yourself and forgive others.
102742 ** May you share freely, never taking more than you give.
102743 **
102744 *************************************************************************
102745 **
102746 ** This file contains functions used to access the internal hash tables
102747 ** of user defined functions and collation sequences.
102748 */
102749 
102750 /* #include "sqliteInt.h" */
102751 
102752 /*
102753 ** Invoke the 'collation needed' callback to request a collation sequence
102754 ** in the encoding enc of name zName, length nName.
102755 */
102756 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
102757  assert( !db->xCollNeeded || !db->xCollNeeded16 );
102758  if( db->xCollNeeded ){
102759  char *zExternal = sqlite3DbStrDup(db, zName);
102760  if( !zExternal ) return;
102761  db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
102762  sqlite3DbFree(db, zExternal);
102763  }
102764 #ifndef SQLITE_OMIT_UTF16
102765  if( db->xCollNeeded16 ){
102766  char const *zExternal;
102767  sqlite3_value *pTmp = sqlite3ValueNew(db);
102768  sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
102769  zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
102770  if( zExternal ){
102771  db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
102772  }
102773  sqlite3ValueFree(pTmp);
102774  }
102775 #endif
102776 }
102777 
102778 /*
102779 ** This routine is called if the collation factory fails to deliver a
102780 ** collation function in the best encoding but there may be other versions
102781 ** of this collation function (for other text encodings) available. Use one
102782 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
102783 ** possible.
102784 */
102785 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
102786  CollSeq *pColl2;
102787  char *z = pColl->zName;
102788  int i;
102789  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
102790  for(i=0; i<3; i++){
102791  pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
102792  if( pColl2->xCmp!=0 ){
102793  memcpy(pColl, pColl2, sizeof(CollSeq));
102794  pColl->xDel = 0; /* Do not copy the destructor */
102795  return SQLITE_OK;
102796  }
102797  }
102798  return SQLITE_ERROR;
102799 }
102800 
102801 /*
102802 ** This function is responsible for invoking the collation factory callback
102803 ** or substituting a collation sequence of a different encoding when the
102804 ** requested collation sequence is not available in the desired encoding.
102805 **
102806 ** If it is not NULL, then pColl must point to the database native encoding
102807 ** collation sequence with name zName, length nName.
102808 **
102809 ** The return value is either the collation sequence to be used in database
102810 ** db for collation type name zName, length nName, or NULL, if no collation
102811 ** sequence can be found. If no collation is found, leave an error message.
102812 **
102813 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
102814 */
102815 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
102816  Parse *pParse, /* Parsing context */
102817  u8 enc, /* The desired encoding for the collating sequence */
102818  CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
102819  const char *zName /* Collating sequence name */
102820 ){
102821  CollSeq *p;
102822  sqlite3 *db = pParse->db;
102823 
102824  p = pColl;
102825  if( !p ){
102826  p = sqlite3FindCollSeq(db, enc, zName, 0);
102827  }
102828  if( !p || !p->xCmp ){
102829  /* No collation sequence of this type for this encoding is registered.
102830  ** Call the collation factory to see if it can supply us with one.
102831  */
102832  callCollNeeded(db, enc, zName);
102833  p = sqlite3FindCollSeq(db, enc, zName, 0);
102834  }
102835  if( p && !p->xCmp && synthCollSeq(db, p) ){
102836  p = 0;
102837  }
102838  assert( !p || p->xCmp );
102839  if( p==0 ){
102840  sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
102841  }
102842  return p;
102843 }
102844 
102845 /*
102846 ** This routine is called on a collation sequence before it is used to
102847 ** check that it is defined. An undefined collation sequence exists when
102848 ** a database is loaded that contains references to collation sequences
102849 ** that have not been defined by sqlite3_create_collation() etc.
102850 **
102851 ** If required, this routine calls the 'collation needed' callback to
102852 ** request a definition of the collating sequence. If this doesn't work,
102853 ** an equivalent collating sequence that uses a text encoding different
102854 ** from the main database is substituted, if one is available.
102855 */
102856 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
102857  if( pColl ){
102858  const char *zName = pColl->zName;
102859  sqlite3 *db = pParse->db;
102860  CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
102861  if( !p ){
102862  return SQLITE_ERROR;
102863  }
102864  assert( p==pColl );
102865  }
102866  return SQLITE_OK;
102867 }
102868 
102869 
102870 
102871 /*
102872 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
102873 ** specified by zName and nName is not found and parameter 'create' is
102874 ** true, then create a new entry. Otherwise return NULL.
102875 **
102876 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
102877 ** array of three CollSeq structures. The first is the collation sequence
102878 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
102879 **
102880 ** Stored immediately after the three collation sequences is a copy of
102881 ** the collation sequence name. A pointer to this string is stored in
102882 ** each collation sequence structure.
102883 */
102884 static CollSeq *findCollSeqEntry(
102885  sqlite3 *db, /* Database connection */
102886  const char *zName, /* Name of the collating sequence */
102887  int create /* Create a new entry if true */
102888 ){
102889  CollSeq *pColl;
102890  pColl = sqlite3HashFind(&db->aCollSeq, zName);
102891 
102892  if( 0==pColl && create ){
102893  int nName = sqlite3Strlen30(zName);
102894  pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
102895  if( pColl ){
102896  CollSeq *pDel = 0;
102897  pColl[0].zName = (char*)&pColl[3];
102898  pColl[0].enc = SQLITE_UTF8;
102899  pColl[1].zName = (char*)&pColl[3];
102900  pColl[1].enc = SQLITE_UTF16LE;
102901  pColl[2].zName = (char*)&pColl[3];
102902  pColl[2].enc = SQLITE_UTF16BE;
102903  memcpy(pColl[0].zName, zName, nName);
102904  pColl[0].zName[nName] = 0;
102905  pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
102906 
102907  /* If a malloc() failure occurred in sqlite3HashInsert(), it will
102908  ** return the pColl pointer to be deleted (because it wasn't added
102909  ** to the hash table).
102910  */
102911  assert( pDel==0 || pDel==pColl );
102912  if( pDel!=0 ){
102913  sqlite3OomFault(db);
102914  sqlite3DbFree(db, pDel);
102915  pColl = 0;
102916  }
102917  }
102918  }
102919  return pColl;
102920 }
102921 
102922 /*
102923 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
102924 ** Return the CollSeq* pointer for the collation sequence named zName
102925 ** for the encoding 'enc' from the database 'db'.
102926 **
102927 ** If the entry specified is not found and 'create' is true, then create a
102928 ** new entry. Otherwise return NULL.
102929 **
102930 ** A separate function sqlite3LocateCollSeq() is a wrapper around
102931 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
102932 ** if necessary and generates an error message if the collating sequence
102933 ** cannot be found.
102934 **
102935 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
102936 */
102937 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
102938  sqlite3 *db,
102939  u8 enc,
102940  const char *zName,
102941  int create
102942 ){
102943  CollSeq *pColl;
102944  if( zName ){
102945  pColl = findCollSeqEntry(db, zName, create);
102946  }else{
102947  pColl = db->pDfltColl;
102948  }
102949  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
102950  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
102951  if( pColl ) pColl += enc-1;
102952  return pColl;
102953 }
102954 
102955 /* During the search for the best function definition, this procedure
102956 ** is called to test how well the function passed as the first argument
102957 ** matches the request for a function with nArg arguments in a system
102958 ** that uses encoding enc. The value returned indicates how well the
102959 ** request is matched. A higher value indicates a better match.
102960 **
102961 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
102962 ** is also -1. In other words, we are searching for a function that
102963 ** takes a variable number of arguments.
102964 **
102965 ** If nArg is -2 that means that we are searching for any function
102966 ** regardless of the number of arguments it uses, so return a positive
102967 ** match score for any
102968 **
102969 ** The returned value is always between 0 and 6, as follows:
102970 **
102971 ** 0: Not a match.
102972 ** 1: UTF8/16 conversion required and function takes any number of arguments.
102973 ** 2: UTF16 byte order change required and function takes any number of args.
102974 ** 3: encoding matches and function takes any number of arguments
102975 ** 4: UTF8/16 conversion required - argument count matches exactly
102976 ** 5: UTF16 byte order conversion required - argument count matches exactly
102977 ** 6: Perfect match: encoding and argument count match exactly.
102978 **
102979 ** If nArg==(-2) then any function with a non-null xSFunc is
102980 ** a perfect match and any function with xSFunc NULL is
102981 ** a non-match.
102982 */
102983 #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
102984 static int matchQuality(
102985  FuncDef *p, /* The function we are evaluating for match quality */
102986  int nArg, /* Desired number of arguments. (-1)==any */
102987  u8 enc /* Desired text encoding */
102988 ){
102989  int match;
102990 
102991  /* nArg of -2 is a special case */
102992  if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
102993 
102994  /* Wrong number of arguments means "no match" */
102995  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
102996 
102997  /* Give a better score to a function with a specific number of arguments
102998  ** than to function that accepts any number of arguments. */
102999  if( p->nArg==nArg ){
103000  match = 4;
103001  }else{
103002  match = 1;
103003  }
103004 
103005  /* Bonus points if the text encoding matches */
103006  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
103007  match += 2; /* Exact encoding match */
103008  }else if( (enc & p->funcFlags & 2)!=0 ){
103009  match += 1; /* Both are UTF16, but with different byte orders */
103010  }
103011 
103012  return match;
103013 }
103014 
103015 /*
103016 ** Search a FuncDefHash for a function with the given name. Return
103017 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
103018 */
103019 static FuncDef *functionSearch(
103020  int h, /* Hash of the name */
103021  const char *zFunc /* Name of function */
103022 ){
103023  FuncDef *p;
103024  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
103025  if( sqlite3StrICmp(p->zName, zFunc)==0 ){
103026  return p;
103027  }
103028  }
103029  return 0;
103030 }
103031 
103032 /*
103033 ** Insert a new FuncDef into a FuncDefHash hash table.
103034 */
103035 SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
103036  FuncDef *aDef, /* List of global functions to be inserted */
103037  int nDef /* Length of the apDef[] list */
103038 ){
103039  int i;
103040  for(i=0; i<nDef; i++){
103041  FuncDef *pOther;
103042  const char *zName = aDef[i].zName;
103043  int nName = sqlite3Strlen30(zName);
103044  int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
103045  pOther = functionSearch(h, zName);
103046  if( pOther ){
103047  assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
103048  aDef[i].pNext = pOther->pNext;
103049  pOther->pNext = &aDef[i];
103050  }else{
103051  aDef[i].pNext = 0;
103052  aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
103053  sqlite3BuiltinFunctions.a[h] = &aDef[i];
103054  }
103055  }
103056 }
103057 
103058 
103059 
103060 /*
103061 ** Locate a user function given a name, a number of arguments and a flag
103062 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
103063 ** pointer to the FuncDef structure that defines that function, or return
103064 ** NULL if the function does not exist.
103065 **
103066 ** If the createFlag argument is true, then a new (blank) FuncDef
103067 ** structure is created and liked into the "db" structure if a
103068 ** no matching function previously existed.
103069 **
103070 ** If nArg is -2, then the first valid function found is returned. A
103071 ** function is valid if xSFunc is non-zero. The nArg==(-2)
103072 ** case is used to see if zName is a valid function name for some number
103073 ** of arguments. If nArg is -2, then createFlag must be 0.
103074 **
103075 ** If createFlag is false, then a function with the required name and
103076 ** number of arguments may be returned even if the eTextRep flag does not
103077 ** match that requested.
103078 */
103079 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
103080  sqlite3 *db, /* An open database */
103081  const char *zName, /* Name of the function. zero-terminated */
103082  int nArg, /* Number of arguments. -1 means any number */
103083  u8 enc, /* Preferred text encoding */
103084  u8 createFlag /* Create new entry if true and does not otherwise exist */
103085 ){
103086  FuncDef *p; /* Iterator variable */
103087  FuncDef *pBest = 0; /* Best match found so far */
103088  int bestScore = 0; /* Score of best match */
103089  int h; /* Hash value */
103090  int nName; /* Length of the name */
103091 
103092  assert( nArg>=(-2) );
103093  assert( nArg>=(-1) || createFlag==0 );
103094  nName = sqlite3Strlen30(zName);
103095 
103096  /* First search for a match amongst the application-defined functions.
103097  */
103098  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
103099  while( p ){
103100  int score = matchQuality(p, nArg, enc);
103101  if( score>bestScore ){
103102  pBest = p;
103103  bestScore = score;
103104  }
103105  p = p->pNext;
103106  }
103107 
103108  /* If no match is found, search the built-in functions.
103109  **
103110  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
103111  ** functions even if a prior app-defined function was found. And give
103112  ** priority to built-in functions.
103113  **
103114  ** Except, if createFlag is true, that means that we are trying to
103115  ** install a new function. Whatever FuncDef structure is returned it will
103116  ** have fields overwritten with new information appropriate for the
103117  ** new function. But the FuncDefs for built-in functions are read-only.
103118  ** So we must not search for built-ins when creating a new function.
103119  */
103120  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
103121  bestScore = 0;
103122  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
103123  p = functionSearch(h, zName);
103124  while( p ){
103125  int score = matchQuality(p, nArg, enc);
103126  if( score>bestScore ){
103127  pBest = p;
103128  bestScore = score;
103129  }
103130  p = p->pNext;
103131  }
103132  }
103133 
103134  /* If the createFlag parameter is true and the search did not reveal an
103135  ** exact match for the name, number of arguments and encoding, then add a
103136  ** new entry to the hash table and return it.
103137  */
103138  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
103139  (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
103140  FuncDef *pOther;
103141  pBest->zName = (const char*)&pBest[1];
103142  pBest->nArg = (u16)nArg;
103143  pBest->funcFlags = enc;
103144  memcpy((char*)&pBest[1], zName, nName+1);
103145  pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
103146  if( pOther==pBest ){
103147  sqlite3DbFree(db, pBest);
103148  sqlite3OomFault(db);
103149  return 0;
103150  }else{
103151  pBest->pNext = pOther;
103152  }
103153  }
103154 
103155  if( pBest && (pBest->xSFunc || createFlag) ){
103156  return pBest;
103157  }
103158  return 0;
103159 }
103160 
103161 /*
103162 ** Free all resources held by the schema structure. The void* argument points
103163 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
103164 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
103165 ** of the schema hash tables).
103166 **
103167 ** The Schema.cache_size variable is not cleared.
103168 */
103169 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
103170  Hash temp1;
103171  Hash temp2;
103172  HashElem *pElem;
103173  Schema *pSchema = (Schema *)p;
103174 
103175  temp1 = pSchema->tblHash;
103176  temp2 = pSchema->trigHash;
103177  sqlite3HashInit(&pSchema->trigHash);
103178  sqlite3HashClear(&pSchema->idxHash);
103179  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
103180  sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
103181  }
103182  sqlite3HashClear(&temp2);
103183  sqlite3HashInit(&pSchema->tblHash);
103184  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
103185  Table *pTab = sqliteHashData(pElem);
103186  sqlite3DeleteTable(0, pTab);
103187  }
103188  sqlite3HashClear(&temp1);
103189  sqlite3HashClear(&pSchema->fkeyHash);
103190  pSchema->pSeqTab = 0;
103191  if( pSchema->schemaFlags & DB_SchemaLoaded ){
103192  pSchema->iGeneration++;
103193  pSchema->schemaFlags &= ~DB_SchemaLoaded;
103194  }
103195 }
103196 
103197 /*
103198 ** Find and return the schema associated with a BTree. Create
103199 ** a new one if necessary.
103200 */
103201 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
103202  Schema * p;
103203  if( pBt ){
103204  p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
103205  }else{
103206  p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
103207  }
103208  if( !p ){
103209  sqlite3OomFault(db);
103210  }else if ( 0==p->file_format ){
103211  sqlite3HashInit(&p->tblHash);
103212  sqlite3HashInit(&p->idxHash);
103213  sqlite3HashInit(&p->trigHash);
103214  sqlite3HashInit(&p->fkeyHash);
103215  p->enc = SQLITE_UTF8;
103216  }
103217  return p;
103218 }
103219 
103220 /************** End of callback.c ********************************************/
103221 /************** Begin file delete.c ******************************************/
103222 /*
103223 ** 2001 September 15
103224 **
103225 ** The author disclaims copyright to this source code. In place of
103226 ** a legal notice, here is a blessing:
103227 **
103228 ** May you do good and not evil.
103229 ** May you find forgiveness for yourself and forgive others.
103230 ** May you share freely, never taking more than you give.
103231 **
103232 *************************************************************************
103233 ** This file contains C code routines that are called by the parser
103234 ** in order to generate code for DELETE FROM statements.
103235 */
103236 /* #include "sqliteInt.h" */
103237 
103238 /*
103239 ** While a SrcList can in general represent multiple tables and subqueries
103240 ** (as in the FROM clause of a SELECT statement) in this case it contains
103241 ** the name of a single table, as one might find in an INSERT, DELETE,
103242 ** or UPDATE statement. Look up that table in the symbol table and
103243 ** return a pointer. Set an error message and return NULL if the table
103244 ** name is not found or if any other error occurs.
103245 **
103246 ** The following fields are initialized appropriate in pSrc:
103247 **
103248 ** pSrc->a[0].pTab Pointer to the Table object
103249 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
103250 **
103251 */
103252 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
103253  struct SrcList_item *pItem = pSrc->a;
103254  Table *pTab;
103255  assert( pItem && pSrc->nSrc==1 );
103256  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
103257  sqlite3DeleteTable(pParse->db, pItem->pTab);
103258  pItem->pTab = pTab;
103259  if( pTab ){
103260  pTab->nRef++;
103261  }
103262  if( sqlite3IndexedByLookup(pParse, pItem) ){
103263  pTab = 0;
103264  }
103265  return pTab;
103266 }
103267 
103268 /*
103269 ** Check to make sure the given table is writable. If it is not
103270 ** writable, generate an error message and return 1. If it is
103271 ** writable return 0;
103272 */
103273 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
103274  /* A table is not writable under the following circumstances:
103275  **
103276  ** 1) It is a virtual table and no implementation of the xUpdate method
103277  ** has been provided, or
103278  ** 2) It is a system table (i.e. sqlite_master), this call is not
103279  ** part of a nested parse and writable_schema pragma has not
103280  ** been specified.
103281  **
103282  ** In either case leave an error message in pParse and return non-zero.
103283  */
103284  if( ( IsVirtual(pTab)
103285  && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
103286  || ( (pTab->tabFlags & TF_Readonly)!=0
103287  && (pParse->db->flags & SQLITE_WriteSchema)==0
103288  && pParse->nested==0 )
103289  ){
103290  sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
103291  return 1;
103292  }
103293 
103294 #ifndef SQLITE_OMIT_VIEW
103295  if( !viewOk && pTab->pSelect ){
103296  sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
103297  return 1;
103298  }
103299 #endif
103300  return 0;
103301 }
103302 
103303 
103304 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
103305 /*
103306 ** Evaluate a view and store its result in an ephemeral table. The
103307 ** pWhere argument is an optional WHERE clause that restricts the
103308 ** set of rows in the view that are to be added to the ephemeral table.
103309 */
103310 SQLITE_PRIVATE void sqlite3MaterializeView(
103311  Parse *pParse, /* Parsing context */
103312  Table *pView, /* View definition */
103313  Expr *pWhere, /* Optional WHERE clause to be added */
103314  int iCur /* Cursor number for ephemeral table */
103315 ){
103316  SelectDest dest;
103317  Select *pSel;
103318  SrcList *pFrom;
103319  sqlite3 *db = pParse->db;
103320  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
103321  pWhere = sqlite3ExprDup(db, pWhere, 0);
103322  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
103323  if( pFrom ){
103324  assert( pFrom->nSrc==1 );
103325  pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
103326  pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
103327  assert( pFrom->a[0].pOn==0 );
103328  assert( pFrom->a[0].pUsing==0 );
103329  }
103330  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
103331  SF_IncludeHidden, 0, 0);
103332  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
103333  sqlite3Select(pParse, pSel, &dest);
103334  sqlite3SelectDelete(db, pSel);
103335 }
103336 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
103337 
103338 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
103339 /*
103340 ** Generate an expression tree to implement the WHERE, ORDER BY,
103341 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
103342 **
103343 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
103344 ** \__________________________/
103345 ** pLimitWhere (pInClause)
103346 */
103347 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
103348  Parse *pParse, /* The parser context */
103349  SrcList *pSrc, /* the FROM clause -- which tables to scan */
103350  Expr *pWhere, /* The WHERE clause. May be null */
103351  ExprList *pOrderBy, /* The ORDER BY clause. May be null */
103352  Expr *pLimit, /* The LIMIT clause. May be null */
103353  Expr *pOffset, /* The OFFSET clause. May be null */
103354  char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
103355 ){
103356  Expr *pWhereRowid = NULL; /* WHERE rowid .. */
103357  Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
103358  Expr *pSelectRowid = NULL; /* SELECT rowid ... */
103359  ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
103360  SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
103361  Select *pSelect = NULL; /* Complete SELECT tree */
103362 
103363  /* Check that there isn't an ORDER BY without a LIMIT clause.
103364  */
103365  if( pOrderBy && (pLimit == 0) ) {
103366  sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
103367  goto limit_where_cleanup;
103368  }
103369 
103370  /* We only need to generate a select expression if there
103371  ** is a limit/offset term to enforce.
103372  */
103373  if( pLimit == 0 ) {
103374  /* if pLimit is null, pOffset will always be null as well. */
103375  assert( pOffset == 0 );
103376  return pWhere;
103377  }
103378 
103379  /* Generate a select expression tree to enforce the limit/offset
103380  ** term for the DELETE or UPDATE statement. For example:
103381  ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
103382  ** becomes:
103383  ** DELETE FROM table_a WHERE rowid IN (
103384  ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
103385  ** );
103386  */
103387 
103388  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
103389  if( pSelectRowid == 0 ) goto limit_where_cleanup;
103390  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
103391  if( pEList == 0 ) goto limit_where_cleanup;
103392 
103393  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
103394  ** and the SELECT subtree. */
103395  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
103396  if( pSelectSrc == 0 ) {
103397  sqlite3ExprListDelete(pParse->db, pEList);
103398  goto limit_where_cleanup;
103399  }
103400 
103401  /* generate the SELECT expression tree. */
103402  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
103403  pOrderBy,0,pLimit,pOffset);
103404  if( pSelect == 0 ) return 0;
103405 
103406  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
103407  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
103408  pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0;
103409  sqlite3PExprAddSelect(pParse, pInClause, pSelect);
103410  return pInClause;
103411 
103412 limit_where_cleanup:
103413  sqlite3ExprDelete(pParse->db, pWhere);
103414  sqlite3ExprListDelete(pParse->db, pOrderBy);
103415  sqlite3ExprDelete(pParse->db, pLimit);
103416  sqlite3ExprDelete(pParse->db, pOffset);
103417  return 0;
103418 }
103419 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
103420  /* && !defined(SQLITE_OMIT_SUBQUERY) */
103421 
103422 /*
103423 ** Generate code for a DELETE FROM statement.
103424 **
103425 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
103426 ** \________/ \________________/
103427 ** pTabList pWhere
103428 */
103429 SQLITE_PRIVATE void sqlite3DeleteFrom(
103430  Parse *pParse, /* The parser context */
103431  SrcList *pTabList, /* The table from which we should delete things */
103432  Expr *pWhere /* The WHERE clause. May be null */
103433 ){
103434  Vdbe *v; /* The virtual database engine */
103435  Table *pTab; /* The table from which records will be deleted */
103436  int i; /* Loop counter */
103437  WhereInfo *pWInfo; /* Information about the WHERE clause */
103438  Index *pIdx; /* For looping over indices of the table */
103439  int iTabCur; /* Cursor number for the table */
103440  int iDataCur = 0; /* VDBE cursor for the canonical data source */
103441  int iIdxCur = 0; /* Cursor number of the first index */
103442  int nIdx; /* Number of indices */
103443  sqlite3 *db; /* Main database structure */
103444  AuthContext sContext; /* Authorization context */
103445  NameContext sNC; /* Name context to resolve expressions in */
103446  int iDb; /* Database number */
103447  int memCnt = -1; /* Memory cell used for change counting */
103448  int rcauth; /* Value returned by authorization callback */
103449  int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
103450  int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
103451  u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
103452  Index *pPk; /* The PRIMARY KEY index on the table */
103453  int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
103454  i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
103455  int iKey; /* Memory cell holding key of row to be deleted */
103456  i16 nKey; /* Number of memory cells in the row key */
103457  int iEphCur = 0; /* Ephemeral table holding all primary key values */
103458  int iRowSet = 0; /* Register for rowset of rows to delete */
103459  int addrBypass = 0; /* Address of jump over the delete logic */
103460  int addrLoop = 0; /* Top of the delete loop */
103461  int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
103462  int bComplex; /* True if there are triggers or FKs or
103463  ** subqueries in the WHERE clause */
103464 
103465 #ifndef SQLITE_OMIT_TRIGGER
103466  int isView; /* True if attempting to delete from a view */
103467  Trigger *pTrigger; /* List of table triggers, if required */
103468 #endif
103469 
103470  memset(&sContext, 0, sizeof(sContext));
103471  db = pParse->db;
103472  if( pParse->nErr || db->mallocFailed ){
103473  goto delete_from_cleanup;
103474  }
103475  assert( pTabList->nSrc==1 );
103476 
103477  /* Locate the table which we want to delete. This table has to be
103478  ** put in an SrcList structure because some of the subroutines we
103479  ** will be calling are designed to work with multiple tables and expect
103480  ** an SrcList* parameter instead of just a Table* parameter.
103481  */
103482  pTab = sqlite3SrcListLookup(pParse, pTabList);
103483  if( pTab==0 ) goto delete_from_cleanup;
103484 
103485  /* Figure out if we have any triggers and if the table being
103486  ** deleted from is a view
103487  */
103488 #ifndef SQLITE_OMIT_TRIGGER
103489  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
103490  isView = pTab->pSelect!=0;
103491  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
103492 #else
103493 # define pTrigger 0
103494 # define isView 0
103495 #endif
103496 #ifdef SQLITE_OMIT_VIEW
103497 # undef isView
103498 # define isView 0
103499 #endif
103500 
103501  /* If pTab is really a view, make sure it has been initialized.
103502  */
103503  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
103504  goto delete_from_cleanup;
103505  }
103506 
103507  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
103508  goto delete_from_cleanup;
103509  }
103510  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103511  assert( iDb<db->nDb );
103512  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
103513  db->aDb[iDb].zDbSName);
103514  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
103515  if( rcauth==SQLITE_DENY ){
103516  goto delete_from_cleanup;
103517  }
103518  assert(!isView || pTrigger);
103519 
103520  /* Assign cursor numbers to the table and all its indices.
103521  */
103522  assert( pTabList->nSrc==1 );
103523  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
103524  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
103525  pParse->nTab++;
103526  }
103527 
103528  /* Start the view context
103529  */
103530  if( isView ){
103531  sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
103532  }
103533 
103534  /* Begin generating code.
103535  */
103536  v = sqlite3GetVdbe(pParse);
103537  if( v==0 ){
103538  goto delete_from_cleanup;
103539  }
103540  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
103541  sqlite3BeginWriteOperation(pParse, 1, iDb);
103542 
103543  /* If we are trying to delete from a view, realize that view into
103544  ** an ephemeral table.
103545  */
103546 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
103547  if( isView ){
103548  sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
103549  iDataCur = iIdxCur = iTabCur;
103550  }
103551 #endif
103552 
103553  /* Resolve the column names in the WHERE clause.
103554  */
103555  memset(&sNC, 0, sizeof(sNC));
103556  sNC.pParse = pParse;
103557  sNC.pSrcList = pTabList;
103558  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
103559  goto delete_from_cleanup;
103560  }
103561 
103562  /* Initialize the counter of the number of rows deleted, if
103563  ** we are counting rows.
103564  */
103565  if( db->flags & SQLITE_CountRows ){
103566  memCnt = ++pParse->nMem;
103567  sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
103568  }
103569 
103570 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
103571  /* Special case: A DELETE without a WHERE clause deletes everything.
103572  ** It is easier just to erase the whole table. Prior to version 3.6.5,
103573  ** this optimization caused the row change count (the value returned by
103574  ** API function sqlite3_count_changes) to be set incorrectly. */
103575  if( rcauth==SQLITE_OK
103576  && pWhere==0
103577  && !bComplex
103578  && !IsVirtual(pTab)
103579 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
103580  && db->xPreUpdateCallback==0
103581 #endif
103582  ){
103583  assert( !isView );
103584  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
103585  if( HasRowid(pTab) ){
103586  sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
103587  pTab->zName, P4_STATIC);
103588  }
103589  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103590  assert( pIdx->pSchema==pTab->pSchema );
103591  sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
103592  }
103593  }else
103594 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
103595  {
103596  u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
103597  if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
103598  wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
103599  if( HasRowid(pTab) ){
103600  /* For a rowid table, initialize the RowSet to an empty set */
103601  pPk = 0;
103602  nPk = 1;
103603  iRowSet = ++pParse->nMem;
103604  sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
103605  }else{
103606  /* For a WITHOUT ROWID table, create an ephemeral table used to
103607  ** hold all primary keys for rows to be deleted. */
103608  pPk = sqlite3PrimaryKeyIndex(pTab);
103609  assert( pPk!=0 );
103610  nPk = pPk->nKeyCol;
103611  iPk = pParse->nMem+1;
103612  pParse->nMem += nPk;
103613  iEphCur = pParse->nTab++;
103614  addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
103615  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
103616  }
103617 
103618  /* Construct a query to find the rowid or primary key for every row
103619  ** to be deleted, based on the WHERE clause. Set variable eOnePass
103620  ** to indicate the strategy used to implement this delete:
103621  **
103622  ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
103623  ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
103624  ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
103625  */
103626  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
103627  if( pWInfo==0 ) goto delete_from_cleanup;
103628  eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
103629  assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
103630  assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
103631 
103632  /* Keep track of the number of rows to be deleted */
103633  if( db->flags & SQLITE_CountRows ){
103634  sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
103635  }
103636 
103637  /* Extract the rowid or primary key for the current row */
103638  if( pPk ){
103639  for(i=0; i<nPk; i++){
103640  assert( pPk->aiColumn[i]>=0 );
103641  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
103642  pPk->aiColumn[i], iPk+i);
103643  }
103644  iKey = iPk;
103645  }else{
103646  iKey = pParse->nMem + 1;
103647  iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
103648  if( iKey>pParse->nMem ) pParse->nMem = iKey;
103649  }
103650 
103651  if( eOnePass!=ONEPASS_OFF ){
103652  /* For ONEPASS, no need to store the rowid/primary-key. There is only
103653  ** one, so just keep it in its register(s) and fall through to the
103654  ** delete code. */
103655  nKey = nPk; /* OP_Found will use an unpacked key */
103656  aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
103657  if( aToOpen==0 ){
103658  sqlite3WhereEnd(pWInfo);
103659  goto delete_from_cleanup;
103660  }
103661  memset(aToOpen, 1, nIdx+1);
103662  aToOpen[nIdx+1] = 0;
103663  if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
103664  if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
103665  if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
103666  }else{
103667  if( pPk ){
103668  /* Add the PK key for this row to the temporary table */
103669  iKey = ++pParse->nMem;
103670  nKey = 0; /* Zero tells OP_Found to use a composite key */
103671  sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
103672  sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
103673  sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
103674  }else{
103675  /* Add the rowid of the row to be deleted to the RowSet */
103676  nKey = 1; /* OP_Seek always uses a single rowid */
103677  sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
103678  }
103679  }
103680 
103681  /* If this DELETE cannot use the ONEPASS strategy, this is the
103682  ** end of the WHERE loop */
103683  if( eOnePass!=ONEPASS_OFF ){
103684  addrBypass = sqlite3VdbeMakeLabel(v);
103685  }else{
103686  sqlite3WhereEnd(pWInfo);
103687  }
103688 
103689  /* Unless this is a view, open cursors for the table we are
103690  ** deleting from and all its indices. If this is a view, then the
103691  ** only effect this statement has is to fire the INSTEAD OF
103692  ** triggers.
103693  */
103694  if( !isView ){
103695  int iAddrOnce = 0;
103696  if( eOnePass==ONEPASS_MULTI ){
103697  iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
103698  }
103699  testcase( IsVirtual(pTab) );
103700  sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
103701  iTabCur, aToOpen, &iDataCur, &iIdxCur);
103702  assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
103703  assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
103704  if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
103705  }
103706 
103707  /* Set up a loop over the rowids/primary-keys that were found in the
103708  ** where-clause loop above.
103709  */
103710  if( eOnePass!=ONEPASS_OFF ){
103711  assert( nKey==nPk ); /* OP_Found will use an unpacked key */
103712  if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
103713  assert( pPk!=0 || pTab->pSelect!=0 );
103714  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
103715  VdbeCoverage(v);
103716  }
103717  }else if( pPk ){
103718  addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
103719  sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
103720  assert( nKey==0 ); /* OP_Found will use a composite key */
103721  }else{
103722  addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
103723  VdbeCoverage(v);
103724  assert( nKey==1 );
103725  }
103726 
103727  /* Delete the row */
103728 #ifndef SQLITE_OMIT_VIRTUALTABLE
103729  if( IsVirtual(pTab) ){
103730  const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
103731  sqlite3VtabMakeWritable(pParse, pTab);
103732  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
103733  sqlite3VdbeChangeP5(v, OE_Abort);
103734  assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
103735  sqlite3MayAbort(pParse);
103736  if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
103737  pParse->isMultiWrite = 0;
103738  }
103739  }else
103740 #endif
103741  {
103742  int count = (pParse->nested==0); /* True to count changes */
103743  int iIdxNoSeek = -1;
103744  if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
103745  iIdxNoSeek = aiCurOnePass[1];
103746  }
103747  sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
103748  iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
103749  }
103750 
103751  /* End of the loop over all rowids/primary-keys. */
103752  if( eOnePass!=ONEPASS_OFF ){
103753  sqlite3VdbeResolveLabel(v, addrBypass);
103754  sqlite3WhereEnd(pWInfo);
103755  }else if( pPk ){
103756  sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
103757  sqlite3VdbeJumpHere(v, addrLoop);
103758  }else{
103759  sqlite3VdbeGoto(v, addrLoop);
103760  sqlite3VdbeJumpHere(v, addrLoop);
103761  }
103762 
103763  /* Close the cursors open on the table and its indexes. */
103764  if( !isView && !IsVirtual(pTab) ){
103765  if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
103766  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
103767  sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
103768  }
103769  }
103770  } /* End non-truncate path */
103771 
103772  /* Update the sqlite_sequence table by storing the content of the
103773  ** maximum rowid counter values recorded while inserting into
103774  ** autoincrement tables.
103775  */
103776  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
103777  sqlite3AutoincrementEnd(pParse);
103778  }
103779 
103780  /* Return the number of rows that were deleted. If this routine is
103781  ** generating code because of a call to sqlite3NestedParse(), do not
103782  ** invoke the callback function.
103783  */
103784  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
103785  sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
103786  sqlite3VdbeSetNumCols(v, 1);
103787  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
103788  }
103789 
103790 delete_from_cleanup:
103791  sqlite3AuthContextPop(&sContext);
103792  sqlite3SrcListDelete(db, pTabList);
103793  sqlite3ExprDelete(db, pWhere);
103794  sqlite3DbFree(db, aToOpen);
103795  return;
103796 }
103797 /* Make sure "isView" and other macros defined above are undefined. Otherwise
103798 ** they may interfere with compilation of other functions in this file
103799 ** (or in another file, if this file becomes part of the amalgamation). */
103800 #ifdef isView
103801  #undef isView
103802 #endif
103803 #ifdef pTrigger
103804  #undef pTrigger
103805 #endif
103806 
103807 /*
103808 ** This routine generates VDBE code that causes a single row of a
103809 ** single table to be deleted. Both the original table entry and
103810 ** all indices are removed.
103811 **
103812 ** Preconditions:
103813 **
103814 ** 1. iDataCur is an open cursor on the btree that is the canonical data
103815 ** store for the table. (This will be either the table itself,
103816 ** in the case of a rowid table, or the PRIMARY KEY index in the case
103817 ** of a WITHOUT ROWID table.)
103818 **
103819 ** 2. Read/write cursors for all indices of pTab must be open as
103820 ** cursor number iIdxCur+i for the i-th index.
103821 **
103822 ** 3. The primary key for the row to be deleted must be stored in a
103823 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
103824 ** that a search record formed from OP_MakeRecord is contained in the
103825 ** single memory location iPk.
103826 **
103827 ** eMode:
103828 ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
103829 ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
103830 ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
103831 ** then this function must seek iDataCur to the entry identified by iPk
103832 ** and nPk before reading from it.
103833 **
103834 ** If eMode is ONEPASS_MULTI, then this call is being made as part
103835 ** of a ONEPASS delete that affects multiple rows. In this case, if
103836 ** iIdxNoSeek is a valid cursor number (>=0), then its position should
103837 ** be preserved following the delete operation. Or, if iIdxNoSeek is not
103838 ** a valid cursor number, the position of iDataCur should be preserved
103839 ** instead.
103840 **
103841 ** iIdxNoSeek:
103842 ** If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
103843 ** index cursor (from within array of cursors starting at iIdxCur) that
103844 ** already points to the index entry to be deleted.
103845 */
103846 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
103847  Parse *pParse, /* Parsing context */
103848  Table *pTab, /* Table containing the row to be deleted */
103849  Trigger *pTrigger, /* List of triggers to (potentially) fire */
103850  int iDataCur, /* Cursor from which column data is extracted */
103851  int iIdxCur, /* First index cursor */
103852  int iPk, /* First memory cell containing the PRIMARY KEY */
103853  i16 nPk, /* Number of PRIMARY KEY memory cells */
103854  u8 count, /* If non-zero, increment the row change counter */
103855  u8 onconf, /* Default ON CONFLICT policy for triggers */
103856  u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
103857  int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
103858 ){
103859  Vdbe *v = pParse->pVdbe; /* Vdbe */
103860  int iOld = 0; /* First register in OLD.* array */
103861  int iLabel; /* Label resolved to end of generated code */
103862  u8 opSeek; /* Seek opcode */
103863 
103864  /* Vdbe is guaranteed to have been allocated by this stage. */
103865  assert( v );
103866  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
103867  iDataCur, iIdxCur, iPk, (int)nPk));
103868 
103869  /* Seek cursor iCur to the row to delete. If this row no longer exists
103870  ** (this can happen if a trigger program has already deleted it), do
103871  ** not attempt to delete it or fire any DELETE triggers. */
103872  iLabel = sqlite3VdbeMakeLabel(v);
103873  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
103874  if( eMode==ONEPASS_OFF ){
103875  sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
103876  VdbeCoverageIf(v, opSeek==OP_NotExists);
103877  VdbeCoverageIf(v, opSeek==OP_NotFound);
103878  }
103879 
103880  /* If there are any triggers to fire, allocate a range of registers to
103881  ** use for the old.* references in the triggers. */
103882  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
103883  u32 mask; /* Mask of OLD.* columns in use */
103884  int iCol; /* Iterator used while populating OLD.* */
103885  int addrStart; /* Start of BEFORE trigger programs */
103886 
103887  /* TODO: Could use temporary registers here. Also could attempt to
103888  ** avoid copying the contents of the rowid register. */
103889  mask = sqlite3TriggerColmask(
103890  pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
103891  );
103892  mask |= sqlite3FkOldmask(pParse, pTab);
103893  iOld = pParse->nMem+1;
103894  pParse->nMem += (1 + pTab->nCol);
103895 
103896  /* Populate the OLD.* pseudo-table register array. These values will be
103897  ** used by any BEFORE and AFTER triggers that exist. */
103898  sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
103899  for(iCol=0; iCol<pTab->nCol; iCol++){
103900  testcase( mask!=0xffffffff && iCol==31 );
103901  testcase( mask!=0xffffffff && iCol==32 );
103902  if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
103903  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
103904  }
103905  }
103906 
103907  /* Invoke BEFORE DELETE trigger programs. */
103908  addrStart = sqlite3VdbeCurrentAddr(v);
103909  sqlite3CodeRowTrigger(pParse, pTrigger,
103910  TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
103911  );
103912 
103913  /* If any BEFORE triggers were coded, then seek the cursor to the
103914  ** row to be deleted again. It may be that the BEFORE triggers moved
103915  ** the cursor or of already deleted the row that the cursor was
103916  ** pointing to.
103917  */
103918  if( addrStart<sqlite3VdbeCurrentAddr(v) ){
103919  sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
103920  VdbeCoverageIf(v, opSeek==OP_NotExists);
103921  VdbeCoverageIf(v, opSeek==OP_NotFound);
103922  }
103923 
103924  /* Do FK processing. This call checks that any FK constraints that
103925  ** refer to this table (i.e. constraints attached to other tables)
103926  ** are not violated by deleting this row. */
103927  sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
103928  }
103929 
103930  /* Delete the index and table entries. Skip this step if pTab is really
103931  ** a view (in which case the only effect of the DELETE statement is to
103932  ** fire the INSTEAD OF triggers).
103933  **
103934  ** If variable 'count' is non-zero, then this OP_Delete instruction should
103935  ** invoke the update-hook. The pre-update-hook, on the other hand should
103936  ** be invoked unless table pTab is a system table. The difference is that
103937  ** the update-hook is not invoked for rows removed by REPLACE, but the
103938  ** pre-update-hook is.
103939  */
103940  if( pTab->pSelect==0 ){
103941  u8 p5 = 0;
103942  sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
103943  sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
103944  sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
103945  if( eMode!=ONEPASS_OFF ){
103946  sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
103947  }
103948  if( iIdxNoSeek>=0 ){
103949  sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
103950  }
103951  if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
103952  sqlite3VdbeChangeP5(v, p5);
103953  }
103954 
103955  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
103956  ** handle rows (possibly in other tables) that refer via a foreign key
103957  ** to the row just deleted. */
103958  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
103959 
103960  /* Invoke AFTER DELETE trigger programs. */
103961  sqlite3CodeRowTrigger(pParse, pTrigger,
103962  TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
103963  );
103964 
103965  /* Jump here if the row had already been deleted before any BEFORE
103966  ** trigger programs were invoked. Or if a trigger program throws a
103967  ** RAISE(IGNORE) exception. */
103968  sqlite3VdbeResolveLabel(v, iLabel);
103969  VdbeModuleComment((v, "END: GenRowDel()"));
103970 }
103971 
103972 /*
103973 ** This routine generates VDBE code that causes the deletion of all
103974 ** index entries associated with a single row of a single table, pTab
103975 **
103976 ** Preconditions:
103977 **
103978 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
103979 ** btree for the table pTab. (This will be either the table itself
103980 ** for rowid tables or to the primary key index for WITHOUT ROWID
103981 ** tables.)
103982 **
103983 ** 2. Read/write cursors for all indices of pTab must be open as
103984 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
103985 ** index is the 0-th index.)
103986 **
103987 ** 3. The "iDataCur" cursor must be already be positioned on the row
103988 ** that is to be deleted.
103989 */
103990 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
103991  Parse *pParse, /* Parsing and code generating context */
103992  Table *pTab, /* Table containing the row to be deleted */
103993  int iDataCur, /* Cursor of table holding data. */
103994  int iIdxCur, /* First index cursor */
103995  int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
103996  int iIdxNoSeek /* Do not delete from this cursor */
103997 ){
103998  int i; /* Index loop counter */
103999  int r1 = -1; /* Register holding an index key */
104000  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
104001  Index *pIdx; /* Current index */
104002  Index *pPrior = 0; /* Prior index */
104003  Vdbe *v; /* The prepared statement under construction */
104004  Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
104005 
104006  v = pParse->pVdbe;
104007  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
104008  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
104009  assert( iIdxCur+i!=iDataCur || pPk==pIdx );
104010  if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
104011  if( pIdx==pPk ) continue;
104012  if( iIdxCur+i==iIdxNoSeek ) continue;
104013  VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
104014  r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
104015  &iPartIdxLabel, pPrior, r1);
104016  sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
104017  pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
104018  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
104019  pPrior = pIdx;
104020  }
104021 }
104022 
104023 /*
104024 ** Generate code that will assemble an index key and stores it in register
104025 ** regOut. The key with be for index pIdx which is an index on pTab.
104026 ** iCur is the index of a cursor open on the pTab table and pointing to
104027 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
104028 ** iCur must be the cursor of the PRIMARY KEY index.
104029 **
104030 ** Return a register number which is the first in a block of
104031 ** registers that holds the elements of the index key. The
104032 ** block of registers has already been deallocated by the time
104033 ** this routine returns.
104034 **
104035 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
104036 ** to that label if pIdx is a partial index that should be skipped.
104037 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
104038 ** A partial index should be skipped if its WHERE clause evaluates
104039 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
104040 ** will be set to zero which is an empty label that is ignored by
104041 ** sqlite3ResolvePartIdxLabel().
104042 **
104043 ** The pPrior and regPrior parameters are used to implement a cache to
104044 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
104045 ** a pointer to a different index for which an index key has just been
104046 ** computed into register regPrior. If the current pIdx index is generating
104047 ** its key into the same sequence of registers and if pPrior and pIdx share
104048 ** a column in common, then the register corresponding to that column already
104049 ** holds the correct value and the loading of that register is skipped.
104050 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
104051 ** on a table with multiple indices, and especially with the ROWID or
104052 ** PRIMARY KEY columns of the index.
104053 */
104054 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
104055  Parse *pParse, /* Parsing context */
104056  Index *pIdx, /* The index for which to generate a key */
104057  int iDataCur, /* Cursor number from which to take column data */
104058  int regOut, /* Put the new key into this register if not 0 */
104059  int prefixOnly, /* Compute only a unique prefix of the key */
104060  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
104061  Index *pPrior, /* Previously generated index key */
104062  int regPrior /* Register holding previous generated key */
104063 ){
104064  Vdbe *v = pParse->pVdbe;
104065  int j;
104066  int regBase;
104067  int nCol;
104068 
104069  if( piPartIdxLabel ){
104070  if( pIdx->pPartIdxWhere ){
104071  *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
104072  pParse->iSelfTab = iDataCur;
104073  sqlite3ExprCachePush(pParse);
104074  sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
104075  SQLITE_JUMPIFNULL);
104076  }else{
104077  *piPartIdxLabel = 0;
104078  }
104079  }
104080  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
104081  regBase = sqlite3GetTempRange(pParse, nCol);
104082  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
104083  for(j=0; j<nCol; j++){
104084  if( pPrior
104085  && pPrior->aiColumn[j]==pIdx->aiColumn[j]
104086  && pPrior->aiColumn[j]!=XN_EXPR
104087  ){
104088  /* This column was already computed by the previous index */
104089  continue;
104090  }
104091  sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
104092  /* If the column affinity is REAL but the number is an integer, then it
104093  ** might be stored in the table as an integer (using a compact
104094  ** representation) then converted to REAL by an OP_RealAffinity opcode.
104095  ** But we are getting ready to store this value back into an index, where
104096  ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
104097  ** opcode if it is present */
104098  sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
104099  }
104100  if( regOut ){
104101  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
104102  }
104103  sqlite3ReleaseTempRange(pParse, regBase, nCol);
104104  return regBase;
104105 }
104106 
104107 /*
104108 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
104109 ** because it was a partial index, then this routine should be called to
104110 ** resolve that label.
104111 */
104112 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
104113  if( iLabel ){
104114  sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
104115  sqlite3ExprCachePop(pParse);
104116  }
104117 }
104118 
104119 /************** End of delete.c **********************************************/
104120 /************** Begin file func.c ********************************************/
104121 /*
104122 ** 2002 February 23
104123 **
104124 ** The author disclaims copyright to this source code. In place of
104125 ** a legal notice, here is a blessing:
104126 **
104127 ** May you do good and not evil.
104128 ** May you find forgiveness for yourself and forgive others.
104129 ** May you share freely, never taking more than you give.
104130 **
104131 *************************************************************************
104132 ** This file contains the C-language implementations for many of the SQL
104133 ** functions of SQLite. (Some function, and in particular the date and
104134 ** time functions, are implemented separately.)
104135 */
104136 /* #include "sqliteInt.h" */
104137 /* #include <stdlib.h> */
104138 /* #include <assert.h> */
104139 /* #include "vdbeInt.h" */
104140 
104141 /*
104142 ** Return the collating function associated with a function.
104143 */
104144 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
104145  VdbeOp *pOp;
104146  assert( context->pVdbe!=0 );
104147  pOp = &context->pVdbe->aOp[context->iOp-1];
104148  assert( pOp->opcode==OP_CollSeq );
104149  assert( pOp->p4type==P4_COLLSEQ );
104150  return pOp->p4.pColl;
104151 }
104152 
104153 /*
104154 ** Indicate that the accumulator load should be skipped on this
104155 ** iteration of the aggregate loop.
104156 */
104157 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
104158  context->skipFlag = 1;
104159 }
104160 
104161 /*
104162 ** Implementation of the non-aggregate min() and max() functions
104163 */
104164 static void minmaxFunc(
104165  sqlite3_context *context,
104166  int argc,
104167  sqlite3_value **argv
104168 ){
104169  int i;
104170  int mask; /* 0 for min() or 0xffffffff for max() */
104171  int iBest;
104172  CollSeq *pColl;
104173 
104174  assert( argc>1 );
104175  mask = sqlite3_user_data(context)==0 ? 0 : -1;
104176  pColl = sqlite3GetFuncCollSeq(context);
104177  assert( pColl );
104178  assert( mask==-1 || mask==0 );
104179  iBest = 0;
104180  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
104181  for(i=1; i<argc; i++){
104182  if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
104183  if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
104184  testcase( mask==0 );
104185  iBest = i;
104186  }
104187  }
104188  sqlite3_result_value(context, argv[iBest]);
104189 }
104190 
104191 /*
104192 ** Return the type of the argument.
104193 */
104194 static void typeofFunc(
104195  sqlite3_context *context,
104196  int NotUsed,
104197  sqlite3_value **argv
104198 ){
104199  const char *z = 0;
104200  UNUSED_PARAMETER(NotUsed);
104201  switch( sqlite3_value_type(argv[0]) ){
104202  case SQLITE_INTEGER: z = "integer"; break;
104203  case SQLITE_TEXT: z = "text"; break;
104204  case SQLITE_FLOAT: z = "real"; break;
104205  case SQLITE_BLOB: z = "blob"; break;
104206  default: z = "null"; break;
104207  }
104208  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
104209 }
104210 
104211 
104212 /*
104213 ** Implementation of the length() function
104214 */
104215 static void lengthFunc(
104216  sqlite3_context *context,
104217  int argc,
104218  sqlite3_value **argv
104219 ){
104220  int len;
104221 
104222  assert( argc==1 );
104223  UNUSED_PARAMETER(argc);
104224  switch( sqlite3_value_type(argv[0]) ){
104225  case SQLITE_BLOB:
104226  case SQLITE_INTEGER:
104227  case SQLITE_FLOAT: {
104228  sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
104229  break;
104230  }
104231  case SQLITE_TEXT: {
104232  const unsigned char *z = sqlite3_value_text(argv[0]);
104233  if( z==0 ) return;
104234  len = 0;
104235  while( *z ){
104236  len++;
104237  SQLITE_SKIP_UTF8(z);
104238  }
104239  sqlite3_result_int(context, len);
104240  break;
104241  }
104242  default: {
104243  sqlite3_result_null(context);
104244  break;
104245  }
104246  }
104247 }
104248 
104249 /*
104250 ** Implementation of the abs() function.
104251 **
104252 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
104253 ** the numeric argument X.
104254 */
104255 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104256  assert( argc==1 );
104257  UNUSED_PARAMETER(argc);
104258  switch( sqlite3_value_type(argv[0]) ){
104259  case SQLITE_INTEGER: {
104260  i64 iVal = sqlite3_value_int64(argv[0]);
104261  if( iVal<0 ){
104262  if( iVal==SMALLEST_INT64 ){
104263  /* IMP: R-31676-45509 If X is the integer -9223372036854775808
104264  ** then abs(X) throws an integer overflow error since there is no
104265  ** equivalent positive 64-bit two complement value. */
104266  sqlite3_result_error(context, "integer overflow", -1);
104267  return;
104268  }
104269  iVal = -iVal;
104270  }
104271  sqlite3_result_int64(context, iVal);
104272  break;
104273  }
104274  case SQLITE_NULL: {
104275  /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
104276  sqlite3_result_null(context);
104277  break;
104278  }
104279  default: {
104280  /* Because sqlite3_value_double() returns 0.0 if the argument is not
104281  ** something that can be converted into a number, we have:
104282  ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
104283  ** that cannot be converted to a numeric value.
104284  */
104285  double rVal = sqlite3_value_double(argv[0]);
104286  if( rVal<0 ) rVal = -rVal;
104287  sqlite3_result_double(context, rVal);
104288  break;
104289  }
104290  }
104291 }
104292 
104293 /*
104294 ** Implementation of the instr() function.
104295 **
104296 ** instr(haystack,needle) finds the first occurrence of needle
104297 ** in haystack and returns the number of previous characters plus 1,
104298 ** or 0 if needle does not occur within haystack.
104299 **
104300 ** If both haystack and needle are BLOBs, then the result is one more than
104301 ** the number of bytes in haystack prior to the first occurrence of needle,
104302 ** or 0 if needle never occurs in haystack.
104303 */
104304 static void instrFunc(
104305  sqlite3_context *context,
104306  int argc,
104307  sqlite3_value **argv
104308 ){
104309  const unsigned char *zHaystack;
104310  const unsigned char *zNeedle;
104311  int nHaystack;
104312  int nNeedle;
104313  int typeHaystack, typeNeedle;
104314  int N = 1;
104315  int isText;
104316 
104317  UNUSED_PARAMETER(argc);
104318  typeHaystack = sqlite3_value_type(argv[0]);
104319  typeNeedle = sqlite3_value_type(argv[1]);
104320  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
104321  nHaystack = sqlite3_value_bytes(argv[0]);
104322  nNeedle = sqlite3_value_bytes(argv[1]);
104323  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
104324  zHaystack = sqlite3_value_blob(argv[0]);
104325  zNeedle = sqlite3_value_blob(argv[1]);
104326  isText = 0;
104327  }else{
104328  zHaystack = sqlite3_value_text(argv[0]);
104329  zNeedle = sqlite3_value_text(argv[1]);
104330  isText = 1;
104331  }
104332  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
104333  N++;
104334  do{
104335  nHaystack--;
104336  zHaystack++;
104337  }while( isText && (zHaystack[0]&0xc0)==0x80 );
104338  }
104339  if( nNeedle>nHaystack ) N = 0;
104340  sqlite3_result_int(context, N);
104341 }
104342 
104343 /*
104344 ** Implementation of the printf() function.
104345 */
104346 static void printfFunc(
104347  sqlite3_context *context,
104348  int argc,
104349  sqlite3_value **argv
104350 ){
104351  PrintfArguments x;
104352  StrAccum str;
104353  const char *zFormat;
104354  int n;
104355  sqlite3 *db = sqlite3_context_db_handle(context);
104356 
104357  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
104358  x.nArg = argc-1;
104359  x.nUsed = 0;
104360  x.apArg = argv+1;
104361  sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
104362  str.printfFlags = SQLITE_PRINTF_SQLFUNC;
104363  sqlite3XPrintf(&str, zFormat, &x);
104364  n = str.nChar;
104365  sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
104366  SQLITE_DYNAMIC);
104367  }
104368 }
104369 
104370 /*
104371 ** Implementation of the substr() function.
104372 **
104373 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
104374 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
104375 ** of x. If x is text, then we actually count UTF-8 characters.
104376 ** If x is a blob, then we count bytes.
104377 **
104378 ** If p1 is negative, then we begin abs(p1) from the end of x[].
104379 **
104380 ** If p2 is negative, return the p2 characters preceding p1.
104381 */
104382 static void substrFunc(
104383  sqlite3_context *context,
104384  int argc,
104385  sqlite3_value **argv
104386 ){
104387  const unsigned char *z;
104388  const unsigned char *z2;
104389  int len;
104390  int p0type;
104391  i64 p1, p2;
104392  int negP2 = 0;
104393 
104394  assert( argc==3 || argc==2 );
104395  if( sqlite3_value_type(argv[1])==SQLITE_NULL
104396  || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
104397  ){
104398  return;
104399  }
104400  p0type = sqlite3_value_type(argv[0]);
104401  p1 = sqlite3_value_int(argv[1]);
104402  if( p0type==SQLITE_BLOB ){
104403  len = sqlite3_value_bytes(argv[0]);
104404  z = sqlite3_value_blob(argv[0]);
104405  if( z==0 ) return;
104406  assert( len==sqlite3_value_bytes(argv[0]) );
104407  }else{
104408  z = sqlite3_value_text(argv[0]);
104409  if( z==0 ) return;
104410  len = 0;
104411  if( p1<0 ){
104412  for(z2=z; *z2; len++){
104413  SQLITE_SKIP_UTF8(z2);
104414  }
104415  }
104416  }
104417 #ifdef SQLITE_SUBSTR_COMPATIBILITY
104418  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
104419  ** as substr(X,1,N) - it returns the first N characters of X. This
104420  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
104421  ** from 2009-02-02 for compatibility of applications that exploited the
104422  ** old buggy behavior. */
104423  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
104424 #endif
104425  if( argc==3 ){
104426  p2 = sqlite3_value_int(argv[2]);
104427  if( p2<0 ){
104428  p2 = -p2;
104429  negP2 = 1;
104430  }
104431  }else{
104432  p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
104433  }
104434  if( p1<0 ){
104435  p1 += len;
104436  if( p1<0 ){
104437  p2 += p1;
104438  if( p2<0 ) p2 = 0;
104439  p1 = 0;
104440  }
104441  }else if( p1>0 ){
104442  p1--;
104443  }else if( p2>0 ){
104444  p2--;
104445  }
104446  if( negP2 ){
104447  p1 -= p2;
104448  if( p1<0 ){
104449  p2 += p1;
104450  p1 = 0;
104451  }
104452  }
104453  assert( p1>=0 && p2>=0 );
104454  if( p0type!=SQLITE_BLOB ){
104455  while( *z && p1 ){
104456  SQLITE_SKIP_UTF8(z);
104457  p1--;
104458  }
104459  for(z2=z; *z2 && p2; p2--){
104460  SQLITE_SKIP_UTF8(z2);
104461  }
104462  sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
104463  SQLITE_UTF8);
104464  }else{
104465  if( p1+p2>len ){
104466  p2 = len-p1;
104467  if( p2<0 ) p2 = 0;
104468  }
104469  sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
104470  }
104471 }
104472 
104473 /*
104474 ** Implementation of the round() function
104475 */
104476 #ifndef SQLITE_OMIT_FLOATING_POINT
104477 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104478  int n = 0;
104479  double r;
104480  char *zBuf;
104481  assert( argc==1 || argc==2 );
104482  if( argc==2 ){
104483  if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
104484  n = sqlite3_value_int(argv[1]);
104485  if( n>30 ) n = 30;
104486  if( n<0 ) n = 0;
104487  }
104488  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
104489  r = sqlite3_value_double(argv[0]);
104490  /* If Y==0 and X will fit in a 64-bit int,
104491  ** handle the rounding directly,
104492  ** otherwise use printf.
104493  */
104494  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
104495  r = (double)((sqlite_int64)(r+0.5));
104496  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
104497  r = -(double)((sqlite_int64)((-r)+0.5));
104498  }else{
104499  zBuf = sqlite3_mprintf("%.*f",n,r);
104500  if( zBuf==0 ){
104501  sqlite3_result_error_nomem(context);
104502  return;
104503  }
104504  sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
104505  sqlite3_free(zBuf);
104506  }
104507  sqlite3_result_double(context, r);
104508 }
104509 #endif
104510 
104511 /*
104512 ** Allocate nByte bytes of space using sqlite3Malloc(). If the
104513 ** allocation fails, call sqlite3_result_error_nomem() to notify
104514 ** the database handle that malloc() has failed and return NULL.
104515 ** If nByte is larger than the maximum string or blob length, then
104516 ** raise an SQLITE_TOOBIG exception and return NULL.
104517 */
104518 static void *contextMalloc(sqlite3_context *context, i64 nByte){
104519  char *z;
104520  sqlite3 *db = sqlite3_context_db_handle(context);
104521  assert( nByte>0 );
104522  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
104523  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
104524  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
104525  sqlite3_result_error_toobig(context);
104526  z = 0;
104527  }else{
104528  z = sqlite3Malloc(nByte);
104529  if( !z ){
104530  sqlite3_result_error_nomem(context);
104531  }
104532  }
104533  return z;
104534 }
104535 
104536 /*
104537 ** Implementation of the upper() and lower() SQL functions.
104538 */
104539 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104540  char *z1;
104541  const char *z2;
104542  int i, n;
104543  UNUSED_PARAMETER(argc);
104544  z2 = (char*)sqlite3_value_text(argv[0]);
104545  n = sqlite3_value_bytes(argv[0]);
104546  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
104547  assert( z2==(char*)sqlite3_value_text(argv[0]) );
104548  if( z2 ){
104549  z1 = contextMalloc(context, ((i64)n)+1);
104550  if( z1 ){
104551  for(i=0; i<n; i++){
104552  z1[i] = (char)sqlite3Toupper(z2[i]);
104553  }
104554  sqlite3_result_text(context, z1, n, sqlite3_free);
104555  }
104556  }
104557 }
104558 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104559  char *z1;
104560  const char *z2;
104561  int i, n;
104562  UNUSED_PARAMETER(argc);
104563  z2 = (char*)sqlite3_value_text(argv[0]);
104564  n = sqlite3_value_bytes(argv[0]);
104565  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
104566  assert( z2==(char*)sqlite3_value_text(argv[0]) );
104567  if( z2 ){
104568  z1 = contextMalloc(context, ((i64)n)+1);
104569  if( z1 ){
104570  for(i=0; i<n; i++){
104571  z1[i] = sqlite3Tolower(z2[i]);
104572  }
104573  sqlite3_result_text(context, z1, n, sqlite3_free);
104574  }
104575  }
104576 }
104577 
104578 /*
104579 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
104580 ** as VDBE code so that unused argument values do not have to be computed.
104581 ** However, we still need some kind of function implementation for this
104582 ** routines in the function table. The noopFunc macro provides this.
104583 ** noopFunc will never be called so it doesn't matter what the implementation
104584 ** is. We might as well use the "version()" function as a substitute.
104585 */
104586 #define noopFunc versionFunc /* Substitute function - never called */
104587 
104588 /*
104589 ** Implementation of random(). Return a random integer.
104590 */
104591 static void randomFunc(
104592  sqlite3_context *context,
104593  int NotUsed,
104594  sqlite3_value **NotUsed2
104595 ){
104596  sqlite_int64 r;
104597  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104598  sqlite3_randomness(sizeof(r), &r);
104599  if( r<0 ){
104600  /* We need to prevent a random number of 0x8000000000000000
104601  ** (or -9223372036854775808) since when you do abs() of that
104602  ** number of you get the same value back again. To do this
104603  ** in a way that is testable, mask the sign bit off of negative
104604  ** values, resulting in a positive value. Then take the
104605  ** 2s complement of that positive value. The end result can
104606  ** therefore be no less than -9223372036854775807.
104607  */
104608  r = -(r & LARGEST_INT64);
104609  }
104610  sqlite3_result_int64(context, r);
104611 }
104612 
104613 /*
104614 ** Implementation of randomblob(N). Return a random blob
104615 ** that is N bytes long.
104616 */
104617 static void randomBlob(
104618  sqlite3_context *context,
104619  int argc,
104620  sqlite3_value **argv
104621 ){
104622  int n;
104623  unsigned char *p;
104624  assert( argc==1 );
104625  UNUSED_PARAMETER(argc);
104626  n = sqlite3_value_int(argv[0]);
104627  if( n<1 ){
104628  n = 1;
104629  }
104630  p = contextMalloc(context, n);
104631  if( p ){
104632  sqlite3_randomness(n, p);
104633  sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
104634  }
104635 }
104636 
104637 /*
104638 ** Implementation of the last_insert_rowid() SQL function. The return
104639 ** value is the same as the sqlite3_last_insert_rowid() API function.
104640 */
104641 static void last_insert_rowid(
104642  sqlite3_context *context,
104643  int NotUsed,
104644  sqlite3_value **NotUsed2
104645 ){
104646  sqlite3 *db = sqlite3_context_db_handle(context);
104647  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104648  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
104649  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
104650  ** function. */
104651  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
104652 }
104653 
104654 /*
104655 ** Implementation of the changes() SQL function.
104656 **
104657 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
104658 ** around the sqlite3_changes() C/C++ function and hence follows the same
104659 ** rules for counting changes.
104660 */
104661 static void changes(
104662  sqlite3_context *context,
104663  int NotUsed,
104664  sqlite3_value **NotUsed2
104665 ){
104666  sqlite3 *db = sqlite3_context_db_handle(context);
104667  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104668  sqlite3_result_int(context, sqlite3_changes(db));
104669 }
104670 
104671 /*
104672 ** Implementation of the total_changes() SQL function. The return value is
104673 ** the same as the sqlite3_total_changes() API function.
104674 */
104675 static void total_changes(
104676  sqlite3_context *context,
104677  int NotUsed,
104678  sqlite3_value **NotUsed2
104679 ){
104680  sqlite3 *db = sqlite3_context_db_handle(context);
104681  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104682  /* IMP: R-52756-41993 This function is a wrapper around the
104683  ** sqlite3_total_changes() C/C++ interface. */
104684  sqlite3_result_int(context, sqlite3_total_changes(db));
104685 }
104686 
104687 /*
104688 ** A structure defining how to do GLOB-style comparisons.
104689 */
104691  u8 matchAll; /* "*" or "%" */
104692  u8 matchOne; /* "?" or "_" */
104693  u8 matchSet; /* "[" or 0 */
104694  u8 noCase; /* true to ignore case differences */
104695 };
104696 
104697 /*
104698 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
104699 ** character is exactly one byte in size. Also, provde the Utf8Read()
104700 ** macro for fast reading of the next character in the common case where
104701 ** the next character is ASCII.
104702 */
104703 #if defined(SQLITE_EBCDIC)
104704 # define sqlite3Utf8Read(A) (*((*A)++))
104705 # define Utf8Read(A) (*(A++))
104706 #else
104707 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
104708 #endif
104709 
104710 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
104711 /* The correct SQL-92 behavior is for the LIKE operator to ignore
104712 ** case. Thus 'a' LIKE 'A' would be true. */
104713 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
104714 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
104715 ** is case sensitive causing 'a' LIKE 'A' to be false */
104716 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
104717 
104718 /*
104719 ** Compare two UTF-8 strings for equality where the first string can
104720 ** potentially be a "glob" or "like" expression. Return true (1) if they
104721 ** are the same and false (0) if they are different.
104722 **
104723 ** Globbing rules:
104724 **
104725 ** '*' Matches any sequence of zero or more characters.
104726 **
104727 ** '?' Matches exactly one character.
104728 **
104729 ** [...] Matches one character from the enclosed list of
104730 ** characters.
104731 **
104732 ** [^...] Matches one character not in the enclosed list.
104733 **
104734 ** With the [...] and [^...] matching, a ']' character can be included
104735 ** in the list by making it the first character after '[' or '^'. A
104736 ** range of characters can be specified using '-'. Example:
104737 ** "[a-z]" matches any single lower-case letter. To match a '-', make
104738 ** it the last character in the list.
104739 **
104740 ** Like matching rules:
104741 **
104742 ** '%' Matches any sequence of zero or more characters
104743 **
104744 *** '_' Matches any one character
104745 **
104746 ** Ec Where E is the "esc" character and c is any other
104747 ** character, including '%', '_', and esc, match exactly c.
104748 **
104749 ** The comments within this routine usually assume glob matching.
104750 **
104751 ** This routine is usually quick, but can be N**2 in the worst case.
104752 */
104753 static int patternCompare(
104754  const u8 *zPattern, /* The glob pattern */
104755  const u8 *zString, /* The string to compare against the glob */
104756  const struct compareInfo *pInfo, /* Information about how to do the compare */
104757  u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
104758 ){
104759  u32 c, c2; /* Next pattern and input string chars */
104760  u32 matchOne = pInfo->matchOne; /* "?" or "_" */
104761  u32 matchAll = pInfo->matchAll; /* "*" or "%" */
104762  u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
104763  const u8 *zEscaped = 0; /* One past the last escaped input char */
104764 
104765  while( (c = Utf8Read(zPattern))!=0 ){
104766  if( c==matchAll ){ /* Match "*" */
104767  /* Skip over multiple "*" characters in the pattern. If there
104768  ** are also "?" characters, skip those as well, but consume a
104769  ** single character of the input string for each "?" skipped */
104770  while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
104771  if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
104772  return 0;
104773  }
104774  }
104775  if( c==0 ){
104776  return 1; /* "*" at the end of the pattern matches */
104777  }else if( c==matchOther ){
104778  if( pInfo->matchSet==0 ){
104779  c = sqlite3Utf8Read(&zPattern);
104780  if( c==0 ) return 0;
104781  }else{
104782  /* "[...]" immediately follows the "*". We have to do a slow
104783  ** recursive search in this case, but it is an unusual case. */
104784  assert( matchOther<0x80 ); /* '[' is a single-byte character */
104785  while( *zString
104786  && patternCompare(&zPattern[-1],zString,pInfo,matchOther)==0 ){
104787  SQLITE_SKIP_UTF8(zString);
104788  }
104789  return *zString!=0;
104790  }
104791  }
104792 
104793  /* At this point variable c contains the first character of the
104794  ** pattern string past the "*". Search in the input string for the
104795  ** first matching character and recursively contine the match from
104796  ** that point.
104797  **
104798  ** For a case-insensitive search, set variable cx to be the same as
104799  ** c but in the other case and search the input string for either
104800  ** c or cx.
104801  */
104802  if( c<=0x80 ){
104803  u32 cx;
104804  if( noCase ){
104805  cx = sqlite3Toupper(c);
104806  c = sqlite3Tolower(c);
104807  }else{
104808  cx = c;
104809  }
104810  while( (c2 = *(zString++))!=0 ){
104811  if( c2!=c && c2!=cx ) continue;
104812  if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
104813  }
104814  }else{
104815  while( (c2 = Utf8Read(zString))!=0 ){
104816  if( c2!=c ) continue;
104817  if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
104818  }
104819  }
104820  return 0;
104821  }
104822  if( c==matchOther ){
104823  if( pInfo->matchSet==0 ){
104824  c = sqlite3Utf8Read(&zPattern);
104825  if( c==0 ) return 0;
104826  zEscaped = zPattern;
104827  }else{
104828  u32 prior_c = 0;
104829  int seen = 0;
104830  int invert = 0;
104831  c = sqlite3Utf8Read(&zString);
104832  if( c==0 ) return 0;
104833  c2 = sqlite3Utf8Read(&zPattern);
104834  if( c2=='^' ){
104835  invert = 1;
104836  c2 = sqlite3Utf8Read(&zPattern);
104837  }
104838  if( c2==']' ){
104839  if( c==']' ) seen = 1;
104840  c2 = sqlite3Utf8Read(&zPattern);
104841  }
104842  while( c2 && c2!=']' ){
104843  if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
104844  c2 = sqlite3Utf8Read(&zPattern);
104845  if( c>=prior_c && c<=c2 ) seen = 1;
104846  prior_c = 0;
104847  }else{
104848  if( c==c2 ){
104849  seen = 1;
104850  }
104851  prior_c = c2;
104852  }
104853  c2 = sqlite3Utf8Read(&zPattern);
104854  }
104855  if( c2==0 || (seen ^ invert)==0 ){
104856  return 0;
104857  }
104858  continue;
104859  }
104860  }
104861  c2 = Utf8Read(zString);
104862  if( c==c2 ) continue;
104863  if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
104864  continue;
104865  }
104866  if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
104867  return 0;
104868  }
104869  return *zString==0;
104870 }
104871 
104872 /*
104873 ** The sqlite3_strglob() interface.
104874 */
104875 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
104876  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[')==0;
104877 }
104878 
104879 /*
104880 ** The sqlite3_strlike() interface.
104881 */
104882 SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
104883  return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0;
104884 }
104885 
104886 /*
104887 ** Count the number of times that the LIKE operator (or GLOB which is
104888 ** just a variation of LIKE) gets called. This is used for testing
104889 ** only.
104890 */
104891 #ifdef SQLITE_TEST
104892 SQLITE_API int sqlite3_like_count = 0;
104893 #endif
104894 
104895 
104896 /*
104897 ** Implementation of the like() SQL function. This function implements
104898 ** the build-in LIKE operator. The first argument to the function is the
104899 ** pattern and the second argument is the string. So, the SQL statements:
104900 **
104901 ** A LIKE B
104902 **
104903 ** is implemented as like(B,A).
104904 **
104905 ** This same function (with a different compareInfo structure) computes
104906 ** the GLOB operator.
104907 */
104908 static void likeFunc(
104909  sqlite3_context *context,
104910  int argc,
104911  sqlite3_value **argv
104912 ){
104913  const unsigned char *zA, *zB;
104914  u32 escape;
104915  int nPat;
104916  sqlite3 *db = sqlite3_context_db_handle(context);
104917  struct compareInfo *pInfo = sqlite3_user_data(context);
104918 
104919 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
104920  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
104921  || sqlite3_value_type(argv[1])==SQLITE_BLOB
104922  ){
104923 #ifdef SQLITE_TEST
104924  sqlite3_like_count++;
104925 #endif
104926  sqlite3_result_int(context, 0);
104927  return;
104928  }
104929 #endif
104930  zB = sqlite3_value_text(argv[0]);
104931  zA = sqlite3_value_text(argv[1]);
104932 
104933  /* Limit the length of the LIKE or GLOB pattern to avoid problems
104934  ** of deep recursion and N*N behavior in patternCompare().
104935  */
104936  nPat = sqlite3_value_bytes(argv[0]);
104937  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
104938  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
104939  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
104940  sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
104941  return;
104942  }
104943  assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
104944 
104945  if( argc==3 ){
104946  /* The escape character string must consist of a single UTF-8 character.
104947  ** Otherwise, return an error.
104948  */
104949  const unsigned char *zEsc = sqlite3_value_text(argv[2]);
104950  if( zEsc==0 ) return;
104951  if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
104952  sqlite3_result_error(context,
104953  "ESCAPE expression must be a single character", -1);
104954  return;
104955  }
104956  escape = sqlite3Utf8Read(&zEsc);
104957  }else{
104958  escape = pInfo->matchSet;
104959  }
104960  if( zA && zB ){
104961 #ifdef SQLITE_TEST
104962  sqlite3_like_count++;
104963 #endif
104964  sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
104965  }
104966 }
104967 
104968 /*
104969 ** Implementation of the NULLIF(x,y) function. The result is the first
104970 ** argument if the arguments are different. The result is NULL if the
104971 ** arguments are equal to each other.
104972 */
104973 static void nullifFunc(
104974  sqlite3_context *context,
104975  int NotUsed,
104976  sqlite3_value **argv
104977 ){
104978  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
104979  UNUSED_PARAMETER(NotUsed);
104980  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
104981  sqlite3_result_value(context, argv[0]);
104982  }
104983 }
104984 
104985 /*
104986 ** Implementation of the sqlite_version() function. The result is the version
104987 ** of the SQLite library that is running.
104988 */
104989 static void versionFunc(
104990  sqlite3_context *context,
104991  int NotUsed,
104992  sqlite3_value **NotUsed2
104993 ){
104994  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104995  /* IMP: R-48699-48617 This function is an SQL wrapper around the
104996  ** sqlite3_libversion() C-interface. */
104997  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
104998 }
104999 
105000 /*
105001 ** Implementation of the sqlite_source_id() function. The result is a string
105002 ** that identifies the particular version of the source code used to build
105003 ** SQLite.
105004 */
105005 static void sourceidFunc(
105006  sqlite3_context *context,
105007  int NotUsed,
105008  sqlite3_value **NotUsed2
105009 ){
105010  UNUSED_PARAMETER2(NotUsed, NotUsed2);
105011  /* IMP: R-24470-31136 This function is an SQL wrapper around the
105012  ** sqlite3_sourceid() C interface. */
105013  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
105014 }
105015 
105016 /*
105017 ** Implementation of the sqlite_log() function. This is a wrapper around
105018 ** sqlite3_log(). The return value is NULL. The function exists purely for
105019 ** its side-effects.
105020 */
105021 static void errlogFunc(
105022  sqlite3_context *context,
105023  int argc,
105024  sqlite3_value **argv
105025 ){
105026  UNUSED_PARAMETER(argc);
105027  UNUSED_PARAMETER(context);
105028  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
105029 }
105030 
105031 /*
105032 ** Implementation of the sqlite_compileoption_used() function.
105033 ** The result is an integer that identifies if the compiler option
105034 ** was used to build SQLite.
105035 */
105036 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
105037 static void compileoptionusedFunc(
105038  sqlite3_context *context,
105039  int argc,
105040  sqlite3_value **argv
105041 ){
105042  const char *zOptName;
105043  assert( argc==1 );
105044  UNUSED_PARAMETER(argc);
105045  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
105046  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
105047  ** function.
105048  */
105049  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
105050  sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
105051  }
105052 }
105053 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
105054 
105055 /*
105056 ** Implementation of the sqlite_compileoption_get() function.
105057 ** The result is a string that identifies the compiler options
105058 ** used to build SQLite.
105059 */
105060 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
105061 static void compileoptiongetFunc(
105062  sqlite3_context *context,
105063  int argc,
105064  sqlite3_value **argv
105065 ){
105066  int n;
105067  assert( argc==1 );
105068  UNUSED_PARAMETER(argc);
105069  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
105070  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
105071  */
105072  n = sqlite3_value_int(argv[0]);
105073  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
105074 }
105075 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
105076 
105077 /* Array for converting from half-bytes (nybbles) into ASCII hex
105078 ** digits. */
105079 static const char hexdigits[] = {
105080  '0', '1', '2', '3', '4', '5', '6', '7',
105081  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
105082 };
105083 
105084 /*
105085 ** Implementation of the QUOTE() function. This function takes a single
105086 ** argument. If the argument is numeric, the return value is the same as
105087 ** the argument. If the argument is NULL, the return value is the string
105088 ** "NULL". Otherwise, the argument is enclosed in single quotes with
105089 ** single-quote escapes.
105090 */
105091 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
105092  assert( argc==1 );
105093  UNUSED_PARAMETER(argc);
105094  switch( sqlite3_value_type(argv[0]) ){
105095  case SQLITE_FLOAT: {
105096  double r1, r2;
105097  char zBuf[50];
105098  r1 = sqlite3_value_double(argv[0]);
105099  sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
105100  sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
105101  if( r1!=r2 ){
105102  sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
105103  }
105104  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
105105  break;
105106  }
105107  case SQLITE_INTEGER: {
105108  sqlite3_result_value(context, argv[0]);
105109  break;
105110  }
105111  case SQLITE_BLOB: {
105112  char *zText = 0;
105113  char const *zBlob = sqlite3_value_blob(argv[0]);
105114  int nBlob = sqlite3_value_bytes(argv[0]);
105115  assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
105116  zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
105117  if( zText ){
105118  int i;
105119  for(i=0; i<nBlob; i++){
105120  zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
105121  zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
105122  }
105123  zText[(nBlob*2)+2] = '\'';
105124  zText[(nBlob*2)+3] = '\0';
105125  zText[0] = 'X';
105126  zText[1] = '\'';
105127  sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
105128  sqlite3_free(zText);
105129  }
105130  break;
105131  }
105132  case SQLITE_TEXT: {
105133  int i,j;
105134  u64 n;
105135  const unsigned char *zArg = sqlite3_value_text(argv[0]);
105136  char *z;
105137 
105138  if( zArg==0 ) return;
105139  for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
105140  z = contextMalloc(context, ((i64)i)+((i64)n)+3);
105141  if( z ){
105142  z[0] = '\'';
105143  for(i=0, j=1; zArg[i]; i++){
105144  z[j++] = zArg[i];
105145  if( zArg[i]=='\'' ){
105146  z[j++] = '\'';
105147  }
105148  }
105149  z[j++] = '\'';
105150  z[j] = 0;
105151  sqlite3_result_text(context, z, j, sqlite3_free);
105152  }
105153  break;
105154  }
105155  default: {
105156  assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
105157  sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
105158  break;
105159  }
105160  }
105161 }
105162 
105163 /*
105164 ** The unicode() function. Return the integer unicode code-point value
105165 ** for the first character of the input string.
105166 */
105167 static void unicodeFunc(
105168  sqlite3_context *context,
105169  int argc,
105170  sqlite3_value **argv
105171 ){
105172  const unsigned char *z = sqlite3_value_text(argv[0]);
105173  (void)argc;
105174  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
105175 }
105176 
105177 /*
105178 ** The char() function takes zero or more arguments, each of which is
105179 ** an integer. It constructs a string where each character of the string
105180 ** is the unicode character for the corresponding integer argument.
105181 */
105182 static void charFunc(
105183  sqlite3_context *context,
105184  int argc,
105185  sqlite3_value **argv
105186 ){
105187  unsigned char *z, *zOut;
105188  int i;
105189  zOut = z = sqlite3_malloc64( argc*4+1 );
105190  if( z==0 ){
105191  sqlite3_result_error_nomem(context);
105192  return;
105193  }
105194  for(i=0; i<argc; i++){
105195  sqlite3_int64 x;
105196  unsigned c;
105197  x = sqlite3_value_int64(argv[i]);
105198  if( x<0 || x>0x10ffff ) x = 0xfffd;
105199  c = (unsigned)(x & 0x1fffff);
105200  if( c<0x00080 ){
105201  *zOut++ = (u8)(c&0xFF);
105202  }else if( c<0x00800 ){
105203  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
105204  *zOut++ = 0x80 + (u8)(c & 0x3F);
105205  }else if( c<0x10000 ){
105206  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
105207  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
105208  *zOut++ = 0x80 + (u8)(c & 0x3F);
105209  }else{
105210  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
105211  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
105212  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
105213  *zOut++ = 0x80 + (u8)(c & 0x3F);
105214  } \
105215  }
105216  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
105217 }
105218 
105219 /*
105220 ** The hex() function. Interpret the argument as a blob. Return
105221 ** a hexadecimal rendering as text.
105222 */
105223 static void hexFunc(
105224  sqlite3_context *context,
105225  int argc,
105226  sqlite3_value **argv
105227 ){
105228  int i, n;
105229  const unsigned char *pBlob;
105230  char *zHex, *z;
105231  assert( argc==1 );
105232  UNUSED_PARAMETER(argc);
105233  pBlob = sqlite3_value_blob(argv[0]);
105234  n = sqlite3_value_bytes(argv[0]);
105235  assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
105236  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
105237  if( zHex ){
105238  for(i=0; i<n; i++, pBlob++){
105239  unsigned char c = *pBlob;
105240  *(z++) = hexdigits[(c>>4)&0xf];
105241  *(z++) = hexdigits[c&0xf];
105242  }
105243  *z = 0;
105244  sqlite3_result_text(context, zHex, n*2, sqlite3_free);
105245  }
105246 }
105247 
105248 /*
105249 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
105250 */
105251 static void zeroblobFunc(
105252  sqlite3_context *context,
105253  int argc,
105254  sqlite3_value **argv
105255 ){
105256  i64 n;
105257  int rc;
105258  assert( argc==1 );
105259  UNUSED_PARAMETER(argc);
105260  n = sqlite3_value_int64(argv[0]);
105261  if( n<0 ) n = 0;
105262  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
105263  if( rc ){
105264  sqlite3_result_error_code(context, rc);
105265  }
105266 }
105267 
105268 /*
105269 ** The replace() function. Three arguments are all strings: call
105270 ** them A, B, and C. The result is also a string which is derived
105271 ** from A by replacing every occurrence of B with C. The match
105272 ** must be exact. Collating sequences are not used.
105273 */
105274 static void replaceFunc(
105275  sqlite3_context *context,
105276  int argc,
105277  sqlite3_value **argv
105278 ){
105279  const unsigned char *zStr; /* The input string A */
105280  const unsigned char *zPattern; /* The pattern string B */
105281  const unsigned char *zRep; /* The replacement string C */
105282  unsigned char *zOut; /* The output */
105283  int nStr; /* Size of zStr */
105284  int nPattern; /* Size of zPattern */
105285  int nRep; /* Size of zRep */
105286  i64 nOut; /* Maximum size of zOut */
105287  int loopLimit; /* Last zStr[] that might match zPattern[] */
105288  int i, j; /* Loop counters */
105289 
105290  assert( argc==3 );
105291  UNUSED_PARAMETER(argc);
105292  zStr = sqlite3_value_text(argv[0]);
105293  if( zStr==0 ) return;
105294  nStr = sqlite3_value_bytes(argv[0]);
105295  assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
105296  zPattern = sqlite3_value_text(argv[1]);
105297  if( zPattern==0 ){
105298  assert( sqlite3_value_type(argv[1])==SQLITE_NULL
105299  || sqlite3_context_db_handle(context)->mallocFailed );
105300  return;
105301  }
105302  if( zPattern[0]==0 ){
105303  assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
105304  sqlite3_result_value(context, argv[0]);
105305  return;
105306  }
105307  nPattern = sqlite3_value_bytes(argv[1]);
105308  assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
105309  zRep = sqlite3_value_text(argv[2]);
105310  if( zRep==0 ) return;
105311  nRep = sqlite3_value_bytes(argv[2]);
105312  assert( zRep==sqlite3_value_text(argv[2]) );
105313  nOut = nStr + 1;
105314  assert( nOut<SQLITE_MAX_LENGTH );
105315  zOut = contextMalloc(context, (i64)nOut);
105316  if( zOut==0 ){
105317  return;
105318  }
105319  loopLimit = nStr - nPattern;
105320  for(i=j=0; i<=loopLimit; i++){
105321  if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
105322  zOut[j++] = zStr[i];
105323  }else{
105324  u8 *zOld;
105325  sqlite3 *db = sqlite3_context_db_handle(context);
105326  nOut += nRep - nPattern;
105327  testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
105328  testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
105329  if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
105330  sqlite3_result_error_toobig(context);
105331  sqlite3_free(zOut);
105332  return;
105333  }
105334  zOld = zOut;
105335  zOut = sqlite3_realloc64(zOut, (int)nOut);
105336  if( zOut==0 ){
105337  sqlite3_result_error_nomem(context);
105338  sqlite3_free(zOld);
105339  return;
105340  }
105341  memcpy(&zOut[j], zRep, nRep);
105342  j += nRep;
105343  i += nPattern-1;
105344  }
105345  }
105346  assert( j+nStr-i+1==nOut );
105347  memcpy(&zOut[j], &zStr[i], nStr-i);
105348  j += nStr - i;
105349  assert( j<=nOut );
105350  zOut[j] = 0;
105351  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
105352 }
105353 
105354 /*
105355 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
105356 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
105357 */
105358 static void trimFunc(
105359  sqlite3_context *context,
105360  int argc,
105361  sqlite3_value **argv
105362 ){
105363  const unsigned char *zIn; /* Input string */
105364  const unsigned char *zCharSet; /* Set of characters to trim */
105365  int nIn; /* Number of bytes in input */
105366  int flags; /* 1: trimleft 2: trimright 3: trim */
105367  int i; /* Loop counter */
105368  unsigned char *aLen = 0; /* Length of each character in zCharSet */
105369  unsigned char **azChar = 0; /* Individual characters in zCharSet */
105370  int nChar; /* Number of characters in zCharSet */
105371 
105372  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
105373  return;
105374  }
105375  zIn = sqlite3_value_text(argv[0]);
105376  if( zIn==0 ) return;
105377  nIn = sqlite3_value_bytes(argv[0]);
105378  assert( zIn==sqlite3_value_text(argv[0]) );
105379  if( argc==1 ){
105380  static const unsigned char lenOne[] = { 1 };
105381  static unsigned char * const azOne[] = { (u8*)" " };
105382  nChar = 1;
105383  aLen = (u8*)lenOne;
105384  azChar = (unsigned char **)azOne;
105385  zCharSet = 0;
105386  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
105387  return;
105388  }else{
105389  const unsigned char *z;
105390  for(z=zCharSet, nChar=0; *z; nChar++){
105391  SQLITE_SKIP_UTF8(z);
105392  }
105393  if( nChar>0 ){
105394  azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
105395  if( azChar==0 ){
105396  return;
105397  }
105398  aLen = (unsigned char*)&azChar[nChar];
105399  for(z=zCharSet, nChar=0; *z; nChar++){
105400  azChar[nChar] = (unsigned char *)z;
105401  SQLITE_SKIP_UTF8(z);
105402  aLen[nChar] = (u8)(z - azChar[nChar]);
105403  }
105404  }
105405  }
105406  if( nChar>0 ){
105407  flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
105408  if( flags & 1 ){
105409  while( nIn>0 ){
105410  int len = 0;
105411  for(i=0; i<nChar; i++){
105412  len = aLen[i];
105413  if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
105414  }
105415  if( i>=nChar ) break;
105416  zIn += len;
105417  nIn -= len;
105418  }
105419  }
105420  if( flags & 2 ){
105421  while( nIn>0 ){
105422  int len = 0;
105423  for(i=0; i<nChar; i++){
105424  len = aLen[i];
105425  if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
105426  }
105427  if( i>=nChar ) break;
105428  nIn -= len;
105429  }
105430  }
105431  if( zCharSet ){
105432  sqlite3_free(azChar);
105433  }
105434  }
105435  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
105436 }
105437 
105438 
105439 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
105440 /*
105441 ** The "unknown" function is automatically substituted in place of
105442 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
105443 ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
105444 ** When the "sqlite3" command-line shell is built using this functionality,
105445 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
105446 ** involving application-defined functions to be examined in a generic
105447 ** sqlite3 shell.
105448 */
105449 static void unknownFunc(
105450  sqlite3_context *context,
105451  int argc,
105452  sqlite3_value **argv
105453 ){
105454  /* no-op */
105455 }
105456 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
105457 
105458 
105459 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
105460 ** is only available if the SQLITE_SOUNDEX compile-time option is used
105461 ** when SQLite is built.
105462 */
105463 #ifdef SQLITE_SOUNDEX
105464 /*
105465 ** Compute the soundex encoding of a word.
105466 **
105467 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
105468 ** soundex encoding of the string X.
105469 */
105470 static void soundexFunc(
105471  sqlite3_context *context,
105472  int argc,
105473  sqlite3_value **argv
105474 ){
105475  char zResult[8];
105476  const u8 *zIn;
105477  int i, j;
105478  static const unsigned char iCode[] = {
105479  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105480  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105481  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105482  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105483  0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
105484  1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
105485  0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
105486  1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
105487  };
105488  assert( argc==1 );
105489  zIn = (u8*)sqlite3_value_text(argv[0]);
105490  if( zIn==0 ) zIn = (u8*)"";
105491  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
105492  if( zIn[i] ){
105493  u8 prevcode = iCode[zIn[i]&0x7f];
105494  zResult[0] = sqlite3Toupper(zIn[i]);
105495  for(j=1; j<4 && zIn[i]; i++){
105496  int code = iCode[zIn[i]&0x7f];
105497  if( code>0 ){
105498  if( code!=prevcode ){
105499  prevcode = code;
105500  zResult[j++] = code + '0';
105501  }
105502  }else{
105503  prevcode = 0;
105504  }
105505  }
105506  while( j<4 ){
105507  zResult[j++] = '0';
105508  }
105509  zResult[j] = 0;
105510  sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
105511  }else{
105512  /* IMP: R-64894-50321 The string "?000" is returned if the argument
105513  ** is NULL or contains no ASCII alphabetic characters. */
105514  sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
105515  }
105516 }
105517 #endif /* SQLITE_SOUNDEX */
105518 
105519 #ifndef SQLITE_OMIT_LOAD_EXTENSION
105520 /*
105521 ** A function that loads a shared-library extension then returns NULL.
105522 */
105523 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
105524  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
105525  const char *zProc;
105526  sqlite3 *db = sqlite3_context_db_handle(context);
105527  char *zErrMsg = 0;
105528 
105529  /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
105530  ** flag is set. See the sqlite3_enable_load_extension() API.
105531  */
105532  if( (db->flags & SQLITE_LoadExtFunc)==0 ){
105533  sqlite3_result_error(context, "not authorized", -1);
105534  return;
105535  }
105536 
105537  if( argc==2 ){
105538  zProc = (const char *)sqlite3_value_text(argv[1]);
105539  }else{
105540  zProc = 0;
105541  }
105542  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
105543  sqlite3_result_error(context, zErrMsg, -1);
105544  sqlite3_free(zErrMsg);
105545  }
105546 }
105547 #endif
105548 
105549 
105550 /*
105551 ** An instance of the following structure holds the context of a
105552 ** sum() or avg() aggregate computation.
105553 */
105554 typedef struct SumCtx SumCtx;
105555 struct SumCtx {
105556  double rSum; /* Floating point sum */
105557  i64 iSum; /* Integer sum */
105558  i64 cnt; /* Number of elements summed */
105559  u8 overflow; /* True if integer overflow seen */
105560  u8 approx; /* True if non-integer value was input to the sum */
105561 };
105562 
105563 /*
105564 ** Routines used to compute the sum, average, and total.
105565 **
105566 ** The SUM() function follows the (broken) SQL standard which means
105567 ** that it returns NULL if it sums over no inputs. TOTAL returns
105568 ** 0.0 in that case. In addition, TOTAL always returns a float where
105569 ** SUM might return an integer if it never encounters a floating point
105570 ** value. TOTAL never fails, but SUM might through an exception if
105571 ** it overflows an integer.
105572 */
105573 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
105574  SumCtx *p;
105575  int type;
105576  assert( argc==1 );
105577  UNUSED_PARAMETER(argc);
105578  p = sqlite3_aggregate_context(context, sizeof(*p));
105579  type = sqlite3_value_numeric_type(argv[0]);
105580  if( p && type!=SQLITE_NULL ){
105581  p->cnt++;
105582  if( type==SQLITE_INTEGER ){
105583  i64 v = sqlite3_value_int64(argv[0]);
105584  p->rSum += v;
105585  if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
105586  p->overflow = 1;
105587  }
105588  }else{
105589  p->rSum += sqlite3_value_double(argv[0]);
105590  p->approx = 1;
105591  }
105592  }
105593 }
105594 static void sumFinalize(sqlite3_context *context){
105595  SumCtx *p;
105596  p = sqlite3_aggregate_context(context, 0);
105597  if( p && p->cnt>0 ){
105598  if( p->overflow ){
105599  sqlite3_result_error(context,"integer overflow",-1);
105600  }else if( p->approx ){
105601  sqlite3_result_double(context, p->rSum);
105602  }else{
105603  sqlite3_result_int64(context, p->iSum);
105604  }
105605  }
105606 }
105607 static void avgFinalize(sqlite3_context *context){
105608  SumCtx *p;
105609  p = sqlite3_aggregate_context(context, 0);
105610  if( p && p->cnt>0 ){
105611  sqlite3_result_double(context, p->rSum/(double)p->cnt);
105612  }
105613 }
105614 static void totalFinalize(sqlite3_context *context){
105615  SumCtx *p;
105616  p = sqlite3_aggregate_context(context, 0);
105617  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
105618  sqlite3_result_double(context, p ? p->rSum : (double)0);
105619 }
105620 
105621 /*
105622 ** The following structure keeps track of state information for the
105623 ** count() aggregate function.
105624 */
105625 typedef struct CountCtx CountCtx;
105626 struct CountCtx {
105627  i64 n;
105628 };
105629 
105630 /*
105631 ** Routines to implement the count() aggregate function.
105632 */
105633 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
105634  CountCtx *p;
105635  p = sqlite3_aggregate_context(context, sizeof(*p));
105636  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
105637  p->n++;
105638  }
105639 
105640 #ifndef SQLITE_OMIT_DEPRECATED
105641  /* The sqlite3_aggregate_count() function is deprecated. But just to make
105642  ** sure it still operates correctly, verify that its count agrees with our
105643  ** internal count when using count(*) and when the total count can be
105644  ** expressed as a 32-bit integer. */
105645  assert( argc==1 || p==0 || p->n>0x7fffffff
105646  || p->n==sqlite3_aggregate_count(context) );
105647 #endif
105648 }
105649 static void countFinalize(sqlite3_context *context){
105650  CountCtx *p;
105651  p = sqlite3_aggregate_context(context, 0);
105652  sqlite3_result_int64(context, p ? p->n : 0);
105653 }
105654 
105655 /*
105656 ** Routines to implement min() and max() aggregate functions.
105657 */
105658 static void minmaxStep(
105659  sqlite3_context *context,
105660  int NotUsed,
105661  sqlite3_value **argv
105662 ){
105663  Mem *pArg = (Mem *)argv[0];
105664  Mem *pBest;
105665  UNUSED_PARAMETER(NotUsed);
105666 
105667  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
105668  if( !pBest ) return;
105669 
105670  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
105671  if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
105672  }else if( pBest->flags ){
105673  int max;
105674  int cmp;
105675  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
105676  /* This step function is used for both the min() and max() aggregates,
105677  ** the only difference between the two being that the sense of the
105678  ** comparison is inverted. For the max() aggregate, the
105679  ** sqlite3_user_data() function returns (void *)-1. For min() it
105680  ** returns (void *)db, where db is the sqlite3* database pointer.
105681  ** Therefore the next statement sets variable 'max' to 1 for the max()
105682  ** aggregate, or 0 for min().
105683  */
105684  max = sqlite3_user_data(context)!=0;
105685  cmp = sqlite3MemCompare(pBest, pArg, pColl);
105686  if( (max && cmp<0) || (!max && cmp>0) ){
105687  sqlite3VdbeMemCopy(pBest, pArg);
105688  }else{
105689  sqlite3SkipAccumulatorLoad(context);
105690  }
105691  }else{
105692  pBest->db = sqlite3_context_db_handle(context);
105693  sqlite3VdbeMemCopy(pBest, pArg);
105694  }
105695 }
105696 static void minMaxFinalize(sqlite3_context *context){
105697  sqlite3_value *pRes;
105698  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
105699  if( pRes ){
105700  if( pRes->flags ){
105701  sqlite3_result_value(context, pRes);
105702  }
105703  sqlite3VdbeMemRelease(pRes);
105704  }
105705 }
105706 
105707 /*
105708 ** group_concat(EXPR, ?SEPARATOR?)
105709 */
105710 static void groupConcatStep(
105711  sqlite3_context *context,
105712  int argc,
105713  sqlite3_value **argv
105714 ){
105715  const char *zVal;
105716  StrAccum *pAccum;
105717  const char *zSep;
105718  int nVal, nSep;
105719  assert( argc==1 || argc==2 );
105720  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
105721  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
105722 
105723  if( pAccum ){
105724  sqlite3 *db = sqlite3_context_db_handle(context);
105725  int firstTerm = pAccum->mxAlloc==0;
105726  pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
105727  if( !firstTerm ){
105728  if( argc==2 ){
105729  zSep = (char*)sqlite3_value_text(argv[1]);
105730  nSep = sqlite3_value_bytes(argv[1]);
105731  }else{
105732  zSep = ",";
105733  nSep = 1;
105734  }
105735  if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
105736  }
105737  zVal = (char*)sqlite3_value_text(argv[0]);
105738  nVal = sqlite3_value_bytes(argv[0]);
105739  if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
105740  }
105741 }
105742 static void groupConcatFinalize(sqlite3_context *context){
105743  StrAccum *pAccum;
105744  pAccum = sqlite3_aggregate_context(context, 0);
105745  if( pAccum ){
105746  if( pAccum->accError==STRACCUM_TOOBIG ){
105747  sqlite3_result_error_toobig(context);
105748  }else if( pAccum->accError==STRACCUM_NOMEM ){
105749  sqlite3_result_error_nomem(context);
105750  }else{
105751  sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
105752  sqlite3_free);
105753  }
105754  }
105755 }
105756 
105757 /*
105758 ** This routine does per-connection function registration. Most
105759 ** of the built-in functions above are part of the global function set.
105760 ** This routine only deals with those that are not global.
105761 */
105762 SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
105763  int rc = sqlite3_overload_function(db, "MATCH", 2);
105764  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
105765  if( rc==SQLITE_NOMEM ){
105766  sqlite3OomFault(db);
105767  }
105768 }
105769 
105770 /*
105771 ** Set the LIKEOPT flag on the 2-argument function with the given name.
105772 */
105773 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
105774  FuncDef *pDef;
105775  pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
105776  if( ALWAYS(pDef) ){
105777  pDef->funcFlags |= flagVal;
105778  }
105779 }
105780 
105781 /*
105782 ** Register the built-in LIKE and GLOB functions. The caseSensitive
105783 ** parameter determines whether or not the LIKE operator is case
105784 ** sensitive. GLOB is always case sensitive.
105785 */
105786 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
105787  struct compareInfo *pInfo;
105788  if( caseSensitive ){
105789  pInfo = (struct compareInfo*)&likeInfoAlt;
105790  }else{
105791  pInfo = (struct compareInfo*)&likeInfoNorm;
105792  }
105793  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
105794  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
105795  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
105796  (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
105797  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
105798  setLikeOptFlag(db, "like",
105799  caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
105800 }
105801 
105802 /*
105803 ** pExpr points to an expression which implements a function. If
105804 ** it is appropriate to apply the LIKE optimization to that function
105805 ** then set aWc[0] through aWc[2] to the wildcard characters and
105806 ** return TRUE. If the function is not a LIKE-style function then
105807 ** return FALSE.
105808 **
105809 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
105810 ** the function (default for LIKE). If the function makes the distinction
105811 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
105812 ** false.
105813 */
105814 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
105815  FuncDef *pDef;
105816  if( pExpr->op!=TK_FUNCTION
105817  || !pExpr->x.pList
105818  || pExpr->x.pList->nExpr!=2
105819  ){
105820  return 0;
105821  }
105822  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
105823  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
105824  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
105825  return 0;
105826  }
105827 
105828  /* The memcpy() statement assumes that the wildcard characters are
105829  ** the first three statements in the compareInfo structure. The
105830  ** asserts() that follow verify that assumption
105831  */
105832  memcpy(aWc, pDef->pUserData, 3);
105833  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
105834  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
105835  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
105836  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
105837  return 1;
105838 }
105839 
105840 /*
105841 ** All of the FuncDef structures in the aBuiltinFunc[] array above
105842 ** to the global function hash table. This occurs at start-time (as
105843 ** a consequence of calling sqlite3_initialize()).
105844 **
105845 ** After this routine runs
105846 */
105847 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
105848  /*
105849  ** The following array holds FuncDef structures for all of the functions
105850  ** defined in this file.
105851  **
105852  ** The array cannot be constant since changes are made to the
105853  ** FuncDef.pHash elements at start-time. The elements of this array
105854  ** are read-only after initialization is complete.
105855  **
105856  ** For peak efficiency, put the most frequently used function last.
105857  */
105858  static FuncDef aBuiltinFunc[] = {
105859 #ifdef SQLITE_SOUNDEX
105860  FUNCTION(soundex, 1, 0, 0, soundexFunc ),
105861 #endif
105862 #ifndef SQLITE_OMIT_LOAD_EXTENSION
105863  VFUNCTION(load_extension, 1, 0, 0, loadExt ),
105864  VFUNCTION(load_extension, 2, 0, 0, loadExt ),
105865 #endif
105866 #if SQLITE_USER_AUTHENTICATION
105867  FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
105868 #endif
105869 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
105870  DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
105871  DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
105872 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
105873  FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
105874  FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
105875  FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
105876  FUNCTION(ltrim, 1, 1, 0, trimFunc ),
105877  FUNCTION(ltrim, 2, 1, 0, trimFunc ),
105878  FUNCTION(rtrim, 1, 2, 0, trimFunc ),
105879  FUNCTION(rtrim, 2, 2, 0, trimFunc ),
105880  FUNCTION(trim, 1, 3, 0, trimFunc ),
105881  FUNCTION(trim, 2, 3, 0, trimFunc ),
105882  FUNCTION(min, -1, 0, 1, minmaxFunc ),
105883  FUNCTION(min, 0, 0, 1, 0 ),
105884  AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
105885  SQLITE_FUNC_MINMAX ),
105886  FUNCTION(max, -1, 1, 1, minmaxFunc ),
105887  FUNCTION(max, 0, 1, 1, 0 ),
105888  AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
105889  SQLITE_FUNC_MINMAX ),
105890  FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
105891  FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
105892  FUNCTION(instr, 2, 0, 0, instrFunc ),
105893  FUNCTION(printf, -1, 0, 0, printfFunc ),
105894  FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
105895  FUNCTION(char, -1, 0, 0, charFunc ),
105896  FUNCTION(abs, 1, 0, 0, absFunc ),
105897 #ifndef SQLITE_OMIT_FLOATING_POINT
105898  FUNCTION(round, 1, 0, 0, roundFunc ),
105899  FUNCTION(round, 2, 0, 0, roundFunc ),
105900 #endif
105901  FUNCTION(upper, 1, 0, 0, upperFunc ),
105902  FUNCTION(lower, 1, 0, 0, lowerFunc ),
105903  FUNCTION(hex, 1, 0, 0, hexFunc ),
105904  FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
105905  VFUNCTION(random, 0, 0, 0, randomFunc ),
105906  VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
105907  FUNCTION(nullif, 2, 0, 1, nullifFunc ),
105908  DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
105909  DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
105910  FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
105911  FUNCTION(quote, 1, 0, 0, quoteFunc ),
105912  VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
105913  VFUNCTION(changes, 0, 0, 0, changes ),
105914  VFUNCTION(total_changes, 0, 0, 0, total_changes ),
105915  FUNCTION(replace, 3, 0, 0, replaceFunc ),
105916  FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
105917  FUNCTION(substr, 2, 0, 0, substrFunc ),
105918  FUNCTION(substr, 3, 0, 0, substrFunc ),
105919  AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
105920  AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
105921  AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
105922  AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
105923  SQLITE_FUNC_COUNT ),
105924  AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
105925  AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
105926  AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
105927 
105928  LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105929 #ifdef SQLITE_CASE_SENSITIVE_LIKE
105930  LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105931  LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105932 #else
105933  LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
105934  LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
105935 #endif
105936 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
105937  FUNCTION(unknown, -1, 0, 0, unknownFunc ),
105938 #endif
105939  FUNCTION(coalesce, 1, 0, 0, 0 ),
105940  FUNCTION(coalesce, 0, 0, 0, 0 ),
105941  FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
105942  };
105943 #ifndef SQLITE_OMIT_ALTERTABLE
105944  sqlite3AlterFunctions();
105945 #endif
105946 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
105947  sqlite3AnalyzeFunctions();
105948 #endif
105949  sqlite3RegisterDateTimeFunctions();
105950  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
105951 
105952 #if 0 /* Enable to print out how the built-in functions are hashed */
105953  {
105954  int i;
105955  FuncDef *p;
105956  for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
105957  printf("FUNC-HASH %02d:", i);
105958  for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
105959  int n = sqlite3Strlen30(p->zName);
105960  int h = p->zName[0] + n;
105961  printf(" %s(%d)", p->zName, h);
105962  }
105963  printf("\n");
105964  }
105965  }
105966 #endif
105967 }
105968 
105969 /************** End of func.c ************************************************/
105970 /************** Begin file fkey.c ********************************************/
105971 /*
105972 **
105973 ** The author disclaims copyright to this source code. In place of
105974 ** a legal notice, here is a blessing:
105975 **
105976 ** May you do good and not evil.
105977 ** May you find forgiveness for yourself and forgive others.
105978 ** May you share freely, never taking more than you give.
105979 **
105980 *************************************************************************
105981 ** This file contains code used by the compiler to add foreign key
105982 ** support to compiled SQL statements.
105983 */
105984 /* #include "sqliteInt.h" */
105985 
105986 #ifndef SQLITE_OMIT_FOREIGN_KEY
105987 #ifndef SQLITE_OMIT_TRIGGER
105988 
105989 /*
105990 ** Deferred and Immediate FKs
105991 ** --------------------------
105992 **
105993 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
105994 ** If an immediate foreign key constraint is violated,
105995 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
105996 ** statement transaction rolled back. If a
105997 ** deferred foreign key constraint is violated, no action is taken
105998 ** immediately. However if the application attempts to commit the
105999 ** transaction before fixing the constraint violation, the attempt fails.
106000 **
106001 ** Deferred constraints are implemented using a simple counter associated
106002 ** with the database handle. The counter is set to zero each time a
106003 ** database transaction is opened. Each time a statement is executed
106004 ** that causes a foreign key violation, the counter is incremented. Each
106005 ** time a statement is executed that removes an existing violation from
106006 ** the database, the counter is decremented. When the transaction is
106007 ** committed, the commit fails if the current value of the counter is
106008 ** greater than zero. This scheme has two big drawbacks:
106009 **
106010 ** * When a commit fails due to a deferred foreign key constraint,
106011 ** there is no way to tell which foreign constraint is not satisfied,
106012 ** or which row it is not satisfied for.
106013 **
106014 ** * If the database contains foreign key violations when the
106015 ** transaction is opened, this may cause the mechanism to malfunction.
106016 **
106017 ** Despite these problems, this approach is adopted as it seems simpler
106018 ** than the alternatives.
106019 **
106020 ** INSERT operations:
106021 **
106022 ** I.1) For each FK for which the table is the child table, search
106023 ** the parent table for a match. If none is found increment the
106024 ** constraint counter.
106025 **
106026 ** I.2) For each FK for which the table is the parent table,
106027 ** search the child table for rows that correspond to the new
106028 ** row in the parent table. Decrement the counter for each row
106029 ** found (as the constraint is now satisfied).
106030 **
106031 ** DELETE operations:
106032 **
106033 ** D.1) For each FK for which the table is the child table,
106034 ** search the parent table for a row that corresponds to the
106035 ** deleted row in the child table. If such a row is not found,
106036 ** decrement the counter.
106037 **
106038 ** D.2) For each FK for which the table is the parent table, search
106039 ** the child table for rows that correspond to the deleted row
106040 ** in the parent table. For each found increment the counter.
106041 **
106042 ** UPDATE operations:
106043 **
106044 ** An UPDATE command requires that all 4 steps above are taken, but only
106045 ** for FK constraints for which the affected columns are actually
106046 ** modified (values must be compared at runtime).
106047 **
106048 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
106049 ** This simplifies the implementation a bit.
106050 **
106051 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
106052 ** resolution is considered to delete rows before the new row is inserted.
106053 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
106054 ** is thrown, even if the FK constraint would be satisfied after the new
106055 ** row is inserted.
106056 **
106057 ** Immediate constraints are usually handled similarly. The only difference
106058 ** is that the counter used is stored as part of each individual statement
106059 ** object (struct Vdbe). If, after the statement has run, its immediate
106060 ** constraint counter is greater than zero,
106061 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
106062 ** and the statement transaction is rolled back. An exception is an INSERT
106063 ** statement that inserts a single row only (no triggers). In this case,
106064 ** instead of using a counter, an exception is thrown immediately if the
106065 ** INSERT violates a foreign key constraint. This is necessary as such
106066 ** an INSERT does not open a statement transaction.
106067 **
106068 ** TODO: How should dropping a table be handled? How should renaming a
106069 ** table be handled?
106070 **
106071 **
106072 ** Query API Notes
106073 ** ---------------
106074 **
106075 ** Before coding an UPDATE or DELETE row operation, the code-generator
106076 ** for those two operations needs to know whether or not the operation
106077 ** requires any FK processing and, if so, which columns of the original
106078 ** row are required by the FK processing VDBE code (i.e. if FKs were
106079 ** implemented using triggers, which of the old.* columns would be
106080 ** accessed). No information is required by the code-generator before
106081 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
106082 ** generation code to query for this information are:
106083 **
106084 ** sqlite3FkRequired() - Test to see if FK processing is required.
106085 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
106086 **
106087 **
106088 ** Externally accessible module functions
106089 ** --------------------------------------
106090 **
106091 ** sqlite3FkCheck() - Check for foreign key violations.
106092 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
106093 ** sqlite3FkDelete() - Delete an FKey structure.
106094 */
106095 
106096 /*
106097 ** VDBE Calling Convention
106098 ** -----------------------
106099 **
106100 ** Example:
106101 **
106102 ** For the following INSERT statement:
106103 **
106104 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
106105 ** INSERT INTO t1 VALUES(1, 2, 3.1);
106106 **
106107 ** Register (x): 2 (type integer)
106108 ** Register (x+1): 1 (type integer)
106109 ** Register (x+2): NULL (type NULL)
106110 ** Register (x+3): 3.1 (type real)
106111 */
106112 
106113 /*
106114 ** A foreign key constraint requires that the key columns in the parent
106115 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
106116 ** Given that pParent is the parent table for foreign key constraint pFKey,
106117 ** search the schema for a unique index on the parent key columns.
106118 **
106119 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
106120 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
106121 ** is set to point to the unique index.
106122 **
106123 ** If the parent key consists of a single column (the foreign key constraint
106124 ** is not a composite foreign key), output variable *paiCol is set to NULL.
106125 ** Otherwise, it is set to point to an allocated array of size N, where
106126 ** N is the number of columns in the parent key. The first element of the
106127 ** array is the index of the child table column that is mapped by the FK
106128 ** constraint to the parent table column stored in the left-most column
106129 ** of index *ppIdx. The second element of the array is the index of the
106130 ** child table column that corresponds to the second left-most column of
106131 ** *ppIdx, and so on.
106132 **
106133 ** If the required index cannot be found, either because:
106134 **
106135 ** 1) The named parent key columns do not exist, or
106136 **
106137 ** 2) The named parent key columns do exist, but are not subject to a
106138 ** UNIQUE or PRIMARY KEY constraint, or
106139 **
106140 ** 3) No parent key columns were provided explicitly as part of the
106141 ** foreign key definition, and the parent table does not have a
106142 ** PRIMARY KEY, or
106143 **
106144 ** 4) No parent key columns were provided explicitly as part of the
106145 ** foreign key definition, and the PRIMARY KEY of the parent table
106146 ** consists of a different number of columns to the child key in
106147 ** the child table.
106148 **
106149 ** then non-zero is returned, and a "foreign key mismatch" error loaded
106150 ** into pParse. If an OOM error occurs, non-zero is returned and the
106151 ** pParse->db->mallocFailed flag is set.
106152 */
106153 SQLITE_PRIVATE int sqlite3FkLocateIndex(
106154  Parse *pParse, /* Parse context to store any error in */
106155  Table *pParent, /* Parent table of FK constraint pFKey */
106156  FKey *pFKey, /* Foreign key to find index for */
106157  Index **ppIdx, /* OUT: Unique index on parent table */
106158  int **paiCol /* OUT: Map of index columns in pFKey */
106159 ){
106160  Index *pIdx = 0; /* Value to return via *ppIdx */
106161  int *aiCol = 0; /* Value to return via *paiCol */
106162  int nCol = pFKey->nCol; /* Number of columns in parent key */
106163  char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
106164 
106165  /* The caller is responsible for zeroing output parameters. */
106166  assert( ppIdx && *ppIdx==0 );
106167  assert( !paiCol || *paiCol==0 );
106168  assert( pParse );
106169 
106170  /* If this is a non-composite (single column) foreign key, check if it
106171  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
106172  ** and *paiCol set to zero and return early.
106173  **
106174  ** Otherwise, for a composite foreign key (more than one column), allocate
106175  ** space for the aiCol array (returned via output parameter *paiCol).
106176  ** Non-composite foreign keys do not require the aiCol array.
106177  */
106178  if( nCol==1 ){
106179  /* The FK maps to the IPK if any of the following are true:
106180  **
106181  ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
106182  ** mapped to the primary key of table pParent, or
106183  ** 2) The FK is explicitly mapped to a column declared as INTEGER
106184  ** PRIMARY KEY.
106185  */
106186  if( pParent->iPKey>=0 ){
106187  if( !zKey ) return 0;
106188  if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
106189  }
106190  }else if( paiCol ){
106191  assert( nCol>1 );
106192  aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
106193  if( !aiCol ) return 1;
106194  *paiCol = aiCol;
106195  }
106196 
106197  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
106198  if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
106199  /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
106200  ** of columns. If each indexed column corresponds to a foreign key
106201  ** column of pFKey, then this index is a winner. */
106202 
106203  if( zKey==0 ){
106204  /* If zKey is NULL, then this foreign key is implicitly mapped to
106205  ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
106206  ** identified by the test. */
106207  if( IsPrimaryKeyIndex(pIdx) ){
106208  if( aiCol ){
106209  int i;
106210  for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
106211  }
106212  break;
106213  }
106214  }else{
106215  /* If zKey is non-NULL, then this foreign key was declared to
106216  ** map to an explicit list of columns in table pParent. Check if this
106217  ** index matches those columns. Also, check that the index uses
106218  ** the default collation sequences for each column. */
106219  int i, j;
106220  for(i=0; i<nCol; i++){
106221  i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
106222  const char *zDfltColl; /* Def. collation for column */
106223  char *zIdxCol; /* Name of indexed column */
106224 
106225  if( iCol<0 ) break; /* No foreign keys against expression indexes */
106226 
106227  /* If the index uses a collation sequence that is different from
106228  ** the default collation sequence for the column, this index is
106229  ** unusable. Bail out early in this case. */
106230  zDfltColl = pParent->aCol[iCol].zColl;
106231  if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
106232  if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
106233 
106234  zIdxCol = pParent->aCol[iCol].zName;
106235  for(j=0; j<nCol; j++){
106236  if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
106237  if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
106238  break;
106239  }
106240  }
106241  if( j==nCol ) break;
106242  }
106243  if( i==nCol ) break; /* pIdx is usable */
106244  }
106245  }
106246  }
106247 
106248  if( !pIdx ){
106249  if( !pParse->disableTriggers ){
106250  sqlite3ErrorMsg(pParse,
106251  "foreign key mismatch - \"%w\" referencing \"%w\"",
106252  pFKey->pFrom->zName, pFKey->zTo);
106253  }
106254  sqlite3DbFree(pParse->db, aiCol);
106255  return 1;
106256  }
106257 
106258  *ppIdx = pIdx;
106259  return 0;
106260 }
106261 
106262 /*
106263 ** This function is called when a row is inserted into or deleted from the
106264 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
106265 ** on the child table of pFKey, this function is invoked twice for each row
106266 ** affected - once to "delete" the old row, and then again to "insert" the
106267 ** new row.
106268 **
106269 ** Each time it is called, this function generates VDBE code to locate the
106270 ** row in the parent table that corresponds to the row being inserted into
106271 ** or deleted from the child table. If the parent row can be found, no
106272 ** special action is taken. Otherwise, if the parent row can *not* be
106273 ** found in the parent table:
106274 **
106275 ** Operation | FK type | Action taken
106276 ** --------------------------------------------------------------------------
106277 ** INSERT immediate Increment the "immediate constraint counter".
106278 **
106279 ** DELETE immediate Decrement the "immediate constraint counter".
106280 **
106281 ** INSERT deferred Increment the "deferred constraint counter".
106282 **
106283 ** DELETE deferred Decrement the "deferred constraint counter".
106284 **
106285 ** These operations are identified in the comment at the top of this file
106286 ** (fkey.c) as "I.1" and "D.1".
106287 */
106288 static void fkLookupParent(
106289  Parse *pParse, /* Parse context */
106290  int iDb, /* Index of database housing pTab */
106291  Table *pTab, /* Parent table of FK pFKey */
106292  Index *pIdx, /* Unique index on parent key columns in pTab */
106293  FKey *pFKey, /* Foreign key constraint */
106294  int *aiCol, /* Map from parent key columns to child table columns */
106295  int regData, /* Address of array containing child table row */
106296  int nIncr, /* Increment constraint counter by this */
106297  int isIgnore /* If true, pretend pTab contains all NULL values */
106298 ){
106299  int i; /* Iterator variable */
106300  Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
106301  int iCur = pParse->nTab - 1; /* Cursor number to use */
106302  int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
106303 
106304  /* If nIncr is less than zero, then check at runtime if there are any
106305  ** outstanding constraints to resolve. If there are not, there is no need
106306  ** to check if deleting this row resolves any outstanding violations.
106307  **
106308  ** Check if any of the key columns in the child table row are NULL. If
106309  ** any are, then the constraint is considered satisfied. No need to
106310  ** search for a matching row in the parent table. */
106311  if( nIncr<0 ){
106312  sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
106313  VdbeCoverage(v);
106314  }
106315  for(i=0; i<pFKey->nCol; i++){
106316  int iReg = aiCol[i] + regData + 1;
106317  sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
106318  }
106319 
106320  if( isIgnore==0 ){
106321  if( pIdx==0 ){
106322  /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
106323  ** column of the parent table (table pTab). */
106324  int iMustBeInt; /* Address of MustBeInt instruction */
106325  int regTemp = sqlite3GetTempReg(pParse);
106326 
106327  /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
106328  ** apply the affinity of the parent key). If this fails, then there
106329  ** is no matching parent key. Before using MustBeInt, make a copy of
106330  ** the value. Otherwise, the value inserted into the child key column
106331  ** will have INTEGER affinity applied to it, which may not be correct. */
106332  sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
106333  iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
106334  VdbeCoverage(v);
106335 
106336  /* If the parent table is the same as the child table, and we are about
106337  ** to increment the constraint-counter (i.e. this is an INSERT operation),
106338  ** then check if the row being inserted matches itself. If so, do not
106339  ** increment the constraint-counter. */
106340  if( pTab==pFKey->pFrom && nIncr==1 ){
106341  sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
106342  sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
106343  }
106344 
106345  sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
106346  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
106347  sqlite3VdbeGoto(v, iOk);
106348  sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
106349  sqlite3VdbeJumpHere(v, iMustBeInt);
106350  sqlite3ReleaseTempReg(pParse, regTemp);
106351  }else{
106352  int nCol = pFKey->nCol;
106353  int regTemp = sqlite3GetTempRange(pParse, nCol);
106354  int regRec = sqlite3GetTempReg(pParse);
106355 
106356  sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
106357  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
106358  for(i=0; i<nCol; i++){
106359  sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
106360  }
106361 
106362  /* If the parent table is the same as the child table, and we are about
106363  ** to increment the constraint-counter (i.e. this is an INSERT operation),
106364  ** then check if the row being inserted matches itself. If so, do not
106365  ** increment the constraint-counter.
106366  **
106367  ** If any of the parent-key values are NULL, then the row cannot match
106368  ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
106369  ** of the parent-key values are NULL (at this point it is known that
106370  ** none of the child key values are).
106371  */
106372  if( pTab==pFKey->pFrom && nIncr==1 ){
106373  int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
106374  for(i=0; i<nCol; i++){
106375  int iChild = aiCol[i]+1+regData;
106376  int iParent = pIdx->aiColumn[i]+1+regData;
106377  assert( pIdx->aiColumn[i]>=0 );
106378  assert( aiCol[i]!=pTab->iPKey );
106379  if( pIdx->aiColumn[i]==pTab->iPKey ){
106380  /* The parent key is a composite key that includes the IPK column */
106381  iParent = regData;
106382  }
106383  sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
106384  sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
106385  }
106386  sqlite3VdbeGoto(v, iOk);
106387  }
106388 
106389  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
106390  sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
106391  sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
106392 
106393  sqlite3ReleaseTempReg(pParse, regRec);
106394  sqlite3ReleaseTempRange(pParse, regTemp, nCol);
106395  }
106396  }
106397 
106398  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
106399  && !pParse->pToplevel
106400  && !pParse->isMultiWrite
106401  ){
106402  /* Special case: If this is an INSERT statement that will insert exactly
106403  ** one row into the table, raise a constraint immediately instead of
106404  ** incrementing a counter. This is necessary as the VM code is being
106405  ** generated for will not open a statement transaction. */
106406  assert( nIncr==1 );
106407  sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
106408  OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
106409  }else{
106410  if( nIncr>0 && pFKey->isDeferred==0 ){
106411  sqlite3MayAbort(pParse);
106412  }
106413  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
106414  }
106415 
106416  sqlite3VdbeResolveLabel(v, iOk);
106417  sqlite3VdbeAddOp1(v, OP_Close, iCur);
106418 }
106419 
106420 
106421 /*
106422 ** Return an Expr object that refers to a memory register corresponding
106423 ** to column iCol of table pTab.
106424 **
106425 ** regBase is the first of an array of register that contains the data
106426 ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
106427 ** column. regBase+2 holds the second column, and so forth.
106428 */
106429 static Expr *exprTableRegister(
106430  Parse *pParse, /* Parsing and code generating context */
106431  Table *pTab, /* The table whose content is at r[regBase]... */
106432  int regBase, /* Contents of table pTab */
106433  i16 iCol /* Which column of pTab is desired */
106434 ){
106435  Expr *pExpr;
106436  Column *pCol;
106437  const char *zColl;
106438  sqlite3 *db = pParse->db;
106439 
106440  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
106441  if( pExpr ){
106442  if( iCol>=0 && iCol!=pTab->iPKey ){
106443  pCol = &pTab->aCol[iCol];
106444  pExpr->iTable = regBase + iCol + 1;
106445  pExpr->affinity = pCol->affinity;
106446  zColl = pCol->zColl;
106447  if( zColl==0 ) zColl = db->pDfltColl->zName;
106448  pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
106449  }else{
106450  pExpr->iTable = regBase;
106451  pExpr->affinity = SQLITE_AFF_INTEGER;
106452  }
106453  }
106454  return pExpr;
106455 }
106456 
106457 /*
106458 ** Return an Expr object that refers to column iCol of table pTab which
106459 ** has cursor iCur.
106460 */
106461 static Expr *exprTableColumn(
106462  sqlite3 *db, /* The database connection */
106463  Table *pTab, /* The table whose column is desired */
106464  int iCursor, /* The open cursor on the table */
106465  i16 iCol /* The column that is wanted */
106466 ){
106467  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
106468  if( pExpr ){
106469  pExpr->pTab = pTab;
106470  pExpr->iTable = iCursor;
106471  pExpr->iColumn = iCol;
106472  }
106473  return pExpr;
106474 }
106475 
106476 /*
106477 ** This function is called to generate code executed when a row is deleted
106478 ** from the parent table of foreign key constraint pFKey and, if pFKey is
106479 ** deferred, when a row is inserted into the same table. When generating
106480 ** code for an SQL UPDATE operation, this function may be called twice -
106481 ** once to "delete" the old row and once to "insert" the new row.
106482 **
106483 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
106484 ** the number of FK violations in the db) or +1 when deleting one (as this
106485 ** may increase the number of FK constraint problems).
106486 **
106487 ** The code generated by this function scans through the rows in the child
106488 ** table that correspond to the parent table row being deleted or inserted.
106489 ** For each child row found, one of the following actions is taken:
106490 **
106491 ** Operation | FK type | Action taken
106492 ** --------------------------------------------------------------------------
106493 ** DELETE immediate Increment the "immediate constraint counter".
106494 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
106495 ** throw a "FOREIGN KEY constraint failed" exception.
106496 **
106497 ** INSERT immediate Decrement the "immediate constraint counter".
106498 **
106499 ** DELETE deferred Increment the "deferred constraint counter".
106500 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
106501 ** throw a "FOREIGN KEY constraint failed" exception.
106502 **
106503 ** INSERT deferred Decrement the "deferred constraint counter".
106504 **
106505 ** These operations are identified in the comment at the top of this file
106506 ** (fkey.c) as "I.2" and "D.2".
106507 */
106508 static void fkScanChildren(
106509  Parse *pParse, /* Parse context */
106510  SrcList *pSrc, /* The child table to be scanned */
106511  Table *pTab, /* The parent table */
106512  Index *pIdx, /* Index on parent covering the foreign key */
106513  FKey *pFKey, /* The foreign key linking pSrc to pTab */
106514  int *aiCol, /* Map from pIdx cols to child table cols */
106515  int regData, /* Parent row data starts here */
106516  int nIncr /* Amount to increment deferred counter by */
106517 ){
106518  sqlite3 *db = pParse->db; /* Database handle */
106519  int i; /* Iterator variable */
106520  Expr *pWhere = 0; /* WHERE clause to scan with */
106521  NameContext sNameContext; /* Context used to resolve WHERE clause */
106522  WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
106523  int iFkIfZero = 0; /* Address of OP_FkIfZero */
106524  Vdbe *v = sqlite3GetVdbe(pParse);
106525 
106526  assert( pIdx==0 || pIdx->pTable==pTab );
106527  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
106528  assert( pIdx!=0 || pFKey->nCol==1 );
106529  assert( pIdx!=0 || HasRowid(pTab) );
106530 
106531  if( nIncr<0 ){
106532  iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
106533  VdbeCoverage(v);
106534  }
106535 
106536  /* Create an Expr object representing an SQL expression like:
106537  **
106538  ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
106539  **
106540  ** The collation sequence used for the comparison should be that of
106541  ** the parent key columns. The affinity of the parent key column should
106542  ** be applied to each child key value before the comparison takes place.
106543  */
106544  for(i=0; i<pFKey->nCol; i++){
106545  Expr *pLeft; /* Value from parent table row */
106546  Expr *pRight; /* Column ref to child table */
106547  Expr *pEq; /* Expression (pLeft = pRight) */
106548  i16 iCol; /* Index of column in child table */
106549  const char *zCol; /* Name of column in child table */
106550 
106551  iCol = pIdx ? pIdx->aiColumn[i] : -1;
106552  pLeft = exprTableRegister(pParse, pTab, regData, iCol);
106553  iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
106554  assert( iCol>=0 );
106555  zCol = pFKey->pFrom->aCol[iCol].zName;
106556  pRight = sqlite3Expr(db, TK_ID, zCol);
106557  pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
106558  pWhere = sqlite3ExprAnd(db, pWhere, pEq);
106559  }
106560 
106561  /* If the child table is the same as the parent table, then add terms
106562  ** to the WHERE clause that prevent this entry from being scanned.
106563  ** The added WHERE clause terms are like this:
106564  **
106565  ** $current_rowid!=rowid
106566  ** NOT( $current_a==a AND $current_b==b AND ... )
106567  **
106568  ** The first form is used for rowid tables. The second form is used
106569  ** for WITHOUT ROWID tables. In the second form, the primary key is
106570  ** (a,b,...)
106571  */
106572  if( pTab==pFKey->pFrom && nIncr>0 ){
106573  Expr *pNe; /* Expression (pLeft != pRight) */
106574  Expr *pLeft; /* Value from parent table row */
106575  Expr *pRight; /* Column ref to child table */
106576  if( HasRowid(pTab) ){
106577  pLeft = exprTableRegister(pParse, pTab, regData, -1);
106578  pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
106579  pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
106580  }else{
106581  Expr *pEq, *pAll = 0;
106582  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
106583  assert( pIdx!=0 );
106584  for(i=0; i<pPk->nKeyCol; i++){
106585  i16 iCol = pIdx->aiColumn[i];
106586  assert( iCol>=0 );
106587  pLeft = exprTableRegister(pParse, pTab, regData, iCol);
106588  pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
106589  pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
106590  pAll = sqlite3ExprAnd(db, pAll, pEq);
106591  }
106592  pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
106593  }
106594  pWhere = sqlite3ExprAnd(db, pWhere, pNe);
106595  }
106596 
106597  /* Resolve the references in the WHERE clause. */
106598  memset(&sNameContext, 0, sizeof(NameContext));
106599  sNameContext.pSrcList = pSrc;
106600  sNameContext.pParse = pParse;
106601  sqlite3ResolveExprNames(&sNameContext, pWhere);
106602 
106603  /* Create VDBE to loop through the entries in pSrc that match the WHERE
106604  ** clause. For each row found, increment either the deferred or immediate
106605  ** foreign key constraint counter. */
106606  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
106607  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
106608  if( pWInfo ){
106609  sqlite3WhereEnd(pWInfo);
106610  }
106611 
106612  /* Clean up the WHERE clause constructed above. */
106613  sqlite3ExprDelete(db, pWhere);
106614  if( iFkIfZero ){
106615  sqlite3VdbeJumpHere(v, iFkIfZero);
106616  }
106617 }
106618 
106619 /*
106620 ** This function returns a linked list of FKey objects (connected by
106621 ** FKey.pNextTo) holding all children of table pTab. For example,
106622 ** given the following schema:
106623 **
106624 ** CREATE TABLE t1(a PRIMARY KEY);
106625 ** CREATE TABLE t2(b REFERENCES t1(a);
106626 **
106627 ** Calling this function with table "t1" as an argument returns a pointer
106628 ** to the FKey structure representing the foreign key constraint on table
106629 ** "t2". Calling this function with "t2" as the argument would return a
106630 ** NULL pointer (as there are no FK constraints for which t2 is the parent
106631 ** table).
106632 */
106633 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
106634  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
106635 }
106636 
106637 /*
106638 ** The second argument is a Trigger structure allocated by the
106639 ** fkActionTrigger() routine. This function deletes the Trigger structure
106640 ** and all of its sub-components.
106641 **
106642 ** The Trigger structure or any of its sub-components may be allocated from
106643 ** the lookaside buffer belonging to database handle dbMem.
106644 */
106645 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
106646  if( p ){
106647  TriggerStep *pStep = p->step_list;
106648  sqlite3ExprDelete(dbMem, pStep->pWhere);
106649  sqlite3ExprListDelete(dbMem, pStep->pExprList);
106650  sqlite3SelectDelete(dbMem, pStep->pSelect);
106651  sqlite3ExprDelete(dbMem, p->pWhen);
106652  sqlite3DbFree(dbMem, p);
106653  }
106654 }
106655 
106656 /*
106657 ** This function is called to generate code that runs when table pTab is
106658 ** being dropped from the database. The SrcList passed as the second argument
106659 ** to this function contains a single entry guaranteed to resolve to
106660 ** table pTab.
106661 **
106662 ** Normally, no code is required. However, if either
106663 **
106664 ** (a) The table is the parent table of a FK constraint, or
106665 ** (b) The table is the child table of a deferred FK constraint and it is
106666 ** determined at runtime that there are outstanding deferred FK
106667 ** constraint violations in the database,
106668 **
106669 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
106670 ** the table from the database. Triggers are disabled while running this
106671 ** DELETE, but foreign key actions are not.
106672 */
106673 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
106674  sqlite3 *db = pParse->db;
106675  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
106676  int iSkip = 0;
106677  Vdbe *v = sqlite3GetVdbe(pParse);
106678 
106679  assert( v ); /* VDBE has already been allocated */
106680  if( sqlite3FkReferences(pTab)==0 ){
106681  /* Search for a deferred foreign key constraint for which this table
106682  ** is the child table. If one cannot be found, return without
106683  ** generating any VDBE code. If one can be found, then jump over
106684  ** the entire DELETE if there are no outstanding deferred constraints
106685  ** when this statement is run. */
106686  FKey *p;
106687  for(p=pTab->pFKey; p; p=p->pNextFrom){
106688  if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
106689  }
106690  if( !p ) return;
106691  iSkip = sqlite3VdbeMakeLabel(v);
106692  sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
106693  }
106694 
106695  pParse->disableTriggers = 1;
106696  sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
106697  pParse->disableTriggers = 0;
106698 
106699  /* If the DELETE has generated immediate foreign key constraint
106700  ** violations, halt the VDBE and return an error at this point, before
106701  ** any modifications to the schema are made. This is because statement
106702  ** transactions are not able to rollback schema changes.
106703  **
106704  ** If the SQLITE_DeferFKs flag is set, then this is not required, as
106705  ** the statement transaction will not be rolled back even if FK
106706  ** constraints are violated.
106707  */
106708  if( (db->flags & SQLITE_DeferFKs)==0 ){
106709  sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
106710  VdbeCoverage(v);
106711  sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
106712  OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
106713  }
106714 
106715  if( iSkip ){
106716  sqlite3VdbeResolveLabel(v, iSkip);
106717  }
106718  }
106719 }
106720 
106721 
106722 /*
106723 ** The second argument points to an FKey object representing a foreign key
106724 ** for which pTab is the child table. An UPDATE statement against pTab
106725 ** is currently being processed. For each column of the table that is
106726 ** actually updated, the corresponding element in the aChange[] array
106727 ** is zero or greater (if a column is unmodified the corresponding element
106728 ** is set to -1). If the rowid column is modified by the UPDATE statement
106729 ** the bChngRowid argument is non-zero.
106730 **
106731 ** This function returns true if any of the columns that are part of the
106732 ** child key for FK constraint *p are modified.
106733 */
106734 static int fkChildIsModified(
106735  Table *pTab, /* Table being updated */
106736  FKey *p, /* Foreign key for which pTab is the child */
106737  int *aChange, /* Array indicating modified columns */
106738  int bChngRowid /* True if rowid is modified by this update */
106739 ){
106740  int i;
106741  for(i=0; i<p->nCol; i++){
106742  int iChildKey = p->aCol[i].iFrom;
106743  if( aChange[iChildKey]>=0 ) return 1;
106744  if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
106745  }
106746  return 0;
106747 }
106748 
106749 /*
106750 ** The second argument points to an FKey object representing a foreign key
106751 ** for which pTab is the parent table. An UPDATE statement against pTab
106752 ** is currently being processed. For each column of the table that is
106753 ** actually updated, the corresponding element in the aChange[] array
106754 ** is zero or greater (if a column is unmodified the corresponding element
106755 ** is set to -1). If the rowid column is modified by the UPDATE statement
106756 ** the bChngRowid argument is non-zero.
106757 **
106758 ** This function returns true if any of the columns that are part of the
106759 ** parent key for FK constraint *p are modified.
106760 */
106761 static int fkParentIsModified(
106762  Table *pTab,
106763  FKey *p,
106764  int *aChange,
106765  int bChngRowid
106766 ){
106767  int i;
106768  for(i=0; i<p->nCol; i++){
106769  char *zKey = p->aCol[i].zCol;
106770  int iKey;
106771  for(iKey=0; iKey<pTab->nCol; iKey++){
106772  if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
106773  Column *pCol = &pTab->aCol[iKey];
106774  if( zKey ){
106775  if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
106776  }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
106777  return 1;
106778  }
106779  }
106780  }
106781  }
106782  return 0;
106783 }
106784 
106785 /*
106786 ** Return true if the parser passed as the first argument is being
106787 ** used to code a trigger that is really a "SET NULL" action belonging
106788 ** to trigger pFKey.
106789 */
106790 static int isSetNullAction(Parse *pParse, FKey *pFKey){
106791  Parse *pTop = sqlite3ParseToplevel(pParse);
106792  if( pTop->pTriggerPrg ){
106793  Trigger *p = pTop->pTriggerPrg->pTrigger;
106794  if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
106795  || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
106796  ){
106797  return 1;
106798  }
106799  }
106800  return 0;
106801 }
106802 
106803 /*
106804 ** This function is called when inserting, deleting or updating a row of
106805 ** table pTab to generate VDBE code to perform foreign key constraint
106806 ** processing for the operation.
106807 **
106808 ** For a DELETE operation, parameter regOld is passed the index of the
106809 ** first register in an array of (pTab->nCol+1) registers containing the
106810 ** rowid of the row being deleted, followed by each of the column values
106811 ** of the row being deleted, from left to right. Parameter regNew is passed
106812 ** zero in this case.
106813 **
106814 ** For an INSERT operation, regOld is passed zero and regNew is passed the
106815 ** first register of an array of (pTab->nCol+1) registers containing the new
106816 ** row data.
106817 **
106818 ** For an UPDATE operation, this function is called twice. Once before
106819 ** the original record is deleted from the table using the calling convention
106820 ** described for DELETE. Then again after the original record is deleted
106821 ** but before the new record is inserted using the INSERT convention.
106822 */
106823 SQLITE_PRIVATE void sqlite3FkCheck(
106824  Parse *pParse, /* Parse context */
106825  Table *pTab, /* Row is being deleted from this table */
106826  int regOld, /* Previous row data is stored here */
106827  int regNew, /* New row data is stored here */
106828  int *aChange, /* Array indicating UPDATEd columns (or 0) */
106829  int bChngRowid /* True if rowid is UPDATEd */
106830 ){
106831  sqlite3 *db = pParse->db; /* Database handle */
106832  FKey *pFKey; /* Used to iterate through FKs */
106833  int iDb; /* Index of database containing pTab */
106834  const char *zDb; /* Name of database containing pTab */
106835  int isIgnoreErrors = pParse->disableTriggers;
106836 
106837  /* Exactly one of regOld and regNew should be non-zero. */
106838  assert( (regOld==0)!=(regNew==0) );
106839 
106840  /* If foreign-keys are disabled, this function is a no-op. */
106841  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
106842 
106843  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
106844  zDb = db->aDb[iDb].zDbSName;
106845 
106846  /* Loop through all the foreign key constraints for which pTab is the
106847  ** child table (the table that the foreign key definition is part of). */
106848  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
106849  Table *pTo; /* Parent table of foreign key pFKey */
106850  Index *pIdx = 0; /* Index on key columns in pTo */
106851  int *aiFree = 0;
106852  int *aiCol;
106853  int iCol;
106854  int i;
106855  int bIgnore = 0;
106856 
106857  if( aChange
106858  && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
106859  && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
106860  ){
106861  continue;
106862  }
106863 
106864  /* Find the parent table of this foreign key. Also find a unique index
106865  ** on the parent key columns in the parent table. If either of these
106866  ** schema items cannot be located, set an error in pParse and return
106867  ** early. */
106868  if( pParse->disableTriggers ){
106869  pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
106870  }else{
106871  pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
106872  }
106873  if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
106874  assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
106875  if( !isIgnoreErrors || db->mallocFailed ) return;
106876  if( pTo==0 ){
106877  /* If isIgnoreErrors is true, then a table is being dropped. In this
106878  ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
106879  ** before actually dropping it in order to check FK constraints.
106880  ** If the parent table of an FK constraint on the current table is
106881  ** missing, behave as if it is empty. i.e. decrement the relevant
106882  ** FK counter for each row of the current table with non-NULL keys.
106883  */
106884  Vdbe *v = sqlite3GetVdbe(pParse);
106885  int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
106886  for(i=0; i<pFKey->nCol; i++){
106887  int iReg = pFKey->aCol[i].iFrom + regOld + 1;
106888  sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
106889  }
106890  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
106891  }
106892  continue;
106893  }
106894  assert( pFKey->nCol==1 || (aiFree && pIdx) );
106895 
106896  if( aiFree ){
106897  aiCol = aiFree;
106898  }else{
106899  iCol = pFKey->aCol[0].iFrom;
106900  aiCol = &iCol;
106901  }
106902  for(i=0; i<pFKey->nCol; i++){
106903  if( aiCol[i]==pTab->iPKey ){
106904  aiCol[i] = -1;
106905  }
106906  assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
106907 #ifndef SQLITE_OMIT_AUTHORIZATION
106908  /* Request permission to read the parent key columns. If the
106909  ** authorization callback returns SQLITE_IGNORE, behave as if any
106910  ** values read from the parent table are NULL. */
106911  if( db->xAuth ){
106912  int rcauth;
106913  char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
106914  rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
106915  bIgnore = (rcauth==SQLITE_IGNORE);
106916  }
106917 #endif
106918  }
106919 
106920  /* Take a shared-cache advisory read-lock on the parent table. Allocate
106921  ** a cursor to use to search the unique index on the parent key columns
106922  ** in the parent table. */
106923  sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
106924  pParse->nTab++;
106925 
106926  if( regOld!=0 ){
106927  /* A row is being removed from the child table. Search for the parent.
106928  ** If the parent does not exist, removing the child row resolves an
106929  ** outstanding foreign key constraint violation. */
106930  fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
106931  }
106932  if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
106933  /* A row is being added to the child table. If a parent row cannot
106934  ** be found, adding the child row has violated the FK constraint.
106935  **
106936  ** If this operation is being performed as part of a trigger program
106937  ** that is actually a "SET NULL" action belonging to this very
106938  ** foreign key, then omit this scan altogether. As all child key
106939  ** values are guaranteed to be NULL, it is not possible for adding
106940  ** this row to cause an FK violation. */
106941  fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
106942  }
106943 
106944  sqlite3DbFree(db, aiFree);
106945  }
106946 
106947  /* Loop through all the foreign key constraints that refer to this table.
106948  ** (the "child" constraints) */
106949  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
106950  Index *pIdx = 0; /* Foreign key index for pFKey */
106951  SrcList *pSrc;
106952  int *aiCol = 0;
106953 
106954  if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
106955  continue;
106956  }
106957 
106958  if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
106959  && !pParse->pToplevel && !pParse->isMultiWrite
106960  ){
106961  assert( regOld==0 && regNew!=0 );
106962  /* Inserting a single row into a parent table cannot cause (or fix)
106963  ** an immediate foreign key violation. So do nothing in this case. */
106964  continue;
106965  }
106966 
106967  if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
106968  if( !isIgnoreErrors || db->mallocFailed ) return;
106969  continue;
106970  }
106971  assert( aiCol || pFKey->nCol==1 );
106972 
106973  /* Create a SrcList structure containing the child table. We need the
106974  ** child table as a SrcList for sqlite3WhereBegin() */
106975  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
106976  if( pSrc ){
106977  struct SrcList_item *pItem = pSrc->a;
106978  pItem->pTab = pFKey->pFrom;
106979  pItem->zName = pFKey->pFrom->zName;
106980  pItem->pTab->nRef++;
106981  pItem->iCursor = pParse->nTab++;
106982 
106983  if( regNew!=0 ){
106984  fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
106985  }
106986  if( regOld!=0 ){
106987  int eAction = pFKey->aAction[aChange!=0];
106988  fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
106989  /* If this is a deferred FK constraint, or a CASCADE or SET NULL
106990  ** action applies, then any foreign key violations caused by
106991  ** removing the parent key will be rectified by the action trigger.
106992  ** So do not set the "may-abort" flag in this case.
106993  **
106994  ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
106995  ** may-abort flag will eventually be set on this statement anyway
106996  ** (when this function is called as part of processing the UPDATE
106997  ** within the action trigger).
106998  **
106999  ** Note 2: At first glance it may seem like SQLite could simply omit
107000  ** all OP_FkCounter related scans when either CASCADE or SET NULL
107001  ** applies. The trouble starts if the CASCADE or SET NULL action
107002  ** trigger causes other triggers or action rules attached to the
107003  ** child table to fire. In these cases the fk constraint counters
107004  ** might be set incorrectly if any OP_FkCounter related scans are
107005  ** omitted. */
107006  if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
107007  sqlite3MayAbort(pParse);
107008  }
107009  }
107010  pItem->zName = 0;
107011  sqlite3SrcListDelete(db, pSrc);
107012  }
107013  sqlite3DbFree(db, aiCol);
107014  }
107015 }
107016 
107017 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
107018 
107019 /*
107020 ** This function is called before generating code to update or delete a
107021 ** row contained in table pTab.
107022 */
107023 SQLITE_PRIVATE u32 sqlite3FkOldmask(
107024  Parse *pParse, /* Parse context */
107025  Table *pTab /* Table being modified */
107026 ){
107027  u32 mask = 0;
107028  if( pParse->db->flags&SQLITE_ForeignKeys ){
107029  FKey *p;
107030  int i;
107031  for(p=pTab->pFKey; p; p=p->pNextFrom){
107032  for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
107033  }
107034  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
107035  Index *pIdx = 0;
107036  sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
107037  if( pIdx ){
107038  for(i=0; i<pIdx->nKeyCol; i++){
107039  assert( pIdx->aiColumn[i]>=0 );
107040  mask |= COLUMN_MASK(pIdx->aiColumn[i]);
107041  }
107042  }
107043  }
107044  }
107045  return mask;
107046 }
107047 
107048 
107049 /*
107050 ** This function is called before generating code to update or delete a
107051 ** row contained in table pTab. If the operation is a DELETE, then
107052 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
107053 ** to an array of size N, where N is the number of columns in table pTab.
107054 ** If the i'th column is not modified by the UPDATE, then the corresponding
107055 ** entry in the aChange[] array is set to -1. If the column is modified,
107056 ** the value is 0 or greater. Parameter chngRowid is set to true if the
107057 ** UPDATE statement modifies the rowid fields of the table.
107058 **
107059 ** If any foreign key processing will be required, this function returns
107060 ** true. If there is no foreign key related processing, this function
107061 ** returns false.
107062 */
107063 SQLITE_PRIVATE int sqlite3FkRequired(
107064  Parse *pParse, /* Parse context */
107065  Table *pTab, /* Table being modified */
107066  int *aChange, /* Non-NULL for UPDATE operations */
107067  int chngRowid /* True for UPDATE that affects rowid */
107068 ){
107069  if( pParse->db->flags&SQLITE_ForeignKeys ){
107070  if( !aChange ){
107071  /* A DELETE operation. Foreign key processing is required if the
107072  ** table in question is either the child or parent table for any
107073  ** foreign key constraint. */
107074  return (sqlite3FkReferences(pTab) || pTab->pFKey);
107075  }else{
107076  /* This is an UPDATE. Foreign key processing is only required if the
107077  ** operation modifies one or more child or parent key columns. */
107078  FKey *p;
107079 
107080  /* Check if any child key columns are being modified. */
107081  for(p=pTab->pFKey; p; p=p->pNextFrom){
107082  if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
107083  }
107084 
107085  /* Check if any parent key columns are being modified. */
107086  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
107087  if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
107088  }
107089  }
107090  }
107091  return 0;
107092 }
107093 
107094 /*
107095 ** This function is called when an UPDATE or DELETE operation is being
107096 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
107097 ** If the current operation is an UPDATE, then the pChanges parameter is
107098 ** passed a pointer to the list of columns being modified. If it is a
107099 ** DELETE, pChanges is passed a NULL pointer.
107100 **
107101 ** It returns a pointer to a Trigger structure containing a trigger
107102 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
107103 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
107104 ** returned (these actions require no special handling by the triggers
107105 ** sub-system, code for them is created by fkScanChildren()).
107106 **
107107 ** For example, if pFKey is the foreign key and pTab is table "p" in
107108 ** the following schema:
107109 **
107110 ** CREATE TABLE p(pk PRIMARY KEY);
107111 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
107112 **
107113 ** then the returned trigger structure is equivalent to:
107114 **
107115 ** CREATE TRIGGER ... DELETE ON p BEGIN
107116 ** DELETE FROM c WHERE ck = old.pk;
107117 ** END;
107118 **
107119 ** The returned pointer is cached as part of the foreign key object. It
107120 ** is eventually freed along with the rest of the foreign key object by
107121 ** sqlite3FkDelete().
107122 */
107123 static Trigger *fkActionTrigger(
107124  Parse *pParse, /* Parse context */
107125  Table *pTab, /* Table being updated or deleted from */
107126  FKey *pFKey, /* Foreign key to get action for */
107127  ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
107128 ){
107129  sqlite3 *db = pParse->db; /* Database handle */
107130  int action; /* One of OE_None, OE_Cascade etc. */
107131  Trigger *pTrigger; /* Trigger definition to return */
107132  int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
107133 
107134  action = pFKey->aAction[iAction];
107135  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
107136  return 0;
107137  }
107138  pTrigger = pFKey->apTrigger[iAction];
107139 
107140  if( action!=OE_None && !pTrigger ){
107141  char const *zFrom; /* Name of child table */
107142  int nFrom; /* Length in bytes of zFrom */
107143  Index *pIdx = 0; /* Parent key index for this FK */
107144  int *aiCol = 0; /* child table cols -> parent key cols */
107145  TriggerStep *pStep = 0; /* First (only) step of trigger program */
107146  Expr *pWhere = 0; /* WHERE clause of trigger step */
107147  ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
107148  Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
107149  int i; /* Iterator variable */
107150  Expr *pWhen = 0; /* WHEN clause for the trigger */
107151 
107152  if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
107153  assert( aiCol || pFKey->nCol==1 );
107154 
107155  for(i=0; i<pFKey->nCol; i++){
107156  Token tOld = { "old", 3 }; /* Literal "old" token */
107157  Token tNew = { "new", 3 }; /* Literal "new" token */
107158  Token tFromCol; /* Name of column in child table */
107159  Token tToCol; /* Name of column in parent table */
107160  int iFromCol; /* Idx of column in child table */
107161  Expr *pEq; /* tFromCol = OLD.tToCol */
107162 
107163  iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
107164  assert( iFromCol>=0 );
107165  assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
107166  assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
107167  sqlite3TokenInit(&tToCol,
107168  pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
107169  sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
107170 
107171  /* Create the expression "OLD.zToCol = zFromCol". It is important
107172  ** that the "OLD.zToCol" term is on the LHS of the = operator, so
107173  ** that the affinity and collation sequence associated with the
107174  ** parent table are used for the comparison. */
107175  pEq = sqlite3PExpr(pParse, TK_EQ,
107176  sqlite3PExpr(pParse, TK_DOT,
107177  sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
107178  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
107179  , 0),
107180  sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
107181  , 0);
107182  pWhere = sqlite3ExprAnd(db, pWhere, pEq);
107183 
107184  /* For ON UPDATE, construct the next term of the WHEN clause.
107185  ** The final WHEN clause will be like this:
107186  **
107187  ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
107188  */
107189  if( pChanges ){
107190  pEq = sqlite3PExpr(pParse, TK_IS,
107191  sqlite3PExpr(pParse, TK_DOT,
107192  sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
107193  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
107194  0),
107195  sqlite3PExpr(pParse, TK_DOT,
107196  sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
107197  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
107198  0),
107199  0);
107200  pWhen = sqlite3ExprAnd(db, pWhen, pEq);
107201  }
107202 
107203  if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
107204  Expr *pNew;
107205  if( action==OE_Cascade ){
107206  pNew = sqlite3PExpr(pParse, TK_DOT,
107207  sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
107208  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
107209  , 0);
107210  }else if( action==OE_SetDflt ){
107211  Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
107212  if( pDflt ){
107213  pNew = sqlite3ExprDup(db, pDflt, 0);
107214  }else{
107215  pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
107216  }
107217  }else{
107218  pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
107219  }
107220  pList = sqlite3ExprListAppend(pParse, pList, pNew);
107221  sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
107222  }
107223  }
107224  sqlite3DbFree(db, aiCol);
107225 
107226  zFrom = pFKey->pFrom->zName;
107227  nFrom = sqlite3Strlen30(zFrom);
107228 
107229  if( action==OE_Restrict ){
107230  Token tFrom;
107231  Expr *pRaise;
107232 
107233  tFrom.z = zFrom;
107234  tFrom.n = nFrom;
107235  pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
107236  if( pRaise ){
107237  pRaise->affinity = OE_Abort;
107238  }
107239  pSelect = sqlite3SelectNew(pParse,
107240  sqlite3ExprListAppend(pParse, 0, pRaise),
107241  sqlite3SrcListAppend(db, 0, &tFrom, 0),
107242  pWhere,
107243  0, 0, 0, 0, 0, 0
107244  );
107245  pWhere = 0;
107246  }
107247 
107248  /* Disable lookaside memory allocation */
107249  db->lookaside.bDisable++;
107250 
107251  pTrigger = (Trigger *)sqlite3DbMallocZero(db,
107252  sizeof(Trigger) + /* struct Trigger */
107253  sizeof(TriggerStep) + /* Single step in trigger program */
107254  nFrom + 1 /* Space for pStep->zTarget */
107255  );
107256  if( pTrigger ){
107257  pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
107258  pStep->zTarget = (char *)&pStep[1];
107259  memcpy((char *)pStep->zTarget, zFrom, nFrom);
107260 
107261  pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
107262  pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
107263  pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
107264  if( pWhen ){
107265  pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
107266  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
107267  }
107268  }
107269 
107270  /* Re-enable the lookaside buffer, if it was disabled earlier. */
107271  db->lookaside.bDisable--;
107272 
107273  sqlite3ExprDelete(db, pWhere);
107274  sqlite3ExprDelete(db, pWhen);
107275  sqlite3ExprListDelete(db, pList);
107276  sqlite3SelectDelete(db, pSelect);
107277  if( db->mallocFailed==1 ){
107278  fkTriggerDelete(db, pTrigger);
107279  return 0;
107280  }
107281  assert( pStep!=0 );
107282 
107283  switch( action ){
107284  case OE_Restrict:
107285  pStep->op = TK_SELECT;
107286  break;
107287  case OE_Cascade:
107288  if( !pChanges ){
107289  pStep->op = TK_DELETE;
107290  break;
107291  }
107292  default:
107293  pStep->op = TK_UPDATE;
107294  }
107295  pStep->pTrig = pTrigger;
107296  pTrigger->pSchema = pTab->pSchema;
107297  pTrigger->pTabSchema = pTab->pSchema;
107298  pFKey->apTrigger[iAction] = pTrigger;
107299  pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
107300  }
107301 
107302  return pTrigger;
107303 }
107304 
107305 /*
107306 ** This function is called when deleting or updating a row to implement
107307 ** any required CASCADE, SET NULL or SET DEFAULT actions.
107308 */
107309 SQLITE_PRIVATE void sqlite3FkActions(
107310  Parse *pParse, /* Parse context */
107311  Table *pTab, /* Table being updated or deleted from */
107312  ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
107313  int regOld, /* Address of array containing old row */
107314  int *aChange, /* Array indicating UPDATEd columns (or 0) */
107315  int bChngRowid /* True if rowid is UPDATEd */
107316 ){
107317  /* If foreign-key support is enabled, iterate through all FKs that
107318  ** refer to table pTab. If there is an action associated with the FK
107319  ** for this operation (either update or delete), invoke the associated
107320  ** trigger sub-program. */
107321  if( pParse->db->flags&SQLITE_ForeignKeys ){
107322  FKey *pFKey; /* Iterator variable */
107323  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
107324  if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
107325  Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
107326  if( pAct ){
107327  sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
107328  }
107329  }
107330  }
107331  }
107332 }
107333 
107334 #endif /* ifndef SQLITE_OMIT_TRIGGER */
107335 
107336 /*
107337 ** Free all memory associated with foreign key definitions attached to
107338 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
107339 ** hash table.
107340 */
107341 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
107342  FKey *pFKey; /* Iterator variable */
107343  FKey *pNext; /* Copy of pFKey->pNextFrom */
107344 
107345  assert( db==0 || IsVirtual(pTab)
107346  || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
107347  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
107348 
107349  /* Remove the FK from the fkeyHash hash table. */
107350  if( !db || db->pnBytesFreed==0 ){
107351  if( pFKey->pPrevTo ){
107352  pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
107353  }else{
107354  void *p = (void *)pFKey->pNextTo;
107355  const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
107356  sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
107357  }
107358  if( pFKey->pNextTo ){
107359  pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
107360  }
107361  }
107362 
107363  /* EV: R-30323-21917 Each foreign key constraint in SQLite is
107364  ** classified as either immediate or deferred.
107365  */
107366  assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
107367 
107368  /* Delete any triggers created to implement actions for this FK. */
107369 #ifndef SQLITE_OMIT_TRIGGER
107370  fkTriggerDelete(db, pFKey->apTrigger[0]);
107371  fkTriggerDelete(db, pFKey->apTrigger[1]);
107372 #endif
107373 
107374  pNext = pFKey->pNextFrom;
107375  sqlite3DbFree(db, pFKey);
107376  }
107377 }
107378 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
107379 
107380 /************** End of fkey.c ************************************************/
107381 /************** Begin file insert.c ******************************************/
107382 /*
107383 ** 2001 September 15
107384 **
107385 ** The author disclaims copyright to this source code. In place of
107386 ** a legal notice, here is a blessing:
107387 **
107388 ** May you do good and not evil.
107389 ** May you find forgiveness for yourself and forgive others.
107390 ** May you share freely, never taking more than you give.
107391 **
107392 *************************************************************************
107393 ** This file contains C code routines that are called by the parser
107394 ** to handle INSERT statements in SQLite.
107395 */
107396 /* #include "sqliteInt.h" */
107397 
107398 /*
107399 ** Generate code that will
107400 **
107401 ** (1) acquire a lock for table pTab then
107402 ** (2) open pTab as cursor iCur.
107403 **
107404 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
107405 ** for that table that is actually opened.
107406 */
107407 SQLITE_PRIVATE void sqlite3OpenTable(
107408  Parse *pParse, /* Generate code into this VDBE */
107409  int iCur, /* The cursor number of the table */
107410  int iDb, /* The database index in sqlite3.aDb[] */
107411  Table *pTab, /* The table to be opened */
107412  int opcode /* OP_OpenRead or OP_OpenWrite */
107413 ){
107414  Vdbe *v;
107415  assert( !IsVirtual(pTab) );
107416  v = sqlite3GetVdbe(pParse);
107417  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
107418  sqlite3TableLock(pParse, iDb, pTab->tnum,
107419  (opcode==OP_OpenWrite)?1:0, pTab->zName);
107420  if( HasRowid(pTab) ){
107421  sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
107422  VdbeComment((v, "%s", pTab->zName));
107423  }else{
107424  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
107425  assert( pPk!=0 );
107426  assert( pPk->tnum==pTab->tnum );
107427  sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
107428  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
107429  VdbeComment((v, "%s", pTab->zName));
107430  }
107431 }
107432 
107433 /*
107434 ** Return a pointer to the column affinity string associated with index
107435 ** pIdx. A column affinity string has one character for each column in
107436 ** the table, according to the affinity of the column:
107437 **
107438 ** Character Column affinity
107439 ** ------------------------------
107440 ** 'A' BLOB
107441 ** 'B' TEXT
107442 ** 'C' NUMERIC
107443 ** 'D' INTEGER
107444 ** 'F' REAL
107445 **
107446 ** An extra 'D' is appended to the end of the string to cover the
107447 ** rowid that appears as the last column in every index.
107448 **
107449 ** Memory for the buffer containing the column index affinity string
107450 ** is managed along with the rest of the Index structure. It will be
107451 ** released when sqlite3DeleteIndex() is called.
107452 */
107453 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
107454  if( !pIdx->zColAff ){
107455  /* The first time a column affinity string for a particular index is
107456  ** required, it is allocated and populated here. It is then stored as
107457  ** a member of the Index structure for subsequent use.
107458  **
107459  ** The column affinity string will eventually be deleted by
107460  ** sqliteDeleteIndex() when the Index structure itself is cleaned
107461  ** up.
107462  */
107463  int n;
107464  Table *pTab = pIdx->pTable;
107465  pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
107466  if( !pIdx->zColAff ){
107467  sqlite3OomFault(db);
107468  return 0;
107469  }
107470  for(n=0; n<pIdx->nColumn; n++){
107471  i16 x = pIdx->aiColumn[n];
107472  if( x>=0 ){
107473  pIdx->zColAff[n] = pTab->aCol[x].affinity;
107474  }else if( x==XN_ROWID ){
107475  pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
107476  }else{
107477  char aff;
107478  assert( x==XN_EXPR );
107479  assert( pIdx->aColExpr!=0 );
107480  aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
107481  if( aff==0 ) aff = SQLITE_AFF_BLOB;
107482  pIdx->zColAff[n] = aff;
107483  }
107484  }
107485  pIdx->zColAff[n] = 0;
107486  }
107487 
107488  return pIdx->zColAff;
107489 }
107490 
107491 /*
107492 ** Compute the affinity string for table pTab, if it has not already been
107493 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
107494 **
107495 ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
107496 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
107497 ** for register iReg and following. Or if affinities exists and iReg==0,
107498 ** then just set the P4 operand of the previous opcode (which should be
107499 ** an OP_MakeRecord) to the affinity string.
107500 **
107501 ** A column affinity string has one character per column:
107502 **
107503 ** Character Column affinity
107504 ** ------------------------------
107505 ** 'A' BLOB
107506 ** 'B' TEXT
107507 ** 'C' NUMERIC
107508 ** 'D' INTEGER
107509 ** 'E' REAL
107510 */
107511 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
107512  int i;
107513  char *zColAff = pTab->zColAff;
107514  if( zColAff==0 ){
107515  sqlite3 *db = sqlite3VdbeDb(v);
107516  zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
107517  if( !zColAff ){
107518  sqlite3OomFault(db);
107519  return;
107520  }
107521 
107522  for(i=0; i<pTab->nCol; i++){
107523  zColAff[i] = pTab->aCol[i].affinity;
107524  }
107525  do{
107526  zColAff[i--] = 0;
107527  }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
107528  pTab->zColAff = zColAff;
107529  }
107530  i = sqlite3Strlen30(zColAff);
107531  if( i ){
107532  if( iReg ){
107533  sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
107534  }else{
107535  sqlite3VdbeChangeP4(v, -1, zColAff, i);
107536  }
107537  }
107538 }
107539 
107540 /*
107541 ** Return non-zero if the table pTab in database iDb or any of its indices
107542 ** have been opened at any point in the VDBE program. This is used to see if
107543 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
107544 ** run without using a temporary table for the results of the SELECT.
107545 */
107546 static int readsTable(Parse *p, int iDb, Table *pTab){
107547  Vdbe *v = sqlite3GetVdbe(p);
107548  int i;
107549  int iEnd = sqlite3VdbeCurrentAddr(v);
107550 #ifndef SQLITE_OMIT_VIRTUALTABLE
107551  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
107552 #endif
107553 
107554  for(i=1; i<iEnd; i++){
107555  VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
107556  assert( pOp!=0 );
107557  if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
107558  Index *pIndex;
107559  int tnum = pOp->p2;
107560  if( tnum==pTab->tnum ){
107561  return 1;
107562  }
107563  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
107564  if( tnum==pIndex->tnum ){
107565  return 1;
107566  }
107567  }
107568  }
107569 #ifndef SQLITE_OMIT_VIRTUALTABLE
107570  if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
107571  assert( pOp->p4.pVtab!=0 );
107572  assert( pOp->p4type==P4_VTAB );
107573  return 1;
107574  }
107575 #endif
107576  }
107577  return 0;
107578 }
107579 
107580 #ifndef SQLITE_OMIT_AUTOINCREMENT
107581 /*
107582 ** Locate or create an AutoincInfo structure associated with table pTab
107583 ** which is in database iDb. Return the register number for the register
107584 ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
107585 ** table. (Also return zero when doing a VACUUM since we do not want to
107586 ** update the AUTOINCREMENT counters during a VACUUM.)
107587 **
107588 ** There is at most one AutoincInfo structure per table even if the
107589 ** same table is autoincremented multiple times due to inserts within
107590 ** triggers. A new AutoincInfo structure is created if this is the
107591 ** first use of table pTab. On 2nd and subsequent uses, the original
107592 ** AutoincInfo structure is used.
107593 **
107594 ** Three memory locations are allocated:
107595 **
107596 ** (1) Register to hold the name of the pTab table.
107597 ** (2) Register to hold the maximum ROWID of pTab.
107598 ** (3) Register to hold the rowid in sqlite_sequence of pTab
107599 **
107600 ** The 2nd register is the one that is returned. That is all the
107601 ** insert routine needs to know about.
107602 */
107603 static int autoIncBegin(
107604  Parse *pParse, /* Parsing context */
107605  int iDb, /* Index of the database holding pTab */
107606  Table *pTab /* The table we are writing to */
107607 ){
107608  int memId = 0; /* Register holding maximum rowid */
107609  if( (pTab->tabFlags & TF_Autoincrement)!=0
107610  && (pParse->db->flags & SQLITE_Vacuum)==0
107611  ){
107612  Parse *pToplevel = sqlite3ParseToplevel(pParse);
107613  AutoincInfo *pInfo;
107614 
107615  pInfo = pToplevel->pAinc;
107616  while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
107617  if( pInfo==0 ){
107618  pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
107619  if( pInfo==0 ) return 0;
107620  pInfo->pNext = pToplevel->pAinc;
107621  pToplevel->pAinc = pInfo;
107622  pInfo->pTab = pTab;
107623  pInfo->iDb = iDb;
107624  pToplevel->nMem++; /* Register to hold name of table */
107625  pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
107626  pToplevel->nMem++; /* Rowid in sqlite_sequence */
107627  }
107628  memId = pInfo->regCtr;
107629  }
107630  return memId;
107631 }
107632 
107633 /*
107634 ** This routine generates code that will initialize all of the
107635 ** register used by the autoincrement tracker.
107636 */
107637 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
107638  AutoincInfo *p; /* Information about an AUTOINCREMENT */
107639  sqlite3 *db = pParse->db; /* The database connection */
107640  Db *pDb; /* Database only autoinc table */
107641  int memId; /* Register holding max rowid */
107642  Vdbe *v = pParse->pVdbe; /* VDBE under construction */
107643 
107644  /* This routine is never called during trigger-generation. It is
107645  ** only called from the top-level */
107646  assert( pParse->pTriggerTab==0 );
107647  assert( sqlite3IsToplevel(pParse) );
107648 
107649  assert( v ); /* We failed long ago if this is not so */
107650  for(p = pParse->pAinc; p; p = p->pNext){
107651  static const int iLn = VDBE_OFFSET_LINENO(2);
107652  static const VdbeOpList autoInc[] = {
107653  /* 0 */ {OP_Null, 0, 0, 0},
107654  /* 1 */ {OP_Rewind, 0, 9, 0},
107655  /* 2 */ {OP_Column, 0, 0, 0},
107656  /* 3 */ {OP_Ne, 0, 7, 0},
107657  /* 4 */ {OP_Rowid, 0, 0, 0},
107658  /* 5 */ {OP_Column, 0, 1, 0},
107659  /* 6 */ {OP_Goto, 0, 9, 0},
107660  /* 7 */ {OP_Next, 0, 2, 0},
107661  /* 8 */ {OP_Integer, 0, 0, 0},
107662  /* 9 */ {OP_Close, 0, 0, 0}
107663  };
107664  VdbeOp *aOp;
107665  pDb = &db->aDb[p->iDb];
107666  memId = p->regCtr;
107667  assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
107668  sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
107669  sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
107670  aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
107671  if( aOp==0 ) break;
107672  aOp[0].p2 = memId;
107673  aOp[0].p3 = memId+1;
107674  aOp[2].p3 = memId;
107675  aOp[3].p1 = memId-1;
107676  aOp[3].p3 = memId;
107677  aOp[3].p5 = SQLITE_JUMPIFNULL;
107678  aOp[4].p2 = memId+1;
107679  aOp[5].p3 = memId;
107680  aOp[8].p2 = memId;
107681  }
107682 }
107683 
107684 /*
107685 ** Update the maximum rowid for an autoincrement calculation.
107686 **
107687 ** This routine should be called when the regRowid register holds a
107688 ** new rowid that is about to be inserted. If that new rowid is
107689 ** larger than the maximum rowid in the memId memory cell, then the
107690 ** memory cell is updated.
107691 */
107692 static void autoIncStep(Parse *pParse, int memId, int regRowid){
107693  if( memId>0 ){
107694  sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
107695  }
107696 }
107697 
107698 /*
107699 ** This routine generates the code needed to write autoincrement
107700 ** maximum rowid values back into the sqlite_sequence register.
107701 ** Every statement that might do an INSERT into an autoincrement
107702 ** table (either directly or through triggers) needs to call this
107703 ** routine just before the "exit" code.
107704 */
107705 static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
107706  AutoincInfo *p;
107707  Vdbe *v = pParse->pVdbe;
107708  sqlite3 *db = pParse->db;
107709 
107710  assert( v );
107711  for(p = pParse->pAinc; p; p = p->pNext){
107712  static const int iLn = VDBE_OFFSET_LINENO(2);
107713  static const VdbeOpList autoIncEnd[] = {
107714  /* 0 */ {OP_NotNull, 0, 2, 0},
107715  /* 1 */ {OP_NewRowid, 0, 0, 0},
107716  /* 2 */ {OP_MakeRecord, 0, 2, 0},
107717  /* 3 */ {OP_Insert, 0, 0, 0},
107718  /* 4 */ {OP_Close, 0, 0, 0}
107719  };
107720  VdbeOp *aOp;
107721  Db *pDb = &db->aDb[p->iDb];
107722  int iRec;
107723  int memId = p->regCtr;
107724 
107725  iRec = sqlite3GetTempReg(pParse);
107726  assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
107727  sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
107728  aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
107729  if( aOp==0 ) break;
107730  aOp[0].p1 = memId+1;
107731  aOp[1].p2 = memId+1;
107732  aOp[2].p1 = memId-1;
107733  aOp[2].p3 = iRec;
107734  aOp[3].p2 = iRec;
107735  aOp[3].p3 = memId+1;
107736  aOp[3].p5 = OPFLAG_APPEND;
107737  sqlite3ReleaseTempReg(pParse, iRec);
107738  }
107739 }
107740 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
107741  if( pParse->pAinc ) autoIncrementEnd(pParse);
107742 }
107743 #else
107744 /*
107745 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
107746 ** above are all no-ops
107747 */
107748 # define autoIncBegin(A,B,C) (0)
107749 # define autoIncStep(A,B,C)
107750 #endif /* SQLITE_OMIT_AUTOINCREMENT */
107751 
107752 
107753 /* Forward declaration */
107754 static int xferOptimization(
107755  Parse *pParse, /* Parser context */
107756  Table *pDest, /* The table we are inserting into */
107757  Select *pSelect, /* A SELECT statement to use as the data source */
107758  int onError, /* How to handle constraint errors */
107759  int iDbDest /* The database of pDest */
107760 );
107761 
107762 /*
107763 ** This routine is called to handle SQL of the following forms:
107764 **
107765 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
107766 ** insert into TABLE (IDLIST) select
107767 ** insert into TABLE (IDLIST) default values
107768 **
107769 ** The IDLIST following the table name is always optional. If omitted,
107770 ** then a list of all (non-hidden) columns for the table is substituted.
107771 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
107772 ** is omitted.
107773 **
107774 ** For the pSelect parameter holds the values to be inserted for the
107775 ** first two forms shown above. A VALUES clause is really just short-hand
107776 ** for a SELECT statement that omits the FROM clause and everything else
107777 ** that follows. If the pSelect parameter is NULL, that means that the
107778 ** DEFAULT VALUES form of the INSERT statement is intended.
107779 **
107780 ** The code generated follows one of four templates. For a simple
107781 ** insert with data coming from a single-row VALUES clause, the code executes
107782 ** once straight down through. Pseudo-code follows (we call this
107783 ** the "1st template"):
107784 **
107785 ** open write cursor to <table> and its indices
107786 ** put VALUES clause expressions into registers
107787 ** write the resulting record into <table>
107788 ** cleanup
107789 **
107790 ** The three remaining templates assume the statement is of the form
107791 **
107792 ** INSERT INTO <table> SELECT ...
107793 **
107794 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
107795 ** in other words if the SELECT pulls all columns from a single table
107796 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
107797 ** if <table2> and <table1> are distinct tables but have identical
107798 ** schemas, including all the same indices, then a special optimization
107799 ** is invoked that copies raw records from <table2> over to <table1>.
107800 ** See the xferOptimization() function for the implementation of this
107801 ** template. This is the 2nd template.
107802 **
107803 ** open a write cursor to <table>
107804 ** open read cursor on <table2>
107805 ** transfer all records in <table2> over to <table>
107806 ** close cursors
107807 ** foreach index on <table>
107808 ** open a write cursor on the <table> index
107809 ** open a read cursor on the corresponding <table2> index
107810 ** transfer all records from the read to the write cursors
107811 ** close cursors
107812 ** end foreach
107813 **
107814 ** The 3rd template is for when the second template does not apply
107815 ** and the SELECT clause does not read from <table> at any time.
107816 ** The generated code follows this template:
107817 **
107818 ** X <- A
107819 ** goto B
107820 ** A: setup for the SELECT
107821 ** loop over the rows in the SELECT
107822 ** load values into registers R..R+n
107823 ** yield X
107824 ** end loop
107825 ** cleanup after the SELECT
107826 ** end-coroutine X
107827 ** B: open write cursor to <table> and its indices
107828 ** C: yield X, at EOF goto D
107829 ** insert the select result into <table> from R..R+n
107830 ** goto C
107831 ** D: cleanup
107832 **
107833 ** The 4th template is used if the insert statement takes its
107834 ** values from a SELECT but the data is being inserted into a table
107835 ** that is also read as part of the SELECT. In the third form,
107836 ** we have to use an intermediate table to store the results of
107837 ** the select. The template is like this:
107838 **
107839 ** X <- A
107840 ** goto B
107841 ** A: setup for the SELECT
107842 ** loop over the tables in the SELECT
107843 ** load value into register R..R+n
107844 ** yield X
107845 ** end loop
107846 ** cleanup after the SELECT
107847 ** end co-routine R
107848 ** B: open temp table
107849 ** L: yield X, at EOF goto M
107850 ** insert row from R..R+n into temp table
107851 ** goto L
107852 ** M: open write cursor to <table> and its indices
107853 ** rewind temp table
107854 ** C: loop over rows of intermediate table
107855 ** transfer values form intermediate table into <table>
107856 ** end loop
107857 ** D: cleanup
107858 */
107859 SQLITE_PRIVATE void sqlite3Insert(
107860  Parse *pParse, /* Parser context */
107861  SrcList *pTabList, /* Name of table into which we are inserting */
107862  Select *pSelect, /* A SELECT statement to use as the data source */
107863  IdList *pColumn, /* Column names corresponding to IDLIST. */
107864  int onError /* How to handle constraint errors */
107865 ){
107866  sqlite3 *db; /* The main database structure */
107867  Table *pTab; /* The table to insert into. aka TABLE */
107868  char *zTab; /* Name of the table into which we are inserting */
107869  int i, j, idx; /* Loop counters */
107870  Vdbe *v; /* Generate code into this virtual machine */
107871  Index *pIdx; /* For looping over indices of the table */
107872  int nColumn; /* Number of columns in the data */
107873  int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
107874  int iDataCur = 0; /* VDBE cursor that is the main data repository */
107875  int iIdxCur = 0; /* First index cursor */
107876  int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
107877  int endOfLoop; /* Label for the end of the insertion loop */
107878  int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
107879  int addrInsTop = 0; /* Jump to label "D" */
107880  int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
107881  SelectDest dest; /* Destination for SELECT on rhs of INSERT */
107882  int iDb; /* Index of database holding TABLE */
107883  u8 useTempTable = 0; /* Store SELECT results in intermediate table */
107884  u8 appendFlag = 0; /* True if the insert is likely to be an append */
107885  u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
107886  u8 bIdListInOrder; /* True if IDLIST is in table order */
107887  ExprList *pList = 0; /* List of VALUES() to be inserted */
107888 
107889  /* Register allocations */
107890  int regFromSelect = 0;/* Base register for data coming from SELECT */
107891  int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
107892  int regRowCount = 0; /* Memory cell used for the row counter */
107893  int regIns; /* Block of regs holding rowid+data being inserted */
107894  int regRowid; /* registers holding insert rowid */
107895  int regData; /* register holding first column to insert */
107896  int *aRegIdx = 0; /* One register allocated to each index */
107897 
107898 #ifndef SQLITE_OMIT_TRIGGER
107899  int isView; /* True if attempting to insert into a view */
107900  Trigger *pTrigger; /* List of triggers on pTab, if required */
107901  int tmask; /* Mask of trigger times */
107902 #endif
107903 
107904  db = pParse->db;
107905  memset(&dest, 0, sizeof(dest));
107906  if( pParse->nErr || db->mallocFailed ){
107907  goto insert_cleanup;
107908  }
107909 
107910  /* If the Select object is really just a simple VALUES() list with a
107911  ** single row (the common case) then keep that one row of values
107912  ** and discard the other (unused) parts of the pSelect object
107913  */
107914  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
107915  pList = pSelect->pEList;
107916  pSelect->pEList = 0;
107917  sqlite3SelectDelete(db, pSelect);
107918  pSelect = 0;
107919  }
107920 
107921  /* Locate the table into which we will be inserting new information.
107922  */
107923  assert( pTabList->nSrc==1 );
107924  zTab = pTabList->a[0].zName;
107925  if( NEVER(zTab==0) ) goto insert_cleanup;
107926  pTab = sqlite3SrcListLookup(pParse, pTabList);
107927  if( pTab==0 ){
107928  goto insert_cleanup;
107929  }
107930  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107931  assert( iDb<db->nDb );
107932  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
107933  db->aDb[iDb].zDbSName) ){
107934  goto insert_cleanup;
107935  }
107936  withoutRowid = !HasRowid(pTab);
107937 
107938  /* Figure out if we have any triggers and if the table being
107939  ** inserted into is a view
107940  */
107941 #ifndef SQLITE_OMIT_TRIGGER
107942  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
107943  isView = pTab->pSelect!=0;
107944 #else
107945 # define pTrigger 0
107946 # define tmask 0
107947 # define isView 0
107948 #endif
107949 #ifdef SQLITE_OMIT_VIEW
107950 # undef isView
107951 # define isView 0
107952 #endif
107953  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
107954 
107955  /* If pTab is really a view, make sure it has been initialized.
107956  ** ViewGetColumnNames() is a no-op if pTab is not a view.
107957  */
107958  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
107959  goto insert_cleanup;
107960  }
107961 
107962  /* Cannot insert into a read-only table.
107963  */
107964  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
107965  goto insert_cleanup;
107966  }
107967 
107968  /* Allocate a VDBE
107969  */
107970  v = sqlite3GetVdbe(pParse);
107971  if( v==0 ) goto insert_cleanup;
107972  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
107973  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
107974 
107975 #ifndef SQLITE_OMIT_XFER_OPT
107976  /* If the statement is of the form
107977  **
107978  ** INSERT INTO <table1> SELECT * FROM <table2>;
107979  **
107980  ** Then special optimizations can be applied that make the transfer
107981  ** very fast and which reduce fragmentation of indices.
107982  **
107983  ** This is the 2nd template.
107984  */
107985  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
107986  assert( !pTrigger );
107987  assert( pList==0 );
107988  goto insert_end;
107989  }
107990 #endif /* SQLITE_OMIT_XFER_OPT */
107991 
107992  /* If this is an AUTOINCREMENT table, look up the sequence number in the
107993  ** sqlite_sequence table and store it in memory cell regAutoinc.
107994  */
107995  regAutoinc = autoIncBegin(pParse, iDb, pTab);
107996 
107997  /* Allocate registers for holding the rowid of the new row,
107998  ** the content of the new row, and the assembled row record.
107999  */
108000  regRowid = regIns = pParse->nMem+1;
108001  pParse->nMem += pTab->nCol + 1;
108002  if( IsVirtual(pTab) ){
108003  regRowid++;
108004  pParse->nMem++;
108005  }
108006  regData = regRowid+1;
108007 
108008  /* If the INSERT statement included an IDLIST term, then make sure
108009  ** all elements of the IDLIST really are columns of the table and
108010  ** remember the column indices.
108011  **
108012  ** If the table has an INTEGER PRIMARY KEY column and that column
108013  ** is named in the IDLIST, then record in the ipkColumn variable
108014  ** the index into IDLIST of the primary key column. ipkColumn is
108015  ** the index of the primary key as it appears in IDLIST, not as
108016  ** is appears in the original table. (The index of the INTEGER
108017  ** PRIMARY KEY in the original table is pTab->iPKey.)
108018  */
108019  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
108020  if( pColumn ){
108021  for(i=0; i<pColumn->nId; i++){
108022  pColumn->a[i].idx = -1;
108023  }
108024  for(i=0; i<pColumn->nId; i++){
108025  for(j=0; j<pTab->nCol; j++){
108026  if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
108027  pColumn->a[i].idx = j;
108028  if( i!=j ) bIdListInOrder = 0;
108029  if( j==pTab->iPKey ){
108030  ipkColumn = i; assert( !withoutRowid );
108031  }
108032  break;
108033  }
108034  }
108035  if( j>=pTab->nCol ){
108036  if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
108037  ipkColumn = i;
108038  bIdListInOrder = 0;
108039  }else{
108040  sqlite3ErrorMsg(pParse, "table %S has no column named %s",
108041  pTabList, 0, pColumn->a[i].zName);
108042  pParse->checkSchema = 1;
108043  goto insert_cleanup;
108044  }
108045  }
108046  }
108047  }
108048 
108049  /* Figure out how many columns of data are supplied. If the data
108050  ** is coming from a SELECT statement, then generate a co-routine that
108051  ** produces a single row of the SELECT on each invocation. The
108052  ** co-routine is the common header to the 3rd and 4th templates.
108053  */
108054  if( pSelect ){
108055  /* Data is coming from a SELECT or from a multi-row VALUES clause.
108056  ** Generate a co-routine to run the SELECT. */
108057  int regYield; /* Register holding co-routine entry-point */
108058  int addrTop; /* Top of the co-routine */
108059  int rc; /* Result code */
108060 
108061  regYield = ++pParse->nMem;
108062  addrTop = sqlite3VdbeCurrentAddr(v) + 1;
108063  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
108064  sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
108065  dest.iSdst = bIdListInOrder ? regData : 0;
108066  dest.nSdst = pTab->nCol;
108067  rc = sqlite3Select(pParse, pSelect, &dest);
108068  regFromSelect = dest.iSdst;
108069  if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
108070  sqlite3VdbeEndCoroutine(v, regYield);
108071  sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
108072  assert( pSelect->pEList );
108073  nColumn = pSelect->pEList->nExpr;
108074 
108075  /* Set useTempTable to TRUE if the result of the SELECT statement
108076  ** should be written into a temporary table (template 4). Set to
108077  ** FALSE if each output row of the SELECT can be written directly into
108078  ** the destination table (template 3).
108079  **
108080  ** A temp table must be used if the table being updated is also one
108081  ** of the tables being read by the SELECT statement. Also use a
108082  ** temp table in the case of row triggers.
108083  */
108084  if( pTrigger || readsTable(pParse, iDb, pTab) ){
108085  useTempTable = 1;
108086  }
108087 
108088  if( useTempTable ){
108089  /* Invoke the coroutine to extract information from the SELECT
108090  ** and add it to a transient table srcTab. The code generated
108091  ** here is from the 4th template:
108092  **
108093  ** B: open temp table
108094  ** L: yield X, goto M at EOF
108095  ** insert row from R..R+n into temp table
108096  ** goto L
108097  ** M: ...
108098  */
108099  int regRec; /* Register to hold packed record */
108100  int regTempRowid; /* Register to hold temp table ROWID */
108101  int addrL; /* Label "L" */
108102 
108103  srcTab = pParse->nTab++;
108104  regRec = sqlite3GetTempReg(pParse);
108105  regTempRowid = sqlite3GetTempReg(pParse);
108106  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
108107  addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
108108  sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
108109  sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
108110  sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
108111  sqlite3VdbeGoto(v, addrL);
108112  sqlite3VdbeJumpHere(v, addrL);
108113  sqlite3ReleaseTempReg(pParse, regRec);
108114  sqlite3ReleaseTempReg(pParse, regTempRowid);
108115  }
108116  }else{
108117  /* This is the case if the data for the INSERT is coming from a
108118  ** single-row VALUES clause
108119  */
108120  NameContext sNC;
108121  memset(&sNC, 0, sizeof(sNC));
108122  sNC.pParse = pParse;
108123  srcTab = -1;
108124  assert( useTempTable==0 );
108125  if( pList ){
108126  nColumn = pList->nExpr;
108127  if( sqlite3ResolveExprListNames(&sNC, pList) ){
108128  goto insert_cleanup;
108129  }
108130  }else{
108131  nColumn = 0;
108132  }
108133  }
108134 
108135  /* If there is no IDLIST term but the table has an integer primary
108136  ** key, the set the ipkColumn variable to the integer primary key
108137  ** column index in the original table definition.
108138  */
108139  if( pColumn==0 && nColumn>0 ){
108140  ipkColumn = pTab->iPKey;
108141  }
108142 
108143  /* Make sure the number of columns in the source data matches the number
108144  ** of columns to be inserted into the table.
108145  */
108146  for(i=0; i<pTab->nCol; i++){
108147  nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
108148  }
108149  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
108150  sqlite3ErrorMsg(pParse,
108151  "table %S has %d columns but %d values were supplied",
108152  pTabList, 0, pTab->nCol-nHidden, nColumn);
108153  goto insert_cleanup;
108154  }
108155  if( pColumn!=0 && nColumn!=pColumn->nId ){
108156  sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
108157  goto insert_cleanup;
108158  }
108159 
108160  /* Initialize the count of rows to be inserted
108161  */
108162  if( db->flags & SQLITE_CountRows ){
108163  regRowCount = ++pParse->nMem;
108164  sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
108165  }
108166 
108167  /* If this is not a view, open the table and and all indices */
108168  if( !isView ){
108169  int nIdx;
108170  nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
108171  &iDataCur, &iIdxCur);
108172  aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
108173  if( aRegIdx==0 ){
108174  goto insert_cleanup;
108175  }
108176  for(i=0; i<nIdx; i++){
108177  aRegIdx[i] = ++pParse->nMem;
108178  }
108179  }
108180 
108181  /* This is the top of the main insertion loop */
108182  if( useTempTable ){
108183  /* This block codes the top of loop only. The complete loop is the
108184  ** following pseudocode (template 4):
108185  **
108186  ** rewind temp table, if empty goto D
108187  ** C: loop over rows of intermediate table
108188  ** transfer values form intermediate table into <table>
108189  ** end loop
108190  ** D: ...
108191  */
108192  addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
108193  addrCont = sqlite3VdbeCurrentAddr(v);
108194  }else if( pSelect ){
108195  /* This block codes the top of loop only. The complete loop is the
108196  ** following pseudocode (template 3):
108197  **
108198  ** C: yield X, at EOF goto D
108199  ** insert the select result into <table> from R..R+n
108200  ** goto C
108201  ** D: ...
108202  */
108203  addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
108204  VdbeCoverage(v);
108205  }
108206 
108207  /* Run the BEFORE and INSTEAD OF triggers, if there are any
108208  */
108209  endOfLoop = sqlite3VdbeMakeLabel(v);
108210  if( tmask & TRIGGER_BEFORE ){
108211  int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
108212 
108213  /* build the NEW.* reference row. Note that if there is an INTEGER
108214  ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
108215  ** translated into a unique ID for the row. But on a BEFORE trigger,
108216  ** we do not know what the unique ID will be (because the insert has
108217  ** not happened yet) so we substitute a rowid of -1
108218  */
108219  if( ipkColumn<0 ){
108220  sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
108221  }else{
108222  int addr1;
108223  assert( !withoutRowid );
108224  if( useTempTable ){
108225  sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
108226  }else{
108227  assert( pSelect==0 ); /* Otherwise useTempTable is true */
108228  sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
108229  }
108230  addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
108231  sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
108232  sqlite3VdbeJumpHere(v, addr1);
108233  sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
108234  }
108235 
108236  /* Cannot have triggers on a virtual table. If it were possible,
108237  ** this block would have to account for hidden column.
108238  */
108239  assert( !IsVirtual(pTab) );
108240 
108241  /* Create the new column data
108242  */
108243  for(i=j=0; i<pTab->nCol; i++){
108244  if( pColumn ){
108245  for(j=0; j<pColumn->nId; j++){
108246  if( pColumn->a[j].idx==i ) break;
108247  }
108248  }
108249  if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
108250  || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
108251  sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
108252  }else if( useTempTable ){
108253  sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
108254  }else{
108255  assert( pSelect==0 ); /* Otherwise useTempTable is true */
108256  sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
108257  }
108258  if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
108259  }
108260 
108261  /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
108262  ** do not attempt any conversions before assembling the record.
108263  ** If this is a real table, attempt conversions as required by the
108264  ** table column affinities.
108265  */
108266  if( !isView ){
108267  sqlite3TableAffinity(v, pTab, regCols+1);
108268  }
108269 
108270  /* Fire BEFORE or INSTEAD OF triggers */
108271  sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
108272  pTab, regCols-pTab->nCol-1, onError, endOfLoop);
108273 
108274  sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
108275  }
108276 
108277  /* Compute the content of the next row to insert into a range of
108278  ** registers beginning at regIns.
108279  */
108280  if( !isView ){
108281  if( IsVirtual(pTab) ){
108282  /* The row that the VUpdate opcode will delete: none */
108283  sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
108284  }
108285  if( ipkColumn>=0 ){
108286  if( useTempTable ){
108287  sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
108288  }else if( pSelect ){
108289  sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
108290  }else{
108291  VdbeOp *pOp;
108292  sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
108293  pOp = sqlite3VdbeGetOp(v, -1);
108294  if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
108295  appendFlag = 1;
108296  pOp->opcode = OP_NewRowid;
108297  pOp->p1 = iDataCur;
108298  pOp->p2 = regRowid;
108299  pOp->p3 = regAutoinc;
108300  }
108301  }
108302  /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
108303  ** to generate a unique primary key value.
108304  */
108305  if( !appendFlag ){
108306  int addr1;
108307  if( !IsVirtual(pTab) ){
108308  addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
108309  sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
108310  sqlite3VdbeJumpHere(v, addr1);
108311  }else{
108312  addr1 = sqlite3VdbeCurrentAddr(v);
108313  sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
108314  }
108315  sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
108316  }
108317  }else if( IsVirtual(pTab) || withoutRowid ){
108318  sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
108319  }else{
108320  sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
108321  appendFlag = 1;
108322  }
108323  autoIncStep(pParse, regAutoinc, regRowid);
108324 
108325  /* Compute data for all columns of the new entry, beginning
108326  ** with the first column.
108327  */
108328  nHidden = 0;
108329  for(i=0; i<pTab->nCol; i++){
108330  int iRegStore = regRowid+1+i;
108331  if( i==pTab->iPKey ){
108332  /* The value of the INTEGER PRIMARY KEY column is always a NULL.
108333  ** Whenever this column is read, the rowid will be substituted
108334  ** in its place. Hence, fill this column with a NULL to avoid
108335  ** taking up data space with information that will never be used.
108336  ** As there may be shallow copies of this value, make it a soft-NULL */
108337  sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
108338  continue;
108339  }
108340  if( pColumn==0 ){
108341  if( IsHiddenColumn(&pTab->aCol[i]) ){
108342  j = -1;
108343  nHidden++;
108344  }else{
108345  j = i - nHidden;
108346  }
108347  }else{
108348  for(j=0; j<pColumn->nId; j++){
108349  if( pColumn->a[j].idx==i ) break;
108350  }
108351  }
108352  if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
108353  sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
108354  }else if( useTempTable ){
108355  sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
108356  }else if( pSelect ){
108357  if( regFromSelect!=regData ){
108358  sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
108359  }
108360  }else{
108361  sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
108362  }
108363  }
108364 
108365  /* Generate code to check constraints and generate index keys and
108366  ** do the insertion.
108367  */
108368 #ifndef SQLITE_OMIT_VIRTUALTABLE
108369  if( IsVirtual(pTab) ){
108370  const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
108371  sqlite3VtabMakeWritable(pParse, pTab);
108372  sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
108373  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
108374  sqlite3MayAbort(pParse);
108375  }else
108376 #endif
108377  {
108378  int isReplace; /* Set to true if constraints may cause a replace */
108379  sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
108380  regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
108381  );
108382  sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
108383  sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
108384  regIns, aRegIdx, 0, appendFlag, isReplace==0);
108385  }
108386  }
108387 
108388  /* Update the count of rows that are inserted
108389  */
108390  if( (db->flags & SQLITE_CountRows)!=0 ){
108391  sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
108392  }
108393 
108394  if( pTrigger ){
108395  /* Code AFTER triggers */
108396  sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
108397  pTab, regData-2-pTab->nCol, onError, endOfLoop);
108398  }
108399 
108400  /* The bottom of the main insertion loop, if the data source
108401  ** is a SELECT statement.
108402  */
108403  sqlite3VdbeResolveLabel(v, endOfLoop);
108404  if( useTempTable ){
108405  sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
108406  sqlite3VdbeJumpHere(v, addrInsTop);
108407  sqlite3VdbeAddOp1(v, OP_Close, srcTab);
108408  }else if( pSelect ){
108409  sqlite3VdbeGoto(v, addrCont);
108410  sqlite3VdbeJumpHere(v, addrInsTop);
108411  }
108412 
108413  if( !IsVirtual(pTab) && !isView ){
108414  /* Close all tables opened */
108415  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
108416  for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
108417  sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
108418  }
108419  }
108420 
108421 insert_end:
108422  /* Update the sqlite_sequence table by storing the content of the
108423  ** maximum rowid counter values recorded while inserting into
108424  ** autoincrement tables.
108425  */
108426  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
108427  sqlite3AutoincrementEnd(pParse);
108428  }
108429 
108430  /*
108431  ** Return the number of rows inserted. If this routine is
108432  ** generating code because of a call to sqlite3NestedParse(), do not
108433  ** invoke the callback function.
108434  */
108435  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
108436  sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
108437  sqlite3VdbeSetNumCols(v, 1);
108438  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
108439  }
108440 
108441 insert_cleanup:
108442  sqlite3SrcListDelete(db, pTabList);
108443  sqlite3ExprListDelete(db, pList);
108444  sqlite3SelectDelete(db, pSelect);
108445  sqlite3IdListDelete(db, pColumn);
108446  sqlite3DbFree(db, aRegIdx);
108447 }
108448 
108449 /* Make sure "isView" and other macros defined above are undefined. Otherwise
108450 ** they may interfere with compilation of other functions in this file
108451 ** (or in another file, if this file becomes part of the amalgamation). */
108452 #ifdef isView
108453  #undef isView
108454 #endif
108455 #ifdef pTrigger
108456  #undef pTrigger
108457 #endif
108458 #ifdef tmask
108459  #undef tmask
108460 #endif
108461 
108462 /*
108463 ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
108464 */
108465 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
108466 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
108467 
108468 /* This is the Walker callback from checkConstraintUnchanged(). Set
108469 ** bit 0x01 of pWalker->eCode if
108470 ** pWalker->eCode to 0 if this expression node references any of the
108471 ** columns that are being modifed by an UPDATE statement.
108472 */
108473 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
108474  if( pExpr->op==TK_COLUMN ){
108475  assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
108476  if( pExpr->iColumn>=0 ){
108477  if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
108478  pWalker->eCode |= CKCNSTRNT_COLUMN;
108479  }
108480  }else{
108481  pWalker->eCode |= CKCNSTRNT_ROWID;
108482  }
108483  }
108484  return WRC_Continue;
108485 }
108486 
108487 /*
108488 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
108489 ** only columns that are modified by the UPDATE are those for which
108490 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
108491 **
108492 ** Return true if CHECK constraint pExpr does not use any of the
108493 ** changing columns (or the rowid if it is changing). In other words,
108494 ** return true if this CHECK constraint can be skipped when validating
108495 ** the new row in the UPDATE statement.
108496 */
108497 static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
108498  Walker w;
108499  memset(&w, 0, sizeof(w));
108500  w.eCode = 0;
108501  w.xExprCallback = checkConstraintExprNode;
108502  w.u.aiCol = aiChng;
108503  sqlite3WalkExpr(&w, pExpr);
108504  if( !chngRowid ){
108505  testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
108506  w.eCode &= ~CKCNSTRNT_ROWID;
108507  }
108508  testcase( w.eCode==0 );
108509  testcase( w.eCode==CKCNSTRNT_COLUMN );
108510  testcase( w.eCode==CKCNSTRNT_ROWID );
108511  testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
108512  return !w.eCode;
108513 }
108514 
108515 /*
108516 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
108517 ** on table pTab.
108518 **
108519 ** The regNewData parameter is the first register in a range that contains
108520 ** the data to be inserted or the data after the update. There will be
108521 ** pTab->nCol+1 registers in this range. The first register (the one
108522 ** that regNewData points to) will contain the new rowid, or NULL in the
108523 ** case of a WITHOUT ROWID table. The second register in the range will
108524 ** contain the content of the first table column. The third register will
108525 ** contain the content of the second table column. And so forth.
108526 **
108527 ** The regOldData parameter is similar to regNewData except that it contains
108528 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
108529 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
108530 ** checking regOldData for zero.
108531 **
108532 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
108533 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
108534 ** might be modified by the UPDATE. If pkChng is false, then the key of
108535 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
108536 **
108537 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
108538 ** was explicitly specified as part of the INSERT statement. If pkChng
108539 ** is zero, it means that the either rowid is computed automatically or
108540 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
108541 ** pkChng will only be true if the INSERT statement provides an integer
108542 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
108543 **
108544 ** The code generated by this routine will store new index entries into
108545 ** registers identified by aRegIdx[]. No index entry is created for
108546 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
108547 ** the same as the order of indices on the linked list of indices
108548 ** at pTab->pIndex.
108549 **
108550 ** The caller must have already opened writeable cursors on the main
108551 ** table and all applicable indices (that is to say, all indices for which
108552 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
108553 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
108554 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
108555 ** for the first index in the pTab->pIndex list. Cursors for other indices
108556 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
108557 **
108558 ** This routine also generates code to check constraints. NOT NULL,
108559 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
108560 ** then the appropriate action is performed. There are five possible
108561 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
108562 **
108563 ** Constraint type Action What Happens
108564 ** --------------- ---------- ----------------------------------------
108565 ** any ROLLBACK The current transaction is rolled back and
108566 ** sqlite3_step() returns immediately with a
108567 ** return code of SQLITE_CONSTRAINT.
108568 **
108569 ** any ABORT Back out changes from the current command
108570 ** only (do not do a complete rollback) then
108571 ** cause sqlite3_step() to return immediately
108572 ** with SQLITE_CONSTRAINT.
108573 **
108574 ** any FAIL Sqlite3_step() returns immediately with a
108575 ** return code of SQLITE_CONSTRAINT. The
108576 ** transaction is not rolled back and any
108577 ** changes to prior rows are retained.
108578 **
108579 ** any IGNORE The attempt in insert or update the current
108580 ** row is skipped, without throwing an error.
108581 ** Processing continues with the next row.
108582 ** (There is an immediate jump to ignoreDest.)
108583 **
108584 ** NOT NULL REPLACE The NULL value is replace by the default
108585 ** value for that column. If the default value
108586 ** is NULL, the action is the same as ABORT.
108587 **
108588 ** UNIQUE REPLACE The other row that conflicts with the row
108589 ** being inserted is removed.
108590 **
108591 ** CHECK REPLACE Illegal. The results in an exception.
108592 **
108593 ** Which action to take is determined by the overrideError parameter.
108594 ** Or if overrideError==OE_Default, then the pParse->onError parameter
108595 ** is used. Or if pParse->onError==OE_Default then the onError value
108596 ** for the constraint is used.
108597 */
108598 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
108599  Parse *pParse, /* The parser context */
108600  Table *pTab, /* The table being inserted or updated */
108601  int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
108602  int iDataCur, /* Canonical data cursor (main table or PK index) */
108603  int iIdxCur, /* First index cursor */
108604  int regNewData, /* First register in a range holding values to insert */
108605  int regOldData, /* Previous content. 0 for INSERTs */
108606  u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
108607  u8 overrideError, /* Override onError to this if not OE_Default */
108608  int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
108609  int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
108610  int *aiChng /* column i is unchanged if aiChng[i]<0 */
108611 ){
108612  Vdbe *v; /* VDBE under constrution */
108613  Index *pIdx; /* Pointer to one of the indices */
108614  Index *pPk = 0; /* The PRIMARY KEY index */
108615  sqlite3 *db; /* Database connection */
108616  int i; /* loop counter */
108617  int ix; /* Index loop counter */
108618  int nCol; /* Number of columns */
108619  int onError; /* Conflict resolution strategy */
108620  int addr1; /* Address of jump instruction */
108621  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
108622  int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
108623  int ipkTop = 0; /* Top of the rowid change constraint check */
108624  int ipkBottom = 0; /* Bottom of the rowid change constraint check */
108625  u8 isUpdate; /* True if this is an UPDATE operation */
108626  u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
108627  int regRowid = -1; /* Register holding ROWID value */
108628 
108629  isUpdate = regOldData!=0;
108630  db = pParse->db;
108631  v = sqlite3GetVdbe(pParse);
108632  assert( v!=0 );
108633  assert( pTab->pSelect==0 ); /* This table is not a VIEW */
108634  nCol = pTab->nCol;
108635 
108636  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
108637  ** normal rowid tables. nPkField is the number of key fields in the
108638  ** pPk index or 1 for a rowid table. In other words, nPkField is the
108639  ** number of fields in the true primary key of the table. */
108640  if( HasRowid(pTab) ){
108641  pPk = 0;
108642  nPkField = 1;
108643  }else{
108644  pPk = sqlite3PrimaryKeyIndex(pTab);
108645  nPkField = pPk->nKeyCol;
108646  }
108647 
108648  /* Record that this module has started */
108649  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
108650  iDataCur, iIdxCur, regNewData, regOldData, pkChng));
108651 
108652  /* Test all NOT NULL constraints.
108653  */
108654  for(i=0; i<nCol; i++){
108655  if( i==pTab->iPKey ){
108656  continue; /* ROWID is never NULL */
108657  }
108658  if( aiChng && aiChng[i]<0 ){
108659  /* Don't bother checking for NOT NULL on columns that do not change */
108660  continue;
108661  }
108662  onError = pTab->aCol[i].notNull;
108663  if( onError==OE_None ) continue; /* This column is allowed to be NULL */
108664  if( overrideError!=OE_Default ){
108665  onError = overrideError;
108666  }else if( onError==OE_Default ){
108667  onError = OE_Abort;
108668  }
108669  if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
108670  onError = OE_Abort;
108671  }
108672  assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
108673  || onError==OE_Ignore || onError==OE_Replace );
108674  switch( onError ){
108675  case OE_Abort:
108676  sqlite3MayAbort(pParse);
108677  /* Fall through */
108678  case OE_Rollback:
108679  case OE_Fail: {
108680  char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
108681  pTab->aCol[i].zName);
108682  sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
108683  regNewData+1+i, zMsg, P4_DYNAMIC);
108684  sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
108685  VdbeCoverage(v);
108686  break;
108687  }
108688  case OE_Ignore: {
108689  sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
108690  VdbeCoverage(v);
108691  break;
108692  }
108693  default: {
108694  assert( onError==OE_Replace );
108695  addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
108696  VdbeCoverage(v);
108697  sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
108698  sqlite3VdbeJumpHere(v, addr1);
108699  break;
108700  }
108701  }
108702  }
108703 
108704  /* Test all CHECK constraints
108705  */
108706 #ifndef SQLITE_OMIT_CHECK
108707  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
108708  ExprList *pCheck = pTab->pCheck;
108709  pParse->ckBase = regNewData+1;
108710  onError = overrideError!=OE_Default ? overrideError : OE_Abort;
108711  for(i=0; i<pCheck->nExpr; i++){
108712  int allOk;
108713  Expr *pExpr = pCheck->a[i].pExpr;
108714  if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
108715  allOk = sqlite3VdbeMakeLabel(v);
108716  sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
108717  if( onError==OE_Ignore ){
108718  sqlite3VdbeGoto(v, ignoreDest);
108719  }else{
108720  char *zName = pCheck->a[i].zName;
108721  if( zName==0 ) zName = pTab->zName;
108722  if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
108723  sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
108724  onError, zName, P4_TRANSIENT,
108725  P5_ConstraintCheck);
108726  }
108727  sqlite3VdbeResolveLabel(v, allOk);
108728  }
108729  }
108730 #endif /* !defined(SQLITE_OMIT_CHECK) */
108731 
108732  /* If rowid is changing, make sure the new rowid does not previously
108733  ** exist in the table.
108734  */
108735  if( pkChng && pPk==0 ){
108736  int addrRowidOk = sqlite3VdbeMakeLabel(v);
108737 
108738  /* Figure out what action to take in case of a rowid collision */
108739  onError = pTab->keyConf;
108740  if( overrideError!=OE_Default ){
108741  onError = overrideError;
108742  }else if( onError==OE_Default ){
108743  onError = OE_Abort;
108744  }
108745 
108746  if( isUpdate ){
108747  /* pkChng!=0 does not mean that the rowid has change, only that
108748  ** it might have changed. Skip the conflict logic below if the rowid
108749  ** is unchanged. */
108750  sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
108751  sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108752  VdbeCoverage(v);
108753  }
108754 
108755  /* If the response to a rowid conflict is REPLACE but the response
108756  ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
108757  ** to defer the running of the rowid conflict checking until after
108758  ** the UNIQUE constraints have run.
108759  */
108760  if( onError==OE_Replace && overrideError!=OE_Replace ){
108761  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
108762  if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
108763  ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
108764  break;
108765  }
108766  }
108767  }
108768 
108769  /* Check to see if the new rowid already exists in the table. Skip
108770  ** the following conflict logic if it does not. */
108771  sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
108772  VdbeCoverage(v);
108773 
108774  /* Generate code that deals with a rowid collision */
108775  switch( onError ){
108776  default: {
108777  onError = OE_Abort;
108778  /* Fall thru into the next case */
108779  }
108780  case OE_Rollback:
108781  case OE_Abort:
108782  case OE_Fail: {
108783  sqlite3RowidConstraint(pParse, onError, pTab);
108784  break;
108785  }
108786  case OE_Replace: {
108787  /* If there are DELETE triggers on this table and the
108788  ** recursive-triggers flag is set, call GenerateRowDelete() to
108789  ** remove the conflicting row from the table. This will fire
108790  ** the triggers and remove both the table and index b-tree entries.
108791  **
108792  ** Otherwise, if there are no triggers or the recursive-triggers
108793  ** flag is not set, but the table has one or more indexes, call
108794  ** GenerateRowIndexDelete(). This removes the index b-tree entries
108795  ** only. The table b-tree entry will be replaced by the new entry
108796  ** when it is inserted.
108797  **
108798  ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
108799  ** also invoke MultiWrite() to indicate that this VDBE may require
108800  ** statement rollback (if the statement is aborted after the delete
108801  ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
108802  ** but being more selective here allows statements like:
108803  **
108804  ** REPLACE INTO t(rowid) VALUES($newrowid)
108805  **
108806  ** to run without a statement journal if there are no indexes on the
108807  ** table.
108808  */
108809  Trigger *pTrigger = 0;
108810  if( db->flags&SQLITE_RecTriggers ){
108811  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
108812  }
108813  if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
108814  sqlite3MultiWrite(pParse);
108815  sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
108816  regNewData, 1, 0, OE_Replace, 1, -1);
108817  }else{
108818 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
108819  if( HasRowid(pTab) ){
108820  /* This OP_Delete opcode fires the pre-update-hook only. It does
108821  ** not modify the b-tree. It is more efficient to let the coming
108822  ** OP_Insert replace the existing entry than it is to delete the
108823  ** existing entry and then insert a new one. */
108824  sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
108825  sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
108826  }
108827 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
108828  if( pTab->pIndex ){
108829  sqlite3MultiWrite(pParse);
108830  sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
108831  }
108832  }
108833  seenReplace = 1;
108834  break;
108835  }
108836  case OE_Ignore: {
108837  /*assert( seenReplace==0 );*/
108838  sqlite3VdbeGoto(v, ignoreDest);
108839  break;
108840  }
108841  }
108842  sqlite3VdbeResolveLabel(v, addrRowidOk);
108843  if( ipkTop ){
108844  ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
108845  sqlite3VdbeJumpHere(v, ipkTop);
108846  }
108847  }
108848 
108849  /* Test all UNIQUE constraints by creating entries for each UNIQUE
108850  ** index and making sure that duplicate entries do not already exist.
108851  ** Compute the revised record entries for indices as we go.
108852  **
108853  ** This loop also handles the case of the PRIMARY KEY index for a
108854  ** WITHOUT ROWID table.
108855  */
108856  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
108857  int regIdx; /* Range of registers hold conent for pIdx */
108858  int regR; /* Range of registers holding conflicting PK */
108859  int iThisCur; /* Cursor for this UNIQUE index */
108860  int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
108861 
108862  if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
108863  if( bAffinityDone==0 ){
108864  sqlite3TableAffinity(v, pTab, regNewData+1);
108865  bAffinityDone = 1;
108866  }
108867  iThisCur = iIdxCur+ix;
108868  addrUniqueOk = sqlite3VdbeMakeLabel(v);
108869 
108870  /* Skip partial indices for which the WHERE clause is not true */
108871  if( pIdx->pPartIdxWhere ){
108872  sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
108873  pParse->ckBase = regNewData+1;
108874  sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
108875  SQLITE_JUMPIFNULL);
108876  pParse->ckBase = 0;
108877  }
108878 
108879  /* Create a record for this index entry as it should appear after
108880  ** the insert or update. Store that record in the aRegIdx[ix] register
108881  */
108882  regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
108883  for(i=0; i<pIdx->nColumn; i++){
108884  int iField = pIdx->aiColumn[i];
108885  int x;
108886  if( iField==XN_EXPR ){
108887  pParse->ckBase = regNewData+1;
108888  sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
108889  pParse->ckBase = 0;
108890  VdbeComment((v, "%s column %d", pIdx->zName, i));
108891  }else{
108892  if( iField==XN_ROWID || iField==pTab->iPKey ){
108893  if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
108894  x = regNewData;
108895  regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
108896  }else{
108897  x = iField + regNewData + 1;
108898  }
108899  sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
108900  VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
108901  }
108902  }
108903  sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
108904  VdbeComment((v, "for %s", pIdx->zName));
108905  sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
108906 
108907  /* In an UPDATE operation, if this index is the PRIMARY KEY index
108908  ** of a WITHOUT ROWID table and there has been no change the
108909  ** primary key, then no collision is possible. The collision detection
108910  ** logic below can all be skipped. */
108911  if( isUpdate && pPk==pIdx && pkChng==0 ){
108912  sqlite3VdbeResolveLabel(v, addrUniqueOk);
108913  continue;
108914  }
108915 
108916  /* Find out what action to take in case there is a uniqueness conflict */
108917  onError = pIdx->onError;
108918  if( onError==OE_None ){
108919  sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
108920  sqlite3VdbeResolveLabel(v, addrUniqueOk);
108921  continue; /* pIdx is not a UNIQUE index */
108922  }
108923  if( overrideError!=OE_Default ){
108924  onError = overrideError;
108925  }else if( onError==OE_Default ){
108926  onError = OE_Abort;
108927  }
108928 
108929  /* Check to see if the new index entry will be unique */
108930  sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
108931  regIdx, pIdx->nKeyCol); VdbeCoverage(v);
108932 
108933  /* Generate code to handle collisions */
108934  regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
108935  if( isUpdate || onError==OE_Replace ){
108936  if( HasRowid(pTab) ){
108937  sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
108938  /* Conflict only if the rowid of the existing index entry
108939  ** is different from old-rowid */
108940  if( isUpdate ){
108941  sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
108942  sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108943  VdbeCoverage(v);
108944  }
108945  }else{
108946  int x;
108947  /* Extract the PRIMARY KEY from the end of the index entry and
108948  ** store it in registers regR..regR+nPk-1 */
108949  if( pIdx!=pPk ){
108950  for(i=0; i<pPk->nKeyCol; i++){
108951  assert( pPk->aiColumn[i]>=0 );
108952  x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
108953  sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
108954  VdbeComment((v, "%s.%s", pTab->zName,
108955  pTab->aCol[pPk->aiColumn[i]].zName));
108956  }
108957  }
108958  if( isUpdate ){
108959  /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
108960  ** table, only conflict if the new PRIMARY KEY values are actually
108961  ** different from the old.
108962  **
108963  ** For a UNIQUE index, only conflict if the PRIMARY KEY values
108964  ** of the matched index row are different from the original PRIMARY
108965  ** KEY values of this row before the update. */
108966  int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
108967  int op = OP_Ne;
108968  int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
108969 
108970  for(i=0; i<pPk->nKeyCol; i++){
108971  char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
108972  x = pPk->aiColumn[i];
108973  assert( x>=0 );
108974  if( i==(pPk->nKeyCol-1) ){
108975  addrJump = addrUniqueOk;
108976  op = OP_Eq;
108977  }
108978  sqlite3VdbeAddOp4(v, op,
108979  regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
108980  );
108981  sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108982  VdbeCoverageIf(v, op==OP_Eq);
108983  VdbeCoverageIf(v, op==OP_Ne);
108984  }
108985  }
108986  }
108987  }
108988 
108989  /* Generate code that executes if the new index entry is not unique */
108990  assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
108991  || onError==OE_Ignore || onError==OE_Replace );
108992  switch( onError ){
108993  case OE_Rollback:
108994  case OE_Abort:
108995  case OE_Fail: {
108996  sqlite3UniqueConstraint(pParse, onError, pIdx);
108997  break;
108998  }
108999  case OE_Ignore: {
109000  sqlite3VdbeGoto(v, ignoreDest);
109001  break;
109002  }
109003  default: {
109004  Trigger *pTrigger = 0;
109005  assert( onError==OE_Replace );
109006  sqlite3MultiWrite(pParse);
109007  if( db->flags&SQLITE_RecTriggers ){
109008  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
109009  }
109010  sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
109011  regR, nPkField, 0, OE_Replace,
109012  (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
109013  seenReplace = 1;
109014  break;
109015  }
109016  }
109017  sqlite3VdbeResolveLabel(v, addrUniqueOk);
109018  sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
109019  if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
109020  }
109021  if( ipkTop ){
109022  sqlite3VdbeGoto(v, ipkTop+1);
109023  sqlite3VdbeJumpHere(v, ipkBottom);
109024  }
109025 
109026  *pbMayReplace = seenReplace;
109027  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
109028 }
109029 
109030 /*
109031 ** This routine generates code to finish the INSERT or UPDATE operation
109032 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
109033 ** A consecutive range of registers starting at regNewData contains the
109034 ** rowid and the content to be inserted.
109035 **
109036 ** The arguments to this routine should be the same as the first six
109037 ** arguments to sqlite3GenerateConstraintChecks.
109038 */
109039 SQLITE_PRIVATE void sqlite3CompleteInsertion(
109040  Parse *pParse, /* The parser context */
109041  Table *pTab, /* the table into which we are inserting */
109042  int iDataCur, /* Cursor of the canonical data source */
109043  int iIdxCur, /* First index cursor */
109044  int regNewData, /* Range of content */
109045  int *aRegIdx, /* Register used by each index. 0 for unused indices */
109046  int isUpdate, /* True for UPDATE, False for INSERT */
109047  int appendBias, /* True if this is likely to be an append */
109048  int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
109049 ){
109050  Vdbe *v; /* Prepared statements under construction */
109051  Index *pIdx; /* An index being inserted or updated */
109052  u8 pik_flags; /* flag values passed to the btree insert */
109053  int regData; /* Content registers (after the rowid) */
109054  int regRec; /* Register holding assembled record for the table */
109055  int i; /* Loop counter */
109056  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
109057 
109058  v = sqlite3GetVdbe(pParse);
109059  assert( v!=0 );
109060  assert( pTab->pSelect==0 ); /* This table is not a VIEW */
109061  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
109062  if( aRegIdx[i]==0 ) continue;
109063  bAffinityDone = 1;
109064  if( pIdx->pPartIdxWhere ){
109065  sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
109066  VdbeCoverage(v);
109067  }
109068  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
109069  pik_flags = 0;
109070  if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
109071  if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
109072  assert( pParse->nested==0 );
109073  pik_flags |= OPFLAG_NCHANGE;
109074  }
109075  sqlite3VdbeChangeP5(v, pik_flags);
109076  }
109077  if( !HasRowid(pTab) ) return;
109078  regData = regNewData + 1;
109079  regRec = sqlite3GetTempReg(pParse);
109080  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
109081  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
109082  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
109083  if( pParse->nested ){
109084  pik_flags = 0;
109085  }else{
109086  pik_flags = OPFLAG_NCHANGE;
109087  pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
109088  }
109089  if( appendBias ){
109090  pik_flags |= OPFLAG_APPEND;
109091  }
109092  if( useSeekResult ){
109093  pik_flags |= OPFLAG_USESEEKRESULT;
109094  }
109095  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
109096  if( !pParse->nested ){
109097  sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
109098  }
109099  sqlite3VdbeChangeP5(v, pik_flags);
109100 }
109101 
109102 /*
109103 ** Allocate cursors for the pTab table and all its indices and generate
109104 ** code to open and initialized those cursors.
109105 **
109106 ** The cursor for the object that contains the complete data (normally
109107 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
109108 ** ROWID table) is returned in *piDataCur. The first index cursor is
109109 ** returned in *piIdxCur. The number of indices is returned.
109110 **
109111 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
109112 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
109113 ** If iBase is negative, then allocate the next available cursor.
109114 **
109115 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
109116 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
109117 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
109118 ** pTab->pIndex list.
109119 **
109120 ** If pTab is a virtual table, then this routine is a no-op and the
109121 ** *piDataCur and *piIdxCur values are left uninitialized.
109122 */
109123 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
109124  Parse *pParse, /* Parsing context */
109125  Table *pTab, /* Table to be opened */
109126  int op, /* OP_OpenRead or OP_OpenWrite */
109127  u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
109128  int iBase, /* Use this for the table cursor, if there is one */
109129  u8 *aToOpen, /* If not NULL: boolean for each table and index */
109130  int *piDataCur, /* Write the database source cursor number here */
109131  int *piIdxCur /* Write the first index cursor number here */
109132 ){
109133  int i;
109134  int iDb;
109135  int iDataCur;
109136  Index *pIdx;
109137  Vdbe *v;
109138 
109139  assert( op==OP_OpenRead || op==OP_OpenWrite );
109140  assert( op==OP_OpenWrite || p5==0 );
109141  if( IsVirtual(pTab) ){
109142  /* This routine is a no-op for virtual tables. Leave the output
109143  ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
109144  ** can detect if they are used by mistake in the caller. */
109145  return 0;
109146  }
109147  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
109148  v = sqlite3GetVdbe(pParse);
109149  assert( v!=0 );
109150  if( iBase<0 ) iBase = pParse->nTab;
109151  iDataCur = iBase++;
109152  if( piDataCur ) *piDataCur = iDataCur;
109153  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
109154  sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
109155  }else{
109156  sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
109157  }
109158  if( piIdxCur ) *piIdxCur = iBase;
109159  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
109160  int iIdxCur = iBase++;
109161  assert( pIdx->pSchema==pTab->pSchema );
109162  if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
109163  if( piDataCur ) *piDataCur = iIdxCur;
109164  p5 = 0;
109165  }
109166  if( aToOpen==0 || aToOpen[i+1] ){
109167  sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
109168  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
109169  sqlite3VdbeChangeP5(v, p5);
109170  VdbeComment((v, "%s", pIdx->zName));
109171  }
109172  }
109173  if( iBase>pParse->nTab ) pParse->nTab = iBase;
109174  return i;
109175 }
109176 
109177 
109178 #ifdef SQLITE_TEST
109179 /*
109180 ** The following global variable is incremented whenever the
109181 ** transfer optimization is used. This is used for testing
109182 ** purposes only - to make sure the transfer optimization really
109183 ** is happening when it is supposed to.
109184 */
109185 SQLITE_API int sqlite3_xferopt_count;
109186 #endif /* SQLITE_TEST */
109187 
109188 
109189 #ifndef SQLITE_OMIT_XFER_OPT
109190 /*
109191 ** Check to see if index pSrc is compatible as a source of data
109192 ** for index pDest in an insert transfer optimization. The rules
109193 ** for a compatible index:
109194 **
109195 ** * The index is over the same set of columns
109196 ** * The same DESC and ASC markings occurs on all columns
109197 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
109198 ** * The same collating sequence on each column
109199 ** * The index has the exact same WHERE clause
109200 */
109201 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
109202  int i;
109203  assert( pDest && pSrc );
109204  assert( pDest->pTable!=pSrc->pTable );
109205  if( pDest->nKeyCol!=pSrc->nKeyCol ){
109206  return 0; /* Different number of columns */
109207  }
109208  if( pDest->onError!=pSrc->onError ){
109209  return 0; /* Different conflict resolution strategies */
109210  }
109211  for(i=0; i<pSrc->nKeyCol; i++){
109212  if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
109213  return 0; /* Different columns indexed */
109214  }
109215  if( pSrc->aiColumn[i]==XN_EXPR ){
109216  assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
109217  if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
109218  pDest->aColExpr->a[i].pExpr, -1)!=0 ){
109219  return 0; /* Different expressions in the index */
109220  }
109221  }
109222  if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
109223  return 0; /* Different sort orders */
109224  }
109225  if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
109226  return 0; /* Different collating sequences */
109227  }
109228  }
109229  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
109230  return 0; /* Different WHERE clauses */
109231  }
109232 
109233  /* If no test above fails then the indices must be compatible */
109234  return 1;
109235 }
109236 
109237 /*
109238 ** Attempt the transfer optimization on INSERTs of the form
109239 **
109240 ** INSERT INTO tab1 SELECT * FROM tab2;
109241 **
109242 ** The xfer optimization transfers raw records from tab2 over to tab1.
109243 ** Columns are not decoded and reassembled, which greatly improves
109244 ** performance. Raw index records are transferred in the same way.
109245 **
109246 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
109247 ** There are lots of rules for determining compatibility - see comments
109248 ** embedded in the code for details.
109249 **
109250 ** This routine returns TRUE if the optimization is guaranteed to be used.
109251 ** Sometimes the xfer optimization will only work if the destination table
109252 ** is empty - a factor that can only be determined at run-time. In that
109253 ** case, this routine generates code for the xfer optimization but also
109254 ** does a test to see if the destination table is empty and jumps over the
109255 ** xfer optimization code if the test fails. In that case, this routine
109256 ** returns FALSE so that the caller will know to go ahead and generate
109257 ** an unoptimized transfer. This routine also returns FALSE if there
109258 ** is no chance that the xfer optimization can be applied.
109259 **
109260 ** This optimization is particularly useful at making VACUUM run faster.
109261 */
109262 static int xferOptimization(
109263  Parse *pParse, /* Parser context */
109264  Table *pDest, /* The table we are inserting into */
109265  Select *pSelect, /* A SELECT statement to use as the data source */
109266  int onError, /* How to handle constraint errors */
109267  int iDbDest /* The database of pDest */
109268 ){
109269  sqlite3 *db = pParse->db;
109270  ExprList *pEList; /* The result set of the SELECT */
109271  Table *pSrc; /* The table in the FROM clause of SELECT */
109272  Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
109273  struct SrcList_item *pItem; /* An element of pSelect->pSrc */
109274  int i; /* Loop counter */
109275  int iDbSrc; /* The database of pSrc */
109276  int iSrc, iDest; /* Cursors from source and destination */
109277  int addr1, addr2; /* Loop addresses */
109278  int emptyDestTest = 0; /* Address of test for empty pDest */
109279  int emptySrcTest = 0; /* Address of test for empty pSrc */
109280  Vdbe *v; /* The VDBE we are building */
109281  int regAutoinc; /* Memory register used by AUTOINC */
109282  int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
109283  int regData, regRowid; /* Registers holding data and rowid */
109284 
109285  if( pSelect==0 ){
109286  return 0; /* Must be of the form INSERT INTO ... SELECT ... */
109287  }
109288  if( pParse->pWith || pSelect->pWith ){
109289  /* Do not attempt to process this query if there are an WITH clauses
109290  ** attached to it. Proceeding may generate a false "no such table: xxx"
109291  ** error if pSelect reads from a CTE named "xxx". */
109292  return 0;
109293  }
109294  if( sqlite3TriggerList(pParse, pDest) ){
109295  return 0; /* tab1 must not have triggers */
109296  }
109297 #ifndef SQLITE_OMIT_VIRTUALTABLE
109298  if( pDest->tabFlags & TF_Virtual ){
109299  return 0; /* tab1 must not be a virtual table */
109300  }
109301 #endif
109302  if( onError==OE_Default ){
109303  if( pDest->iPKey>=0 ) onError = pDest->keyConf;
109304  if( onError==OE_Default ) onError = OE_Abort;
109305  }
109306  assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
109307  if( pSelect->pSrc->nSrc!=1 ){
109308  return 0; /* FROM clause must have exactly one term */
109309  }
109310  if( pSelect->pSrc->a[0].pSelect ){
109311  return 0; /* FROM clause cannot contain a subquery */
109312  }
109313  if( pSelect->pWhere ){
109314  return 0; /* SELECT may not have a WHERE clause */
109315  }
109316  if( pSelect->pOrderBy ){
109317  return 0; /* SELECT may not have an ORDER BY clause */
109318  }
109319  /* Do not need to test for a HAVING clause. If HAVING is present but
109320  ** there is no ORDER BY, we will get an error. */
109321  if( pSelect->pGroupBy ){
109322  return 0; /* SELECT may not have a GROUP BY clause */
109323  }
109324  if( pSelect->pLimit ){
109325  return 0; /* SELECT may not have a LIMIT clause */
109326  }
109327  assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
109328  if( pSelect->pPrior ){
109329  return 0; /* SELECT may not be a compound query */
109330  }
109331  if( pSelect->selFlags & SF_Distinct ){
109332  return 0; /* SELECT may not be DISTINCT */
109333  }
109334  pEList = pSelect->pEList;
109335  assert( pEList!=0 );
109336  if( pEList->nExpr!=1 ){
109337  return 0; /* The result set must have exactly one column */
109338  }
109339  assert( pEList->a[0].pExpr );
109340  if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
109341  return 0; /* The result set must be the special operator "*" */
109342  }
109343 
109344  /* At this point we have established that the statement is of the
109345  ** correct syntactic form to participate in this optimization. Now
109346  ** we have to check the semantics.
109347  */
109348  pItem = pSelect->pSrc->a;
109349  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
109350  if( pSrc==0 ){
109351  return 0; /* FROM clause does not contain a real table */
109352  }
109353  if( pSrc==pDest ){
109354  return 0; /* tab1 and tab2 may not be the same table */
109355  }
109356  if( HasRowid(pDest)!=HasRowid(pSrc) ){
109357  return 0; /* source and destination must both be WITHOUT ROWID or not */
109358  }
109359 #ifndef SQLITE_OMIT_VIRTUALTABLE
109360  if( pSrc->tabFlags & TF_Virtual ){
109361  return 0; /* tab2 must not be a virtual table */
109362  }
109363 #endif
109364  if( pSrc->pSelect ){
109365  return 0; /* tab2 may not be a view */
109366  }
109367  if( pDest->nCol!=pSrc->nCol ){
109368  return 0; /* Number of columns must be the same in tab1 and tab2 */
109369  }
109370  if( pDest->iPKey!=pSrc->iPKey ){
109371  return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
109372  }
109373  for(i=0; i<pDest->nCol; i++){
109374  Column *pDestCol = &pDest->aCol[i];
109375  Column *pSrcCol = &pSrc->aCol[i];
109376 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
109377  if( (db->flags & SQLITE_Vacuum)==0
109378  && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
109379  ){
109380  return 0; /* Neither table may have __hidden__ columns */
109381  }
109382 #endif
109383  if( pDestCol->affinity!=pSrcCol->affinity ){
109384  return 0; /* Affinity must be the same on all columns */
109385  }
109386  if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
109387  return 0; /* Collating sequence must be the same on all columns */
109388  }
109389  if( pDestCol->notNull && !pSrcCol->notNull ){
109390  return 0; /* tab2 must be NOT NULL if tab1 is */
109391  }
109392  /* Default values for second and subsequent columns need to match. */
109393  if( i>0 ){
109394  assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
109395  assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
109396  if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
109397  || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
109398  pSrcCol->pDflt->u.zToken)!=0)
109399  ){
109400  return 0; /* Default values must be the same for all columns */
109401  }
109402  }
109403  }
109404  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
109405  if( IsUniqueIndex(pDestIdx) ){
109406  destHasUniqueIdx = 1;
109407  }
109408  for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
109409  if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
109410  }
109411  if( pSrcIdx==0 ){
109412  return 0; /* pDestIdx has no corresponding index in pSrc */
109413  }
109414  }
109415 #ifndef SQLITE_OMIT_CHECK
109416  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
109417  return 0; /* Tables have different CHECK constraints. Ticket #2252 */
109418  }
109419 #endif
109420 #ifndef SQLITE_OMIT_FOREIGN_KEY
109421  /* Disallow the transfer optimization if the destination table constains
109422  ** any foreign key constraints. This is more restrictive than necessary.
109423  ** But the main beneficiary of the transfer optimization is the VACUUM
109424  ** command, and the VACUUM command disables foreign key constraints. So
109425  ** the extra complication to make this rule less restrictive is probably
109426  ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
109427  */
109428  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
109429  return 0;
109430  }
109431 #endif
109432  if( (db->flags & SQLITE_CountRows)!=0 ){
109433  return 0; /* xfer opt does not play well with PRAGMA count_changes */
109434  }
109435 
109436  /* If we get this far, it means that the xfer optimization is at
109437  ** least a possibility, though it might only work if the destination
109438  ** table (tab1) is initially empty.
109439  */
109440 #ifdef SQLITE_TEST
109441  sqlite3_xferopt_count++;
109442 #endif
109443  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
109444  v = sqlite3GetVdbe(pParse);
109445  sqlite3CodeVerifySchema(pParse, iDbSrc);
109446  iSrc = pParse->nTab++;
109447  iDest = pParse->nTab++;
109448  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
109449  regData = sqlite3GetTempReg(pParse);
109450  regRowid = sqlite3GetTempReg(pParse);
109451  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
109452  assert( HasRowid(pDest) || destHasUniqueIdx );
109453  if( (db->flags & SQLITE_Vacuum)==0 && (
109454  (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
109455  || destHasUniqueIdx /* (2) */
109456  || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
109457  )){
109458  /* In some circumstances, we are able to run the xfer optimization
109459  ** only if the destination table is initially empty. Unless the
109460  ** SQLITE_Vacuum flag is set, this block generates code to make
109461  ** that determination. If SQLITE_Vacuum is set, then the destination
109462  ** table is always empty.
109463  **
109464  ** Conditions under which the destination must be empty:
109465  **
109466  ** (1) There is no INTEGER PRIMARY KEY but there are indices.
109467  ** (If the destination is not initially empty, the rowid fields
109468  ** of index entries might need to change.)
109469  **
109470  ** (2) The destination has a unique index. (The xfer optimization
109471  ** is unable to test uniqueness.)
109472  **
109473  ** (3) onError is something other than OE_Abort and OE_Rollback.
109474  */
109475  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
109476  emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
109477  sqlite3VdbeJumpHere(v, addr1);
109478  }
109479  if( HasRowid(pSrc) ){
109480  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
109481  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
109482  if( pDest->iPKey>=0 ){
109483  addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
109484  addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
109485  VdbeCoverage(v);
109486  sqlite3RowidConstraint(pParse, onError, pDest);
109487  sqlite3VdbeJumpHere(v, addr2);
109488  autoIncStep(pParse, regAutoinc, regRowid);
109489  }else if( pDest->pIndex==0 ){
109490  addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
109491  }else{
109492  addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
109493  assert( (pDest->tabFlags & TF_Autoincrement)==0 );
109494  }
109495  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
109496  sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
109497  (char*)pDest, P4_TABLE);
109498  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
109499  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
109500  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
109501  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
109502  }else{
109503  sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
109504  sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
109505  }
109506  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
109507  u8 idxInsFlags = 0;
109508  for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
109509  if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
109510  }
109511  assert( pSrcIdx );
109512  sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
109513  sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
109514  VdbeComment((v, "%s", pSrcIdx->zName));
109515  sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
109516  sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
109517  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
109518  VdbeComment((v, "%s", pDestIdx->zName));
109519  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
109520  sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
109521  if( db->flags & SQLITE_Vacuum ){
109522  /* This INSERT command is part of a VACUUM operation, which guarantees
109523  ** that the destination table is empty. If all indexed columns use
109524  ** collation sequence BINARY, then it can also be assumed that the
109525  ** index will be populated by inserting keys in strictly sorted
109526  ** order. In this case, instead of seeking within the b-tree as part
109527  ** of every OP_IdxInsert opcode, an OP_Last is added before the
109528  ** OP_IdxInsert to seek to the point within the b-tree where each key
109529  ** should be inserted. This is faster.
109530  **
109531  ** If any of the indexed columns use a collation sequence other than
109532  ** BINARY, this optimization is disabled. This is because the user
109533  ** might change the definition of a collation sequence and then run
109534  ** a VACUUM command. In that case keys may not be written in strictly
109535  ** sorted order. */
109536  for(i=0; i<pSrcIdx->nColumn; i++){
109537  const char *zColl = pSrcIdx->azColl[i];
109538  assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
109539  || sqlite3StrBINARY==zColl );
109540  if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
109541  }
109542  if( i==pSrcIdx->nColumn ){
109543  idxInsFlags = OPFLAG_USESEEKRESULT;
109544  sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
109545  }
109546  }
109547  if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
109548  idxInsFlags |= OPFLAG_NCHANGE;
109549  }
109550  sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
109551  sqlite3VdbeChangeP5(v, idxInsFlags);
109552  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
109553  sqlite3VdbeJumpHere(v, addr1);
109554  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
109555  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
109556  }
109557  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
109558  sqlite3ReleaseTempReg(pParse, regRowid);
109559  sqlite3ReleaseTempReg(pParse, regData);
109560  if( emptyDestTest ){
109561  sqlite3AutoincrementEnd(pParse);
109562  sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
109563  sqlite3VdbeJumpHere(v, emptyDestTest);
109564  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
109565  return 0;
109566  }else{
109567  return 1;
109568  }
109569 }
109570 #endif /* SQLITE_OMIT_XFER_OPT */
109571 
109572 /************** End of insert.c **********************************************/
109573 /************** Begin file legacy.c ******************************************/
109574 /*
109575 ** 2001 September 15
109576 **
109577 ** The author disclaims copyright to this source code. In place of
109578 ** a legal notice, here is a blessing:
109579 **
109580 ** May you do good and not evil.
109581 ** May you find forgiveness for yourself and forgive others.
109582 ** May you share freely, never taking more than you give.
109583 **
109584 *************************************************************************
109585 ** Main file for the SQLite library. The routines in this file
109586 ** implement the programmer interface to the library. Routines in
109587 ** other files are for internal use by SQLite and should not be
109588 ** accessed by users of the library.
109589 */
109590 
109591 /* #include "sqliteInt.h" */
109592 
109593 /*
109594 ** Execute SQL code. Return one of the SQLITE_ success/failure
109595 ** codes. Also write an error message into memory obtained from
109596 ** malloc() and make *pzErrMsg point to that message.
109597 **
109598 ** If the SQL is a query, then for each row in the query result
109599 ** the xCallback() function is called. pArg becomes the first
109600 ** argument to xCallback(). If xCallback=NULL then no callback
109601 ** is invoked, even for queries.
109602 */
109603 SQLITE_API int sqlite3_exec(
109604  sqlite3 *db, /* The database on which the SQL executes */
109605  const char *zSql, /* The SQL to be executed */
109606  sqlite3_callback xCallback, /* Invoke this callback routine */
109607  void *pArg, /* First argument to xCallback() */
109608  char **pzErrMsg /* Write error messages here */
109609 ){
109610  int rc = SQLITE_OK; /* Return code */
109611  const char *zLeftover; /* Tail of unprocessed SQL */
109612  sqlite3_stmt *pStmt = 0; /* The current SQL statement */
109613  char **azCols = 0; /* Names of result columns */
109614  int callbackIsInit; /* True if callback data is initialized */
109615 
109616  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
109617  if( zSql==0 ) zSql = "";
109618 
109619  sqlite3_mutex_enter(db->mutex);
109620  sqlite3Error(db, SQLITE_OK);
109621  while( rc==SQLITE_OK && zSql[0] ){
109622  int nCol;
109623  char **azVals = 0;
109624 
109625  pStmt = 0;
109626  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
109627  assert( rc==SQLITE_OK || pStmt==0 );
109628  if( rc!=SQLITE_OK ){
109629  continue;
109630  }
109631  if( !pStmt ){
109632  /* this happens for a comment or white-space */
109633  zSql = zLeftover;
109634  continue;
109635  }
109636 
109637  callbackIsInit = 0;
109638  nCol = sqlite3_column_count(pStmt);
109639 
109640  while( 1 ){
109641  int i;
109642  rc = sqlite3_step(pStmt);
109643 
109644  /* Invoke the callback function if required */
109645  if( xCallback && (SQLITE_ROW==rc ||
109646  (SQLITE_DONE==rc && !callbackIsInit
109647  && db->flags&SQLITE_NullCallback)) ){
109648  if( !callbackIsInit ){
109649  azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
109650  if( azCols==0 ){
109651  goto exec_out;
109652  }
109653  for(i=0; i<nCol; i++){
109654  azCols[i] = (char *)sqlite3_column_name(pStmt, i);
109655  /* sqlite3VdbeSetColName() installs column names as UTF8
109656  ** strings so there is no way for sqlite3_column_name() to fail. */
109657  assert( azCols[i]!=0 );
109658  }
109659  callbackIsInit = 1;
109660  }
109661  if( rc==SQLITE_ROW ){
109662  azVals = &azCols[nCol];
109663  for(i=0; i<nCol; i++){
109664  azVals[i] = (char *)sqlite3_column_text(pStmt, i);
109665  if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
109666  sqlite3OomFault(db);
109667  goto exec_out;
109668  }
109669  }
109670  }
109671  if( xCallback(pArg, nCol, azVals, azCols) ){
109672  /* EVIDENCE-OF: R-38229-40159 If the callback function to
109673  ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
109674  ** return SQLITE_ABORT. */
109675  rc = SQLITE_ABORT;
109676  sqlite3VdbeFinalize((Vdbe *)pStmt);
109677  pStmt = 0;
109678  sqlite3Error(db, SQLITE_ABORT);
109679  goto exec_out;
109680  }
109681  }
109682 
109683  if( rc!=SQLITE_ROW ){
109684  rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
109685  pStmt = 0;
109686  zSql = zLeftover;
109687  while( sqlite3Isspace(zSql[0]) ) zSql++;
109688  break;
109689  }
109690  }
109691 
109692  sqlite3DbFree(db, azCols);
109693  azCols = 0;
109694  }
109695 
109696 exec_out:
109697  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
109698  sqlite3DbFree(db, azCols);
109699 
109700  rc = sqlite3ApiExit(db, rc);
109701  if( rc!=SQLITE_OK && pzErrMsg ){
109702  int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
109703  *pzErrMsg = sqlite3Malloc(nErrMsg);
109704  if( *pzErrMsg ){
109705  memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
109706  }else{
109707  rc = SQLITE_NOMEM_BKPT;
109708  sqlite3Error(db, SQLITE_NOMEM);
109709  }
109710  }else if( pzErrMsg ){
109711  *pzErrMsg = 0;
109712  }
109713 
109714  assert( (rc&db->errMask)==rc );
109715  sqlite3_mutex_leave(db->mutex);
109716  return rc;
109717 }
109718 
109719 /************** End of legacy.c **********************************************/
109720 /************** Begin file loadext.c *****************************************/
109721 /*
109722 ** 2006 June 7
109723 **
109724 ** The author disclaims copyright to this source code. In place of
109725 ** a legal notice, here is a blessing:
109726 **
109727 ** May you do good and not evil.
109728 ** May you find forgiveness for yourself and forgive others.
109729 ** May you share freely, never taking more than you give.
109730 **
109731 *************************************************************************
109732 ** This file contains code used to dynamically load extensions into
109733 ** the SQLite library.
109734 */
109735 
109736 #ifndef SQLITE_CORE
109737  #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
109738 #endif
109739 /************** Include sqlite3ext.h in the middle of loadext.c **************/
109740 /************** Begin file sqlite3ext.h **************************************/
109741 /*
109742 ** 2006 June 7
109743 **
109744 ** The author disclaims copyright to this source code. In place of
109745 ** a legal notice, here is a blessing:
109746 **
109747 ** May you do good and not evil.
109748 ** May you find forgiveness for yourself and forgive others.
109749 ** May you share freely, never taking more than you give.
109750 **
109751 *************************************************************************
109752 ** This header file defines the SQLite interface for use by
109753 ** shared libraries that want to be imported as extensions into
109754 ** an SQLite instance. Shared libraries that intend to be loaded
109755 ** as extensions by SQLite should #include this file instead of
109756 ** sqlite3.h.
109757 */
109758 #ifndef SQLITE3EXT_H
109759 #define SQLITE3EXT_H
109760 /* #include "sqlite3.h" */
109761 
109762 /*
109763 ** The following structure holds pointers to all of the SQLite API
109764 ** routines.
109765 **
109766 ** WARNING: In order to maintain backwards compatibility, add new
109767 ** interfaces to the end of this structure only. If you insert new
109768 ** interfaces in the middle of this structure, then older different
109769 ** versions of SQLite will not be able to load each other's shared
109770 ** libraries!
109771 */
109773  void * (*aggregate_context)(sqlite3_context*,int nBytes);
109774  int (*aggregate_count)(sqlite3_context*);
109775  int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
109776  int (*bind_double)(sqlite3_stmt*,int,double);
109777  int (*bind_int)(sqlite3_stmt*,int,int);
109778  int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
109779  int (*bind_null)(sqlite3_stmt*,int);
109780  int (*bind_parameter_count)(sqlite3_stmt*);
109781  int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
109782  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
109783  int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
109784  int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
109785  int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
109786  int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
109787  int (*busy_timeout)(sqlite3*,int ms);
109788  int (*changes)(sqlite3*);
109789  int (*close)(sqlite3*);
109790  int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
109791  int eTextRep,const char*));
109792  int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
109793  int eTextRep,const void*));
109794  const void * (*column_blob)(sqlite3_stmt*,int iCol);
109795  int (*column_bytes)(sqlite3_stmt*,int iCol);
109796  int (*column_bytes16)(sqlite3_stmt*,int iCol);
109797  int (*column_count)(sqlite3_stmt*pStmt);
109798  const char * (*column_database_name)(sqlite3_stmt*,int);
109799  const void * (*column_database_name16)(sqlite3_stmt*,int);
109800  const char * (*column_decltype)(sqlite3_stmt*,int i);
109801  const void * (*column_decltype16)(sqlite3_stmt*,int);
109802  double (*column_double)(sqlite3_stmt*,int iCol);
109803  int (*column_int)(sqlite3_stmt*,int iCol);
109804  sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
109805  const char * (*column_name)(sqlite3_stmt*,int);
109806  const void * (*column_name16)(sqlite3_stmt*,int);
109807  const char * (*column_origin_name)(sqlite3_stmt*,int);
109808  const void * (*column_origin_name16)(sqlite3_stmt*,int);
109809  const char * (*column_table_name)(sqlite3_stmt*,int);
109810  const void * (*column_table_name16)(sqlite3_stmt*,int);
109811  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
109812  const void * (*column_text16)(sqlite3_stmt*,int iCol);
109813  int (*column_type)(sqlite3_stmt*,int iCol);
109814  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
109815  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
109816  int (*complete)(const char*sql);
109817  int (*complete16)(const void*sql);
109818  int (*create_collation)(sqlite3*,const char*,int,void*,
109819  int(*)(void*,int,const void*,int,const void*));
109820  int (*create_collation16)(sqlite3*,const void*,int,void*,
109821  int(*)(void*,int,const void*,int,const void*));
109822  int (*create_function)(sqlite3*,const char*,int,int,void*,
109823  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109824  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109825  void (*xFinal)(sqlite3_context*));
109826  int (*create_function16)(sqlite3*,const void*,int,int,void*,
109827  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109828  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109829  void (*xFinal)(sqlite3_context*));
109830  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
109831  int (*data_count)(sqlite3_stmt*pStmt);
109832  sqlite3 * (*db_handle)(sqlite3_stmt*);
109833  int (*declare_vtab)(sqlite3*,const char*);
109834  int (*enable_shared_cache)(int);
109835  int (*errcode)(sqlite3*db);
109836  const char * (*errmsg)(sqlite3*);
109837  const void * (*errmsg16)(sqlite3*);
109838  int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
109839  int (*expired)(sqlite3_stmt*);
109840  int (*finalize)(sqlite3_stmt*pStmt);
109841  void (*free)(void*);
109842  void (*free_table)(char**result);
109843  int (*get_autocommit)(sqlite3*);
109844  void * (*get_auxdata)(sqlite3_context*,int);
109845  int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
109846  int (*global_recover)(void);
109847  void (*interruptx)(sqlite3*);
109848  sqlite_int64 (*last_insert_rowid)(sqlite3*);
109849  const char * (*libversion)(void);
109850  int (*libversion_number)(void);
109851  void *(*malloc)(int);
109852  char * (*mprintf)(const char*,...);
109853  int (*open)(const char*,sqlite3**);
109854  int (*open16)(const void*,sqlite3**);
109855  int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
109856  int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
109857  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
109858  void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
109859  void *(*realloc)(void*,int);
109860  int (*reset)(sqlite3_stmt*pStmt);
109861  void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
109862  void (*result_double)(sqlite3_context*,double);
109863  void (*result_error)(sqlite3_context*,const char*,int);
109864  void (*result_error16)(sqlite3_context*,const void*,int);
109865  void (*result_int)(sqlite3_context*,int);
109866  void (*result_int64)(sqlite3_context*,sqlite_int64);
109867  void (*result_null)(sqlite3_context*);
109868  void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
109869  void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
109870  void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
109871  void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
109872  void (*result_value)(sqlite3_context*,sqlite3_value*);
109873  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
109874  int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
109875  const char*,const char*),void*);
109876  void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
109877  char * (*snprintf)(int,char*,const char*,...);
109878  int (*step)(sqlite3_stmt*);
109879  int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
109880  char const**,char const**,int*,int*,int*);
109881  void (*thread_cleanup)(void);
109882  int (*total_changes)(sqlite3*);
109883  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
109884  int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
109885  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
109886  sqlite_int64),void*);
109887  void * (*user_data)(sqlite3_context*);
109888  const void * (*value_blob)(sqlite3_value*);
109889  int (*value_bytes)(sqlite3_value*);
109890  int (*value_bytes16)(sqlite3_value*);
109891  double (*value_double)(sqlite3_value*);
109892  int (*value_int)(sqlite3_value*);
109893  sqlite_int64 (*value_int64)(sqlite3_value*);
109894  int (*value_numeric_type)(sqlite3_value*);
109895  const unsigned char * (*value_text)(sqlite3_value*);
109896  const void * (*value_text16)(sqlite3_value*);
109897  const void * (*value_text16be)(sqlite3_value*);
109898  const void * (*value_text16le)(sqlite3_value*);
109899  int (*value_type)(sqlite3_value*);
109900  char *(*vmprintf)(const char*,va_list);
109901  /* Added ??? */
109902  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
109903  /* Added by 3.3.13 */
109904  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
109905  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
109906  int (*clear_bindings)(sqlite3_stmt*);
109907  /* Added by 3.4.1 */
109908  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
109909  void (*xDestroy)(void *));
109910  /* Added by 3.5.0 */
109911  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
109912  int (*blob_bytes)(sqlite3_blob*);
109913  int (*blob_close)(sqlite3_blob*);
109914  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
109915  int,sqlite3_blob**);
109916  int (*blob_read)(sqlite3_blob*,void*,int,int);
109917  int (*blob_write)(sqlite3_blob*,const void*,int,int);
109918  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
109919  int(*)(void*,int,const void*,int,const void*),
109920  void(*)(void*));
109921  int (*file_control)(sqlite3*,const char*,int,void*);
109922  sqlite3_int64 (*memory_highwater)(int);
109923  sqlite3_int64 (*memory_used)(void);
109924  sqlite3_mutex *(*mutex_alloc)(int);
109925  void (*mutex_enter)(sqlite3_mutex*);
109926  void (*mutex_free)(sqlite3_mutex*);
109927  void (*mutex_leave)(sqlite3_mutex*);
109928  int (*mutex_try)(sqlite3_mutex*);
109929  int (*open_v2)(const char*,sqlite3**,int,const char*);
109930  int (*release_memory)(int);
109931  void (*result_error_nomem)(sqlite3_context*);
109932  void (*result_error_toobig)(sqlite3_context*);
109933  int (*sleep)(int);
109934  void (*soft_heap_limit)(int);
109935  sqlite3_vfs *(*vfs_find)(const char*);
109936  int (*vfs_register)(sqlite3_vfs*,int);
109937  int (*vfs_unregister)(sqlite3_vfs*);
109938  int (*xthreadsafe)(void);
109939  void (*result_zeroblob)(sqlite3_context*,int);
109940  void (*result_error_code)(sqlite3_context*,int);
109941  int (*test_control)(int, ...);
109942  void (*randomness)(int,void*);
109943  sqlite3 *(*context_db_handle)(sqlite3_context*);
109944  int (*extended_result_codes)(sqlite3*,int);
109945  int (*limit)(sqlite3*,int,int);
109946  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
109947  const char *(*sql)(sqlite3_stmt*);
109948  int (*status)(int,int*,int*,int);
109949  int (*backup_finish)(sqlite3_backup*);
109950  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
109951  int (*backup_pagecount)(sqlite3_backup*);
109952  int (*backup_remaining)(sqlite3_backup*);
109953  int (*backup_step)(sqlite3_backup*,int);
109954  const char *(*compileoption_get)(int);
109955  int (*compileoption_used)(const char*);
109956  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
109957  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109958  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109959  void (*xFinal)(sqlite3_context*),
109960  void(*xDestroy)(void*));
109961  int (*db_config)(sqlite3*,int,...);
109962  sqlite3_mutex *(*db_mutex)(sqlite3*);
109963  int (*db_status)(sqlite3*,int,int*,int*,int);
109964  int (*extended_errcode)(sqlite3*);
109965  void (*log)(int,const char*,...);
109966  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
109967  const char *(*sourceid)(void);
109968  int (*stmt_status)(sqlite3_stmt*,int,int);
109969  int (*strnicmp)(const char*,const char*,int);
109970  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
109971  int (*wal_autocheckpoint)(sqlite3*,int);
109972  int (*wal_checkpoint)(sqlite3*,const char*);
109973  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
109974  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
109975  int (*vtab_config)(sqlite3*,int op,...);
109976  int (*vtab_on_conflict)(sqlite3*);
109977  /* Version 3.7.16 and later */
109978  int (*close_v2)(sqlite3*);
109979  const char *(*db_filename)(sqlite3*,const char*);
109980  int (*db_readonly)(sqlite3*,const char*);
109981  int (*db_release_memory)(sqlite3*);
109982  const char *(*errstr)(int);
109983  int (*stmt_busy)(sqlite3_stmt*);
109984  int (*stmt_readonly)(sqlite3_stmt*);
109985  int (*stricmp)(const char*,const char*);
109986  int (*uri_boolean)(const char*,const char*,int);
109987  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
109988  const char *(*uri_parameter)(const char*,const char*);
109989  char *(*vsnprintf)(int,char*,const char*,va_list);
109990  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
109991  /* Version 3.8.7 and later */
109992  int (*auto_extension)(void(*)(void));
109993  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
109994  void(*)(void*));
109995  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
109996  void(*)(void*),unsigned char);
109997  int (*cancel_auto_extension)(void(*)(void));
109998  int (*load_extension)(sqlite3*,const char*,const char*,char**);
109999  void *(*malloc64)(sqlite3_uint64);
110000  sqlite3_uint64 (*msize)(void*);
110001  void *(*realloc64)(void*,sqlite3_uint64);
110002  void (*reset_auto_extension)(void);
110003  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
110004  void(*)(void*));
110005  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
110006  void(*)(void*), unsigned char);
110007  int (*strglob)(const char*,const char*);
110008  /* Version 3.8.11 and later */
110009  sqlite3_value *(*value_dup)(const sqlite3_value*);
110010  void (*value_free)(sqlite3_value*);
110011  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
110012  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
110013  /* Version 3.9.0 and later */
110014  unsigned int (*value_subtype)(sqlite3_value*);
110015  void (*result_subtype)(sqlite3_context*,unsigned int);
110016  /* Version 3.10.0 and later */
110017  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
110018  int (*strlike)(const char*,const char*,unsigned int);
110019  int (*db_cacheflush)(sqlite3*);
110020  /* Version 3.12.0 and later */
110021  int (*system_errno)(sqlite3*);
110022  /* Version 3.14.0 and later */
110023  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
110024  char *(*expanded_sql)(sqlite3_stmt*);
110025 };
110026 
110027 /*
110028 ** This is the function signature used for all extension entry points. It
110029 ** is also defined in the file "loadext.c".
110030 */
110031 typedef int (*sqlite3_loadext_entry)(
110032  sqlite3 *db, /* Handle to the database. */
110033  char **pzErrMsg, /* Used to set error string on failure. */
110034  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
110035 );
110036 
110037 /*
110038 ** The following macros redefine the API routines so that they are
110039 ** redirected through the global sqlite3_api structure.
110040 **
110041 ** This header file is also used by the loadext.c source file
110042 ** (part of the main SQLite library - not an extension) so that
110043 ** it can get access to the sqlite3_api_routines structure
110044 ** definition. But the main library does not want to redefine
110045 ** the API. So the redefinition macros are only valid if the
110046 ** SQLITE_CORE macros is undefined.
110047 */
110048 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
110049 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
110050 #ifndef SQLITE_OMIT_DEPRECATED
110051 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
110052 #endif
110053 #define sqlite3_bind_blob sqlite3_api->bind_blob
110054 #define sqlite3_bind_double sqlite3_api->bind_double
110055 #define sqlite3_bind_int sqlite3_api->bind_int
110056 #define sqlite3_bind_int64 sqlite3_api->bind_int64
110057 #define sqlite3_bind_null sqlite3_api->bind_null
110058 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
110059 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
110060 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
110061 #define sqlite3_bind_text sqlite3_api->bind_text
110062 #define sqlite3_bind_text16 sqlite3_api->bind_text16
110063 #define sqlite3_bind_value sqlite3_api->bind_value
110064 #define sqlite3_busy_handler sqlite3_api->busy_handler
110065 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
110066 #define sqlite3_changes sqlite3_api->changes
110067 #define sqlite3_close sqlite3_api->close
110068 #define sqlite3_collation_needed sqlite3_api->collation_needed
110069 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
110070 #define sqlite3_column_blob sqlite3_api->column_blob
110071 #define sqlite3_column_bytes sqlite3_api->column_bytes
110072 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
110073 #define sqlite3_column_count sqlite3_api->column_count
110074 #define sqlite3_column_database_name sqlite3_api->column_database_name
110075 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
110076 #define sqlite3_column_decltype sqlite3_api->column_decltype
110077 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
110078 #define sqlite3_column_double sqlite3_api->column_double
110079 #define sqlite3_column_int sqlite3_api->column_int
110080 #define sqlite3_column_int64 sqlite3_api->column_int64
110081 #define sqlite3_column_name sqlite3_api->column_name
110082 #define sqlite3_column_name16 sqlite3_api->column_name16
110083 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
110084 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
110085 #define sqlite3_column_table_name sqlite3_api->column_table_name
110086 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
110087 #define sqlite3_column_text sqlite3_api->column_text
110088 #define sqlite3_column_text16 sqlite3_api->column_text16
110089 #define sqlite3_column_type sqlite3_api->column_type
110090 #define sqlite3_column_value sqlite3_api->column_value
110091 #define sqlite3_commit_hook sqlite3_api->commit_hook
110092 #define sqlite3_complete sqlite3_api->complete
110093 #define sqlite3_complete16 sqlite3_api->complete16
110094 #define sqlite3_create_collation sqlite3_api->create_collation
110095 #define sqlite3_create_collation16 sqlite3_api->create_collation16
110096 #define sqlite3_create_function sqlite3_api->create_function
110097 #define sqlite3_create_function16 sqlite3_api->create_function16
110098 #define sqlite3_create_module sqlite3_api->create_module
110099 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
110100 #define sqlite3_data_count sqlite3_api->data_count
110101 #define sqlite3_db_handle sqlite3_api->db_handle
110102 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
110103 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
110104 #define sqlite3_errcode sqlite3_api->errcode
110105 #define sqlite3_errmsg sqlite3_api->errmsg
110106 #define sqlite3_errmsg16 sqlite3_api->errmsg16
110107 #define sqlite3_exec sqlite3_api->exec
110108 #ifndef SQLITE_OMIT_DEPRECATED
110109 #define sqlite3_expired sqlite3_api->expired
110110 #endif
110111 #define sqlite3_finalize sqlite3_api->finalize
110112 #define sqlite3_free sqlite3_api->free
110113 #define sqlite3_free_table sqlite3_api->free_table
110114 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
110115 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
110116 #define sqlite3_get_table sqlite3_api->get_table
110117 #ifndef SQLITE_OMIT_DEPRECATED
110118 #define sqlite3_global_recover sqlite3_api->global_recover
110119 #endif
110120 #define sqlite3_interrupt sqlite3_api->interruptx
110121 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
110122 #define sqlite3_libversion sqlite3_api->libversion
110123 #define sqlite3_libversion_number sqlite3_api->libversion_number
110124 #define sqlite3_malloc sqlite3_api->malloc
110125 #define sqlite3_mprintf sqlite3_api->mprintf
110126 #define sqlite3_open sqlite3_api->open
110127 #define sqlite3_open16 sqlite3_api->open16
110128 #define sqlite3_prepare sqlite3_api->prepare
110129 #define sqlite3_prepare16 sqlite3_api->prepare16
110130 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
110131 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
110132 #define sqlite3_profile sqlite3_api->profile
110133 #define sqlite3_progress_handler sqlite3_api->progress_handler
110134 #define sqlite3_realloc sqlite3_api->realloc
110135 #define sqlite3_reset sqlite3_api->reset
110136 #define sqlite3_result_blob sqlite3_api->result_blob
110137 #define sqlite3_result_double sqlite3_api->result_double
110138 #define sqlite3_result_error sqlite3_api->result_error
110139 #define sqlite3_result_error16 sqlite3_api->result_error16
110140 #define sqlite3_result_int sqlite3_api->result_int
110141 #define sqlite3_result_int64 sqlite3_api->result_int64
110142 #define sqlite3_result_null sqlite3_api->result_null
110143 #define sqlite3_result_text sqlite3_api->result_text
110144 #define sqlite3_result_text16 sqlite3_api->result_text16
110145 #define sqlite3_result_text16be sqlite3_api->result_text16be
110146 #define sqlite3_result_text16le sqlite3_api->result_text16le
110147 #define sqlite3_result_value sqlite3_api->result_value
110148 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
110149 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
110150 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
110151 #define sqlite3_snprintf sqlite3_api->snprintf
110152 #define sqlite3_step sqlite3_api->step
110153 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
110154 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
110155 #define sqlite3_total_changes sqlite3_api->total_changes
110156 #define sqlite3_trace sqlite3_api->trace
110157 #ifndef SQLITE_OMIT_DEPRECATED
110158 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
110159 #endif
110160 #define sqlite3_update_hook sqlite3_api->update_hook
110161 #define sqlite3_user_data sqlite3_api->user_data
110162 #define sqlite3_value_blob sqlite3_api->value_blob
110163 #define sqlite3_value_bytes sqlite3_api->value_bytes
110164 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
110165 #define sqlite3_value_double sqlite3_api->value_double
110166 #define sqlite3_value_int sqlite3_api->value_int
110167 #define sqlite3_value_int64 sqlite3_api->value_int64
110168 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
110169 #define sqlite3_value_text sqlite3_api->value_text
110170 #define sqlite3_value_text16 sqlite3_api->value_text16
110171 #define sqlite3_value_text16be sqlite3_api->value_text16be
110172 #define sqlite3_value_text16le sqlite3_api->value_text16le
110173 #define sqlite3_value_type sqlite3_api->value_type
110174 #define sqlite3_vmprintf sqlite3_api->vmprintf
110175 #define sqlite3_vsnprintf sqlite3_api->vsnprintf
110176 #define sqlite3_overload_function sqlite3_api->overload_function
110177 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
110178 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
110179 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
110180 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
110181 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
110182 #define sqlite3_blob_close sqlite3_api->blob_close
110183 #define sqlite3_blob_open sqlite3_api->blob_open
110184 #define sqlite3_blob_read sqlite3_api->blob_read
110185 #define sqlite3_blob_write sqlite3_api->blob_write
110186 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
110187 #define sqlite3_file_control sqlite3_api->file_control
110188 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
110189 #define sqlite3_memory_used sqlite3_api->memory_used
110190 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
110191 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
110192 #define sqlite3_mutex_free sqlite3_api->mutex_free
110193 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
110194 #define sqlite3_mutex_try sqlite3_api->mutex_try
110195 #define sqlite3_open_v2 sqlite3_api->open_v2
110196 #define sqlite3_release_memory sqlite3_api->release_memory
110197 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
110198 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
110199 #define sqlite3_sleep sqlite3_api->sleep
110200 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
110201 #define sqlite3_vfs_find sqlite3_api->vfs_find
110202 #define sqlite3_vfs_register sqlite3_api->vfs_register
110203 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
110204 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
110205 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
110206 #define sqlite3_result_error_code sqlite3_api->result_error_code
110207 #define sqlite3_test_control sqlite3_api->test_control
110208 #define sqlite3_randomness sqlite3_api->randomness
110209 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
110210 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
110211 #define sqlite3_limit sqlite3_api->limit
110212 #define sqlite3_next_stmt sqlite3_api->next_stmt
110213 #define sqlite3_sql sqlite3_api->sql
110214 #define sqlite3_status sqlite3_api->status
110215 #define sqlite3_backup_finish sqlite3_api->backup_finish
110216 #define sqlite3_backup_init sqlite3_api->backup_init
110217 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
110218 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
110219 #define sqlite3_backup_step sqlite3_api->backup_step
110220 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
110221 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
110222 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
110223 #define sqlite3_db_config sqlite3_api->db_config
110224 #define sqlite3_db_mutex sqlite3_api->db_mutex
110225 #define sqlite3_db_status sqlite3_api->db_status
110226 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
110227 #define sqlite3_log sqlite3_api->log
110228 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
110229 #define sqlite3_sourceid sqlite3_api->sourceid
110230 #define sqlite3_stmt_status sqlite3_api->stmt_status
110231 #define sqlite3_strnicmp sqlite3_api->strnicmp
110232 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
110233 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
110234 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
110235 #define sqlite3_wal_hook sqlite3_api->wal_hook
110236 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
110237 #define sqlite3_vtab_config sqlite3_api->vtab_config
110238 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
110239 /* Version 3.7.16 and later */
110240 #define sqlite3_close_v2 sqlite3_api->close_v2
110241 #define sqlite3_db_filename sqlite3_api->db_filename
110242 #define sqlite3_db_readonly sqlite3_api->db_readonly
110243 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
110244 #define sqlite3_errstr sqlite3_api->errstr
110245 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
110246 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
110247 #define sqlite3_stricmp sqlite3_api->stricmp
110248 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
110249 #define sqlite3_uri_int64 sqlite3_api->uri_int64
110250 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
110251 #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
110252 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
110253 /* Version 3.8.7 and later */
110254 #define sqlite3_auto_extension sqlite3_api->auto_extension
110255 #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
110256 #define sqlite3_bind_text64 sqlite3_api->bind_text64
110257 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
110258 #define sqlite3_load_extension sqlite3_api->load_extension
110259 #define sqlite3_malloc64 sqlite3_api->malloc64
110260 #define sqlite3_msize sqlite3_api->msize
110261 #define sqlite3_realloc64 sqlite3_api->realloc64
110262 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
110263 #define sqlite3_result_blob64 sqlite3_api->result_blob64
110264 #define sqlite3_result_text64 sqlite3_api->result_text64
110265 #define sqlite3_strglob sqlite3_api->strglob
110266 /* Version 3.8.11 and later */
110267 #define sqlite3_value_dup sqlite3_api->value_dup
110268 #define sqlite3_value_free sqlite3_api->value_free
110269 #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
110270 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
110271 /* Version 3.9.0 and later */
110272 #define sqlite3_value_subtype sqlite3_api->value_subtype
110273 #define sqlite3_result_subtype sqlite3_api->result_subtype
110274 /* Version 3.10.0 and later */
110275 #define sqlite3_status64 sqlite3_api->status64
110276 #define sqlite3_strlike sqlite3_api->strlike
110277 #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
110278 /* Version 3.12.0 and later */
110279 #define sqlite3_system_errno sqlite3_api->system_errno
110280 /* Version 3.14.0 and later */
110281 #define sqlite3_trace_v2 sqlite3_api->trace_v2
110282 #define sqlite3_expanded_sql sqlite3_api->expanded_sql
110283 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
110284 
110285 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
110286  /* This case when the file really is being compiled as a loadable
110287  ** extension */
110288 # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
110289 # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
110290 # define SQLITE_EXTENSION_INIT3 \
110291  extern const sqlite3_api_routines *sqlite3_api;
110292 #else
110293  /* This case when the file is being statically linked into the
110294  ** application */
110295 # define SQLITE_EXTENSION_INIT1 /*no-op*/
110296 # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
110297 # define SQLITE_EXTENSION_INIT3 /*no-op*/
110298 #endif
110299 
110300 #endif /* SQLITE3EXT_H */
110301 
110302 /************** End of sqlite3ext.h ******************************************/
110303 /************** Continuing where we left off in loadext.c ********************/
110304 /* #include "sqliteInt.h" */
110305 /* #include <string.h> */
110306 
110307 #ifndef SQLITE_OMIT_LOAD_EXTENSION
110308 /*
110309 ** Some API routines are omitted when various features are
110310 ** excluded from a build of SQLite. Substitute a NULL pointer
110311 ** for any missing APIs.
110312 */
110313 #ifndef SQLITE_ENABLE_COLUMN_METADATA
110314 # define sqlite3_column_database_name 0
110315 # define sqlite3_column_database_name16 0
110316 # define sqlite3_column_table_name 0
110317 # define sqlite3_column_table_name16 0
110318 # define sqlite3_column_origin_name 0
110319 # define sqlite3_column_origin_name16 0
110320 #endif
110321 
110322 #ifdef SQLITE_OMIT_AUTHORIZATION
110323 # define sqlite3_set_authorizer 0
110324 #endif
110325 
110326 #ifdef SQLITE_OMIT_UTF16
110327 # define sqlite3_bind_text16 0
110328 # define sqlite3_collation_needed16 0
110329 # define sqlite3_column_decltype16 0
110330 # define sqlite3_column_name16 0
110331 # define sqlite3_column_text16 0
110332 # define sqlite3_complete16 0
110333 # define sqlite3_create_collation16 0
110334 # define sqlite3_create_function16 0
110335 # define sqlite3_errmsg16 0
110336 # define sqlite3_open16 0
110337 # define sqlite3_prepare16 0
110338 # define sqlite3_prepare16_v2 0
110339 # define sqlite3_result_error16 0
110340 # define sqlite3_result_text16 0
110341 # define sqlite3_result_text16be 0
110342 # define sqlite3_result_text16le 0
110343 # define sqlite3_value_text16 0
110344 # define sqlite3_value_text16be 0
110345 # define sqlite3_value_text16le 0
110346 # define sqlite3_column_database_name16 0
110347 # define sqlite3_column_table_name16 0
110348 # define sqlite3_column_origin_name16 0
110349 #endif
110350 
110351 #ifdef SQLITE_OMIT_COMPLETE
110352 # define sqlite3_complete 0
110353 # define sqlite3_complete16 0
110354 #endif
110355 
110356 #ifdef SQLITE_OMIT_DECLTYPE
110357 # define sqlite3_column_decltype16 0
110358 # define sqlite3_column_decltype 0
110359 #endif
110360 
110361 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
110362 # define sqlite3_progress_handler 0
110363 #endif
110364 
110365 #ifdef SQLITE_OMIT_VIRTUALTABLE
110366 # define sqlite3_create_module 0
110367 # define sqlite3_create_module_v2 0
110368 # define sqlite3_declare_vtab 0
110369 # define sqlite3_vtab_config 0
110370 # define sqlite3_vtab_on_conflict 0
110371 #endif
110372 
110373 #ifdef SQLITE_OMIT_SHARED_CACHE
110374 # define sqlite3_enable_shared_cache 0
110375 #endif
110376 
110377 #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
110378 # define sqlite3_profile 0
110379 # define sqlite3_trace 0
110380 #endif
110381 
110382 #ifdef SQLITE_OMIT_GET_TABLE
110383 # define sqlite3_free_table 0
110384 # define sqlite3_get_table 0
110385 #endif
110386 
110387 #ifdef SQLITE_OMIT_INCRBLOB
110388 #define sqlite3_bind_zeroblob 0
110389 #define sqlite3_blob_bytes 0
110390 #define sqlite3_blob_close 0
110391 #define sqlite3_blob_open 0
110392 #define sqlite3_blob_read 0
110393 #define sqlite3_blob_write 0
110394 #define sqlite3_blob_reopen 0
110395 #endif
110396 
110397 #if defined(SQLITE_OMIT_TRACE)
110398 # define sqlite3_trace_v2 0
110399 #endif
110400 
110401 /*
110402 ** The following structure contains pointers to all SQLite API routines.
110403 ** A pointer to this structure is passed into extensions when they are
110404 ** loaded so that the extension can make calls back into the SQLite
110405 ** library.
110406 **
110407 ** When adding new APIs, add them to the bottom of this structure
110408 ** in order to preserve backwards compatibility.
110409 **
110410 ** Extensions that use newer APIs should first call the
110411 ** sqlite3_libversion_number() to make sure that the API they
110412 ** intend to use is supported by the library. Extensions should
110413 ** also check to make sure that the pointer to the function is
110414 ** not NULL before calling it.
110415 */
110416 static const sqlite3_api_routines sqlite3Apis = {
110417  sqlite3_aggregate_context,
110418 #ifndef SQLITE_OMIT_DEPRECATED
110419  sqlite3_aggregate_count,
110420 #else
110421  0,
110422 #endif
110423  sqlite3_bind_blob,
110424  sqlite3_bind_double,
110425  sqlite3_bind_int,
110426  sqlite3_bind_int64,
110427  sqlite3_bind_null,
110428  sqlite3_bind_parameter_count,
110429  sqlite3_bind_parameter_index,
110430  sqlite3_bind_parameter_name,
110431  sqlite3_bind_text,
110432  sqlite3_bind_text16,
110433  sqlite3_bind_value,
110434  sqlite3_busy_handler,
110435  sqlite3_busy_timeout,
110436  sqlite3_changes,
110437  sqlite3_close,
110438  sqlite3_collation_needed,
110439  sqlite3_collation_needed16,
110440  sqlite3_column_blob,
110441  sqlite3_column_bytes,
110442  sqlite3_column_bytes16,
110443  sqlite3_column_count,
110444  sqlite3_column_database_name,
110445  sqlite3_column_database_name16,
110446  sqlite3_column_decltype,
110447  sqlite3_column_decltype16,
110448  sqlite3_column_double,
110449  sqlite3_column_int,
110450  sqlite3_column_int64,
110451  sqlite3_column_name,
110452  sqlite3_column_name16,
110453  sqlite3_column_origin_name,
110454  sqlite3_column_origin_name16,
110455  sqlite3_column_table_name,
110456  sqlite3_column_table_name16,
110457  sqlite3_column_text,
110458  sqlite3_column_text16,
110459  sqlite3_column_type,
110460  sqlite3_column_value,
110461  sqlite3_commit_hook,
110462  sqlite3_complete,
110463  sqlite3_complete16,
110464  sqlite3_create_collation,
110465  sqlite3_create_collation16,
110466  sqlite3_create_function,
110467  sqlite3_create_function16,
110468  sqlite3_create_module,
110469  sqlite3_data_count,
110470  sqlite3_db_handle,
110471  sqlite3_declare_vtab,
110472  sqlite3_enable_shared_cache,
110473  sqlite3_errcode,
110474  sqlite3_errmsg,
110475  sqlite3_errmsg16,
110476  sqlite3_exec,
110477 #ifndef SQLITE_OMIT_DEPRECATED
110478  sqlite3_expired,
110479 #else
110480  0,
110481 #endif
110482  sqlite3_finalize,
110483  sqlite3_free,
110484  sqlite3_free_table,
110485  sqlite3_get_autocommit,
110486  sqlite3_get_auxdata,
110487  sqlite3_get_table,
110488  0, /* Was sqlite3_global_recover(), but that function is deprecated */
110489  sqlite3_interrupt,
110490  sqlite3_last_insert_rowid,
110491  sqlite3_libversion,
110492  sqlite3_libversion_number,
110493  sqlite3_malloc,
110494  sqlite3_mprintf,
110495  sqlite3_open,
110496  sqlite3_open16,
110497  sqlite3_prepare,
110498  sqlite3_prepare16,
110499  sqlite3_profile,
110500  sqlite3_progress_handler,
110501  sqlite3_realloc,
110502  sqlite3_reset,
110503  sqlite3_result_blob,
110504  sqlite3_result_double,
110505  sqlite3_result_error,
110506  sqlite3_result_error16,
110507  sqlite3_result_int,
110508  sqlite3_result_int64,
110509  sqlite3_result_null,
110510  sqlite3_result_text,
110511  sqlite3_result_text16,
110512  sqlite3_result_text16be,
110513  sqlite3_result_text16le,
110514  sqlite3_result_value,
110515  sqlite3_rollback_hook,
110516  sqlite3_set_authorizer,
110517  sqlite3_set_auxdata,
110518  sqlite3_snprintf,
110519  sqlite3_step,
110520  sqlite3_table_column_metadata,
110521 #ifndef SQLITE_OMIT_DEPRECATED
110522  sqlite3_thread_cleanup,
110523 #else
110524  0,
110525 #endif
110526  sqlite3_total_changes,
110527  sqlite3_trace,
110528 #ifndef SQLITE_OMIT_DEPRECATED
110529  sqlite3_transfer_bindings,
110530 #else
110531  0,
110532 #endif
110533  sqlite3_update_hook,
110534  sqlite3_user_data,
110535  sqlite3_value_blob,
110536  sqlite3_value_bytes,
110537  sqlite3_value_bytes16,
110538  sqlite3_value_double,
110539  sqlite3_value_int,
110540  sqlite3_value_int64,
110541  sqlite3_value_numeric_type,
110542  sqlite3_value_text,
110543  sqlite3_value_text16,
110544  sqlite3_value_text16be,
110545  sqlite3_value_text16le,
110546  sqlite3_value_type,
110547  sqlite3_vmprintf,
110548  /*
110549  ** The original API set ends here. All extensions can call any
110550  ** of the APIs above provided that the pointer is not NULL. But
110551  ** before calling APIs that follow, extension should check the
110552  ** sqlite3_libversion_number() to make sure they are dealing with
110553  ** a library that is new enough to support that API.
110554  *************************************************************************
110555  */
110556  sqlite3_overload_function,
110557 
110558  /*
110559  ** Added after 3.3.13
110560  */
110561  sqlite3_prepare_v2,
110562  sqlite3_prepare16_v2,
110563  sqlite3_clear_bindings,
110564 
110565  /*
110566  ** Added for 3.4.1
110567  */
110568  sqlite3_create_module_v2,
110569 
110570  /*
110571  ** Added for 3.5.0
110572  */
110573  sqlite3_bind_zeroblob,
110574  sqlite3_blob_bytes,
110575  sqlite3_blob_close,
110576  sqlite3_blob_open,
110577  sqlite3_blob_read,
110578  sqlite3_blob_write,
110579  sqlite3_create_collation_v2,
110580  sqlite3_file_control,
110581  sqlite3_memory_highwater,
110582  sqlite3_memory_used,
110583 #ifdef SQLITE_MUTEX_OMIT
110584  0,
110585  0,
110586  0,
110587  0,
110588  0,
110589 #else
110590  sqlite3_mutex_alloc,
110591  sqlite3_mutex_enter,
110592  sqlite3_mutex_free,
110593  sqlite3_mutex_leave,
110594  sqlite3_mutex_try,
110595 #endif
110596  sqlite3_open_v2,
110597  sqlite3_release_memory,
110598  sqlite3_result_error_nomem,
110599  sqlite3_result_error_toobig,
110600  sqlite3_sleep,
110601  sqlite3_soft_heap_limit,
110602  sqlite3_vfs_find,
110603  sqlite3_vfs_register,
110604  sqlite3_vfs_unregister,
110605 
110606  /*
110607  ** Added for 3.5.8
110608  */
110609  sqlite3_threadsafe,
110610  sqlite3_result_zeroblob,
110611  sqlite3_result_error_code,
110612  sqlite3_test_control,
110613  sqlite3_randomness,
110614  sqlite3_context_db_handle,
110615 
110616  /*
110617  ** Added for 3.6.0
110618  */
110619  sqlite3_extended_result_codes,
110620  sqlite3_limit,
110621  sqlite3_next_stmt,
110622  sqlite3_sql,
110623  sqlite3_status,
110624 
110625  /*
110626  ** Added for 3.7.4
110627  */
110628  sqlite3_backup_finish,
110629  sqlite3_backup_init,
110630  sqlite3_backup_pagecount,
110631  sqlite3_backup_remaining,
110632  sqlite3_backup_step,
110633 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
110634  sqlite3_compileoption_get,
110635  sqlite3_compileoption_used,
110636 #else
110637  0,
110638  0,
110639 #endif
110640  sqlite3_create_function_v2,
110641  sqlite3_db_config,
110642  sqlite3_db_mutex,
110643  sqlite3_db_status,
110644  sqlite3_extended_errcode,
110645  sqlite3_log,
110646  sqlite3_soft_heap_limit64,
110647  sqlite3_sourceid,
110648  sqlite3_stmt_status,
110649  sqlite3_strnicmp,
110650 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
110651  sqlite3_unlock_notify,
110652 #else
110653  0,
110654 #endif
110655 #ifndef SQLITE_OMIT_WAL
110656  sqlite3_wal_autocheckpoint,
110657  sqlite3_wal_checkpoint,
110658  sqlite3_wal_hook,
110659 #else
110660  0,
110661  0,
110662  0,
110663 #endif
110664  sqlite3_blob_reopen,
110665  sqlite3_vtab_config,
110666  sqlite3_vtab_on_conflict,
110667  sqlite3_close_v2,
110668  sqlite3_db_filename,
110669  sqlite3_db_readonly,
110670  sqlite3_db_release_memory,
110671  sqlite3_errstr,
110672  sqlite3_stmt_busy,
110673  sqlite3_stmt_readonly,
110674  sqlite3_stricmp,
110675  sqlite3_uri_boolean,
110676  sqlite3_uri_int64,
110677  sqlite3_uri_parameter,
110678  sqlite3_vsnprintf,
110679  sqlite3_wal_checkpoint_v2,
110680  /* Version 3.8.7 and later */
110681  sqlite3_auto_extension,
110682  sqlite3_bind_blob64,
110683  sqlite3_bind_text64,
110684  sqlite3_cancel_auto_extension,
110685  sqlite3_load_extension,
110686  sqlite3_malloc64,
110687  sqlite3_msize,
110688  sqlite3_realloc64,
110689  sqlite3_reset_auto_extension,
110690  sqlite3_result_blob64,
110691  sqlite3_result_text64,
110692  sqlite3_strglob,
110693  /* Version 3.8.11 and later */
110694  (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
110695  sqlite3_value_free,
110696  sqlite3_result_zeroblob64,
110697  sqlite3_bind_zeroblob64,
110698  /* Version 3.9.0 and later */
110699  sqlite3_value_subtype,
110700  sqlite3_result_subtype,
110701  /* Version 3.10.0 and later */
110702  sqlite3_status64,
110703  sqlite3_strlike,
110704  sqlite3_db_cacheflush,
110705  /* Version 3.12.0 and later */
110706  sqlite3_system_errno,
110707  /* Version 3.14.0 and later */
110708  sqlite3_trace_v2,
110709  sqlite3_expanded_sql
110710 };
110711 
110712 /*
110713 ** Attempt to load an SQLite extension library contained in the file
110714 ** zFile. The entry point is zProc. zProc may be 0 in which case a
110715 ** default entry point name (sqlite3_extension_init) is used. Use
110716 ** of the default name is recommended.
110717 **
110718 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
110719 **
110720 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
110721 ** error message text. The calling function should free this memory
110722 ** by calling sqlite3DbFree(db, ).
110723 */
110724 static int sqlite3LoadExtension(
110725  sqlite3 *db, /* Load the extension into this database connection */
110726  const char *zFile, /* Name of the shared library containing extension */
110727  const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
110728  char **pzErrMsg /* Put error message here if not 0 */
110729 ){
110730  sqlite3_vfs *pVfs = db->pVfs;
110731  void *handle;
110732  sqlite3_loadext_entry xInit;
110733  char *zErrmsg = 0;
110734  const char *zEntry;
110735  char *zAltEntry = 0;
110736  void **aHandle;
110737  u64 nMsg = 300 + sqlite3Strlen30(zFile);
110738  int ii;
110739  int rc;
110740 
110741  /* Shared library endings to try if zFile cannot be loaded as written */
110742  static const char *azEndings[] = {
110743 #if SQLITE_OS_WIN
110744  "dll"
110745 #elif defined(__APPLE__)
110746  "dylib"
110747 #else
110748  "so"
110749 #endif
110750  };
110751 
110752 
110753  if( pzErrMsg ) *pzErrMsg = 0;
110754 
110755  /* Ticket #1863. To avoid a creating security problems for older
110756  ** applications that relink against newer versions of SQLite, the
110757  ** ability to run load_extension is turned off by default. One
110758  ** must call either sqlite3_enable_load_extension(db) or
110759  ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
110760  ** to turn on extension loading.
110761  */
110762  if( (db->flags & SQLITE_LoadExtension)==0 ){
110763  if( pzErrMsg ){
110764  *pzErrMsg = sqlite3_mprintf("not authorized");
110765  }
110766  return SQLITE_ERROR;
110767  }
110768 
110769  zEntry = zProc ? zProc : "sqlite3_extension_init";
110770 
110771  handle = sqlite3OsDlOpen(pVfs, zFile);
110772 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
110773  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
110774  char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
110775  if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
110776  handle = sqlite3OsDlOpen(pVfs, zAltFile);
110777  sqlite3_free(zAltFile);
110778  }
110779 #endif
110780  if( handle==0 ){
110781  if( pzErrMsg ){
110782  *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
110783  if( zErrmsg ){
110784  sqlite3_snprintf(nMsg, zErrmsg,
110785  "unable to open shared library [%s]", zFile);
110786  sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
110787  }
110788  }
110789  return SQLITE_ERROR;
110790  }
110791  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
110792 
110793  /* If no entry point was specified and the default legacy
110794  ** entry point name "sqlite3_extension_init" was not found, then
110795  ** construct an entry point name "sqlite3_X_init" where the X is
110796  ** replaced by the lowercase value of every ASCII alphabetic
110797  ** character in the filename after the last "/" upto the first ".",
110798  ** and eliding the first three characters if they are "lib".
110799  ** Examples:
110800  **
110801  ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
110802  ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
110803  */
110804  if( xInit==0 && zProc==0 ){
110805  int iFile, iEntry, c;
110806  int ncFile = sqlite3Strlen30(zFile);
110807  zAltEntry = sqlite3_malloc64(ncFile+30);
110808  if( zAltEntry==0 ){
110809  sqlite3OsDlClose(pVfs, handle);
110810  return SQLITE_NOMEM_BKPT;
110811  }
110812  memcpy(zAltEntry, "sqlite3_", 8);
110813  for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
110814  iFile++;
110815  if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
110816  for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
110817  if( sqlite3Isalpha(c) ){
110818  zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
110819  }
110820  }
110821  memcpy(zAltEntry+iEntry, "_init", 6);
110822  zEntry = zAltEntry;
110823  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
110824  }
110825  if( xInit==0 ){
110826  if( pzErrMsg ){
110827  nMsg += sqlite3Strlen30(zEntry);
110828  *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
110829  if( zErrmsg ){
110830  sqlite3_snprintf(nMsg, zErrmsg,
110831  "no entry point [%s] in shared library [%s]", zEntry, zFile);
110832  sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
110833  }
110834  }
110835  sqlite3OsDlClose(pVfs, handle);
110836  sqlite3_free(zAltEntry);
110837  return SQLITE_ERROR;
110838  }
110839  sqlite3_free(zAltEntry);
110840  rc = xInit(db, &zErrmsg, &sqlite3Apis);
110841  if( rc ){
110842  if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
110843  if( pzErrMsg ){
110844  *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
110845  }
110846  sqlite3_free(zErrmsg);
110847  sqlite3OsDlClose(pVfs, handle);
110848  return SQLITE_ERROR;
110849  }
110850 
110851  /* Append the new shared library handle to the db->aExtension array. */
110852  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
110853  if( aHandle==0 ){
110854  return SQLITE_NOMEM_BKPT;
110855  }
110856  if( db->nExtension>0 ){
110857  memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
110858  }
110859  sqlite3DbFree(db, db->aExtension);
110860  db->aExtension = aHandle;
110861 
110862  db->aExtension[db->nExtension++] = handle;
110863  return SQLITE_OK;
110864 }
110865 SQLITE_API int sqlite3_load_extension(
110866  sqlite3 *db, /* Load the extension into this database connection */
110867  const char *zFile, /* Name of the shared library containing extension */
110868  const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
110869  char **pzErrMsg /* Put error message here if not 0 */
110870 ){
110871  int rc;
110872  sqlite3_mutex_enter(db->mutex);
110873  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
110874  rc = sqlite3ApiExit(db, rc);
110875  sqlite3_mutex_leave(db->mutex);
110876  return rc;
110877 }
110878 
110879 /*
110880 ** Call this routine when the database connection is closing in order
110881 ** to clean up loaded extensions
110882 */
110883 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
110884  int i;
110885  assert( sqlite3_mutex_held(db->mutex) );
110886  for(i=0; i<db->nExtension; i++){
110887  sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
110888  }
110889  sqlite3DbFree(db, db->aExtension);
110890 }
110891 
110892 /*
110893 ** Enable or disable extension loading. Extension loading is disabled by
110894 ** default so as not to open security holes in older applications.
110895 */
110896 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
110897  sqlite3_mutex_enter(db->mutex);
110898  if( onoff ){
110899  db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
110900  }else{
110901  db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
110902  }
110903  sqlite3_mutex_leave(db->mutex);
110904  return SQLITE_OK;
110905 }
110906 
110907 #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
110908 
110909 /*
110910 ** The following object holds the list of automatically loaded
110911 ** extensions.
110912 **
110913 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
110914 ** mutex must be held while accessing this list.
110915 */
110916 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
110917 static SQLITE_WSD struct sqlite3AutoExtList {
110918  u32 nExt; /* Number of entries in aExt[] */
110919  void (**aExt)(void); /* Pointers to the extension init functions */
110920 } sqlite3Autoext = { 0, 0 };
110921 
110922 /* The "wsdAutoext" macro will resolve to the autoextension
110923 ** state vector. If writable static data is unsupported on the target,
110924 ** we have to locate the state vector at run-time. In the more common
110925 ** case where writable static data is supported, wsdStat can refer directly
110926 ** to the "sqlite3Autoext" state vector declared above.
110927 */
110928 #ifdef SQLITE_OMIT_WSD
110929 # define wsdAutoextInit \
110930  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
110931 # define wsdAutoext x[0]
110932 #else
110933 # define wsdAutoextInit
110934 # define wsdAutoext sqlite3Autoext
110935 #endif
110936 
110937 
110938 /*
110939 ** Register a statically linked extension that is automatically
110940 ** loaded by every new database connection.
110941 */
110942 SQLITE_API int sqlite3_auto_extension(
110943  void (*xInit)(void)
110944 ){
110945  int rc = SQLITE_OK;
110946 #ifndef SQLITE_OMIT_AUTOINIT
110947  rc = sqlite3_initialize();
110948  if( rc ){
110949  return rc;
110950  }else
110951 #endif
110952  {
110953  u32 i;
110954 #if SQLITE_THREADSAFE
110955  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110956 #endif
110957  wsdAutoextInit;
110958  sqlite3_mutex_enter(mutex);
110959  for(i=0; i<wsdAutoext.nExt; i++){
110960  if( wsdAutoext.aExt[i]==xInit ) break;
110961  }
110962  if( i==wsdAutoext.nExt ){
110963  u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
110964  void (**aNew)(void);
110965  aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
110966  if( aNew==0 ){
110967  rc = SQLITE_NOMEM_BKPT;
110968  }else{
110969  wsdAutoext.aExt = aNew;
110970  wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
110971  wsdAutoext.nExt++;
110972  }
110973  }
110974  sqlite3_mutex_leave(mutex);
110975  assert( (rc&0xff)==rc );
110976  return rc;
110977  }
110978 }
110979 
110980 /*
110981 ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
110982 ** set of routines that is invoked for each new database connection, if it
110983 ** is currently on the list. If xInit is not on the list, then this
110984 ** routine is a no-op.
110985 **
110986 ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
110987 ** was not on the list.
110988 */
110989 SQLITE_API int sqlite3_cancel_auto_extension(
110990  void (*xInit)(void)
110991 ){
110992 #if SQLITE_THREADSAFE
110993  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110994 #endif
110995  int i;
110996  int n = 0;
110997  wsdAutoextInit;
110998  sqlite3_mutex_enter(mutex);
110999  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
111000  if( wsdAutoext.aExt[i]==xInit ){
111001  wsdAutoext.nExt--;
111002  wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
111003  n++;
111004  break;
111005  }
111006  }
111007  sqlite3_mutex_leave(mutex);
111008  return n;
111009 }
111010 
111011 /*
111012 ** Reset the automatic extension loading mechanism.
111013 */
111014 SQLITE_API void sqlite3_reset_auto_extension(void){
111015 #ifndef SQLITE_OMIT_AUTOINIT
111016  if( sqlite3_initialize()==SQLITE_OK )
111017 #endif
111018  {
111019 #if SQLITE_THREADSAFE
111020  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
111021 #endif
111022  wsdAutoextInit;
111023  sqlite3_mutex_enter(mutex);
111024  sqlite3_free(wsdAutoext.aExt);
111025  wsdAutoext.aExt = 0;
111026  wsdAutoext.nExt = 0;
111027  sqlite3_mutex_leave(mutex);
111028  }
111029 }
111030 
111031 /*
111032 ** Load all automatic extensions.
111033 **
111034 ** If anything goes wrong, set an error in the database connection.
111035 */
111036 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
111037  u32 i;
111038  int go = 1;
111039  int rc;
111040  sqlite3_loadext_entry xInit;
111041 
111042  wsdAutoextInit;
111043  if( wsdAutoext.nExt==0 ){
111044  /* Common case: early out without every having to acquire a mutex */
111045  return;
111046  }
111047  for(i=0; go; i++){
111048  char *zErrmsg;
111049 #if SQLITE_THREADSAFE
111050  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
111051 #endif
111052 #ifdef SQLITE_OMIT_LOAD_EXTENSION
111053  const sqlite3_api_routines *pThunk = 0;
111054 #else
111055  const sqlite3_api_routines *pThunk = &sqlite3Apis;
111056 #endif
111057  sqlite3_mutex_enter(mutex);
111058  if( i>=wsdAutoext.nExt ){
111059  xInit = 0;
111060  go = 0;
111061  }else{
111062  xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
111063  }
111064  sqlite3_mutex_leave(mutex);
111065  zErrmsg = 0;
111066  if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
111067  sqlite3ErrorWithMsg(db, rc,
111068  "automatic extension loading failed: %s", zErrmsg);
111069  go = 0;
111070  }
111071  sqlite3_free(zErrmsg);
111072  }
111073 }
111074 
111075 /************** End of loadext.c *********************************************/
111076 /************** Begin file pragma.c ******************************************/
111077 /*
111078 ** 2003 April 6
111079 **
111080 ** The author disclaims copyright to this source code. In place of
111081 ** a legal notice, here is a blessing:
111082 **
111083 ** May you do good and not evil.
111084 ** May you find forgiveness for yourself and forgive others.
111085 ** May you share freely, never taking more than you give.
111086 **
111087 *************************************************************************
111088 ** This file contains code used to implement the PRAGMA command.
111089 */
111090 /* #include "sqliteInt.h" */
111091 
111092 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
111093 # if defined(__APPLE__)
111094 # define SQLITE_ENABLE_LOCKING_STYLE 1
111095 # else
111096 # define SQLITE_ENABLE_LOCKING_STYLE 0
111097 # endif
111098 #endif
111099 
111100 /***************************************************************************
111101 ** The "pragma.h" include file is an automatically generated file that
111102 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
111103 ** object. This ensures that the aPragmaName[] table is arranged in
111104 ** lexicographical order to facility a binary search of the pragma name.
111105 ** Do not edit pragma.h directly. Edit and rerun the script in at
111106 ** ../tool/mkpragmatab.tcl. */
111107 /************** Include pragma.h in the middle of pragma.c *******************/
111108 /************** Begin file pragma.h ******************************************/
111109 /* DO NOT EDIT!
111110 ** This file is automatically generated by the script at
111111 ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
111112 ** that script and rerun it.
111113 */
111114 #define PragTyp_HEADER_VALUE 0
111115 #define PragTyp_AUTO_VACUUM 1
111116 #define PragTyp_FLAG 2
111117 #define PragTyp_BUSY_TIMEOUT 3
111118 #define PragTyp_CACHE_SIZE 4
111119 #define PragTyp_CACHE_SPILL 5
111120 #define PragTyp_CASE_SENSITIVE_LIKE 6
111121 #define PragTyp_COLLATION_LIST 7
111122 #define PragTyp_COMPILE_OPTIONS 8
111123 #define PragTyp_DATA_STORE_DIRECTORY 9
111124 #define PragTyp_DATABASE_LIST 10
111125 #define PragTyp_DEFAULT_CACHE_SIZE 11
111126 #define PragTyp_ENCODING 12
111127 #define PragTyp_FOREIGN_KEY_CHECK 13
111128 #define PragTyp_FOREIGN_KEY_LIST 14
111129 #define PragTyp_INCREMENTAL_VACUUM 15
111130 #define PragTyp_INDEX_INFO 16
111131 #define PragTyp_INDEX_LIST 17
111132 #define PragTyp_INTEGRITY_CHECK 18
111133 #define PragTyp_JOURNAL_MODE 19
111134 #define PragTyp_JOURNAL_SIZE_LIMIT 20
111135 #define PragTyp_LOCK_PROXY_FILE 21
111136 #define PragTyp_LOCKING_MODE 22
111137 #define PragTyp_PAGE_COUNT 23
111138 #define PragTyp_MMAP_SIZE 24
111139 #define PragTyp_PAGE_SIZE 25
111140 #define PragTyp_SECURE_DELETE 26
111141 #define PragTyp_SHRINK_MEMORY 27
111142 #define PragTyp_SOFT_HEAP_LIMIT 28
111143 #define PragTyp_STATS 29
111144 #define PragTyp_SYNCHRONOUS 30
111145 #define PragTyp_TABLE_INFO 31
111146 #define PragTyp_TEMP_STORE 32
111147 #define PragTyp_TEMP_STORE_DIRECTORY 33
111148 #define PragTyp_THREADS 34
111149 #define PragTyp_WAL_AUTOCHECKPOINT 35
111150 #define PragTyp_WAL_CHECKPOINT 36
111151 #define PragTyp_ACTIVATE_EXTENSIONS 37
111152 #define PragTyp_HEXKEY 38
111153 #define PragTyp_KEY 39
111154 #define PragTyp_REKEY 40
111155 #define PragTyp_LOCK_STATUS 41
111156 #define PragTyp_PARSER_TRACE 42
111157 #define PragFlag_NeedSchema 0x01
111158 #define PragFlag_ReadOnly 0x02
111159 static const struct sPragmaNames {
111160  const char *const zName; /* Name of pragma */
111161  u8 ePragTyp; /* PragTyp_XXX value */
111162  u8 mPragFlag; /* Zero or more PragFlag_XXX values */
111163  u32 iArg; /* Extra argument */
111164 } aPragmaNames[] = {
111165 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
111166  { /* zName: */ "activate_extensions",
111167  /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
111168  /* ePragFlag: */ 0,
111169  /* iArg: */ 0 },
111170 #endif
111171 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111172  { /* zName: */ "application_id",
111173  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111174  /* ePragFlag: */ 0,
111175  /* iArg: */ BTREE_APPLICATION_ID },
111176 #endif
111177 #if !defined(SQLITE_OMIT_AUTOVACUUM)
111178  { /* zName: */ "auto_vacuum",
111179  /* ePragTyp: */ PragTyp_AUTO_VACUUM,
111180  /* ePragFlag: */ PragFlag_NeedSchema,
111181  /* iArg: */ 0 },
111182 #endif
111183 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111184 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
111185  { /* zName: */ "automatic_index",
111186  /* ePragTyp: */ PragTyp_FLAG,
111187  /* ePragFlag: */ 0,
111188  /* iArg: */ SQLITE_AutoIndex },
111189 #endif
111190 #endif
111191  { /* zName: */ "busy_timeout",
111192  /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
111193  /* ePragFlag: */ 0,
111194  /* iArg: */ 0 },
111195 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111196  { /* zName: */ "cache_size",
111197  /* ePragTyp: */ PragTyp_CACHE_SIZE,
111198  /* ePragFlag: */ PragFlag_NeedSchema,
111199  /* iArg: */ 0 },
111200 #endif
111201 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111202  { /* zName: */ "cache_spill",
111203  /* ePragTyp: */ PragTyp_CACHE_SPILL,
111204  /* ePragFlag: */ 0,
111205  /* iArg: */ 0 },
111206 #endif
111207  { /* zName: */ "case_sensitive_like",
111208  /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
111209  /* ePragFlag: */ 0,
111210  /* iArg: */ 0 },
111211  { /* zName: */ "cell_size_check",
111212  /* ePragTyp: */ PragTyp_FLAG,
111213  /* ePragFlag: */ 0,
111214  /* iArg: */ SQLITE_CellSizeCk },
111215 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111216  { /* zName: */ "checkpoint_fullfsync",
111217  /* ePragTyp: */ PragTyp_FLAG,
111218  /* ePragFlag: */ 0,
111219  /* iArg: */ SQLITE_CkptFullFSync },
111220 #endif
111221 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111222  { /* zName: */ "collation_list",
111223  /* ePragTyp: */ PragTyp_COLLATION_LIST,
111224  /* ePragFlag: */ 0,
111225  /* iArg: */ 0 },
111226 #endif
111227 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
111228  { /* zName: */ "compile_options",
111229  /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
111230  /* ePragFlag: */ 0,
111231  /* iArg: */ 0 },
111232 #endif
111233 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111234  { /* zName: */ "count_changes",
111235  /* ePragTyp: */ PragTyp_FLAG,
111236  /* ePragFlag: */ 0,
111237  /* iArg: */ SQLITE_CountRows },
111238 #endif
111239 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
111240  { /* zName: */ "data_store_directory",
111241  /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
111242  /* ePragFlag: */ 0,
111243  /* iArg: */ 0 },
111244 #endif
111245 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111246  { /* zName: */ "data_version",
111247  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111248  /* ePragFlag: */ PragFlag_ReadOnly,
111249  /* iArg: */ BTREE_DATA_VERSION },
111250 #endif
111251 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111252  { /* zName: */ "database_list",
111253  /* ePragTyp: */ PragTyp_DATABASE_LIST,
111254  /* ePragFlag: */ PragFlag_NeedSchema,
111255  /* iArg: */ 0 },
111256 #endif
111257 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
111258  { /* zName: */ "default_cache_size",
111259  /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
111260  /* ePragFlag: */ PragFlag_NeedSchema,
111261  /* iArg: */ 0 },
111262 #endif
111263 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111264 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
111265  { /* zName: */ "defer_foreign_keys",
111266  /* ePragTyp: */ PragTyp_FLAG,
111267  /* ePragFlag: */ 0,
111268  /* iArg: */ SQLITE_DeferFKs },
111269 #endif
111270 #endif
111271 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111272  { /* zName: */ "empty_result_callbacks",
111273  /* ePragTyp: */ PragTyp_FLAG,
111274  /* ePragFlag: */ 0,
111275  /* iArg: */ SQLITE_NullCallback },
111276 #endif
111277 #if !defined(SQLITE_OMIT_UTF16)
111278  { /* zName: */ "encoding",
111279  /* ePragTyp: */ PragTyp_ENCODING,
111280  /* ePragFlag: */ 0,
111281  /* iArg: */ 0 },
111282 #endif
111283 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
111284  { /* zName: */ "foreign_key_check",
111285  /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
111286  /* ePragFlag: */ PragFlag_NeedSchema,
111287  /* iArg: */ 0 },
111288 #endif
111289 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
111290  { /* zName: */ "foreign_key_list",
111291  /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
111292  /* ePragFlag: */ PragFlag_NeedSchema,
111293  /* iArg: */ 0 },
111294 #endif
111295 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111296 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
111297  { /* zName: */ "foreign_keys",
111298  /* ePragTyp: */ PragTyp_FLAG,
111299  /* ePragFlag: */ 0,
111300  /* iArg: */ SQLITE_ForeignKeys },
111301 #endif
111302 #endif
111303 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111304  { /* zName: */ "freelist_count",
111305  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111306  /* ePragFlag: */ PragFlag_ReadOnly,
111307  /* iArg: */ BTREE_FREE_PAGE_COUNT },
111308 #endif
111309 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111310  { /* zName: */ "full_column_names",
111311  /* ePragTyp: */ PragTyp_FLAG,
111312  /* ePragFlag: */ 0,
111313  /* iArg: */ SQLITE_FullColNames },
111314  { /* zName: */ "fullfsync",
111315  /* ePragTyp: */ PragTyp_FLAG,
111316  /* ePragFlag: */ 0,
111317  /* iArg: */ SQLITE_FullFSync },
111318 #endif
111319 #if defined(SQLITE_HAS_CODEC)
111320  { /* zName: */ "hexkey",
111321  /* ePragTyp: */ PragTyp_HEXKEY,
111322  /* ePragFlag: */ 0,
111323  /* iArg: */ 0 },
111324  { /* zName: */ "hexrekey",
111325  /* ePragTyp: */ PragTyp_HEXKEY,
111326  /* ePragFlag: */ 0,
111327  /* iArg: */ 0 },
111328 #endif
111329 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111330 #if !defined(SQLITE_OMIT_CHECK)
111331  { /* zName: */ "ignore_check_constraints",
111332  /* ePragTyp: */ PragTyp_FLAG,
111333  /* ePragFlag: */ 0,
111334  /* iArg: */ SQLITE_IgnoreChecks },
111335 #endif
111336 #endif
111337 #if !defined(SQLITE_OMIT_AUTOVACUUM)
111338  { /* zName: */ "incremental_vacuum",
111339  /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
111340  /* ePragFlag: */ PragFlag_NeedSchema,
111341  /* iArg: */ 0 },
111342 #endif
111343 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111344  { /* zName: */ "index_info",
111345  /* ePragTyp: */ PragTyp_INDEX_INFO,
111346  /* ePragFlag: */ PragFlag_NeedSchema,
111347  /* iArg: */ 0 },
111348  { /* zName: */ "index_list",
111349  /* ePragTyp: */ PragTyp_INDEX_LIST,
111350  /* ePragFlag: */ PragFlag_NeedSchema,
111351  /* iArg: */ 0 },
111352  { /* zName: */ "index_xinfo",
111353  /* ePragTyp: */ PragTyp_INDEX_INFO,
111354  /* ePragFlag: */ PragFlag_NeedSchema,
111355  /* iArg: */ 1 },
111356 #endif
111357 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
111358  { /* zName: */ "integrity_check",
111359  /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
111360  /* ePragFlag: */ PragFlag_NeedSchema,
111361  /* iArg: */ 0 },
111362 #endif
111363 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111364  { /* zName: */ "journal_mode",
111365  /* ePragTyp: */ PragTyp_JOURNAL_MODE,
111366  /* ePragFlag: */ PragFlag_NeedSchema,
111367  /* iArg: */ 0 },
111368  { /* zName: */ "journal_size_limit",
111369  /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
111370  /* ePragFlag: */ 0,
111371  /* iArg: */ 0 },
111372 #endif
111373 #if defined(SQLITE_HAS_CODEC)
111374  { /* zName: */ "key",
111375  /* ePragTyp: */ PragTyp_KEY,
111376  /* ePragFlag: */ 0,
111377  /* iArg: */ 0 },
111378 #endif
111379 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111380  { /* zName: */ "legacy_file_format",
111381  /* ePragTyp: */ PragTyp_FLAG,
111382  /* ePragFlag: */ 0,
111383  /* iArg: */ SQLITE_LegacyFileFmt },
111384 #endif
111385 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
111386  { /* zName: */ "lock_proxy_file",
111387  /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
111388  /* ePragFlag: */ 0,
111389  /* iArg: */ 0 },
111390 #endif
111391 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
111392  { /* zName: */ "lock_status",
111393  /* ePragTyp: */ PragTyp_LOCK_STATUS,
111394  /* ePragFlag: */ 0,
111395  /* iArg: */ 0 },
111396 #endif
111397 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111398  { /* zName: */ "locking_mode",
111399  /* ePragTyp: */ PragTyp_LOCKING_MODE,
111400  /* ePragFlag: */ 0,
111401  /* iArg: */ 0 },
111402  { /* zName: */ "max_page_count",
111403  /* ePragTyp: */ PragTyp_PAGE_COUNT,
111404  /* ePragFlag: */ PragFlag_NeedSchema,
111405  /* iArg: */ 0 },
111406  { /* zName: */ "mmap_size",
111407  /* ePragTyp: */ PragTyp_MMAP_SIZE,
111408  /* ePragFlag: */ 0,
111409  /* iArg: */ 0 },
111410  { /* zName: */ "page_count",
111411  /* ePragTyp: */ PragTyp_PAGE_COUNT,
111412  /* ePragFlag: */ PragFlag_NeedSchema,
111413  /* iArg: */ 0 },
111414  { /* zName: */ "page_size",
111415  /* ePragTyp: */ PragTyp_PAGE_SIZE,
111416  /* ePragFlag: */ 0,
111417  /* iArg: */ 0 },
111418 #endif
111419 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
111420  { /* zName: */ "parser_trace",
111421  /* ePragTyp: */ PragTyp_PARSER_TRACE,
111422  /* ePragFlag: */ 0,
111423  /* iArg: */ 0 },
111424 #endif
111425 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111426  { /* zName: */ "query_only",
111427  /* ePragTyp: */ PragTyp_FLAG,
111428  /* ePragFlag: */ 0,
111429  /* iArg: */ SQLITE_QueryOnly },
111430 #endif
111431 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
111432  { /* zName: */ "quick_check",
111433  /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
111434  /* ePragFlag: */ PragFlag_NeedSchema,
111435  /* iArg: */ 0 },
111436 #endif
111437 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111438  { /* zName: */ "read_uncommitted",
111439  /* ePragTyp: */ PragTyp_FLAG,
111440  /* ePragFlag: */ 0,
111441  /* iArg: */ SQLITE_ReadUncommitted },
111442  { /* zName: */ "recursive_triggers",
111443  /* ePragTyp: */ PragTyp_FLAG,
111444  /* ePragFlag: */ 0,
111445  /* iArg: */ SQLITE_RecTriggers },
111446 #endif
111447 #if defined(SQLITE_HAS_CODEC)
111448  { /* zName: */ "rekey",
111449  /* ePragTyp: */ PragTyp_REKEY,
111450  /* ePragFlag: */ 0,
111451  /* iArg: */ 0 },
111452 #endif
111453 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111454  { /* zName: */ "reverse_unordered_selects",
111455  /* ePragTyp: */ PragTyp_FLAG,
111456  /* ePragFlag: */ 0,
111457  /* iArg: */ SQLITE_ReverseOrder },
111458 #endif
111459 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111460  { /* zName: */ "schema_version",
111461  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111462  /* ePragFlag: */ 0,
111463  /* iArg: */ BTREE_SCHEMA_VERSION },
111464 #endif
111465 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111466  { /* zName: */ "secure_delete",
111467  /* ePragTyp: */ PragTyp_SECURE_DELETE,
111468  /* ePragFlag: */ 0,
111469  /* iArg: */ 0 },
111470 #endif
111471 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111472  { /* zName: */ "short_column_names",
111473  /* ePragTyp: */ PragTyp_FLAG,
111474  /* ePragFlag: */ 0,
111475  /* iArg: */ SQLITE_ShortColNames },
111476 #endif
111477  { /* zName: */ "shrink_memory",
111478  /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
111479  /* ePragFlag: */ 0,
111480  /* iArg: */ 0 },
111481  { /* zName: */ "soft_heap_limit",
111482  /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
111483  /* ePragFlag: */ 0,
111484  /* iArg: */ 0 },
111485 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111486 #if defined(SQLITE_DEBUG)
111487  { /* zName: */ "sql_trace",
111488  /* ePragTyp: */ PragTyp_FLAG,
111489  /* ePragFlag: */ 0,
111490  /* iArg: */ SQLITE_SqlTrace },
111491 #endif
111492 #endif
111493 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111494  { /* zName: */ "stats",
111495  /* ePragTyp: */ PragTyp_STATS,
111496  /* ePragFlag: */ PragFlag_NeedSchema,
111497  /* iArg: */ 0 },
111498 #endif
111499 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111500  { /* zName: */ "synchronous",
111501  /* ePragTyp: */ PragTyp_SYNCHRONOUS,
111502  /* ePragFlag: */ PragFlag_NeedSchema,
111503  /* iArg: */ 0 },
111504 #endif
111505 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111506  { /* zName: */ "table_info",
111507  /* ePragTyp: */ PragTyp_TABLE_INFO,
111508  /* ePragFlag: */ PragFlag_NeedSchema,
111509  /* iArg: */ 0 },
111510 #endif
111511 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111512  { /* zName: */ "temp_store",
111513  /* ePragTyp: */ PragTyp_TEMP_STORE,
111514  /* ePragFlag: */ 0,
111515  /* iArg: */ 0 },
111516  { /* zName: */ "temp_store_directory",
111517  /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
111518  /* ePragFlag: */ 0,
111519  /* iArg: */ 0 },
111520 #endif
111521  { /* zName: */ "threads",
111522  /* ePragTyp: */ PragTyp_THREADS,
111523  /* ePragFlag: */ 0,
111524  /* iArg: */ 0 },
111525 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111526  { /* zName: */ "user_version",
111527  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111528  /* ePragFlag: */ 0,
111529  /* iArg: */ BTREE_USER_VERSION },
111530 #endif
111531 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111532 #if defined(SQLITE_DEBUG)
111533  { /* zName: */ "vdbe_addoptrace",
111534  /* ePragTyp: */ PragTyp_FLAG,
111535  /* ePragFlag: */ 0,
111536  /* iArg: */ SQLITE_VdbeAddopTrace },
111537  { /* zName: */ "vdbe_debug",
111538  /* ePragTyp: */ PragTyp_FLAG,
111539  /* ePragFlag: */ 0,
111540  /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
111541  { /* zName: */ "vdbe_eqp",
111542  /* ePragTyp: */ PragTyp_FLAG,
111543  /* ePragFlag: */ 0,
111544  /* iArg: */ SQLITE_VdbeEQP },
111545  { /* zName: */ "vdbe_listing",
111546  /* ePragTyp: */ PragTyp_FLAG,
111547  /* ePragFlag: */ 0,
111548  /* iArg: */ SQLITE_VdbeListing },
111549  { /* zName: */ "vdbe_trace",
111550  /* ePragTyp: */ PragTyp_FLAG,
111551  /* ePragFlag: */ 0,
111552  /* iArg: */ SQLITE_VdbeTrace },
111553 #endif
111554 #endif
111555 #if !defined(SQLITE_OMIT_WAL)
111556  { /* zName: */ "wal_autocheckpoint",
111557  /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
111558  /* ePragFlag: */ 0,
111559  /* iArg: */ 0 },
111560  { /* zName: */ "wal_checkpoint",
111561  /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
111562  /* ePragFlag: */ PragFlag_NeedSchema,
111563  /* iArg: */ 0 },
111564 #endif
111565 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111566  { /* zName: */ "writable_schema",
111567  /* ePragTyp: */ PragTyp_FLAG,
111568  /* ePragFlag: */ 0,
111569  /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
111570 #endif
111571 };
111572 /* Number of pragmas: 60 on by default, 73 total. */
111573 
111574 /************** End of pragma.h **********************************************/
111575 /************** Continuing where we left off in pragma.c *********************/
111576 
111577 /*
111578 ** Interpret the given string as a safety level. Return 0 for OFF,
111579 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
111580 ** unrecognized string argument. The FULL and EXTRA option is disallowed
111581 ** if the omitFull parameter it 1.
111582 **
111583 ** Note that the values returned are one less that the values that
111584 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
111585 ** to support legacy SQL code. The safety level used to be boolean
111586 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
111587 */
111588 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
111589  /* 123456789 123456789 123 */
111590  static const char zText[] = "onoffalseyestruextrafull";
111591  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
111592  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
111593  static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
111594  /* on no off false yes true extra full */
111595  int i, n;
111596  if( sqlite3Isdigit(*z) ){
111597  return (u8)sqlite3Atoi(z);
111598  }
111599  n = sqlite3Strlen30(z);
111600  for(i=0; i<ArraySize(iLength); i++){
111601  if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
111602  && (!omitFull || iValue[i]<=1)
111603  ){
111604  return iValue[i];
111605  }
111606  }
111607  return dflt;
111608 }
111609 
111610 /*
111611 ** Interpret the given string as a boolean value.
111612 */
111613 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
111614  return getSafetyLevel(z,1,dflt)!=0;
111615 }
111616 
111617 /* The sqlite3GetBoolean() function is used by other modules but the
111618 ** remainder of this file is specific to PRAGMA processing. So omit
111619 ** the rest of the file if PRAGMAs are omitted from the build.
111620 */
111621 #if !defined(SQLITE_OMIT_PRAGMA)
111622 
111623 /*
111624 ** Interpret the given string as a locking mode value.
111625 */
111626 static int getLockingMode(const char *z){
111627  if( z ){
111628  if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
111629  if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
111630  }
111631  return PAGER_LOCKINGMODE_QUERY;
111632 }
111633 
111634 #ifndef SQLITE_OMIT_AUTOVACUUM
111635 /*
111636 ** Interpret the given string as an auto-vacuum mode value.
111637 **
111638 ** The following strings, "none", "full" and "incremental" are
111639 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
111640 */
111641 static int getAutoVacuum(const char *z){
111642  int i;
111643  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
111644  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
111645  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
111646  i = sqlite3Atoi(z);
111647  return (u8)((i>=0&&i<=2)?i:0);
111648 }
111649 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
111650 
111651 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
111652 /*
111653 ** Interpret the given string as a temp db location. Return 1 for file
111654 ** backed temporary databases, 2 for the Red-Black tree in memory database
111655 ** and 0 to use the compile-time default.
111656 */
111657 static int getTempStore(const char *z){
111658  if( z[0]>='0' && z[0]<='2' ){
111659  return z[0] - '0';
111660  }else if( sqlite3StrICmp(z, "file")==0 ){
111661  return 1;
111662  }else if( sqlite3StrICmp(z, "memory")==0 ){
111663  return 2;
111664  }else{
111665  return 0;
111666  }
111667 }
111668 #endif /* SQLITE_PAGER_PRAGMAS */
111669 
111670 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
111671 /*
111672 ** Invalidate temp storage, either when the temp storage is changed
111673 ** from default, or when 'file' and the temp_store_directory has changed
111674 */
111675 static int invalidateTempStorage(Parse *pParse){
111676  sqlite3 *db = pParse->db;
111677  if( db->aDb[1].pBt!=0 ){
111678  if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
111679  sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
111680  "from within a transaction");
111681  return SQLITE_ERROR;
111682  }
111683  sqlite3BtreeClose(db->aDb[1].pBt);
111684  db->aDb[1].pBt = 0;
111685  sqlite3ResetAllSchemasOfConnection(db);
111686  }
111687  return SQLITE_OK;
111688 }
111689 #endif /* SQLITE_PAGER_PRAGMAS */
111690 
111691 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
111692 /*
111693 ** If the TEMP database is open, close it and mark the database schema
111694 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
111695 ** or DEFAULT_TEMP_STORE pragmas.
111696 */
111697 static int changeTempStorage(Parse *pParse, const char *zStorageType){
111698  int ts = getTempStore(zStorageType);
111699  sqlite3 *db = pParse->db;
111700  if( db->temp_store==ts ) return SQLITE_OK;
111701  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
111702  return SQLITE_ERROR;
111703  }
111704  db->temp_store = (u8)ts;
111705  return SQLITE_OK;
111706 }
111707 #endif /* SQLITE_PAGER_PRAGMAS */
111708 
111709 /*
111710 ** Set the names of the first N columns to the values in azCol[]
111711 */
111712 static void setAllColumnNames(
111713  Vdbe *v, /* The query under construction */
111714  int N, /* Number of columns */
111715  const char **azCol /* Names of columns */
111716 ){
111717  int i;
111718  sqlite3VdbeSetNumCols(v, N);
111719  for(i=0; i<N; i++){
111720  sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
111721  }
111722 }
111723 static void setOneColumnName(Vdbe *v, const char *z){
111724  setAllColumnNames(v, 1, &z);
111725 }
111726 
111727 /*
111728 ** Generate code to return a single integer value.
111729 */
111730 static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
111731  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
111732  setOneColumnName(v, zLabel);
111733  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
111734 }
111735 
111736 /*
111737 ** Generate code to return a single text value.
111738 */
111739 static void returnSingleText(
111740  Vdbe *v, /* Prepared statement under construction */
111741  const char *zLabel, /* Name of the result column */
111742  const char *zValue /* Value to be returned */
111743 ){
111744  if( zValue ){
111745  sqlite3VdbeLoadString(v, 1, (const char*)zValue);
111746  setOneColumnName(v, zLabel);
111747  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
111748  }
111749 }
111750 
111751 
111752 /*
111753 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
111754 ** set these values for all pagers.
111755 */
111756 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
111757 static void setAllPagerFlags(sqlite3 *db){
111758  if( db->autoCommit ){
111759  Db *pDb = db->aDb;
111760  int n = db->nDb;
111761  assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
111762  assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
111763  assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
111764  assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
111765  == PAGER_FLAGS_MASK );
111766  assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
111767  while( (n--) > 0 ){
111768  if( pDb->pBt ){
111769  sqlite3BtreeSetPagerFlags(pDb->pBt,
111770  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
111771  }
111772  pDb++;
111773  }
111774  }
111775 }
111776 #else
111777 # define setAllPagerFlags(X) /* no-op */
111778 #endif
111779 
111780 
111781 /*
111782 ** Return a human-readable name for a constraint resolution action.
111783 */
111784 #ifndef SQLITE_OMIT_FOREIGN_KEY
111785 static const char *actionName(u8 action){
111786  const char *zName;
111787  switch( action ){
111788  case OE_SetNull: zName = "SET NULL"; break;
111789  case OE_SetDflt: zName = "SET DEFAULT"; break;
111790  case OE_Cascade: zName = "CASCADE"; break;
111791  case OE_Restrict: zName = "RESTRICT"; break;
111792  default: zName = "NO ACTION";
111793  assert( action==OE_None ); break;
111794  }
111795  return zName;
111796 }
111797 #endif
111798 
111799 
111800 /*
111801 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
111802 ** defined in pager.h. This function returns the associated lowercase
111803 ** journal-mode name.
111804 */
111805 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
111806  static char * const azModeName[] = {
111807  "delete", "persist", "off", "truncate", "memory"
111808 #ifndef SQLITE_OMIT_WAL
111809  , "wal"
111810 #endif
111811  };
111812  assert( PAGER_JOURNALMODE_DELETE==0 );
111813  assert( PAGER_JOURNALMODE_PERSIST==1 );
111814  assert( PAGER_JOURNALMODE_OFF==2 );
111815  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
111816  assert( PAGER_JOURNALMODE_MEMORY==4 );
111817  assert( PAGER_JOURNALMODE_WAL==5 );
111818  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
111819 
111820  if( eMode==ArraySize(azModeName) ) return 0;
111821  return azModeName[eMode];
111822 }
111823 
111824 /*
111825 ** Process a pragma statement.
111826 **
111827 ** Pragmas are of this form:
111828 **
111829 ** PRAGMA [schema.]id [= value]
111830 **
111831 ** The identifier might also be a string. The value is a string, and
111832 ** identifier, or a number. If minusFlag is true, then the value is
111833 ** a number that was preceded by a minus sign.
111834 **
111835 ** If the left side is "database.id" then pId1 is the database name
111836 ** and pId2 is the id. If the left side is just "id" then pId1 is the
111837 ** id and pId2 is any empty string.
111838 */
111839 SQLITE_PRIVATE void sqlite3Pragma(
111840  Parse *pParse,
111841  Token *pId1, /* First part of [schema.]id field */
111842  Token *pId2, /* Second part of [schema.]id field, or NULL */
111843  Token *pValue, /* Token for <value>, or NULL */
111844  int minusFlag /* True if a '-' sign preceded <value> */
111845 ){
111846  char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
111847  char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
111848  const char *zDb = 0; /* The database name */
111849  Token *pId; /* Pointer to <id> token */
111850  char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
111851  int iDb; /* Database index for <database> */
111852  int lwr, upr, mid = 0; /* Binary search bounds */
111853  int rc; /* return value form SQLITE_FCNTL_PRAGMA */
111854  sqlite3 *db = pParse->db; /* The database connection */
111855  Db *pDb; /* The specific database being pragmaed */
111856  Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
111857  const struct sPragmaNames *pPragma;
111858 
111859  if( v==0 ) return;
111860  sqlite3VdbeRunOnlyOnce(v);
111861  pParse->nMem = 2;
111862 
111863  /* Interpret the [schema.] part of the pragma statement. iDb is the
111864  ** index of the database this pragma is being applied to in db.aDb[]. */
111865  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
111866  if( iDb<0 ) return;
111867  pDb = &db->aDb[iDb];
111868 
111869  /* If the temp database has been explicitly named as part of the
111870  ** pragma, make sure it is open.
111871  */
111872  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
111873  return;
111874  }
111875 
111876  zLeft = sqlite3NameFromToken(db, pId);
111877  if( !zLeft ) return;
111878  if( minusFlag ){
111879  zRight = sqlite3MPrintf(db, "-%T", pValue);
111880  }else{
111881  zRight = sqlite3NameFromToken(db, pValue);
111882  }
111883 
111884  assert( pId2 );
111885  zDb = pId2->n>0 ? pDb->zDbSName : 0;
111886  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
111887  goto pragma_out;
111888  }
111889 
111890  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
111891  ** connection. If it returns SQLITE_OK, then assume that the VFS
111892  ** handled the pragma and generate a no-op prepared statement.
111893  **
111894  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
111895  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
111896  ** object corresponding to the database file to which the pragma
111897  ** statement refers.
111898  **
111899  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
111900  ** file control is an array of pointers to strings (char**) in which the
111901  ** second element of the array is the name of the pragma and the third
111902  ** element is the argument to the pragma or NULL if the pragma has no
111903  ** argument.
111904  */
111905  aFcntl[0] = 0;
111906  aFcntl[1] = zLeft;
111907  aFcntl[2] = zRight;
111908  aFcntl[3] = 0;
111909  db->busyHandler.nBusy = 0;
111910  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
111911  if( rc==SQLITE_OK ){
111912  returnSingleText(v, "result", aFcntl[0]);
111913  sqlite3_free(aFcntl[0]);
111914  goto pragma_out;
111915  }
111916  if( rc!=SQLITE_NOTFOUND ){
111917  if( aFcntl[0] ){
111918  sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
111919  sqlite3_free(aFcntl[0]);
111920  }
111921  pParse->nErr++;
111922  pParse->rc = rc;
111923  goto pragma_out;
111924  }
111925 
111926  /* Locate the pragma in the lookup table */
111927  lwr = 0;
111928  upr = ArraySize(aPragmaNames)-1;
111929  while( lwr<=upr ){
111930  mid = (lwr+upr)/2;
111931  rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
111932  if( rc==0 ) break;
111933  if( rc<0 ){
111934  upr = mid - 1;
111935  }else{
111936  lwr = mid + 1;
111937  }
111938  }
111939  if( lwr>upr ) goto pragma_out;
111940  pPragma = &aPragmaNames[mid];
111941 
111942  /* Make sure the database schema is loaded if the pragma requires that */
111943  if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
111944  if( sqlite3ReadSchema(pParse) ) goto pragma_out;
111945  }
111946 
111947  /* Jump to the appropriate pragma handler */
111948  switch( pPragma->ePragTyp ){
111949 
111950 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
111951  /*
111952  ** PRAGMA [schema.]default_cache_size
111953  ** PRAGMA [schema.]default_cache_size=N
111954  **
111955  ** The first form reports the current persistent setting for the
111956  ** page cache size. The value returned is the maximum number of
111957  ** pages in the page cache. The second form sets both the current
111958  ** page cache size value and the persistent page cache size value
111959  ** stored in the database file.
111960  **
111961  ** Older versions of SQLite would set the default cache size to a
111962  ** negative number to indicate synchronous=OFF. These days, synchronous
111963  ** is always on by default regardless of the sign of the default cache
111964  ** size. But continue to take the absolute value of the default cache
111965  ** size of historical compatibility.
111966  */
111967  case PragTyp_DEFAULT_CACHE_SIZE: {
111968  static const int iLn = VDBE_OFFSET_LINENO(2);
111969  static const VdbeOpList getCacheSize[] = {
111970  { OP_Transaction, 0, 0, 0}, /* 0 */
111971  { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
111972  { OP_IfPos, 1, 8, 0},
111973  { OP_Integer, 0, 2, 0},
111974  { OP_Subtract, 1, 2, 1},
111975  { OP_IfPos, 1, 8, 0},
111976  { OP_Integer, 0, 1, 0}, /* 6 */
111977  { OP_Noop, 0, 0, 0},
111978  { OP_ResultRow, 1, 1, 0},
111979  };
111980  VdbeOp *aOp;
111981  sqlite3VdbeUsesBtree(v, iDb);
111982  if( !zRight ){
111983  setOneColumnName(v, "cache_size");
111984  pParse->nMem += 2;
111985  sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
111986  aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
111987  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111988  aOp[0].p1 = iDb;
111989  aOp[1].p1 = iDb;
111990  aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
111991  }else{
111992  int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
111993  sqlite3BeginWriteOperation(pParse, 0, iDb);
111994  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
111995  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111996  pDb->pSchema->cache_size = size;
111997  sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
111998  }
111999  break;
112000  }
112001 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
112002 
112003 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
112004  /*
112005  ** PRAGMA [schema.]page_size
112006  ** PRAGMA [schema.]page_size=N
112007  **
112008  ** The first form reports the current setting for the
112009  ** database page size in bytes. The second form sets the
112010  ** database page size value. The value can only be set if
112011  ** the database has not yet been created.
112012  */
112013  case PragTyp_PAGE_SIZE: {
112014  Btree *pBt = pDb->pBt;
112015  assert( pBt!=0 );
112016  if( !zRight ){
112017  int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
112018  returnSingleInt(v, "page_size", size);
112019  }else{
112020  /* Malloc may fail when setting the page-size, as there is an internal
112021  ** buffer that the pager module resizes using sqlite3_realloc().
112022  */
112023  db->nextPagesize = sqlite3Atoi(zRight);
112024  if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
112025  sqlite3OomFault(db);
112026  }
112027  }
112028  break;
112029  }
112030 
112031  /*
112032  ** PRAGMA [schema.]secure_delete
112033  ** PRAGMA [schema.]secure_delete=ON/OFF
112034  **
112035  ** The first form reports the current setting for the
112036  ** secure_delete flag. The second form changes the secure_delete
112037  ** flag setting and reports thenew value.
112038  */
112039  case PragTyp_SECURE_DELETE: {
112040  Btree *pBt = pDb->pBt;
112041  int b = -1;
112042  assert( pBt!=0 );
112043  if( zRight ){
112044  b = sqlite3GetBoolean(zRight, 0);
112045  }
112046  if( pId2->n==0 && b>=0 ){
112047  int ii;
112048  for(ii=0; ii<db->nDb; ii++){
112049  sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
112050  }
112051  }
112052  b = sqlite3BtreeSecureDelete(pBt, b);
112053  returnSingleInt(v, "secure_delete", b);
112054  break;
112055  }
112056 
112057  /*
112058  ** PRAGMA [schema.]max_page_count
112059  ** PRAGMA [schema.]max_page_count=N
112060  **
112061  ** The first form reports the current setting for the
112062  ** maximum number of pages in the database file. The
112063  ** second form attempts to change this setting. Both
112064  ** forms return the current setting.
112065  **
112066  ** The absolute value of N is used. This is undocumented and might
112067  ** change. The only purpose is to provide an easy way to test
112068  ** the sqlite3AbsInt32() function.
112069  **
112070  ** PRAGMA [schema.]page_count
112071  **
112072  ** Return the number of pages in the specified database.
112073  */
112074  case PragTyp_PAGE_COUNT: {
112075  int iReg;
112076  sqlite3CodeVerifySchema(pParse, iDb);
112077  iReg = ++pParse->nMem;
112078  if( sqlite3Tolower(zLeft[0])=='p' ){
112079  sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
112080  }else{
112081  sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
112082  sqlite3AbsInt32(sqlite3Atoi(zRight)));
112083  }
112084  sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
112085  sqlite3VdbeSetNumCols(v, 1);
112086  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
112087  break;
112088  }
112089 
112090  /*
112091  ** PRAGMA [schema.]locking_mode
112092  ** PRAGMA [schema.]locking_mode = (normal|exclusive)
112093  */
112094  case PragTyp_LOCKING_MODE: {
112095  const char *zRet = "normal";
112096  int eMode = getLockingMode(zRight);
112097 
112098  if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
112099  /* Simple "PRAGMA locking_mode;" statement. This is a query for
112100  ** the current default locking mode (which may be different to
112101  ** the locking-mode of the main database).
112102  */
112103  eMode = db->dfltLockMode;
112104  }else{
112105  Pager *pPager;
112106  if( pId2->n==0 ){
112107  /* This indicates that no database name was specified as part
112108  ** of the PRAGMA command. In this case the locking-mode must be
112109  ** set on all attached databases, as well as the main db file.
112110  **
112111  ** Also, the sqlite3.dfltLockMode variable is set so that
112112  ** any subsequently attached databases also use the specified
112113  ** locking mode.
112114  */
112115  int ii;
112116  assert(pDb==&db->aDb[0]);
112117  for(ii=2; ii<db->nDb; ii++){
112118  pPager = sqlite3BtreePager(db->aDb[ii].pBt);
112119  sqlite3PagerLockingMode(pPager, eMode);
112120  }
112121  db->dfltLockMode = (u8)eMode;
112122  }
112123  pPager = sqlite3BtreePager(pDb->pBt);
112124  eMode = sqlite3PagerLockingMode(pPager, eMode);
112125  }
112126 
112127  assert( eMode==PAGER_LOCKINGMODE_NORMAL
112128  || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
112129  if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
112130  zRet = "exclusive";
112131  }
112132  returnSingleText(v, "locking_mode", zRet);
112133  break;
112134  }
112135 
112136  /*
112137  ** PRAGMA [schema.]journal_mode
112138  ** PRAGMA [schema.]journal_mode =
112139  ** (delete|persist|off|truncate|memory|wal|off)
112140  */
112141  case PragTyp_JOURNAL_MODE: {
112142  int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
112143  int ii; /* Loop counter */
112144 
112145  setOneColumnName(v, "journal_mode");
112146  if( zRight==0 ){
112147  /* If there is no "=MODE" part of the pragma, do a query for the
112148  ** current mode */
112149  eMode = PAGER_JOURNALMODE_QUERY;
112150  }else{
112151  const char *zMode;
112152  int n = sqlite3Strlen30(zRight);
112153  for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
112154  if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
112155  }
112156  if( !zMode ){
112157  /* If the "=MODE" part does not match any known journal mode,
112158  ** then do a query */
112159  eMode = PAGER_JOURNALMODE_QUERY;
112160  }
112161  }
112162  if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
112163  /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
112164  iDb = 0;
112165  pId2->n = 1;
112166  }
112167  for(ii=db->nDb-1; ii>=0; ii--){
112168  if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
112169  sqlite3VdbeUsesBtree(v, ii);
112170  sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
112171  }
112172  }
112173  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
112174  break;
112175  }
112176 
112177  /*
112178  ** PRAGMA [schema.]journal_size_limit
112179  ** PRAGMA [schema.]journal_size_limit=N
112180  **
112181  ** Get or set the size limit on rollback journal files.
112182  */
112183  case PragTyp_JOURNAL_SIZE_LIMIT: {
112184  Pager *pPager = sqlite3BtreePager(pDb->pBt);
112185  i64 iLimit = -2;
112186  if( zRight ){
112187  sqlite3DecOrHexToI64(zRight, &iLimit);
112188  if( iLimit<-1 ) iLimit = -1;
112189  }
112190  iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
112191  returnSingleInt(v, "journal_size_limit", iLimit);
112192  break;
112193  }
112194 
112195 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
112196 
112197  /*
112198  ** PRAGMA [schema.]auto_vacuum
112199  ** PRAGMA [schema.]auto_vacuum=N
112200  **
112201  ** Get or set the value of the database 'auto-vacuum' parameter.
112202  ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
112203  */
112204 #ifndef SQLITE_OMIT_AUTOVACUUM
112205  case PragTyp_AUTO_VACUUM: {
112206  Btree *pBt = pDb->pBt;
112207  assert( pBt!=0 );
112208  if( !zRight ){
112209  returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
112210  }else{
112211  int eAuto = getAutoVacuum(zRight);
112212  assert( eAuto>=0 && eAuto<=2 );
112213  db->nextAutovac = (u8)eAuto;
112214  /* Call SetAutoVacuum() to set initialize the internal auto and
112215  ** incr-vacuum flags. This is required in case this connection
112216  ** creates the database file. It is important that it is created
112217  ** as an auto-vacuum capable db.
112218  */
112219  rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
112220  if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
112221  /* When setting the auto_vacuum mode to either "full" or
112222  ** "incremental", write the value of meta[6] in the database
112223  ** file. Before writing to meta[6], check that meta[3] indicates
112224  ** that this really is an auto-vacuum capable database.
112225  */
112226  static const int iLn = VDBE_OFFSET_LINENO(2);
112227  static const VdbeOpList setMeta6[] = {
112228  { OP_Transaction, 0, 1, 0}, /* 0 */
112229  { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
112230  { OP_If, 1, 0, 0}, /* 2 */
112231  { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
112232  { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
112233  };
112234  VdbeOp *aOp;
112235  int iAddr = sqlite3VdbeCurrentAddr(v);
112236  sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
112237  aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
112238  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
112239  aOp[0].p1 = iDb;
112240  aOp[1].p1 = iDb;
112241  aOp[2].p2 = iAddr+4;
112242  aOp[4].p1 = iDb;
112243  aOp[4].p3 = eAuto - 1;
112244  sqlite3VdbeUsesBtree(v, iDb);
112245  }
112246  }
112247  break;
112248  }
112249 #endif
112250 
112251  /*
112252  ** PRAGMA [schema.]incremental_vacuum(N)
112253  **
112254  ** Do N steps of incremental vacuuming on a database.
112255  */
112256 #ifndef SQLITE_OMIT_AUTOVACUUM
112257  case PragTyp_INCREMENTAL_VACUUM: {
112258  int iLimit, addr;
112259  if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
112260  iLimit = 0x7fffffff;
112261  }
112262  sqlite3BeginWriteOperation(pParse, 0, iDb);
112263  sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
112264  addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
112265  sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
112266  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
112267  sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
112268  sqlite3VdbeJumpHere(v, addr);
112269  break;
112270  }
112271 #endif
112272 
112273 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
112274  /*
112275  ** PRAGMA [schema.]cache_size
112276  ** PRAGMA [schema.]cache_size=N
112277  **
112278  ** The first form reports the current local setting for the
112279  ** page cache size. The second form sets the local
112280  ** page cache size value. If N is positive then that is the
112281  ** number of pages in the cache. If N is negative, then the
112282  ** number of pages is adjusted so that the cache uses -N kibibytes
112283  ** of memory.
112284  */
112285  case PragTyp_CACHE_SIZE: {
112286  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112287  if( !zRight ){
112288  returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
112289  }else{
112290  int size = sqlite3Atoi(zRight);
112291  pDb->pSchema->cache_size = size;
112292  sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
112293  }
112294  break;
112295  }
112296 
112297  /*
112298  ** PRAGMA [schema.]cache_spill
112299  ** PRAGMA cache_spill=BOOLEAN
112300  ** PRAGMA [schema.]cache_spill=N
112301  **
112302  ** The first form reports the current local setting for the
112303  ** page cache spill size. The second form turns cache spill on
112304  ** or off. When turnning cache spill on, the size is set to the
112305  ** current cache_size. The third form sets a spill size that
112306  ** may be different form the cache size.
112307  ** If N is positive then that is the
112308  ** number of pages in the cache. If N is negative, then the
112309  ** number of pages is adjusted so that the cache uses -N kibibytes
112310  ** of memory.
112311  **
112312  ** If the number of cache_spill pages is less then the number of
112313  ** cache_size pages, no spilling occurs until the page count exceeds
112314  ** the number of cache_size pages.
112315  **
112316  ** The cache_spill=BOOLEAN setting applies to all attached schemas,
112317  ** not just the schema specified.
112318  */
112319  case PragTyp_CACHE_SPILL: {
112320  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112321  if( !zRight ){
112322  returnSingleInt(v, "cache_spill",
112323  (db->flags & SQLITE_CacheSpill)==0 ? 0 :
112324  sqlite3BtreeSetSpillSize(pDb->pBt,0));
112325  }else{
112326  int size = 1;
112327  if( sqlite3GetInt32(zRight, &size) ){
112328  sqlite3BtreeSetSpillSize(pDb->pBt, size);
112329  }
112330  if( sqlite3GetBoolean(zRight, size!=0) ){
112331  db->flags |= SQLITE_CacheSpill;
112332  }else{
112333  db->flags &= ~SQLITE_CacheSpill;
112334  }
112335  setAllPagerFlags(db);
112336  }
112337  break;
112338  }
112339 
112340  /*
112341  ** PRAGMA [schema.]mmap_size(N)
112342  **
112343  ** Used to set mapping size limit. The mapping size limit is
112344  ** used to limit the aggregate size of all memory mapped regions of the
112345  ** database file. If this parameter is set to zero, then memory mapping
112346  ** is not used at all. If N is negative, then the default memory map
112347  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
112348  ** The parameter N is measured in bytes.
112349  **
112350  ** This value is advisory. The underlying VFS is free to memory map
112351  ** as little or as much as it wants. Except, if N is set to 0 then the
112352  ** upper layers will never invoke the xFetch interfaces to the VFS.
112353  */
112354  case PragTyp_MMAP_SIZE: {
112355  sqlite3_int64 sz;
112356 #if SQLITE_MAX_MMAP_SIZE>0
112357  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112358  if( zRight ){
112359  int ii;
112360  sqlite3DecOrHexToI64(zRight, &sz);
112361  if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
112362  if( pId2->n==0 ) db->szMmap = sz;
112363  for(ii=db->nDb-1; ii>=0; ii--){
112364  if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
112365  sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
112366  }
112367  }
112368  }
112369  sz = -1;
112370  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
112371 #else
112372  sz = 0;
112373  rc = SQLITE_OK;
112374 #endif
112375  if( rc==SQLITE_OK ){
112376  returnSingleInt(v, "mmap_size", sz);
112377  }else if( rc!=SQLITE_NOTFOUND ){
112378  pParse->nErr++;
112379  pParse->rc = rc;
112380  }
112381  break;
112382  }
112383 
112384  /*
112385  ** PRAGMA temp_store
112386  ** PRAGMA temp_store = "default"|"memory"|"file"
112387  **
112388  ** Return or set the local value of the temp_store flag. Changing
112389  ** the local value does not make changes to the disk file and the default
112390  ** value will be restored the next time the database is opened.
112391  **
112392  ** Note that it is possible for the library compile-time options to
112393  ** override this setting
112394  */
112395  case PragTyp_TEMP_STORE: {
112396  if( !zRight ){
112397  returnSingleInt(v, "temp_store", db->temp_store);
112398  }else{
112399  changeTempStorage(pParse, zRight);
112400  }
112401  break;
112402  }
112403 
112404  /*
112405  ** PRAGMA temp_store_directory
112406  ** PRAGMA temp_store_directory = ""|"directory_name"
112407  **
112408  ** Return or set the local value of the temp_store_directory flag. Changing
112409  ** the value sets a specific directory to be used for temporary files.
112410  ** Setting to a null string reverts to the default temporary directory search.
112411  ** If temporary directory is changed, then invalidateTempStorage.
112412  **
112413  */
112414  case PragTyp_TEMP_STORE_DIRECTORY: {
112415  if( !zRight ){
112416  returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
112417  }else{
112418 #ifndef SQLITE_OMIT_WSD
112419  if( zRight[0] ){
112420  int res;
112421  rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
112422  if( rc!=SQLITE_OK || res==0 ){
112423  sqlite3ErrorMsg(pParse, "not a writable directory");
112424  goto pragma_out;
112425  }
112426  }
112427  if( SQLITE_TEMP_STORE==0
112428  || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
112429  || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
112430  ){
112431  invalidateTempStorage(pParse);
112432  }
112433  sqlite3_free(sqlite3_temp_directory);
112434  if( zRight[0] ){
112435  sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
112436  }else{
112437  sqlite3_temp_directory = 0;
112438  }
112439 #endif /* SQLITE_OMIT_WSD */
112440  }
112441  break;
112442  }
112443 
112444 #if SQLITE_OS_WIN
112445  /*
112446  ** PRAGMA data_store_directory
112447  ** PRAGMA data_store_directory = ""|"directory_name"
112448  **
112449  ** Return or set the local value of the data_store_directory flag. Changing
112450  ** the value sets a specific directory to be used for database files that
112451  ** were specified with a relative pathname. Setting to a null string reverts
112452  ** to the default database directory, which for database files specified with
112453  ** a relative path will probably be based on the current directory for the
112454  ** process. Database file specified with an absolute path are not impacted
112455  ** by this setting, regardless of its value.
112456  **
112457  */
112458  case PragTyp_DATA_STORE_DIRECTORY: {
112459  if( !zRight ){
112460  returnSingleText(v, "data_store_directory", sqlite3_data_directory);
112461  }else{
112462 #ifndef SQLITE_OMIT_WSD
112463  if( zRight[0] ){
112464  int res;
112465  rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
112466  if( rc!=SQLITE_OK || res==0 ){
112467  sqlite3ErrorMsg(pParse, "not a writable directory");
112468  goto pragma_out;
112469  }
112470  }
112471  sqlite3_free(sqlite3_data_directory);
112472  if( zRight[0] ){
112473  sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
112474  }else{
112475  sqlite3_data_directory = 0;
112476  }
112477 #endif /* SQLITE_OMIT_WSD */
112478  }
112479  break;
112480  }
112481 #endif
112482 
112483 #if SQLITE_ENABLE_LOCKING_STYLE
112484  /*
112485  ** PRAGMA [schema.]lock_proxy_file
112486  ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
112487  **
112488  ** Return or set the value of the lock_proxy_file flag. Changing
112489  ** the value sets a specific file to be used for database access locks.
112490  **
112491  */
112492  case PragTyp_LOCK_PROXY_FILE: {
112493  if( !zRight ){
112494  Pager *pPager = sqlite3BtreePager(pDb->pBt);
112495  char *proxy_file_path = NULL;
112496  sqlite3_file *pFile = sqlite3PagerFile(pPager);
112497  sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
112498  &proxy_file_path);
112499  returnSingleText(v, "lock_proxy_file", proxy_file_path);
112500  }else{
112501  Pager *pPager = sqlite3BtreePager(pDb->pBt);
112502  sqlite3_file *pFile = sqlite3PagerFile(pPager);
112503  int res;
112504  if( zRight[0] ){
112505  res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
112506  zRight);
112507  } else {
112508  res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
112509  NULL);
112510  }
112511  if( res!=SQLITE_OK ){
112512  sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
112513  goto pragma_out;
112514  }
112515  }
112516  break;
112517  }
112518 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
112519 
112520  /*
112521  ** PRAGMA [schema.]synchronous
112522  ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
112523  **
112524  ** Return or set the local value of the synchronous flag. Changing
112525  ** the local value does not make changes to the disk file and the
112526  ** default value will be restored the next time the database is
112527  ** opened.
112528  */
112529  case PragTyp_SYNCHRONOUS: {
112530  if( !zRight ){
112531  returnSingleInt(v, "synchronous", pDb->safety_level-1);
112532  }else{
112533  if( !db->autoCommit ){
112534  sqlite3ErrorMsg(pParse,
112535  "Safety level may not be changed inside a transaction");
112536  }else{
112537  int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
112538  if( iLevel==0 ) iLevel = 1;
112539  pDb->safety_level = iLevel;
112540  pDb->bSyncSet = 1;
112541  setAllPagerFlags(db);
112542  }
112543  }
112544  break;
112545  }
112546 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
112547 
112548 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
112549  case PragTyp_FLAG: {
112550  if( zRight==0 ){
112551  returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
112552  }else{
112553  int mask = pPragma->iArg; /* Mask of bits to set or clear. */
112554  if( db->autoCommit==0 ){
112555  /* Foreign key support may not be enabled or disabled while not
112556  ** in auto-commit mode. */
112557  mask &= ~(SQLITE_ForeignKeys);
112558  }
112559 #if SQLITE_USER_AUTHENTICATION
112560  if( db->auth.authLevel==UAUTH_User ){
112561  /* Do not allow non-admin users to modify the schema arbitrarily */
112562  mask &= ~(SQLITE_WriteSchema);
112563  }
112564 #endif
112565 
112566  if( sqlite3GetBoolean(zRight, 0) ){
112567  db->flags |= mask;
112568  }else{
112569  db->flags &= ~mask;
112570  if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
112571  }
112572 
112573  /* Many of the flag-pragmas modify the code generated by the SQL
112574  ** compiler (eg. count_changes). So add an opcode to expire all
112575  ** compiled SQL statements after modifying a pragma value.
112576  */
112577  sqlite3VdbeAddOp0(v, OP_Expire);
112578  setAllPagerFlags(db);
112579  }
112580  break;
112581  }
112582 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
112583 
112584 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
112585  /*
112586  ** PRAGMA table_info(<table>)
112587  **
112588  ** Return a single row for each column of the named table. The columns of
112589  ** the returned data set are:
112590  **
112591  ** cid: Column id (numbered from left to right, starting at 0)
112592  ** name: Column name
112593  ** type: Column declaration type.
112594  ** notnull: True if 'NOT NULL' is part of column declaration
112595  ** dflt_value: The default value for the column, if any.
112596  */
112597  case PragTyp_TABLE_INFO: if( zRight ){
112598  Table *pTab;
112599  pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
112600  if( pTab ){
112601  static const char *azCol[] = {
112602  "cid", "name", "type", "notnull", "dflt_value", "pk"
112603  };
112604  int i, k;
112605  int nHidden = 0;
112606  Column *pCol;
112607  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
112608  pParse->nMem = 6;
112609  sqlite3CodeVerifySchema(pParse, iDb);
112610  setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
112611  sqlite3ViewGetColumnNames(pParse, pTab);
112612  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
112613  if( IsHiddenColumn(pCol) ){
112614  nHidden++;
112615  continue;
112616  }
112617  if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
112618  k = 0;
112619  }else if( pPk==0 ){
112620  k = 1;
112621  }else{
112622  for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
112623  }
112624  assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
112625  sqlite3VdbeMultiLoad(v, 1, "issisi",
112626  i-nHidden,
112627  pCol->zName,
112628  sqlite3ColumnType(pCol,""),
112629  pCol->notNull ? 1 : 0,
112630  pCol->pDflt ? pCol->pDflt->u.zToken : 0,
112631  k);
112632  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
112633  }
112634  }
112635  }
112636  break;
112637 
112638  case PragTyp_STATS: {
112639  static const char *azCol[] = { "table", "index", "width", "height" };
112640  Index *pIdx;
112641  HashElem *i;
112642  v = sqlite3GetVdbe(pParse);
112643  pParse->nMem = 4;
112644  sqlite3CodeVerifySchema(pParse, iDb);
112645  setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
112646  for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
112647  Table *pTab = sqliteHashData(i);
112648  sqlite3VdbeMultiLoad(v, 1, "ssii",
112649  pTab->zName,
112650  0,
112651  pTab->szTabRow,
112652  pTab->nRowLogEst);
112653  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
112654  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
112655  sqlite3VdbeMultiLoad(v, 2, "sii",
112656  pIdx->zName,
112657  pIdx->szIdxRow,
112658  pIdx->aiRowLogEst[0]);
112659  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
112660  }
112661  }
112662  }
112663  break;
112664 
112665  case PragTyp_INDEX_INFO: if( zRight ){
112666  Index *pIdx;
112667  Table *pTab;
112668  pIdx = sqlite3FindIndex(db, zRight, zDb);
112669  if( pIdx ){
112670  static const char *azCol[] = {
112671  "seqno", "cid", "name", "desc", "coll", "key"
112672  };
112673  int i;
112674  int mx;
112675  if( pPragma->iArg ){
112676  /* PRAGMA index_xinfo (newer version with more rows and columns) */
112677  mx = pIdx->nColumn;
112678  pParse->nMem = 6;
112679  }else{
112680  /* PRAGMA index_info (legacy version) */
112681  mx = pIdx->nKeyCol;
112682  pParse->nMem = 3;
112683  }
112684  pTab = pIdx->pTable;
112685  sqlite3CodeVerifySchema(pParse, iDb);
112686  assert( pParse->nMem<=ArraySize(azCol) );
112687  setAllColumnNames(v, pParse->nMem, azCol);
112688  for(i=0; i<mx; i++){
112689  i16 cnum = pIdx->aiColumn[i];
112690  sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
112691  cnum<0 ? 0 : pTab->aCol[cnum].zName);
112692  if( pPragma->iArg ){
112693  sqlite3VdbeMultiLoad(v, 4, "isi",
112694  pIdx->aSortOrder[i],
112695  pIdx->azColl[i],
112696  i<pIdx->nKeyCol);
112697  }
112698  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
112699  }
112700  }
112701  }
112702  break;
112703 
112704  case PragTyp_INDEX_LIST: if( zRight ){
112705  Index *pIdx;
112706  Table *pTab;
112707  int i;
112708  pTab = sqlite3FindTable(db, zRight, zDb);
112709  if( pTab ){
112710  static const char *azCol[] = {
112711  "seq", "name", "unique", "origin", "partial"
112712  };
112713  v = sqlite3GetVdbe(pParse);
112714  pParse->nMem = 5;
112715  sqlite3CodeVerifySchema(pParse, iDb);
112716  setAllColumnNames(v, 5, azCol); assert( 5==ArraySize(azCol) );
112717  for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
112718  const char *azOrigin[] = { "c", "u", "pk" };
112719  sqlite3VdbeMultiLoad(v, 1, "isisi",
112720  i,
112721  pIdx->zName,
112722  IsUniqueIndex(pIdx),
112723  azOrigin[pIdx->idxType],
112724  pIdx->pPartIdxWhere!=0);
112725  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
112726  }
112727  }
112728  }
112729  break;
112730 
112731  case PragTyp_DATABASE_LIST: {
112732  static const char *azCol[] = { "seq", "name", "file" };
112733  int i;
112734  pParse->nMem = 3;
112735  setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
112736  for(i=0; i<db->nDb; i++){
112737  if( db->aDb[i].pBt==0 ) continue;
112738  assert( db->aDb[i].zDbSName!=0 );
112739  sqlite3VdbeMultiLoad(v, 1, "iss",
112740  i,
112741  db->aDb[i].zDbSName,
112742  sqlite3BtreeGetFilename(db->aDb[i].pBt));
112743  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
112744  }
112745  }
112746  break;
112747 
112748  case PragTyp_COLLATION_LIST: {
112749  static const char *azCol[] = { "seq", "name" };
112750  int i = 0;
112751  HashElem *p;
112752  pParse->nMem = 2;
112753  setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
112754  for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
112755  CollSeq *pColl = (CollSeq *)sqliteHashData(p);
112756  sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
112757  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
112758  }
112759  }
112760  break;
112761 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
112762 
112763 #ifndef SQLITE_OMIT_FOREIGN_KEY
112764  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
112765  FKey *pFK;
112766  Table *pTab;
112767  pTab = sqlite3FindTable(db, zRight, zDb);
112768  if( pTab ){
112769  v = sqlite3GetVdbe(pParse);
112770  pFK = pTab->pFKey;
112771  if( pFK ){
112772  static const char *azCol[] = {
112773  "id", "seq", "table", "from", "to", "on_update", "on_delete",
112774  "match"
112775  };
112776  int i = 0;
112777  pParse->nMem = 8;
112778  sqlite3CodeVerifySchema(pParse, iDb);
112779  setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
112780  while(pFK){
112781  int j;
112782  for(j=0; j<pFK->nCol; j++){
112783  sqlite3VdbeMultiLoad(v, 1, "iissssss",
112784  i,
112785  j,
112786  pFK->zTo,
112787  pTab->aCol[pFK->aCol[j].iFrom].zName,
112788  pFK->aCol[j].zCol,
112789  actionName(pFK->aAction[1]), /* ON UPDATE */
112790  actionName(pFK->aAction[0]), /* ON DELETE */
112791  "NONE");
112792  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
112793  }
112794  ++i;
112795  pFK = pFK->pNextFrom;
112796  }
112797  }
112798  }
112799  }
112800  break;
112801 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
112802 
112803 #ifndef SQLITE_OMIT_FOREIGN_KEY
112804 #ifndef SQLITE_OMIT_TRIGGER
112805  case PragTyp_FOREIGN_KEY_CHECK: {
112806  FKey *pFK; /* A foreign key constraint */
112807  Table *pTab; /* Child table contain "REFERENCES" keyword */
112808  Table *pParent; /* Parent table that child points to */
112809  Index *pIdx; /* Index in the parent table */
112810  int i; /* Loop counter: Foreign key number for pTab */
112811  int j; /* Loop counter: Field of the foreign key */
112812  HashElem *k; /* Loop counter: Next table in schema */
112813  int x; /* result variable */
112814  int regResult; /* 3 registers to hold a result row */
112815  int regKey; /* Register to hold key for checking the FK */
112816  int regRow; /* Registers to hold a row from pTab */
112817  int addrTop; /* Top of a loop checking foreign keys */
112818  int addrOk; /* Jump here if the key is OK */
112819  int *aiCols; /* child to parent column mapping */
112820  static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
112821 
112822  regResult = pParse->nMem+1;
112823  pParse->nMem += 4;
112824  regKey = ++pParse->nMem;
112825  regRow = ++pParse->nMem;
112826  v = sqlite3GetVdbe(pParse);
112827  setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
112828  sqlite3CodeVerifySchema(pParse, iDb);
112829  k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
112830  while( k ){
112831  if( zRight ){
112832  pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
112833  k = 0;
112834  }else{
112835  pTab = (Table*)sqliteHashData(k);
112836  k = sqliteHashNext(k);
112837  }
112838  if( pTab==0 || pTab->pFKey==0 ) continue;
112839  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
112840  if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
112841  sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
112842  sqlite3VdbeLoadString(v, regResult, pTab->zName);
112843  for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
112844  pParent = sqlite3FindTable(db, pFK->zTo, zDb);
112845  if( pParent==0 ) continue;
112846  pIdx = 0;
112847  sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
112848  x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
112849  if( x==0 ){
112850  if( pIdx==0 ){
112851  sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
112852  }else{
112853  sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
112854  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
112855  }
112856  }else{
112857  k = 0;
112858  break;
112859  }
112860  }
112861  assert( pParse->nErr>0 || pFK==0 );
112862  if( pFK ) break;
112863  if( pParse->nTab<i ) pParse->nTab = i;
112864  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
112865  for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
112866  pParent = sqlite3FindTable(db, pFK->zTo, zDb);
112867  pIdx = 0;
112868  aiCols = 0;
112869  if( pParent ){
112870  x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
112871  assert( x==0 );
112872  }
112873  addrOk = sqlite3VdbeMakeLabel(v);
112874  if( pParent && pIdx==0 ){
112875  int iKey = pFK->aCol[0].iFrom;
112876  assert( iKey>=0 && iKey<pTab->nCol );
112877  if( iKey!=pTab->iPKey ){
112878  sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
112879  sqlite3ColumnDefault(v, pTab, iKey, regRow);
112880  sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
112881  }else{
112882  sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
112883  }
112884  sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v);
112885  sqlite3VdbeGoto(v, addrOk);
112886  sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
112887  }else{
112888  for(j=0; j<pFK->nCol; j++){
112889  sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
112890  aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
112891  sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
112892  }
112893  if( pParent ){
112894  sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
112895  sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
112896  sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
112897  VdbeCoverage(v);
112898  }
112899  }
112900  sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
112901  sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
112902  sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
112903  sqlite3VdbeResolveLabel(v, addrOk);
112904  sqlite3DbFree(db, aiCols);
112905  }
112906  sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
112907  sqlite3VdbeJumpHere(v, addrTop);
112908  }
112909  }
112910  break;
112911 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
112912 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
112913 
112914 #ifndef NDEBUG
112915  case PragTyp_PARSER_TRACE: {
112916  if( zRight ){
112917  if( sqlite3GetBoolean(zRight, 0) ){
112918  sqlite3ParserTrace(stdout, "parser: ");
112919  }else{
112920  sqlite3ParserTrace(0, 0);
112921  }
112922  }
112923  }
112924  break;
112925 #endif
112926 
112927  /* Reinstall the LIKE and GLOB functions. The variant of LIKE
112928  ** used will be case sensitive or not depending on the RHS.
112929  */
112930  case PragTyp_CASE_SENSITIVE_LIKE: {
112931  if( zRight ){
112932  sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
112933  }
112934  }
112935  break;
112936 
112937 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
112938 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
112939 #endif
112940 
112941 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
112942  /* Pragma "quick_check" is reduced version of
112943  ** integrity_check designed to detect most database corruption
112944  ** without most of the overhead of a full integrity-check.
112945  */
112946  case PragTyp_INTEGRITY_CHECK: {
112947  int i, j, addr, mxErr;
112948 
112949  int isQuick = (sqlite3Tolower(zLeft[0])=='q');
112950 
112951  /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
112952  ** then iDb is set to the index of the database identified by <db>.
112953  ** In this case, the integrity of database iDb only is verified by
112954  ** the VDBE created below.
112955  **
112956  ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
112957  ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
112958  ** to -1 here, to indicate that the VDBE should verify the integrity
112959  ** of all attached databases. */
112960  assert( iDb>=0 );
112961  assert( iDb==0 || pId2->z );
112962  if( pId2->z==0 ) iDb = -1;
112963 
112964  /* Initialize the VDBE program */
112965  pParse->nMem = 6;
112966  setOneColumnName(v, "integrity_check");
112967 
112968  /* Set the maximum error count */
112969  mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
112970  if( zRight ){
112971  sqlite3GetInt32(zRight, &mxErr);
112972  if( mxErr<=0 ){
112973  mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
112974  }
112975  }
112976  sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
112977 
112978  /* Do an integrity check on each database file */
112979  for(i=0; i<db->nDb; i++){
112980  HashElem *x;
112981  Hash *pTbls;
112982  int *aRoot;
112983  int cnt = 0;
112984  int mxIdx = 0;
112985  int nIdx;
112986 
112987  if( OMIT_TEMPDB && i==1 ) continue;
112988  if( iDb>=0 && i!=iDb ) continue;
112989 
112990  sqlite3CodeVerifySchema(pParse, i);
112991  addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
112992  VdbeCoverage(v);
112993  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112994  sqlite3VdbeJumpHere(v, addr);
112995 
112996  /* Do an integrity check of the B-Tree
112997  **
112998  ** Begin by finding the root pages numbers
112999  ** for all tables and indices in the database.
113000  */
113001  assert( sqlite3SchemaMutexHeld(db, i, 0) );
113002  pTbls = &db->aDb[i].pSchema->tblHash;
113003  for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
113004  Table *pTab = sqliteHashData(x);
113005  Index *pIdx;
113006  if( HasRowid(pTab) ) cnt++;
113007  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
113008  if( nIdx>mxIdx ) mxIdx = nIdx;
113009  }
113010  aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
113011  if( aRoot==0 ) break;
113012  for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
113013  Table *pTab = sqliteHashData(x);
113014  Index *pIdx;
113015  if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
113016  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
113017  aRoot[cnt++] = pIdx->tnum;
113018  }
113019  }
113020  aRoot[cnt] = 0;
113021 
113022  /* Make sure sufficient number of registers have been allocated */
113023  pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
113024 
113025  /* Do the b-tree integrity checks */
113026  sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
113027  sqlite3VdbeChangeP5(v, (u8)i);
113028  addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
113029  sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
113030  sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
113031  P4_DYNAMIC);
113032  sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
113033  sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
113034  sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
113035  sqlite3VdbeJumpHere(v, addr);
113036 
113037  /* Make sure all the indices are constructed correctly.
113038  */
113039  for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
113040  Table *pTab = sqliteHashData(x);
113041  Index *pIdx, *pPk;
113042  Index *pPrior = 0;
113043  int loopTop;
113044  int iDataCur, iIdxCur;
113045  int r1 = -1;
113046 
113047  if( pTab->pIndex==0 ) continue;
113048  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
113049  addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
113050  VdbeCoverage(v);
113051  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
113052  sqlite3VdbeJumpHere(v, addr);
113053  sqlite3ExprCacheClear(pParse);
113054  sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
113055  1, 0, &iDataCur, &iIdxCur);
113056  sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
113057  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
113058  sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
113059  }
113060  assert( pParse->nMem>=8+j );
113061  assert( sqlite3NoTempsInRange(pParse,1,7+j) );
113062  sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
113063  loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
113064  /* Verify that all NOT NULL columns really are NOT NULL */
113065  for(j=0; j<pTab->nCol; j++){
113066  char *zErr;
113067  int jmp2, jmp3;
113068  if( j==pTab->iPKey ) continue;
113069  if( pTab->aCol[j].notNull==0 ) continue;
113070  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
113071  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
113072  jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
113073  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
113074  zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
113075  pTab->aCol[j].zName);
113076  sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
113077  sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
113078  jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
113079  sqlite3VdbeAddOp0(v, OP_Halt);
113080  sqlite3VdbeJumpHere(v, jmp2);
113081  sqlite3VdbeJumpHere(v, jmp3);
113082  }
113083  /* Validate index entries for the current row */
113084  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
113085  int jmp2, jmp3, jmp4, jmp5;
113086  int ckUniq = sqlite3VdbeMakeLabel(v);
113087  if( pPk==pIdx ) continue;
113088  r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
113089  pPrior, r1);
113090  pPrior = pIdx;
113091  sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
113092  /* Verify that an index entry exists for the current table row */
113093  jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
113094  pIdx->nColumn); VdbeCoverage(v);
113095  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
113096  sqlite3VdbeLoadString(v, 3, "row ");
113097  sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
113098  sqlite3VdbeLoadString(v, 4, " missing from index ");
113099  sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
113100  jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
113101  sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
113102  sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
113103  jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
113104  sqlite3VdbeAddOp0(v, OP_Halt);
113105  sqlite3VdbeJumpHere(v, jmp2);
113106  /* For UNIQUE indexes, verify that only one entry exists with the
113107  ** current key. The entry is unique if (1) any column is NULL
113108  ** or (2) the next entry has a different key */
113109  if( IsUniqueIndex(pIdx) ){
113110  int uniqOk = sqlite3VdbeMakeLabel(v);
113111  int jmp6;
113112  int kk;
113113  for(kk=0; kk<pIdx->nKeyCol; kk++){
113114  int iCol = pIdx->aiColumn[kk];
113115  assert( iCol!=XN_ROWID && iCol<pTab->nCol );
113116  if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
113117  sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
113118  VdbeCoverage(v);
113119  }
113120  jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
113121  sqlite3VdbeGoto(v, uniqOk);
113122  sqlite3VdbeJumpHere(v, jmp6);
113123  sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
113124  pIdx->nKeyCol); VdbeCoverage(v);
113125  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
113126  sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
113127  sqlite3VdbeGoto(v, jmp5);
113128  sqlite3VdbeResolveLabel(v, uniqOk);
113129  }
113130  sqlite3VdbeJumpHere(v, jmp4);
113131  sqlite3ResolvePartIdxLabel(pParse, jmp3);
113132  }
113133  sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
113134  sqlite3VdbeJumpHere(v, loopTop-1);
113135 #ifndef SQLITE_OMIT_BTREECOUNT
113136  sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
113137  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
113138  if( pPk==pIdx ) continue;
113139  addr = sqlite3VdbeCurrentAddr(v);
113140  sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
113141  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
113142  sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
113143  sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
113144  sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
113145  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
113146  sqlite3VdbeLoadString(v, 3, pIdx->zName);
113147  sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
113148  sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
113149  }
113150 #endif /* SQLITE_OMIT_BTREECOUNT */
113151  }
113152  }
113153  {
113154  static const int iLn = VDBE_OFFSET_LINENO(2);
113155  static const VdbeOpList endCode[] = {
113156  { OP_AddImm, 1, 0, 0}, /* 0 */
113157  { OP_If, 1, 4, 0}, /* 1 */
113158  { OP_String8, 0, 3, 0}, /* 2 */
113159  { OP_ResultRow, 3, 1, 0}, /* 3 */
113160  };
113161  VdbeOp *aOp;
113162 
113163  aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
113164  if( aOp ){
113165  aOp[0].p2 = -mxErr;
113166  aOp[2].p4type = P4_STATIC;
113167  aOp[2].p4.z = "ok";
113168  }
113169  }
113170  }
113171  break;
113172 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
113173 
113174 #ifndef SQLITE_OMIT_UTF16
113175  /*
113176  ** PRAGMA encoding
113177  ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
113178  **
113179  ** In its first form, this pragma returns the encoding of the main
113180  ** database. If the database is not initialized, it is initialized now.
113181  **
113182  ** The second form of this pragma is a no-op if the main database file
113183  ** has not already been initialized. In this case it sets the default
113184  ** encoding that will be used for the main database file if a new file
113185  ** is created. If an existing main database file is opened, then the
113186  ** default text encoding for the existing database is used.
113187  **
113188  ** In all cases new databases created using the ATTACH command are
113189  ** created to use the same default text encoding as the main database. If
113190  ** the main database has not been initialized and/or created when ATTACH
113191  ** is executed, this is done before the ATTACH operation.
113192  **
113193  ** In the second form this pragma sets the text encoding to be used in
113194  ** new database files created using this database handle. It is only
113195  ** useful if invoked immediately after the main database i
113196  */
113197  case PragTyp_ENCODING: {
113198  static const struct EncName {
113199  char *zName;
113200  u8 enc;
113201  } encnames[] = {
113202  { "UTF8", SQLITE_UTF8 },
113203  { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
113204  { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
113205  { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
113206  { "UTF16le", SQLITE_UTF16LE },
113207  { "UTF16be", SQLITE_UTF16BE },
113208  { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
113209  { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
113210  { 0, 0 }
113211  };
113212  const struct EncName *pEnc;
113213  if( !zRight ){ /* "PRAGMA encoding" */
113214  if( sqlite3ReadSchema(pParse) ) goto pragma_out;
113215  assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
113216  assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
113217  assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
113218  returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
113219  }else{ /* "PRAGMA encoding = XXX" */
113220  /* Only change the value of sqlite.enc if the database handle is not
113221  ** initialized. If the main database exists, the new sqlite.enc value
113222  ** will be overwritten when the schema is next loaded. If it does not
113223  ** already exists, it will be created to use the new encoding value.
113224  */
113225  if(
113226  !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
113227  DbHasProperty(db, 0, DB_Empty)
113228  ){
113229  for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
113230  if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
113231  SCHEMA_ENC(db) = ENC(db) =
113232  pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
113233  break;
113234  }
113235  }
113236  if( !pEnc->zName ){
113237  sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
113238  }
113239  }
113240  }
113241  }
113242  break;
113243 #endif /* SQLITE_OMIT_UTF16 */
113244 
113245 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
113246  /*
113247  ** PRAGMA [schema.]schema_version
113248  ** PRAGMA [schema.]schema_version = <integer>
113249  **
113250  ** PRAGMA [schema.]user_version
113251  ** PRAGMA [schema.]user_version = <integer>
113252  **
113253  ** PRAGMA [schema.]freelist_count
113254  **
113255  ** PRAGMA [schema.]data_version
113256  **
113257  ** PRAGMA [schema.]application_id
113258  ** PRAGMA [schema.]application_id = <integer>
113259  **
113260  ** The pragma's schema_version and user_version are used to set or get
113261  ** the value of the schema-version and user-version, respectively. Both
113262  ** the schema-version and the user-version are 32-bit signed integers
113263  ** stored in the database header.
113264  **
113265  ** The schema-cookie is usually only manipulated internally by SQLite. It
113266  ** is incremented by SQLite whenever the database schema is modified (by
113267  ** creating or dropping a table or index). The schema version is used by
113268  ** SQLite each time a query is executed to ensure that the internal cache
113269  ** of the schema used when compiling the SQL query matches the schema of
113270  ** the database against which the compiled query is actually executed.
113271  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
113272  ** the schema-version is potentially dangerous and may lead to program
113273  ** crashes or database corruption. Use with caution!
113274  **
113275  ** The user-version is not used internally by SQLite. It may be used by
113276  ** applications for any purpose.
113277  */
113278  case PragTyp_HEADER_VALUE: {
113279  int iCookie = pPragma->iArg; /* Which cookie to read or write */
113280  sqlite3VdbeUsesBtree(v, iDb);
113281  if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
113282  /* Write the specified cookie value */
113283  static const VdbeOpList setCookie[] = {
113284  { OP_Transaction, 0, 1, 0}, /* 0 */
113285  { OP_SetCookie, 0, 0, 0}, /* 1 */
113286  };
113287  VdbeOp *aOp;
113288  sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
113289  aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
113290  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
113291  aOp[0].p1 = iDb;
113292  aOp[1].p1 = iDb;
113293  aOp[1].p2 = iCookie;
113294  aOp[1].p3 = sqlite3Atoi(zRight);
113295  }else{
113296  /* Read the specified cookie value */
113297  static const VdbeOpList readCookie[] = {
113298  { OP_Transaction, 0, 0, 0}, /* 0 */
113299  { OP_ReadCookie, 0, 1, 0}, /* 1 */
113300  { OP_ResultRow, 1, 1, 0}
113301  };
113302  VdbeOp *aOp;
113303  sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
113304  aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
113305  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
113306  aOp[0].p1 = iDb;
113307  aOp[1].p1 = iDb;
113308  aOp[1].p3 = iCookie;
113309  sqlite3VdbeSetNumCols(v, 1);
113310  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
113311  sqlite3VdbeReusable(v);
113312  }
113313  }
113314  break;
113315 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
113316 
113317 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
113318  /*
113319  ** PRAGMA compile_options
113320  **
113321  ** Return the names of all compile-time options used in this build,
113322  ** one option per row.
113323  */
113324  case PragTyp_COMPILE_OPTIONS: {
113325  int i = 0;
113326  const char *zOpt;
113327  pParse->nMem = 1;
113328  setOneColumnName(v, "compile_option");
113329  while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
113330  sqlite3VdbeLoadString(v, 1, zOpt);
113331  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
113332  }
113333  sqlite3VdbeReusable(v);
113334  }
113335  break;
113336 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
113337 
113338 #ifndef SQLITE_OMIT_WAL
113339  /*
113340  ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
113341  **
113342  ** Checkpoint the database.
113343  */
113344  case PragTyp_WAL_CHECKPOINT: {
113345  static const char *azCol[] = { "busy", "log", "checkpointed" };
113346  int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
113347  int eMode = SQLITE_CHECKPOINT_PASSIVE;
113348  if( zRight ){
113349  if( sqlite3StrICmp(zRight, "full")==0 ){
113350  eMode = SQLITE_CHECKPOINT_FULL;
113351  }else if( sqlite3StrICmp(zRight, "restart")==0 ){
113352  eMode = SQLITE_CHECKPOINT_RESTART;
113353  }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
113354  eMode = SQLITE_CHECKPOINT_TRUNCATE;
113355  }
113356  }
113357  setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
113358  pParse->nMem = 3;
113359  sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
113360  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
113361  }
113362  break;
113363 
113364  /*
113365  ** PRAGMA wal_autocheckpoint
113366  ** PRAGMA wal_autocheckpoint = N
113367  **
113368  ** Configure a database connection to automatically checkpoint a database
113369  ** after accumulating N frames in the log. Or query for the current value
113370  ** of N.
113371  */
113372  case PragTyp_WAL_AUTOCHECKPOINT: {
113373  if( zRight ){
113374  sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
113375  }
113376  returnSingleInt(v, "wal_autocheckpoint",
113377  db->xWalCallback==sqlite3WalDefaultHook ?
113378  SQLITE_PTR_TO_INT(db->pWalArg) : 0);
113379  }
113380  break;
113381 #endif
113382 
113383  /*
113384  ** PRAGMA shrink_memory
113385  **
113386  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
113387  ** connection on which it is invoked to free up as much memory as it
113388  ** can, by calling sqlite3_db_release_memory().
113389  */
113390  case PragTyp_SHRINK_MEMORY: {
113391  sqlite3_db_release_memory(db);
113392  break;
113393  }
113394 
113395  /*
113396  ** PRAGMA busy_timeout
113397  ** PRAGMA busy_timeout = N
113398  **
113399  ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
113400  ** if one is set. If no busy handler or a different busy handler is set
113401  ** then 0 is returned. Setting the busy_timeout to 0 or negative
113402  ** disables the timeout.
113403  */
113404  /*case PragTyp_BUSY_TIMEOUT*/ default: {
113405  assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
113406  if( zRight ){
113407  sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
113408  }
113409  returnSingleInt(v, "timeout", db->busyTimeout);
113410  break;
113411  }
113412 
113413  /*
113414  ** PRAGMA soft_heap_limit
113415  ** PRAGMA soft_heap_limit = N
113416  **
113417  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
113418  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
113419  ** specified and is a non-negative integer.
113420  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
113421  ** returns the same integer that would be returned by the
113422  ** sqlite3_soft_heap_limit64(-1) C-language function.
113423  */
113424  case PragTyp_SOFT_HEAP_LIMIT: {
113425  sqlite3_int64 N;
113426  if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
113427  sqlite3_soft_heap_limit64(N);
113428  }
113429  returnSingleInt(v, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
113430  break;
113431  }
113432 
113433  /*
113434  ** PRAGMA threads
113435  ** PRAGMA threads = N
113436  **
113437  ** Configure the maximum number of worker threads. Return the new
113438  ** maximum, which might be less than requested.
113439  */
113440  case PragTyp_THREADS: {
113441  sqlite3_int64 N;
113442  if( zRight
113443  && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
113444  && N>=0
113445  ){
113446  sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
113447  }
113448  returnSingleInt(v, "threads",
113449  sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
113450  break;
113451  }
113452 
113453 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
113454  /*
113455  ** Report the current state of file logs for all databases
113456  */
113457  case PragTyp_LOCK_STATUS: {
113458  static const char *const azLockName[] = {
113459  "unlocked", "shared", "reserved", "pending", "exclusive"
113460  };
113461  static const char *azCol[] = { "database", "status" };
113462  int i;
113463  setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
113464  pParse->nMem = 2;
113465  for(i=0; i<db->nDb; i++){
113466  Btree *pBt;
113467  const char *zState = "unknown";
113468  int j;
113469  if( db->aDb[i].zDbSName==0 ) continue;
113470  pBt = db->aDb[i].pBt;
113471  if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
113472  zState = "closed";
113473  }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
113474  SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
113475  zState = azLockName[j];
113476  }
113477  sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
113478  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
113479  }
113480  break;
113481  }
113482 #endif
113483 
113484 #ifdef SQLITE_HAS_CODEC
113485  case PragTyp_KEY: {
113486  if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
113487  break;
113488  }
113489  case PragTyp_REKEY: {
113490  if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
113491  break;
113492  }
113493  case PragTyp_HEXKEY: {
113494  if( zRight ){
113495  u8 iByte;
113496  int i;
113497  char zKey[40];
113498  for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
113499  iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
113500  if( (i&1)!=0 ) zKey[i/2] = iByte;
113501  }
113502  if( (zLeft[3] & 0xf)==0xb ){
113503  sqlite3_key_v2(db, zDb, zKey, i/2);
113504  }else{
113505  sqlite3_rekey_v2(db, zDb, zKey, i/2);
113506  }
113507  }
113508  break;
113509  }
113510 #endif
113511 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
113512  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
113513 #ifdef SQLITE_HAS_CODEC
113514  if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
113515  sqlite3_activate_see(&zRight[4]);
113516  }
113517 #endif
113518 #ifdef SQLITE_ENABLE_CEROD
113519  if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
113520  sqlite3_activate_cerod(&zRight[6]);
113521  }
113522 #endif
113523  }
113524  break;
113525 #endif
113526 
113527  } /* End of the PRAGMA switch */
113528 
113529 pragma_out:
113530  sqlite3DbFree(db, zLeft);
113531  sqlite3DbFree(db, zRight);
113532 }
113533 
113534 #endif /* SQLITE_OMIT_PRAGMA */
113535 
113536 /************** End of pragma.c **********************************************/
113537 /************** Begin file prepare.c *****************************************/
113538 /*
113539 ** 2005 May 25
113540 **
113541 ** The author disclaims copyright to this source code. In place of
113542 ** a legal notice, here is a blessing:
113543 **
113544 ** May you do good and not evil.
113545 ** May you find forgiveness for yourself and forgive others.
113546 ** May you share freely, never taking more than you give.
113547 **
113548 *************************************************************************
113549 ** This file contains the implementation of the sqlite3_prepare()
113550 ** interface, and routines that contribute to loading the database schema
113551 ** from disk.
113552 */
113553 /* #include "sqliteInt.h" */
113554 
113555 /*
113556 ** Fill the InitData structure with an error message that indicates
113557 ** that the database is corrupt.
113558 */
113559 static void corruptSchema(
113560  InitData *pData, /* Initialization context */
113561  const char *zObj, /* Object being parsed at the point of error */
113562  const char *zExtra /* Error information */
113563 ){
113564  sqlite3 *db = pData->db;
113565  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
113566  char *z;
113567  if( zObj==0 ) zObj = "?";
113568  z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
113569  if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
113570  sqlite3DbFree(db, *pData->pzErrMsg);
113571  *pData->pzErrMsg = z;
113572  }
113573  pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
113574 }
113575 
113576 /*
113577 ** This is the callback routine for the code that initializes the
113578 ** database. See sqlite3Init() below for additional information.
113579 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
113580 **
113581 ** Each callback contains the following information:
113582 **
113583 ** argv[0] = name of thing being created
113584 ** argv[1] = root page number for table or index. 0 for trigger or view.
113585 ** argv[2] = SQL text for the CREATE statement.
113586 **
113587 */
113588 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
113589  InitData *pData = (InitData*)pInit;
113590  sqlite3 *db = pData->db;
113591  int iDb = pData->iDb;
113592 
113593  assert( argc==3 );
113594  UNUSED_PARAMETER2(NotUsed, argc);
113595  assert( sqlite3_mutex_held(db->mutex) );
113596  DbClearProperty(db, iDb, DB_Empty);
113597  if( db->mallocFailed ){
113598  corruptSchema(pData, argv[0], 0);
113599  return 1;
113600  }
113601 
113602  assert( iDb>=0 && iDb<db->nDb );
113603  if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
113604  if( argv[1]==0 ){
113605  corruptSchema(pData, argv[0], 0);
113606  }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
113607  /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
113608  ** But because db->init.busy is set to 1, no VDBE code is generated
113609  ** or executed. All the parser does is build the internal data
113610  ** structures that describe the table, index, or view.
113611  */
113612  int rc;
113613  u8 saved_iDb = db->init.iDb;
113614  sqlite3_stmt *pStmt;
113615  TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
113616 
113617  assert( db->init.busy );
113618  db->init.iDb = iDb;
113619  db->init.newTnum = sqlite3Atoi(argv[1]);
113620  db->init.orphanTrigger = 0;
113621  TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
113622  rc = db->errCode;
113623  assert( (rc&0xFF)==(rcp&0xFF) );
113624  db->init.iDb = saved_iDb;
113625  assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 );
113626  if( SQLITE_OK!=rc ){
113627  if( db->init.orphanTrigger ){
113628  assert( iDb==1 );
113629  }else{
113630  pData->rc = rc;
113631  if( rc==SQLITE_NOMEM ){
113632  sqlite3OomFault(db);
113633  }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
113634  corruptSchema(pData, argv[0], sqlite3_errmsg(db));
113635  }
113636  }
113637  }
113638  sqlite3_finalize(pStmt);
113639  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
113640  corruptSchema(pData, argv[0], 0);
113641  }else{
113642  /* If the SQL column is blank it means this is an index that
113643  ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
113644  ** constraint for a CREATE TABLE. The index should have already
113645  ** been created when we processed the CREATE TABLE. All we have
113646  ** to do here is record the root page number for that index.
113647  */
113648  Index *pIndex;
113649  pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
113650  if( pIndex==0 ){
113651  /* This can occur if there exists an index on a TEMP table which
113652  ** has the same name as another index on a permanent index. Since
113653  ** the permanent table is hidden by the TEMP table, we can also
113654  ** safely ignore the index on the permanent table.
113655  */
113656  /* Do Nothing */;
113657  }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
113658  corruptSchema(pData, argv[0], "invalid rootpage");
113659  }
113660  }
113661  return 0;
113662 }
113663 
113664 /*
113665 ** Attempt to read the database schema and initialize internal
113666 ** data structures for a single database file. The index of the
113667 ** database file is given by iDb. iDb==0 is used for the main
113668 ** database. iDb==1 should never be used. iDb>=2 is used for
113669 ** auxiliary databases. Return one of the SQLITE_ error codes to
113670 ** indicate success or failure.
113671 */
113672 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
113673  int rc;
113674  int i;
113675 #ifndef SQLITE_OMIT_DEPRECATED
113676  int size;
113677 #endif
113678  Db *pDb;
113679  char const *azArg[4];
113680  int meta[5];
113681  InitData initData;
113682  const char *zMasterName;
113683  int openedTransaction = 0;
113684 
113685  assert( iDb>=0 && iDb<db->nDb );
113686  assert( db->aDb[iDb].pSchema );
113687  assert( sqlite3_mutex_held(db->mutex) );
113688  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
113689 
113690  /* Construct the in-memory representation schema tables (sqlite_master or
113691  ** sqlite_temp_master) by invoking the parser directly. The appropriate
113692  ** table name will be inserted automatically by the parser so we can just
113693  ** use the abbreviation "x" here. The parser will also automatically tag
113694  ** the schema table as read-only. */
113695  azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
113696  azArg[1] = "1";
113697  azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
113698  "rootpage integer,sql text)";
113699  azArg[3] = 0;
113700  initData.db = db;
113701  initData.iDb = iDb;
113702  initData.rc = SQLITE_OK;
113703  initData.pzErrMsg = pzErrMsg;
113704  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
113705  if( initData.rc ){
113706  rc = initData.rc;
113707  goto error_out;
113708  }
113709 
113710  /* Create a cursor to hold the database open
113711  */
113712  pDb = &db->aDb[iDb];
113713  if( pDb->pBt==0 ){
113714  if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
113715  DbSetProperty(db, 1, DB_SchemaLoaded);
113716  }
113717  return SQLITE_OK;
113718  }
113719 
113720  /* If there is not already a read-only (or read-write) transaction opened
113721  ** on the b-tree database, open one now. If a transaction is opened, it
113722  ** will be closed before this function returns. */
113723  sqlite3BtreeEnter(pDb->pBt);
113724  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
113725  rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
113726  if( rc!=SQLITE_OK ){
113727  sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
113728  goto initone_error_out;
113729  }
113730  openedTransaction = 1;
113731  }
113732 
113733  /* Get the database meta information.
113734  **
113735  ** Meta values are as follows:
113736  ** meta[0] Schema cookie. Changes with each schema change.
113737  ** meta[1] File format of schema layer.
113738  ** meta[2] Size of the page cache.
113739  ** meta[3] Largest rootpage (auto/incr_vacuum mode)
113740  ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
113741  ** meta[5] User version
113742  ** meta[6] Incremental vacuum mode
113743  ** meta[7] unused
113744  ** meta[8] unused
113745  ** meta[9] unused
113746  **
113747  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
113748  ** the possible values of meta[4].
113749  */
113750  for(i=0; i<ArraySize(meta); i++){
113751  sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
113752  }
113753  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
113754 
113755  /* If opening a non-empty database, check the text encoding. For the
113756  ** main database, set sqlite3.enc to the encoding of the main database.
113757  ** For an attached db, it is an error if the encoding is not the same
113758  ** as sqlite3.enc.
113759  */
113760  if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
113761  if( iDb==0 ){
113762 #ifndef SQLITE_OMIT_UTF16
113763  u8 encoding;
113764  /* If opening the main database, set ENC(db). */
113765  encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
113766  if( encoding==0 ) encoding = SQLITE_UTF8;
113767  ENC(db) = encoding;
113768 #else
113769  ENC(db) = SQLITE_UTF8;
113770 #endif
113771  }else{
113772  /* If opening an attached database, the encoding much match ENC(db) */
113773  if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
113774  sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
113775  " text encoding as main database");
113776  rc = SQLITE_ERROR;
113777  goto initone_error_out;
113778  }
113779  }
113780  }else{
113781  DbSetProperty(db, iDb, DB_Empty);
113782  }
113783  pDb->pSchema->enc = ENC(db);
113784 
113785  if( pDb->pSchema->cache_size==0 ){
113786 #ifndef SQLITE_OMIT_DEPRECATED
113787  size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
113788  if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
113789  pDb->pSchema->cache_size = size;
113790 #else
113791  pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
113792 #endif
113793  sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
113794  }
113795 
113796  /*
113797  ** file_format==1 Version 3.0.0.
113798  ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
113799  ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
113800  ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
113801  */
113802  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
113803  if( pDb->pSchema->file_format==0 ){
113804  pDb->pSchema->file_format = 1;
113805  }
113806  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
113807  sqlite3SetString(pzErrMsg, db, "unsupported file format");
113808  rc = SQLITE_ERROR;
113809  goto initone_error_out;
113810  }
113811 
113812  /* Ticket #2804: When we open a database in the newer file format,
113813  ** clear the legacy_file_format pragma flag so that a VACUUM will
113814  ** not downgrade the database and thus invalidate any descending
113815  ** indices that the user might have created.
113816  */
113817  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
113818  db->flags &= ~SQLITE_LegacyFileFmt;
113819  }
113820 
113821  /* Read the schema information out of the schema tables
113822  */
113823  assert( db->init.busy );
113824  {
113825  char *zSql;
113826  zSql = sqlite3MPrintf(db,
113827  "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
113828  db->aDb[iDb].zDbSName, zMasterName);
113829 #ifndef SQLITE_OMIT_AUTHORIZATION
113830  {
113831  sqlite3_xauth xAuth;
113832  xAuth = db->xAuth;
113833  db->xAuth = 0;
113834 #endif
113835  rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
113836 #ifndef SQLITE_OMIT_AUTHORIZATION
113837  db->xAuth = xAuth;
113838  }
113839 #endif
113840  if( rc==SQLITE_OK ) rc = initData.rc;
113841  sqlite3DbFree(db, zSql);
113842 #ifndef SQLITE_OMIT_ANALYZE
113843  if( rc==SQLITE_OK ){
113844  sqlite3AnalysisLoad(db, iDb);
113845  }
113846 #endif
113847  }
113848  if( db->mallocFailed ){
113849  rc = SQLITE_NOMEM_BKPT;
113850  sqlite3ResetAllSchemasOfConnection(db);
113851  }
113852  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
113853  /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
113854  ** the schema loaded, even if errors occurred. In this situation the
113855  ** current sqlite3_prepare() operation will fail, but the following one
113856  ** will attempt to compile the supplied statement against whatever subset
113857  ** of the schema was loaded before the error occurred. The primary
113858  ** purpose of this is to allow access to the sqlite_master table
113859  ** even when its contents have been corrupted.
113860  */
113861  DbSetProperty(db, iDb, DB_SchemaLoaded);
113862  rc = SQLITE_OK;
113863  }
113864 
113865  /* Jump here for an error that occurs after successfully allocating
113866  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
113867  ** before that point, jump to error_out.
113868  */
113869 initone_error_out:
113870  if( openedTransaction ){
113871  sqlite3BtreeCommit(pDb->pBt);
113872  }
113873  sqlite3BtreeLeave(pDb->pBt);
113874 
113875 error_out:
113876  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
113877  sqlite3OomFault(db);
113878  }
113879  return rc;
113880 }
113881 
113882 /*
113883 ** Initialize all database files - the main database file, the file
113884 ** used to store temporary tables, and any additional database files
113885 ** created using ATTACH statements. Return a success code. If an
113886 ** error occurs, write an error message into *pzErrMsg.
113887 **
113888 ** After a database is initialized, the DB_SchemaLoaded bit is set
113889 ** bit is set in the flags field of the Db structure. If the database
113890 ** file was of zero-length, then the DB_Empty flag is also set.
113891 */
113892 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
113893  int i, rc;
113894  int commit_internal = !(db->flags&SQLITE_InternChanges);
113895 
113896  assert( sqlite3_mutex_held(db->mutex) );
113897  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
113898  assert( db->init.busy==0 );
113899  rc = SQLITE_OK;
113900  db->init.busy = 1;
113901  ENC(db) = SCHEMA_ENC(db);
113902  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
113903  if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
113904  rc = sqlite3InitOne(db, i, pzErrMsg);
113905  if( rc ){
113906  sqlite3ResetOneSchema(db, i);
113907  }
113908  }
113909 
113910  /* Once all the other databases have been initialized, load the schema
113911  ** for the TEMP database. This is loaded last, as the TEMP database
113912  ** schema may contain references to objects in other databases.
113913  */
113914 #ifndef SQLITE_OMIT_TEMPDB
113915  assert( db->nDb>1 );
113916  if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
113917  rc = sqlite3InitOne(db, 1, pzErrMsg);
113918  if( rc ){
113919  sqlite3ResetOneSchema(db, 1);
113920  }
113921  }
113922 #endif
113923 
113924  db->init.busy = 0;
113925  if( rc==SQLITE_OK && commit_internal ){
113926  sqlite3CommitInternalChanges(db);
113927  }
113928 
113929  return rc;
113930 }
113931 
113932 /*
113933 ** This routine is a no-op if the database schema is already initialized.
113934 ** Otherwise, the schema is loaded. An error code is returned.
113935 */
113936 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
113937  int rc = SQLITE_OK;
113938  sqlite3 *db = pParse->db;
113939  assert( sqlite3_mutex_held(db->mutex) );
113940  if( !db->init.busy ){
113941  rc = sqlite3Init(db, &pParse->zErrMsg);
113942  }
113943  if( rc!=SQLITE_OK ){
113944  pParse->rc = rc;
113945  pParse->nErr++;
113946  }
113947  return rc;
113948 }
113949 
113950 
113951 /*
113952 ** Check schema cookies in all databases. If any cookie is out
113953 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
113954 ** make no changes to pParse->rc.
113955 */
113956 static void schemaIsValid(Parse *pParse){
113957  sqlite3 *db = pParse->db;
113958  int iDb;
113959  int rc;
113960  int cookie;
113961 
113962  assert( pParse->checkSchema );
113963  assert( sqlite3_mutex_held(db->mutex) );
113964  for(iDb=0; iDb<db->nDb; iDb++){
113965  int openedTransaction = 0; /* True if a transaction is opened */
113966  Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
113967  if( pBt==0 ) continue;
113968 
113969  /* If there is not already a read-only (or read-write) transaction opened
113970  ** on the b-tree database, open one now. If a transaction is opened, it
113971  ** will be closed immediately after reading the meta-value. */
113972  if( !sqlite3BtreeIsInReadTrans(pBt) ){
113973  rc = sqlite3BtreeBeginTrans(pBt, 0);
113974  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
113975  sqlite3OomFault(db);
113976  }
113977  if( rc!=SQLITE_OK ) return;
113978  openedTransaction = 1;
113979  }
113980 
113981  /* Read the schema cookie from the database. If it does not match the
113982  ** value stored as part of the in-memory schema representation,
113983  ** set Parse.rc to SQLITE_SCHEMA. */
113984  sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
113985  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113986  if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
113987  sqlite3ResetOneSchema(db, iDb);
113988  pParse->rc = SQLITE_SCHEMA;
113989  }
113990 
113991  /* Close the transaction, if one was opened. */
113992  if( openedTransaction ){
113993  sqlite3BtreeCommit(pBt);
113994  }
113995  }
113996 }
113997 
113998 /*
113999 ** Convert a schema pointer into the iDb index that indicates
114000 ** which database file in db->aDb[] the schema refers to.
114001 **
114002 ** If the same database is attached more than once, the first
114003 ** attached database is returned.
114004 */
114005 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
114006  int i = -1000000;
114007 
114008  /* If pSchema is NULL, then return -1000000. This happens when code in
114009  ** expr.c is trying to resolve a reference to a transient table (i.e. one
114010  ** created by a sub-select). In this case the return value of this
114011  ** function should never be used.
114012  **
114013  ** We return -1000000 instead of the more usual -1 simply because using
114014  ** -1000000 as the incorrect index into db->aDb[] is much
114015  ** more likely to cause a segfault than -1 (of course there are assert()
114016  ** statements too, but it never hurts to play the odds).
114017  */
114018  assert( sqlite3_mutex_held(db->mutex) );
114019  if( pSchema ){
114020  for(i=0; ALWAYS(i<db->nDb); i++){
114021  if( db->aDb[i].pSchema==pSchema ){
114022  break;
114023  }
114024  }
114025  assert( i>=0 && i<db->nDb );
114026  }
114027  return i;
114028 }
114029 
114030 /*
114031 ** Free all memory allocations in the pParse object
114032 */
114033 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
114034  if( pParse ){
114035  sqlite3 *db = pParse->db;
114036  sqlite3DbFree(db, pParse->aLabel);
114037  sqlite3ExprListDelete(db, pParse->pConstExpr);
114038  if( db ){
114039  assert( db->lookaside.bDisable >= pParse->disableLookaside );
114040  db->lookaside.bDisable -= pParse->disableLookaside;
114041  }
114042  pParse->disableLookaside = 0;
114043  }
114044 }
114045 
114046 /*
114047 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
114048 */
114049 static int sqlite3Prepare(
114050  sqlite3 *db, /* Database handle. */
114051  const char *zSql, /* UTF-8 encoded SQL statement. */
114052  int nBytes, /* Length of zSql in bytes. */
114053  int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
114054  Vdbe *pReprepare, /* VM being reprepared */
114055  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114056  const char **pzTail /* OUT: End of parsed string */
114057 ){
114058  char *zErrMsg = 0; /* Error message */
114059  int rc = SQLITE_OK; /* Result code */
114060  int i; /* Loop counter */
114061  Parse sParse; /* Parsing context */
114062 
114063  memset(&sParse, 0, PARSE_HDR_SZ);
114064  memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
114065  sParse.pReprepare = pReprepare;
114066  assert( ppStmt && *ppStmt==0 );
114067  /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
114068  assert( sqlite3_mutex_held(db->mutex) );
114069 
114070  /* Check to verify that it is possible to get a read lock on all
114071  ** database schemas. The inability to get a read lock indicates that
114072  ** some other database connection is holding a write-lock, which in
114073  ** turn means that the other connection has made uncommitted changes
114074  ** to the schema.
114075  **
114076  ** Were we to proceed and prepare the statement against the uncommitted
114077  ** schema changes and if those schema changes are subsequently rolled
114078  ** back and different changes are made in their place, then when this
114079  ** prepared statement goes to run the schema cookie would fail to detect
114080  ** the schema change. Disaster would follow.
114081  **
114082  ** This thread is currently holding mutexes on all Btrees (because
114083  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
114084  ** is not possible for another thread to start a new schema change
114085  ** while this routine is running. Hence, we do not need to hold
114086  ** locks on the schema, we just need to make sure nobody else is
114087  ** holding them.
114088  **
114089  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
114090  ** but it does *not* override schema lock detection, so this all still
114091  ** works even if READ_UNCOMMITTED is set.
114092  */
114093  for(i=0; i<db->nDb; i++) {
114094  Btree *pBt = db->aDb[i].pBt;
114095  if( pBt ){
114096  assert( sqlite3BtreeHoldsMutex(pBt) );
114097  rc = sqlite3BtreeSchemaLocked(pBt);
114098  if( rc ){
114099  const char *zDb = db->aDb[i].zDbSName;
114100  sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
114101  testcase( db->flags & SQLITE_ReadUncommitted );
114102  goto end_prepare;
114103  }
114104  }
114105  }
114106 
114107  sqlite3VtabUnlockList(db);
114108 
114109  sParse.db = db;
114110  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
114111  char *zSqlCopy;
114112  int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
114113  testcase( nBytes==mxLen );
114114  testcase( nBytes==mxLen+1 );
114115  if( nBytes>mxLen ){
114116  sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
114117  rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
114118  goto end_prepare;
114119  }
114120  zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
114121  if( zSqlCopy ){
114122  sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
114123  sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
114124  sqlite3DbFree(db, zSqlCopy);
114125  }else{
114126  sParse.zTail = &zSql[nBytes];
114127  }
114128  }else{
114129  sqlite3RunParser(&sParse, zSql, &zErrMsg);
114130  }
114131  assert( 0==sParse.nQueryLoop );
114132 
114133  if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
114134  if( sParse.checkSchema ){
114135  schemaIsValid(&sParse);
114136  }
114137  if( db->mallocFailed ){
114138  sParse.rc = SQLITE_NOMEM_BKPT;
114139  }
114140  if( pzTail ){
114141  *pzTail = sParse.zTail;
114142  }
114143  rc = sParse.rc;
114144 
114145 #ifndef SQLITE_OMIT_EXPLAIN
114146  if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
114147  static const char * const azColName[] = {
114148  "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
114149  "selectid", "order", "from", "detail"
114150  };
114151  int iFirst, mx;
114152  if( sParse.explain==2 ){
114153  sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
114154  iFirst = 8;
114155  mx = 12;
114156  }else{
114157  sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
114158  iFirst = 0;
114159  mx = 8;
114160  }
114161  for(i=iFirst; i<mx; i++){
114162  sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
114163  azColName[i], SQLITE_STATIC);
114164  }
114165  }
114166 #endif
114167 
114168  if( db->init.busy==0 ){
114169  Vdbe *pVdbe = sParse.pVdbe;
114170  sqlite3VdbeSetSql(pVdbe, zSql, (int)(sParse.zTail-zSql), saveSqlFlag);
114171  }
114172  if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
114173  sqlite3VdbeFinalize(sParse.pVdbe);
114174  assert(!(*ppStmt));
114175  }else{
114176  *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
114177  }
114178 
114179  if( zErrMsg ){
114180  sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
114181  sqlite3DbFree(db, zErrMsg);
114182  }else{
114183  sqlite3Error(db, rc);
114184  }
114185 
114186  /* Delete any TriggerPrg structures allocated while parsing this statement. */
114187  while( sParse.pTriggerPrg ){
114188  TriggerPrg *pT = sParse.pTriggerPrg;
114189  sParse.pTriggerPrg = pT->pNext;
114190  sqlite3DbFree(db, pT);
114191  }
114192 
114193 end_prepare:
114194 
114195  sqlite3ParserReset(&sParse);
114196  rc = sqlite3ApiExit(db, rc);
114197  assert( (rc&db->errMask)==rc );
114198  return rc;
114199 }
114200 static int sqlite3LockAndPrepare(
114201  sqlite3 *db, /* Database handle. */
114202  const char *zSql, /* UTF-8 encoded SQL statement. */
114203  int nBytes, /* Length of zSql in bytes. */
114204  int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
114205  Vdbe *pOld, /* VM being reprepared */
114206  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114207  const char **pzTail /* OUT: End of parsed string */
114208 ){
114209  int rc;
114210 
114211 #ifdef SQLITE_ENABLE_API_ARMOR
114212  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
114213 #endif
114214  *ppStmt = 0;
114215  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
114216  return SQLITE_MISUSE_BKPT;
114217  }
114218  sqlite3_mutex_enter(db->mutex);
114219  sqlite3BtreeEnterAll(db);
114220  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
114221  if( rc==SQLITE_SCHEMA ){
114222  sqlite3_finalize(*ppStmt);
114223  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
114224  }
114225  sqlite3BtreeLeaveAll(db);
114226  sqlite3_mutex_leave(db->mutex);
114227  assert( rc==SQLITE_OK || *ppStmt==0 );
114228  return rc;
114229 }
114230 
114231 /*
114232 ** Rerun the compilation of a statement after a schema change.
114233 **
114234 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
114235 ** if the statement cannot be recompiled because another connection has
114236 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
114237 ** occurs, return SQLITE_SCHEMA.
114238 */
114239 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
114240  int rc;
114241  sqlite3_stmt *pNew;
114242  const char *zSql;
114243  sqlite3 *db;
114244 
114245  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
114246  zSql = sqlite3_sql((sqlite3_stmt *)p);
114247  assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
114248  db = sqlite3VdbeDb(p);
114249  assert( sqlite3_mutex_held(db->mutex) );
114250  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
114251  if( rc ){
114252  if( rc==SQLITE_NOMEM ){
114253  sqlite3OomFault(db);
114254  }
114255  assert( pNew==0 );
114256  return rc;
114257  }else{
114258  assert( pNew!=0 );
114259  }
114260  sqlite3VdbeSwap((Vdbe*)pNew, p);
114261  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
114262  sqlite3VdbeResetStepResult((Vdbe*)pNew);
114263  sqlite3VdbeFinalize((Vdbe*)pNew);
114264  return SQLITE_OK;
114265 }
114266 
114267 
114268 /*
114269 ** Two versions of the official API. Legacy and new use. In the legacy
114270 ** version, the original SQL text is not saved in the prepared statement
114271 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
114272 ** sqlite3_step(). In the new version, the original SQL text is retained
114273 ** and the statement is automatically recompiled if an schema change
114274 ** occurs.
114275 */
114276 SQLITE_API int sqlite3_prepare(
114277  sqlite3 *db, /* Database handle. */
114278  const char *zSql, /* UTF-8 encoded SQL statement. */
114279  int nBytes, /* Length of zSql in bytes. */
114280  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114281  const char **pzTail /* OUT: End of parsed string */
114282 ){
114283  int rc;
114284  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
114285  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
114286  return rc;
114287 }
114288 SQLITE_API int sqlite3_prepare_v2(
114289  sqlite3 *db, /* Database handle. */
114290  const char *zSql, /* UTF-8 encoded SQL statement. */
114291  int nBytes, /* Length of zSql in bytes. */
114292  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114293  const char **pzTail /* OUT: End of parsed string */
114294 ){
114295  int rc;
114296  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
114297  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
114298  return rc;
114299 }
114300 
114301 
114302 #ifndef SQLITE_OMIT_UTF16
114303 /*
114304 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
114305 */
114306 static int sqlite3Prepare16(
114307  sqlite3 *db, /* Database handle. */
114308  const void *zSql, /* UTF-16 encoded SQL statement. */
114309  int nBytes, /* Length of zSql in bytes. */
114310  int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
114311  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114312  const void **pzTail /* OUT: End of parsed string */
114313 ){
114314  /* This function currently works by first transforming the UTF-16
114315  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
114316  ** tricky bit is figuring out the pointer to return in *pzTail.
114317  */
114318  char *zSql8;
114319  const char *zTail8 = 0;
114320  int rc = SQLITE_OK;
114321 
114322 #ifdef SQLITE_ENABLE_API_ARMOR
114323  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
114324 #endif
114325  *ppStmt = 0;
114326  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
114327  return SQLITE_MISUSE_BKPT;
114328  }
114329  if( nBytes>=0 ){
114330  int sz;
114331  const char *z = (const char*)zSql;
114332  for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
114333  nBytes = sz;
114334  }
114335  sqlite3_mutex_enter(db->mutex);
114336  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
114337  if( zSql8 ){
114338  rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
114339  }
114340 
114341  if( zTail8 && pzTail ){
114342  /* If sqlite3_prepare returns a tail pointer, we calculate the
114343  ** equivalent pointer into the UTF-16 string by counting the unicode
114344  ** characters between zSql8 and zTail8, and then returning a pointer
114345  ** the same number of characters into the UTF-16 string.
114346  */
114347  int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
114348  *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
114349  }
114350  sqlite3DbFree(db, zSql8);
114351  rc = sqlite3ApiExit(db, rc);
114352  sqlite3_mutex_leave(db->mutex);
114353  return rc;
114354 }
114355 
114356 /*
114357 ** Two versions of the official API. Legacy and new use. In the legacy
114358 ** version, the original SQL text is not saved in the prepared statement
114359 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
114360 ** sqlite3_step(). In the new version, the original SQL text is retained
114361 ** and the statement is automatically recompiled if an schema change
114362 ** occurs.
114363 */
114364 SQLITE_API int sqlite3_prepare16(
114365  sqlite3 *db, /* Database handle. */
114366  const void *zSql, /* UTF-16 encoded SQL statement. */
114367  int nBytes, /* Length of zSql in bytes. */
114368  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114369  const void **pzTail /* OUT: End of parsed string */
114370 ){
114371  int rc;
114372  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
114373  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
114374  return rc;
114375 }
114376 SQLITE_API int sqlite3_prepare16_v2(
114377  sqlite3 *db, /* Database handle. */
114378  const void *zSql, /* UTF-16 encoded SQL statement. */
114379  int nBytes, /* Length of zSql in bytes. */
114380  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114381  const void **pzTail /* OUT: End of parsed string */
114382 ){
114383  int rc;
114384  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
114385  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
114386  return rc;
114387 }
114388 
114389 #endif /* SQLITE_OMIT_UTF16 */
114390 
114391 /************** End of prepare.c *********************************************/
114392 /************** Begin file select.c ******************************************/
114393 /*
114394 ** 2001 September 15
114395 **
114396 ** The author disclaims copyright to this source code. In place of
114397 ** a legal notice, here is a blessing:
114398 **
114399 ** May you do good and not evil.
114400 ** May you find forgiveness for yourself and forgive others.
114401 ** May you share freely, never taking more than you give.
114402 **
114403 *************************************************************************
114404 ** This file contains C code routines that are called by the parser
114405 ** to handle SELECT statements in SQLite.
114406 */
114407 /* #include "sqliteInt.h" */
114408 
114409 /*
114410 ** Trace output macros
114411 */
114412 #if SELECTTRACE_ENABLED
114413 /***/ int sqlite3SelectTrace = 0;
114414 # define SELECTTRACE(K,P,S,X) \
114415  if(sqlite3SelectTrace&(K)) \
114416  sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
114417  (S)->zSelName,(S)),\
114418  sqlite3DebugPrintf X
114419 #else
114420 # define SELECTTRACE(K,P,S,X)
114421 #endif
114422 
114423 
114424 /*
114425 ** An instance of the following object is used to record information about
114426 ** how to process the DISTINCT keyword, to simplify passing that information
114427 ** into the selectInnerLoop() routine.
114428 */
114429 typedef struct DistinctCtx DistinctCtx;
114430 struct DistinctCtx {
114431  u8 isTnct; /* True if the DISTINCT keyword is present */
114432  u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
114433  int tabTnct; /* Ephemeral table used for DISTINCT processing */
114434  int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
114435 };
114436 
114437 /*
114438 ** An instance of the following object is used to record information about
114439 ** the ORDER BY (or GROUP BY) clause of query is being coded.
114440 */
114441 typedef struct SortCtx SortCtx;
114442 struct SortCtx {
114443  ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
114444  int nOBSat; /* Number of ORDER BY terms satisfied by indices */
114445  int iECursor; /* Cursor number for the sorter */
114446  int regReturn; /* Register holding block-output return address */
114447  int labelBkOut; /* Start label for the block-output subroutine */
114448  int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
114449  int labelDone; /* Jump here when done, ex: LIMIT reached */
114450  u8 sortFlags; /* Zero or more SORTFLAG_* bits */
114451  u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
114452 };
114453 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
114454 
114455 /*
114456 ** Delete all the content of a Select structure. Deallocate the structure
114457 ** itself only if bFree is true.
114458 */
114459 static void clearSelect(sqlite3 *db, Select *p, int bFree){
114460  while( p ){
114461  Select *pPrior = p->pPrior;
114462  sqlite3ExprListDelete(db, p->pEList);
114463  sqlite3SrcListDelete(db, p->pSrc);
114464  sqlite3ExprDelete(db, p->pWhere);
114465  sqlite3ExprListDelete(db, p->pGroupBy);
114466  sqlite3ExprDelete(db, p->pHaving);
114467  sqlite3ExprListDelete(db, p->pOrderBy);
114468  sqlite3ExprDelete(db, p->pLimit);
114469  sqlite3ExprDelete(db, p->pOffset);
114470  if( p->pWith ) sqlite3WithDelete(db, p->pWith);
114471  if( bFree ) sqlite3DbFree(db, p);
114472  p = pPrior;
114473  bFree = 1;
114474  }
114475 }
114476 
114477 /*
114478 ** Initialize a SelectDest structure.
114479 */
114480 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
114481  pDest->eDest = (u8)eDest;
114482  pDest->iSDParm = iParm;
114483  pDest->zAffSdst = 0;
114484  pDest->iSdst = 0;
114485  pDest->nSdst = 0;
114486 }
114487 
114488 
114489 /*
114490 ** Allocate a new Select structure and return a pointer to that
114491 ** structure.
114492 */
114493 SQLITE_PRIVATE Select *sqlite3SelectNew(
114494  Parse *pParse, /* Parsing context */
114495  ExprList *pEList, /* which columns to include in the result */
114496  SrcList *pSrc, /* the FROM clause -- which tables to scan */
114497  Expr *pWhere, /* the WHERE clause */
114498  ExprList *pGroupBy, /* the GROUP BY clause */
114499  Expr *pHaving, /* the HAVING clause */
114500  ExprList *pOrderBy, /* the ORDER BY clause */
114501  u32 selFlags, /* Flag parameters, such as SF_Distinct */
114502  Expr *pLimit, /* LIMIT value. NULL means not used */
114503  Expr *pOffset /* OFFSET value. NULL means no offset */
114504 ){
114505  Select *pNew;
114506  Select standin;
114507  sqlite3 *db = pParse->db;
114508  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
114509  if( pNew==0 ){
114510  assert( db->mallocFailed );
114511  pNew = &standin;
114512  }
114513  if( pEList==0 ){
114514  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
114515  }
114516  pNew->pEList = pEList;
114517  pNew->op = TK_SELECT;
114518  pNew->selFlags = selFlags;
114519  pNew->iLimit = 0;
114520  pNew->iOffset = 0;
114521 #if SELECTTRACE_ENABLED
114522  pNew->zSelName[0] = 0;
114523 #endif
114524  pNew->addrOpenEphm[0] = -1;
114525  pNew->addrOpenEphm[1] = -1;
114526  pNew->nSelectRow = 0;
114527  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
114528  pNew->pSrc = pSrc;
114529  pNew->pWhere = pWhere;
114530  pNew->pGroupBy = pGroupBy;
114531  pNew->pHaving = pHaving;
114532  pNew->pOrderBy = pOrderBy;
114533  pNew->pPrior = 0;
114534  pNew->pNext = 0;
114535  pNew->pLimit = pLimit;
114536  pNew->pOffset = pOffset;
114537  pNew->pWith = 0;
114538  assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
114539  if( db->mallocFailed ) {
114540  clearSelect(db, pNew, pNew!=&standin);
114541  pNew = 0;
114542  }else{
114543  assert( pNew->pSrc!=0 || pParse->nErr>0 );
114544  }
114545  assert( pNew!=&standin );
114546  return pNew;
114547 }
114548 
114549 #if SELECTTRACE_ENABLED
114550 /*
114551 ** Set the name of a Select object
114552 */
114553 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
114554  if( p && zName ){
114555  sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
114556  }
114557 }
114558 #endif
114559 
114560 
114561 /*
114562 ** Delete the given Select structure and all of its substructures.
114563 */
114564 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
114565  if( p ) clearSelect(db, p, 1);
114566 }
114567 
114568 /*
114569 ** Return a pointer to the right-most SELECT statement in a compound.
114570 */
114571 static Select *findRightmost(Select *p){
114572  while( p->pNext ) p = p->pNext;
114573  return p;
114574 }
114575 
114576 /*
114577 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
114578 ** type of join. Return an integer constant that expresses that type
114579 ** in terms of the following bit values:
114580 **
114581 ** JT_INNER
114582 ** JT_CROSS
114583 ** JT_OUTER
114584 ** JT_NATURAL
114585 ** JT_LEFT
114586 ** JT_RIGHT
114587 **
114588 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
114589 **
114590 ** If an illegal or unsupported join type is seen, then still return
114591 ** a join type, but put an error in the pParse structure.
114592 */
114593 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
114594  int jointype = 0;
114595  Token *apAll[3];
114596  Token *p;
114597  /* 0123456789 123456789 123456789 123 */
114598  static const char zKeyText[] = "naturaleftouterightfullinnercross";
114599  static const struct {
114600  u8 i; /* Beginning of keyword text in zKeyText[] */
114601  u8 nChar; /* Length of the keyword in characters */
114602  u8 code; /* Join type mask */
114603  } aKeyword[] = {
114604  /* natural */ { 0, 7, JT_NATURAL },
114605  /* left */ { 6, 4, JT_LEFT|JT_OUTER },
114606  /* outer */ { 10, 5, JT_OUTER },
114607  /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
114608  /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
114609  /* inner */ { 23, 5, JT_INNER },
114610  /* cross */ { 28, 5, JT_INNER|JT_CROSS },
114611  };
114612  int i, j;
114613  apAll[0] = pA;
114614  apAll[1] = pB;
114615  apAll[2] = pC;
114616  for(i=0; i<3 && apAll[i]; i++){
114617  p = apAll[i];
114618  for(j=0; j<ArraySize(aKeyword); j++){
114619  if( p->n==aKeyword[j].nChar
114620  && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
114621  jointype |= aKeyword[j].code;
114622  break;
114623  }
114624  }
114625  testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
114626  if( j>=ArraySize(aKeyword) ){
114627  jointype |= JT_ERROR;
114628  break;
114629  }
114630  }
114631  if(
114632  (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
114633  (jointype & JT_ERROR)!=0
114634  ){
114635  const char *zSp = " ";
114636  assert( pB!=0 );
114637  if( pC==0 ){ zSp++; }
114638  sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
114639  "%T %T%s%T", pA, pB, zSp, pC);
114640  jointype = JT_INNER;
114641  }else if( (jointype & JT_OUTER)!=0
114642  && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
114643  sqlite3ErrorMsg(pParse,
114644  "RIGHT and FULL OUTER JOINs are not currently supported");
114645  jointype = JT_INNER;
114646  }
114647  return jointype;
114648 }
114649 
114650 /*
114651 ** Return the index of a column in a table. Return -1 if the column
114652 ** is not contained in the table.
114653 */
114654 static int columnIndex(Table *pTab, const char *zCol){
114655  int i;
114656  for(i=0; i<pTab->nCol; i++){
114657  if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
114658  }
114659  return -1;
114660 }
114661 
114662 /*
114663 ** Search the first N tables in pSrc, from left to right, looking for a
114664 ** table that has a column named zCol.
114665 **
114666 ** When found, set *piTab and *piCol to the table index and column index
114667 ** of the matching column and return TRUE.
114668 **
114669 ** If not found, return FALSE.
114670 */
114671 static int tableAndColumnIndex(
114672  SrcList *pSrc, /* Array of tables to search */
114673  int N, /* Number of tables in pSrc->a[] to search */
114674  const char *zCol, /* Name of the column we are looking for */
114675  int *piTab, /* Write index of pSrc->a[] here */
114676  int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
114677 ){
114678  int i; /* For looping over tables in pSrc */
114679  int iCol; /* Index of column matching zCol */
114680 
114681  assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
114682  for(i=0; i<N; i++){
114683  iCol = columnIndex(pSrc->a[i].pTab, zCol);
114684  if( iCol>=0 ){
114685  if( piTab ){
114686  *piTab = i;
114687  *piCol = iCol;
114688  }
114689  return 1;
114690  }
114691  }
114692  return 0;
114693 }
114694 
114695 /*
114696 ** This function is used to add terms implied by JOIN syntax to the
114697 ** WHERE clause expression of a SELECT statement. The new term, which
114698 ** is ANDed with the existing WHERE clause, is of the form:
114699 **
114700 ** (tab1.col1 = tab2.col2)
114701 **
114702 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
114703 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
114704 ** column iColRight of tab2.
114705 */
114706 static void addWhereTerm(
114707  Parse *pParse, /* Parsing context */
114708  SrcList *pSrc, /* List of tables in FROM clause */
114709  int iLeft, /* Index of first table to join in pSrc */
114710  int iColLeft, /* Index of column in first table */
114711  int iRight, /* Index of second table in pSrc */
114712  int iColRight, /* Index of column in second table */
114713  int isOuterJoin, /* True if this is an OUTER join */
114714  Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
114715 ){
114716  sqlite3 *db = pParse->db;
114717  Expr *pE1;
114718  Expr *pE2;
114719  Expr *pEq;
114720 
114721  assert( iLeft<iRight );
114722  assert( pSrc->nSrc>iRight );
114723  assert( pSrc->a[iLeft].pTab );
114724  assert( pSrc->a[iRight].pTab );
114725 
114726  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
114727  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
114728 
114729  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
114730  if( pEq && isOuterJoin ){
114731  ExprSetProperty(pEq, EP_FromJoin);
114732  assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
114733  ExprSetVVAProperty(pEq, EP_NoReduce);
114734  pEq->iRightJoinTable = (i16)pE2->iTable;
114735  }
114736  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
114737 }
114738 
114739 /*
114740 ** Set the EP_FromJoin property on all terms of the given expression.
114741 ** And set the Expr.iRightJoinTable to iTable for every term in the
114742 ** expression.
114743 **
114744 ** The EP_FromJoin property is used on terms of an expression to tell
114745 ** the LEFT OUTER JOIN processing logic that this term is part of the
114746 ** join restriction specified in the ON or USING clause and not a part
114747 ** of the more general WHERE clause. These terms are moved over to the
114748 ** WHERE clause during join processing but we need to remember that they
114749 ** originated in the ON or USING clause.
114750 **
114751 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
114752 ** expression depends on table iRightJoinTable even if that table is not
114753 ** explicitly mentioned in the expression. That information is needed
114754 ** for cases like this:
114755 **
114756 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
114757 **
114758 ** The where clause needs to defer the handling of the t1.x=5
114759 ** term until after the t2 loop of the join. In that way, a
114760 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
114761 ** defer the handling of t1.x=5, it will be processed immediately
114762 ** after the t1 loop and rows with t1.x!=5 will never appear in
114763 ** the output, which is incorrect.
114764 */
114765 static void setJoinExpr(Expr *p, int iTable){
114766  while( p ){
114767  ExprSetProperty(p, EP_FromJoin);
114768  assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
114769  ExprSetVVAProperty(p, EP_NoReduce);
114770  p->iRightJoinTable = (i16)iTable;
114771  if( p->op==TK_FUNCTION && p->x.pList ){
114772  int i;
114773  for(i=0; i<p->x.pList->nExpr; i++){
114774  setJoinExpr(p->x.pList->a[i].pExpr, iTable);
114775  }
114776  }
114777  setJoinExpr(p->pLeft, iTable);
114778  p = p->pRight;
114779  }
114780 }
114781 
114782 /*
114783 ** This routine processes the join information for a SELECT statement.
114784 ** ON and USING clauses are converted into extra terms of the WHERE clause.
114785 ** NATURAL joins also create extra WHERE clause terms.
114786 **
114787 ** The terms of a FROM clause are contained in the Select.pSrc structure.
114788 ** The left most table is the first entry in Select.pSrc. The right-most
114789 ** table is the last entry. The join operator is held in the entry to
114790 ** the left. Thus entry 0 contains the join operator for the join between
114791 ** entries 0 and 1. Any ON or USING clauses associated with the join are
114792 ** also attached to the left entry.
114793 **
114794 ** This routine returns the number of errors encountered.
114795 */
114796 static int sqliteProcessJoin(Parse *pParse, Select *p){
114797  SrcList *pSrc; /* All tables in the FROM clause */
114798  int i, j; /* Loop counters */
114799  struct SrcList_item *pLeft; /* Left table being joined */
114800  struct SrcList_item *pRight; /* Right table being joined */
114801 
114802  pSrc = p->pSrc;
114803  pLeft = &pSrc->a[0];
114804  pRight = &pLeft[1];
114805  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
114806  Table *pLeftTab = pLeft->pTab;
114807  Table *pRightTab = pRight->pTab;
114808  int isOuter;
114809 
114810  if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
114811  isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
114812 
114813  /* When the NATURAL keyword is present, add WHERE clause terms for
114814  ** every column that the two tables have in common.
114815  */
114816  if( pRight->fg.jointype & JT_NATURAL ){
114817  if( pRight->pOn || pRight->pUsing ){
114818  sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
114819  "an ON or USING clause", 0);
114820  return 1;
114821  }
114822  for(j=0; j<pRightTab->nCol; j++){
114823  char *zName; /* Name of column in the right table */
114824  int iLeft; /* Matching left table */
114825  int iLeftCol; /* Matching column in the left table */
114826 
114827  zName = pRightTab->aCol[j].zName;
114828  if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
114829  addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
114830  isOuter, &p->pWhere);
114831  }
114832  }
114833  }
114834 
114835  /* Disallow both ON and USING clauses in the same join
114836  */
114837  if( pRight->pOn && pRight->pUsing ){
114838  sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
114839  "clauses in the same join");
114840  return 1;
114841  }
114842 
114843  /* Add the ON clause to the end of the WHERE clause, connected by
114844  ** an AND operator.
114845  */
114846  if( pRight->pOn ){
114847  if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
114848  p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
114849  pRight->pOn = 0;
114850  }
114851 
114852  /* Create extra terms on the WHERE clause for each column named
114853  ** in the USING clause. Example: If the two tables to be joined are
114854  ** A and B and the USING clause names X, Y, and Z, then add this
114855  ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
114856  ** Report an error if any column mentioned in the USING clause is
114857  ** not contained in both tables to be joined.
114858  */
114859  if( pRight->pUsing ){
114860  IdList *pList = pRight->pUsing;
114861  for(j=0; j<pList->nId; j++){
114862  char *zName; /* Name of the term in the USING clause */
114863  int iLeft; /* Table on the left with matching column name */
114864  int iLeftCol; /* Column number of matching column on the left */
114865  int iRightCol; /* Column number of matching column on the right */
114866 
114867  zName = pList->a[j].zName;
114868  iRightCol = columnIndex(pRightTab, zName);
114869  if( iRightCol<0
114870  || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
114871  ){
114872  sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
114873  "not present in both tables", zName);
114874  return 1;
114875  }
114876  addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
114877  isOuter, &p->pWhere);
114878  }
114879  }
114880  }
114881  return 0;
114882 }
114883 
114884 /* Forward reference */
114885 static KeyInfo *keyInfoFromExprList(
114886  Parse *pParse, /* Parsing context */
114887  ExprList *pList, /* Form the KeyInfo object from this ExprList */
114888  int iStart, /* Begin with this column of pList */
114889  int nExtra /* Add this many extra columns to the end */
114890 );
114891 
114892 /*
114893 ** Generate code that will push the record in registers regData
114894 ** through regData+nData-1 onto the sorter.
114895 */
114896 static void pushOntoSorter(
114897  Parse *pParse, /* Parser context */
114898  SortCtx *pSort, /* Information about the ORDER BY clause */
114899  Select *pSelect, /* The whole SELECT statement */
114900  int regData, /* First register holding data to be sorted */
114901  int regOrigData, /* First register holding data before packing */
114902  int nData, /* Number of elements in the data array */
114903  int nPrefixReg /* No. of reg prior to regData available for use */
114904 ){
114905  Vdbe *v = pParse->pVdbe; /* Stmt under construction */
114906  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
114907  int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
114908  int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
114909  int regBase; /* Regs for sorter record */
114910  int regRecord = ++pParse->nMem; /* Assembled sorter record */
114911  int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
114912  int op; /* Opcode to add sorter record to sorter */
114913  int iLimit; /* LIMIT counter */
114914 
114915  assert( bSeq==0 || bSeq==1 );
114916  assert( nData==1 || regData==regOrigData );
114917  if( nPrefixReg ){
114918  assert( nPrefixReg==nExpr+bSeq );
114919  regBase = regData - nExpr - bSeq;
114920  }else{
114921  regBase = pParse->nMem + 1;
114922  pParse->nMem += nBase;
114923  }
114924  assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
114925  iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
114926  pSort->labelDone = sqlite3VdbeMakeLabel(v);
114927  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
114928  SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
114929  if( bSeq ){
114930  sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
114931  }
114932  if( nPrefixReg==0 ){
114933  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
114934  }
114935  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
114936  if( nOBSat>0 ){
114937  int regPrevKey; /* The first nOBSat columns of the previous row */
114938  int addrFirst; /* Address of the OP_IfNot opcode */
114939  int addrJmp; /* Address of the OP_Jump opcode */
114940  VdbeOp *pOp; /* Opcode that opens the sorter */
114941  int nKey; /* Number of sorting key columns, including OP_Sequence */
114942  KeyInfo *pKI; /* Original KeyInfo on the sorter table */
114943 
114944  regPrevKey = pParse->nMem+1;
114945  pParse->nMem += pSort->nOBSat;
114946  nKey = nExpr - pSort->nOBSat + bSeq;
114947  if( bSeq ){
114948  addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
114949  }else{
114950  addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
114951  }
114952  VdbeCoverage(v);
114953  sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
114954  pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
114955  if( pParse->db->mallocFailed ) return;
114956  pOp->p2 = nKey + nData;
114957  pKI = pOp->p4.pKeyInfo;
114958  memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
114959  sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
114960  testcase( pKI->nXField>2 );
114961  pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
114962  pKI->nXField-1);
114963  addrJmp = sqlite3VdbeCurrentAddr(v);
114964  sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
114965  pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
114966  pSort->regReturn = ++pParse->nMem;
114967  sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
114968  sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
114969  if( iLimit ){
114970  sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
114971  VdbeCoverage(v);
114972  }
114973  sqlite3VdbeJumpHere(v, addrFirst);
114974  sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
114975  sqlite3VdbeJumpHere(v, addrJmp);
114976  }
114977  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114978  op = OP_SorterInsert;
114979  }else{
114980  op = OP_IdxInsert;
114981  }
114982  sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
114983  if( iLimit ){
114984  int addr;
114985  int r1 = 0;
114986  /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit
114987  ** register is initialized with value of LIMIT+OFFSET.) After the sorter
114988  ** fills up, delete the least entry in the sorter after each insert.
114989  ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
114990  addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
114991  sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
114992  if( pSort->bOrderedInnerLoop ){
114993  r1 = ++pParse->nMem;
114994  sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
114995  VdbeComment((v, "seq"));
114996  }
114997  sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
114998  if( pSort->bOrderedInnerLoop ){
114999  /* If the inner loop is driven by an index such that values from
115000  ** the same iteration of the inner loop are in sorted order, then
115001  ** immediately jump to the next iteration of an inner loop if the
115002  ** entry from the current iteration does not fit into the top
115003  ** LIMIT+OFFSET entries of the sorter. */
115004  int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
115005  sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
115006  sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
115007  VdbeCoverage(v);
115008  }
115009  sqlite3VdbeJumpHere(v, addr);
115010  }
115011 }
115012 
115013 /*
115014 ** Add code to implement the OFFSET
115015 */
115016 static void codeOffset(
115017  Vdbe *v, /* Generate code into this VM */
115018  int iOffset, /* Register holding the offset counter */
115019  int iContinue /* Jump here to skip the current record */
115020 ){
115021  if( iOffset>0 ){
115022  sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
115023  VdbeComment((v, "OFFSET"));
115024  }
115025 }
115026 
115027 /*
115028 ** Add code that will check to make sure the N registers starting at iMem
115029 ** form a distinct entry. iTab is a sorting index that holds previously
115030 ** seen combinations of the N values. A new entry is made in iTab
115031 ** if the current N values are new.
115032 **
115033 ** A jump to addrRepeat is made and the N+1 values are popped from the
115034 ** stack if the top N elements are not distinct.
115035 */
115036 static void codeDistinct(
115037  Parse *pParse, /* Parsing and code generating context */
115038  int iTab, /* A sorting index used to test for distinctness */
115039  int addrRepeat, /* Jump to here if not distinct */
115040  int N, /* Number of elements */
115041  int iMem /* First element */
115042 ){
115043  Vdbe *v;
115044  int r1;
115045 
115046  v = pParse->pVdbe;
115047  r1 = sqlite3GetTempReg(pParse);
115048  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
115049  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
115050  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
115051  sqlite3ReleaseTempReg(pParse, r1);
115052 }
115053 
115054 /*
115055 ** This routine generates the code for the inside of the inner loop
115056 ** of a SELECT.
115057 **
115058 ** If srcTab is negative, then the pEList expressions
115059 ** are evaluated in order to get the data for this row. If srcTab is
115060 ** zero or more, then data is pulled from srcTab and pEList is used only
115061 ** to get number columns and the datatype for each column.
115062 */
115063 static void selectInnerLoop(
115064  Parse *pParse, /* The parser context */
115065  Select *p, /* The complete select statement being coded */
115066  ExprList *pEList, /* List of values being extracted */
115067  int srcTab, /* Pull data from this table */
115068  SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
115069  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
115070  SelectDest *pDest, /* How to dispose of the results */
115071  int iContinue, /* Jump here to continue with next row */
115072  int iBreak /* Jump here to break out of the inner loop */
115073 ){
115074  Vdbe *v = pParse->pVdbe;
115075  int i;
115076  int hasDistinct; /* True if the DISTINCT keyword is present */
115077  int regResult; /* Start of memory holding result set */
115078  int eDest = pDest->eDest; /* How to dispose of results */
115079  int iParm = pDest->iSDParm; /* First argument to disposal method */
115080  int nResultCol; /* Number of result columns */
115081  int nPrefixReg = 0; /* Number of extra registers before regResult */
115082 
115083  assert( v );
115084  assert( pEList!=0 );
115085  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
115086  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
115087  if( pSort==0 && !hasDistinct ){
115088  assert( iContinue!=0 );
115089  codeOffset(v, p->iOffset, iContinue);
115090  }
115091 
115092  /* Pull the requested columns.
115093  */
115094  nResultCol = pEList->nExpr;
115095 
115096  if( pDest->iSdst==0 ){
115097  if( pSort ){
115098  nPrefixReg = pSort->pOrderBy->nExpr;
115099  if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
115100  pParse->nMem += nPrefixReg;
115101  }
115102  pDest->iSdst = pParse->nMem+1;
115103  pParse->nMem += nResultCol;
115104  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
115105  /* This is an error condition that can result, for example, when a SELECT
115106  ** on the right-hand side of an INSERT contains more result columns than
115107  ** there are columns in the table on the left. The error will be caught
115108  ** and reported later. But we need to make sure enough memory is allocated
115109  ** to avoid other spurious errors in the meantime. */
115110  pParse->nMem += nResultCol;
115111  }
115112  pDest->nSdst = nResultCol;
115113  regResult = pDest->iSdst;
115114  if( srcTab>=0 ){
115115  for(i=0; i<nResultCol; i++){
115116  sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
115117  VdbeComment((v, "%s", pEList->a[i].zName));
115118  }
115119  }else if( eDest!=SRT_Exists ){
115120  /* If the destination is an EXISTS(...) expression, the actual
115121  ** values returned by the SELECT are not required.
115122  */
115123  u8 ecelFlags;
115124  if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
115125  ecelFlags = SQLITE_ECEL_DUP;
115126  }else{
115127  ecelFlags = 0;
115128  }
115129  sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
115130  }
115131 
115132  /* If the DISTINCT keyword was present on the SELECT statement
115133  ** and this row has been seen before, then do not make this row
115134  ** part of the result.
115135  */
115136  if( hasDistinct ){
115137  switch( pDistinct->eTnctType ){
115138  case WHERE_DISTINCT_ORDERED: {
115139  VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
115140  int iJump; /* Jump destination */
115141  int regPrev; /* Previous row content */
115142 
115143  /* Allocate space for the previous row */
115144  regPrev = pParse->nMem+1;
115145  pParse->nMem += nResultCol;
115146 
115147  /* Change the OP_OpenEphemeral coded earlier to an OP_Null
115148  ** sets the MEM_Cleared bit on the first register of the
115149  ** previous value. This will cause the OP_Ne below to always
115150  ** fail on the first iteration of the loop even if the first
115151  ** row is all NULLs.
115152  */
115153  sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
115154  pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
115155  pOp->opcode = OP_Null;
115156  pOp->p1 = 1;
115157  pOp->p2 = regPrev;
115158 
115159  iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
115160  for(i=0; i<nResultCol; i++){
115161  CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
115162  if( i<nResultCol-1 ){
115163  sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
115164  VdbeCoverage(v);
115165  }else{
115166  sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
115167  VdbeCoverage(v);
115168  }
115169  sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
115170  sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
115171  }
115172  assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
115173  sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
115174  break;
115175  }
115176 
115177  case WHERE_DISTINCT_UNIQUE: {
115178  sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
115179  break;
115180  }
115181 
115182  default: {
115183  assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
115184  codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
115185  regResult);
115186  break;
115187  }
115188  }
115189  if( pSort==0 ){
115190  codeOffset(v, p->iOffset, iContinue);
115191  }
115192  }
115193 
115194  switch( eDest ){
115195  /* In this mode, write each query result to the key of the temporary
115196  ** table iParm.
115197  */
115198 #ifndef SQLITE_OMIT_COMPOUND_SELECT
115199  case SRT_Union: {
115200  int r1;
115201  r1 = sqlite3GetTempReg(pParse);
115202  sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
115203  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
115204  sqlite3ReleaseTempReg(pParse, r1);
115205  break;
115206  }
115207 
115208  /* Construct a record from the query result, but instead of
115209  ** saving that record, use it as a key to delete elements from
115210  ** the temporary table iParm.
115211  */
115212  case SRT_Except: {
115213  sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
115214  break;
115215  }
115216 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
115217 
115218  /* Store the result as data using a unique key.
115219  */
115220  case SRT_Fifo:
115221  case SRT_DistFifo:
115222  case SRT_Table:
115223  case SRT_EphemTab: {
115224  int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
115225  testcase( eDest==SRT_Table );
115226  testcase( eDest==SRT_EphemTab );
115227  testcase( eDest==SRT_Fifo );
115228  testcase( eDest==SRT_DistFifo );
115229  sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
115230 #ifndef SQLITE_OMIT_CTE
115231  if( eDest==SRT_DistFifo ){
115232  /* If the destination is DistFifo, then cursor (iParm+1) is open
115233  ** on an ephemeral index. If the current row is already present
115234  ** in the index, do not write it to the output. If not, add the
115235  ** current row to the index and proceed with writing it to the
115236  ** output table as well. */
115237  int addr = sqlite3VdbeCurrentAddr(v) + 4;
115238  sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
115239  VdbeCoverage(v);
115240  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
115241  assert( pSort==0 );
115242  }
115243 #endif
115244  if( pSort ){
115245  pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
115246  }else{
115247  int r2 = sqlite3GetTempReg(pParse);
115248  sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
115249  sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
115250  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
115251  sqlite3ReleaseTempReg(pParse, r2);
115252  }
115253  sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
115254  break;
115255  }
115256 
115257 #ifndef SQLITE_OMIT_SUBQUERY
115258  /* If we are creating a set for an "expr IN (SELECT ...)" construct,
115259  ** then there should be a single item on the stack. Write this
115260  ** item into the set table with bogus data.
115261  */
115262  case SRT_Set: {
115263  if( pSort ){
115264  /* At first glance you would think we could optimize out the
115265  ** ORDER BY in this case since the order of entries in the set
115266  ** does not matter. But there might be a LIMIT clause, in which
115267  ** case the order does matter */
115268  pushOntoSorter(
115269  pParse, pSort, p, regResult, regResult, nResultCol, nPrefixReg);
115270  }else{
115271  int r1 = sqlite3GetTempReg(pParse);
115272  assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
115273  sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
115274  r1, pDest->zAffSdst, nResultCol);
115275  sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
115276  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
115277  sqlite3ReleaseTempReg(pParse, r1);
115278  }
115279  break;
115280  }
115281 
115282  /* If any row exist in the result set, record that fact and abort.
115283  */
115284  case SRT_Exists: {
115285  sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
115286  /* The LIMIT clause will terminate the loop for us */
115287  break;
115288  }
115289 
115290  /* If this is a scalar select that is part of an expression, then
115291  ** store the results in the appropriate memory cell or array of
115292  ** memory cells and break out of the scan loop.
115293  */
115294  case SRT_Mem: {
115295  assert( nResultCol==pDest->nSdst );
115296  if( pSort ){
115297  pushOntoSorter(
115298  pParse, pSort, p, regResult, regResult, nResultCol, nPrefixReg);
115299  }else{
115300  assert( regResult==iParm );
115301  /* The LIMIT clause will jump out of the loop for us */
115302  }
115303  break;
115304  }
115305 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
115306 
115307  case SRT_Coroutine: /* Send data to a co-routine */
115308  case SRT_Output: { /* Return the results */
115309  testcase( eDest==SRT_Coroutine );
115310  testcase( eDest==SRT_Output );
115311  if( pSort ){
115312  pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
115313  nPrefixReg);
115314  }else if( eDest==SRT_Coroutine ){
115315  sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
115316  }else{
115317  sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
115318  sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
115319  }
115320  break;
115321  }
115322 
115323 #ifndef SQLITE_OMIT_CTE
115324  /* Write the results into a priority queue that is order according to
115325  ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
115326  ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
115327  ** pSO->nExpr columns, then make sure all keys are unique by adding a
115328  ** final OP_Sequence column. The last column is the record as a blob.
115329  */
115330  case SRT_DistQueue:
115331  case SRT_Queue: {
115332  int nKey;
115333  int r1, r2, r3;
115334  int addrTest = 0;
115335  ExprList *pSO;
115336  pSO = pDest->pOrderBy;
115337  assert( pSO );
115338  nKey = pSO->nExpr;
115339  r1 = sqlite3GetTempReg(pParse);
115340  r2 = sqlite3GetTempRange(pParse, nKey+2);
115341  r3 = r2+nKey+1;
115342  if( eDest==SRT_DistQueue ){
115343  /* If the destination is DistQueue, then cursor (iParm+1) is open
115344  ** on a second ephemeral index that holds all values every previously
115345  ** added to the queue. */
115346  addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
115347  regResult, nResultCol);
115348  VdbeCoverage(v);
115349  }
115350  sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
115351  if( eDest==SRT_DistQueue ){
115352  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
115353  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
115354  }
115355  for(i=0; i<nKey; i++){
115356  sqlite3VdbeAddOp2(v, OP_SCopy,
115357  regResult + pSO->a[i].u.x.iOrderByCol - 1,
115358  r2+i);
115359  }
115360  sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
115361  sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
115362  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
115363  if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
115364  sqlite3ReleaseTempReg(pParse, r1);
115365  sqlite3ReleaseTempRange(pParse, r2, nKey+2);
115366  break;
115367  }
115368 #endif /* SQLITE_OMIT_CTE */
115369 
115370 
115371 
115372 #if !defined(SQLITE_OMIT_TRIGGER)
115373  /* Discard the results. This is used for SELECT statements inside
115374  ** the body of a TRIGGER. The purpose of such selects is to call
115375  ** user-defined functions that have side effects. We do not care
115376  ** about the actual results of the select.
115377  */
115378  default: {
115379  assert( eDest==SRT_Discard );
115380  break;
115381  }
115382 #endif
115383  }
115384 
115385  /* Jump to the end of the loop if the LIMIT is reached. Except, if
115386  ** there is a sorter, in which case the sorter has already limited
115387  ** the output for us.
115388  */
115389  if( pSort==0 && p->iLimit ){
115390  sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
115391  }
115392 }
115393 
115394 /*
115395 ** Allocate a KeyInfo object sufficient for an index of N key columns and
115396 ** X extra columns.
115397 */
115398 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
115399  int nExtra = (N+X)*(sizeof(CollSeq*)+1);
115400  KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
115401  if( p ){
115402  p->aSortOrder = (u8*)&p->aColl[N+X];
115403  p->nField = (u16)N;
115404  p->nXField = (u16)X;
115405  p->enc = ENC(db);
115406  p->db = db;
115407  p->nRef = 1;
115408  memset(&p[1], 0, nExtra);
115409  }else{
115410  sqlite3OomFault(db);
115411  }
115412  return p;
115413 }
115414 
115415 /*
115416 ** Deallocate a KeyInfo object
115417 */
115418 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
115419  if( p ){
115420  assert( p->nRef>0 );
115421  p->nRef--;
115422  if( p->nRef==0 ) sqlite3DbFree(p->db, p);
115423  }
115424 }
115425 
115426 /*
115427 ** Make a new pointer to a KeyInfo object
115428 */
115429 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
115430  if( p ){
115431  assert( p->nRef>0 );
115432  p->nRef++;
115433  }
115434  return p;
115435 }
115436 
115437 #ifdef SQLITE_DEBUG
115438 /*
115439 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
115440 ** can only be changed if this is just a single reference to the object.
115441 **
115442 ** This routine is used only inside of assert() statements.
115443 */
115444 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
115445 #endif /* SQLITE_DEBUG */
115446 
115447 /*
115448 ** Given an expression list, generate a KeyInfo structure that records
115449 ** the collating sequence for each expression in that expression list.
115450 **
115451 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
115452 ** KeyInfo structure is appropriate for initializing a virtual index to
115453 ** implement that clause. If the ExprList is the result set of a SELECT
115454 ** then the KeyInfo structure is appropriate for initializing a virtual
115455 ** index to implement a DISTINCT test.
115456 **
115457 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
115458 ** function is responsible for seeing that this structure is eventually
115459 ** freed.
115460 */
115461 static KeyInfo *keyInfoFromExprList(
115462  Parse *pParse, /* Parsing context */
115463  ExprList *pList, /* Form the KeyInfo object from this ExprList */
115464  int iStart, /* Begin with this column of pList */
115465  int nExtra /* Add this many extra columns to the end */
115466 ){
115467  int nExpr;
115468  KeyInfo *pInfo;
115469  struct ExprList_item *pItem;
115470  sqlite3 *db = pParse->db;
115471  int i;
115472 
115473  nExpr = pList->nExpr;
115474  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
115475  if( pInfo ){
115476  assert( sqlite3KeyInfoIsWriteable(pInfo) );
115477  for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
115478  CollSeq *pColl;
115479  pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
115480  if( !pColl ) pColl = db->pDfltColl;
115481  pInfo->aColl[i-iStart] = pColl;
115482  pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
115483  }
115484  }
115485  return pInfo;
115486 }
115487 
115488 /*
115489 ** Name of the connection operator, used for error messages.
115490 */
115491 static const char *selectOpName(int id){
115492  char *z;
115493  switch( id ){
115494  case TK_ALL: z = "UNION ALL"; break;
115495  case TK_INTERSECT: z = "INTERSECT"; break;
115496  case TK_EXCEPT: z = "EXCEPT"; break;
115497  default: z = "UNION"; break;
115498  }
115499  return z;
115500 }
115501 
115502 #ifndef SQLITE_OMIT_EXPLAIN
115503 /*
115504 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
115505 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
115506 ** where the caption is of the form:
115507 **
115508 ** "USE TEMP B-TREE FOR xxx"
115509 **
115510 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
115511 ** is determined by the zUsage argument.
115512 */
115513 static void explainTempTable(Parse *pParse, const char *zUsage){
115514  if( pParse->explain==2 ){
115515  Vdbe *v = pParse->pVdbe;
115516  char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
115517  sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
115518  }
115519 }
115520 
115521 /*
115522 ** Assign expression b to lvalue a. A second, no-op, version of this macro
115523 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
115524 ** in sqlite3Select() to assign values to structure member variables that
115525 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
115526 ** code with #ifndef directives.
115527 */
115528 # define explainSetInteger(a, b) a = b
115529 
115530 #else
115531 /* No-op versions of the explainXXX() functions and macros. */
115532 # define explainTempTable(y,z)
115533 # define explainSetInteger(y,z)
115534 #endif
115535 
115536 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
115537 /*
115538 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
115539 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
115540 ** where the caption is of one of the two forms:
115541 **
115542 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
115543 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
115544 **
115545 ** where iSub1 and iSub2 are the integers passed as the corresponding
115546 ** function parameters, and op is the text representation of the parameter
115547 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
115548 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
115549 ** false, or the second form if it is true.
115550 */
115551 static void explainComposite(
115552  Parse *pParse, /* Parse context */
115553  int op, /* One of TK_UNION, TK_EXCEPT etc. */
115554  int iSub1, /* Subquery id 1 */
115555  int iSub2, /* Subquery id 2 */
115556  int bUseTmp /* True if a temp table was used */
115557 ){
115558  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
115559  if( pParse->explain==2 ){
115560  Vdbe *v = pParse->pVdbe;
115561  char *zMsg = sqlite3MPrintf(
115562  pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
115563  bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
115564  );
115565  sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
115566  }
115567 }
115568 #else
115569 /* No-op versions of the explainXXX() functions and macros. */
115570 # define explainComposite(v,w,x,y,z)
115571 #endif
115572 
115573 /*
115574 ** If the inner loop was generated using a non-null pOrderBy argument,
115575 ** then the results were placed in a sorter. After the loop is terminated
115576 ** we need to run the sorter and output the results. The following
115577 ** routine generates the code needed to do that.
115578 */
115579 static void generateSortTail(
115580  Parse *pParse, /* Parsing context */
115581  Select *p, /* The SELECT statement */
115582  SortCtx *pSort, /* Information on the ORDER BY clause */
115583  int nColumn, /* Number of columns of data */
115584  SelectDest *pDest /* Write the sorted results here */
115585 ){
115586  Vdbe *v = pParse->pVdbe; /* The prepared statement */
115587  int addrBreak = pSort->labelDone; /* Jump here to exit loop */
115588  int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
115589  int addr;
115590  int addrOnce = 0;
115591  int iTab;
115592  ExprList *pOrderBy = pSort->pOrderBy;
115593  int eDest = pDest->eDest;
115594  int iParm = pDest->iSDParm;
115595  int regRow;
115596  int regRowid;
115597  int nKey;
115598  int iSortTab; /* Sorter cursor to read from */
115599  int nSortData; /* Trailing values to read from sorter */
115600  int i;
115601  int bSeq; /* True if sorter record includes seq. no. */
115602 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
115603  struct ExprList_item *aOutEx = p->pEList->a;
115604 #endif
115605 
115606  assert( addrBreak<0 );
115607  if( pSort->labelBkOut ){
115608  sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
115609  sqlite3VdbeGoto(v, addrBreak);
115610  sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
115611  }
115612  iTab = pSort->iECursor;
115613  if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
115614  regRowid = 0;
115615  regRow = pDest->iSdst;
115616  nSortData = nColumn;
115617  }else{
115618  regRowid = sqlite3GetTempReg(pParse);
115619  regRow = sqlite3GetTempRange(pParse, nColumn);
115620  nSortData = nColumn;
115621  }
115622  nKey = pOrderBy->nExpr - pSort->nOBSat;
115623  if( pSort->sortFlags & SORTFLAG_UseSorter ){
115624  int regSortOut = ++pParse->nMem;
115625  iSortTab = pParse->nTab++;
115626  if( pSort->labelBkOut ){
115627  addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
115628  }
115629  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
115630  if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
115631  addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
115632  VdbeCoverage(v);
115633  codeOffset(v, p->iOffset, addrContinue);
115634  sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
115635  bSeq = 0;
115636  }else{
115637  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
115638  codeOffset(v, p->iOffset, addrContinue);
115639  iSortTab = iTab;
115640  bSeq = 1;
115641  }
115642  for(i=0; i<nSortData; i++){
115643  sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
115644  VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
115645  }
115646  switch( eDest ){
115647  case SRT_EphemTab: {
115648  sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
115649  sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
115650  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
115651  break;
115652  }
115653 #ifndef SQLITE_OMIT_SUBQUERY
115654  case SRT_Set: {
115655  assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
115656  sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
115657  pDest->zAffSdst, nColumn);
115658  sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
115659  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
115660  break;
115661  }
115662  case SRT_Mem: {
115663  /* The LIMIT clause will terminate the loop for us */
115664  break;
115665  }
115666 #endif
115667  default: {
115668  assert( eDest==SRT_Output || eDest==SRT_Coroutine );
115669  testcase( eDest==SRT_Output );
115670  testcase( eDest==SRT_Coroutine );
115671  if( eDest==SRT_Output ){
115672  sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
115673  sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
115674  }else{
115675  sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
115676  }
115677  break;
115678  }
115679  }
115680  if( regRowid ){
115681  if( eDest==SRT_Set ){
115682  sqlite3ReleaseTempRange(pParse, regRow, nColumn);
115683  }else{
115684  sqlite3ReleaseTempReg(pParse, regRow);
115685  }
115686  sqlite3ReleaseTempReg(pParse, regRowid);
115687  }
115688  /* The bottom of the loop
115689  */
115690  sqlite3VdbeResolveLabel(v, addrContinue);
115691  if( pSort->sortFlags & SORTFLAG_UseSorter ){
115692  sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
115693  }else{
115694  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
115695  }
115696  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
115697  sqlite3VdbeResolveLabel(v, addrBreak);
115698 }
115699 
115700 /*
115701 ** Return a pointer to a string containing the 'declaration type' of the
115702 ** expression pExpr. The string may be treated as static by the caller.
115703 **
115704 ** Also try to estimate the size of the returned value and return that
115705 ** result in *pEstWidth.
115706 **
115707 ** The declaration type is the exact datatype definition extracted from the
115708 ** original CREATE TABLE statement if the expression is a column. The
115709 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
115710 ** is considered a column can be complex in the presence of subqueries. The
115711 ** result-set expression in all of the following SELECT statements is
115712 ** considered a column by this function.
115713 **
115714 ** SELECT col FROM tbl;
115715 ** SELECT (SELECT col FROM tbl;
115716 ** SELECT (SELECT col FROM tbl);
115717 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
115718 **
115719 ** The declaration type for any expression other than a column is NULL.
115720 **
115721 ** This routine has either 3 or 6 parameters depending on whether or not
115722 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
115723 */
115724 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115725 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
115726 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
115727 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
115728 #endif
115729 static const char *columnTypeImpl(
115730  NameContext *pNC,
115731  Expr *pExpr,
115732 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115733  const char **pzOrigDb,
115734  const char **pzOrigTab,
115735  const char **pzOrigCol,
115736 #endif
115737  u8 *pEstWidth
115738 ){
115739  char const *zType = 0;
115740  int j;
115741  u8 estWidth = 1;
115742 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115743  char const *zOrigDb = 0;
115744  char const *zOrigTab = 0;
115745  char const *zOrigCol = 0;
115746 #endif
115747 
115748  assert( pExpr!=0 );
115749  assert( pNC->pSrcList!=0 );
115750  switch( pExpr->op ){
115751  case TK_AGG_COLUMN:
115752  case TK_COLUMN: {
115753  /* The expression is a column. Locate the table the column is being
115754  ** extracted from in NameContext.pSrcList. This table may be real
115755  ** database table or a subquery.
115756  */
115757  Table *pTab = 0; /* Table structure column is extracted from */
115758  Select *pS = 0; /* Select the column is extracted from */
115759  int iCol = pExpr->iColumn; /* Index of column in pTab */
115760  testcase( pExpr->op==TK_AGG_COLUMN );
115761  testcase( pExpr->op==TK_COLUMN );
115762  while( pNC && !pTab ){
115763  SrcList *pTabList = pNC->pSrcList;
115764  for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
115765  if( j<pTabList->nSrc ){
115766  pTab = pTabList->a[j].pTab;
115767  pS = pTabList->a[j].pSelect;
115768  }else{
115769  pNC = pNC->pNext;
115770  }
115771  }
115772 
115773  if( pTab==0 ){
115774  /* At one time, code such as "SELECT new.x" within a trigger would
115775  ** cause this condition to run. Since then, we have restructured how
115776  ** trigger code is generated and so this condition is no longer
115777  ** possible. However, it can still be true for statements like
115778  ** the following:
115779  **
115780  ** CREATE TABLE t1(col INTEGER);
115781  ** SELECT (SELECT t1.col) FROM FROM t1;
115782  **
115783  ** when columnType() is called on the expression "t1.col" in the
115784  ** sub-select. In this case, set the column type to NULL, even
115785  ** though it should really be "INTEGER".
115786  **
115787  ** This is not a problem, as the column type of "t1.col" is never
115788  ** used. When columnType() is called on the expression
115789  ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
115790  ** branch below. */
115791  break;
115792  }
115793 
115794  assert( pTab && pExpr->pTab==pTab );
115795  if( pS ){
115796  /* The "table" is actually a sub-select or a view in the FROM clause
115797  ** of the SELECT statement. Return the declaration type and origin
115798  ** data for the result-set column of the sub-select.
115799  */
115800  if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
115801  /* If iCol is less than zero, then the expression requests the
115802  ** rowid of the sub-select or view. This expression is legal (see
115803  ** test case misc2.2.2) - it always evaluates to NULL.
115804  **
115805  ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
115806  ** caught already by name resolution.
115807  */
115808  NameContext sNC;
115809  Expr *p = pS->pEList->a[iCol].pExpr;
115810  sNC.pSrcList = pS->pSrc;
115811  sNC.pNext = pNC;
115812  sNC.pParse = pNC->pParse;
115813  zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
115814  }
115815  }else if( pTab->pSchema ){
115816  /* A real table */
115817  assert( !pS );
115818  if( iCol<0 ) iCol = pTab->iPKey;
115819  assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
115820 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115821  if( iCol<0 ){
115822  zType = "INTEGER";
115823  zOrigCol = "rowid";
115824  }else{
115825  zOrigCol = pTab->aCol[iCol].zName;
115826  zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
115827  estWidth = pTab->aCol[iCol].szEst;
115828  }
115829  zOrigTab = pTab->zName;
115830  if( pNC->pParse ){
115831  int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
115832  zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
115833  }
115834 #else
115835  if( iCol<0 ){
115836  zType = "INTEGER";
115837  }else{
115838  zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
115839  estWidth = pTab->aCol[iCol].szEst;
115840  }
115841 #endif
115842  }
115843  break;
115844  }
115845 #ifndef SQLITE_OMIT_SUBQUERY
115846  case TK_SELECT: {
115847  /* The expression is a sub-select. Return the declaration type and
115848  ** origin info for the single column in the result set of the SELECT
115849  ** statement.
115850  */
115851  NameContext sNC;
115852  Select *pS = pExpr->x.pSelect;
115853  Expr *p = pS->pEList->a[0].pExpr;
115854  assert( ExprHasProperty(pExpr, EP_xIsSelect) );
115855  sNC.pSrcList = pS->pSrc;
115856  sNC.pNext = pNC;
115857  sNC.pParse = pNC->pParse;
115858  zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
115859  break;
115860  }
115861 #endif
115862  }
115863 
115864 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115865  if( pzOrigDb ){
115866  assert( pzOrigTab && pzOrigCol );
115867  *pzOrigDb = zOrigDb;
115868  *pzOrigTab = zOrigTab;
115869  *pzOrigCol = zOrigCol;
115870  }
115871 #endif
115872  if( pEstWidth ) *pEstWidth = estWidth;
115873  return zType;
115874 }
115875 
115876 /*
115877 ** Generate code that will tell the VDBE the declaration types of columns
115878 ** in the result set.
115879 */
115880 static void generateColumnTypes(
115881  Parse *pParse, /* Parser context */
115882  SrcList *pTabList, /* List of tables */
115883  ExprList *pEList /* Expressions defining the result set */
115884 ){
115885 #ifndef SQLITE_OMIT_DECLTYPE
115886  Vdbe *v = pParse->pVdbe;
115887  int i;
115888  NameContext sNC;
115889  sNC.pSrcList = pTabList;
115890  sNC.pParse = pParse;
115891  for(i=0; i<pEList->nExpr; i++){
115892  Expr *p = pEList->a[i].pExpr;
115893  const char *zType;
115894 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115895  const char *zOrigDb = 0;
115896  const char *zOrigTab = 0;
115897  const char *zOrigCol = 0;
115898  zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
115899 
115900  /* The vdbe must make its own copy of the column-type and other
115901  ** column specific strings, in case the schema is reset before this
115902  ** virtual machine is deleted.
115903  */
115904  sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
115905  sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
115906  sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
115907 #else
115908  zType = columnType(&sNC, p, 0, 0, 0, 0);
115909 #endif
115910  sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
115911  }
115912 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
115913 }
115914 
115915 /*
115916 ** Generate code that will tell the VDBE the names of columns
115917 ** in the result set. This information is used to provide the
115918 ** azCol[] values in the callback.
115919 */
115920 static void generateColumnNames(
115921  Parse *pParse, /* Parser context */
115922  SrcList *pTabList, /* List of tables */
115923  ExprList *pEList /* Expressions defining the result set */
115924 ){
115925  Vdbe *v = pParse->pVdbe;
115926  int i, j;
115927  sqlite3 *db = pParse->db;
115928  int fullNames, shortNames;
115929 
115930 #ifndef SQLITE_OMIT_EXPLAIN
115931  /* If this is an EXPLAIN, skip this step */
115932  if( pParse->explain ){
115933  return;
115934  }
115935 #endif
115936 
115937  if( pParse->colNamesSet || db->mallocFailed ) return;
115938  assert( v!=0 );
115939  assert( pTabList!=0 );
115940  pParse->colNamesSet = 1;
115941  fullNames = (db->flags & SQLITE_FullColNames)!=0;
115942  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
115943  sqlite3VdbeSetNumCols(v, pEList->nExpr);
115944  for(i=0; i<pEList->nExpr; i++){
115945  Expr *p;
115946  p = pEList->a[i].pExpr;
115947  if( NEVER(p==0) ) continue;
115948  if( pEList->a[i].zName ){
115949  char *zName = pEList->a[i].zName;
115950  sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
115951  }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
115952  Table *pTab;
115953  char *zCol;
115954  int iCol = p->iColumn;
115955  for(j=0; ALWAYS(j<pTabList->nSrc); j++){
115956  if( pTabList->a[j].iCursor==p->iTable ) break;
115957  }
115958  assert( j<pTabList->nSrc );
115959  pTab = pTabList->a[j].pTab;
115960  if( iCol<0 ) iCol = pTab->iPKey;
115961  assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
115962  if( iCol<0 ){
115963  zCol = "rowid";
115964  }else{
115965  zCol = pTab->aCol[iCol].zName;
115966  }
115967  if( !shortNames && !fullNames ){
115968  sqlite3VdbeSetColName(v, i, COLNAME_NAME,
115969  sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
115970  }else if( fullNames ){
115971  char *zName = 0;
115972  zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
115973  sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
115974  }else{
115975  sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
115976  }
115977  }else{
115978  const char *z = pEList->a[i].zSpan;
115979  z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
115980  sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
115981  }
115982  }
115983  generateColumnTypes(pParse, pTabList, pEList);
115984 }
115985 
115986 /*
115987 ** Given an expression list (which is really the list of expressions
115988 ** that form the result set of a SELECT statement) compute appropriate
115989 ** column names for a table that would hold the expression list.
115990 **
115991 ** All column names will be unique.
115992 **
115993 ** Only the column names are computed. Column.zType, Column.zColl,
115994 ** and other fields of Column are zeroed.
115995 **
115996 ** Return SQLITE_OK on success. If a memory allocation error occurs,
115997 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
115998 */
115999 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
116000  Parse *pParse, /* Parsing context */
116001  ExprList *pEList, /* Expr list from which to derive column names */
116002  i16 *pnCol, /* Write the number of columns here */
116003  Column **paCol /* Write the new column list here */
116004 ){
116005  sqlite3 *db = pParse->db; /* Database connection */
116006  int i, j; /* Loop counters */
116007  u32 cnt; /* Index added to make the name unique */
116008  Column *aCol, *pCol; /* For looping over result columns */
116009  int nCol; /* Number of columns in the result set */
116010  Expr *p; /* Expression for a single result column */
116011  char *zName; /* Column name */
116012  int nName; /* Size of name in zName[] */
116013  Hash ht; /* Hash table of column names */
116014 
116015  sqlite3HashInit(&ht);
116016  if( pEList ){
116017  nCol = pEList->nExpr;
116018  aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
116019  testcase( aCol==0 );
116020  }else{
116021  nCol = 0;
116022  aCol = 0;
116023  }
116024  assert( nCol==(i16)nCol );
116025  *pnCol = nCol;
116026  *paCol = aCol;
116027 
116028  for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
116029  /* Get an appropriate name for the column
116030  */
116031  p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
116032  if( (zName = pEList->a[i].zName)!=0 ){
116033  /* If the column contains an "AS <name>" phrase, use <name> as the name */
116034  }else{
116035  Expr *pColExpr = p; /* The expression that is the result column name */
116036  Table *pTab; /* Table associated with this expression */
116037  while( pColExpr->op==TK_DOT ){
116038  pColExpr = pColExpr->pRight;
116039  assert( pColExpr!=0 );
116040  }
116041  if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
116042  /* For columns use the column name name */
116043  int iCol = pColExpr->iColumn;
116044  pTab = pColExpr->pTab;
116045  if( iCol<0 ) iCol = pTab->iPKey;
116046  zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
116047  }else if( pColExpr->op==TK_ID ){
116048  assert( !ExprHasProperty(pColExpr, EP_IntValue) );
116049  zName = pColExpr->u.zToken;
116050  }else{
116051  /* Use the original text of the column expression as its name */
116052  zName = pEList->a[i].zSpan;
116053  }
116054  }
116055  zName = sqlite3MPrintf(db, "%s", zName);
116056 
116057  /* Make sure the column name is unique. If the name is not unique,
116058  ** append an integer to the name so that it becomes unique.
116059  */
116060  cnt = 0;
116061  while( zName && sqlite3HashFind(&ht, zName)!=0 ){
116062  nName = sqlite3Strlen30(zName);
116063  if( nName>0 ){
116064  for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
116065  if( zName[j]==':' ) nName = j;
116066  }
116067  zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
116068  if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
116069  }
116070  pCol->zName = zName;
116071  sqlite3ColumnPropertiesFromName(0, pCol);
116072  if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
116073  sqlite3OomFault(db);
116074  }
116075  }
116076  sqlite3HashClear(&ht);
116077  if( db->mallocFailed ){
116078  for(j=0; j<i; j++){
116079  sqlite3DbFree(db, aCol[j].zName);
116080  }
116081  sqlite3DbFree(db, aCol);
116082  *paCol = 0;
116083  *pnCol = 0;
116084  return SQLITE_NOMEM_BKPT;
116085  }
116086  return SQLITE_OK;
116087 }
116088 
116089 /*
116090 ** Add type and collation information to a column list based on
116091 ** a SELECT statement.
116092 **
116093 ** The column list presumably came from selectColumnNamesFromExprList().
116094 ** The column list has only names, not types or collations. This
116095 ** routine goes through and adds the types and collations.
116096 **
116097 ** This routine requires that all identifiers in the SELECT
116098 ** statement be resolved.
116099 */
116100 SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
116101  Parse *pParse, /* Parsing contexts */
116102  Table *pTab, /* Add column type information to this table */
116103  Select *pSelect /* SELECT used to determine types and collations */
116104 ){
116105  sqlite3 *db = pParse->db;
116106  NameContext sNC;
116107  Column *pCol;
116108  CollSeq *pColl;
116109  int i;
116110  Expr *p;
116111  struct ExprList_item *a;
116112  u64 szAll = 0;
116113 
116114  assert( pSelect!=0 );
116115  assert( (pSelect->selFlags & SF_Resolved)!=0 );
116116  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
116117  if( db->mallocFailed ) return;
116118  memset(&sNC, 0, sizeof(sNC));
116119  sNC.pSrcList = pSelect->pSrc;
116120  a = pSelect->pEList->a;
116121  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
116122  const char *zType;
116123  int n, m;
116124  p = a[i].pExpr;
116125  zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
116126  szAll += pCol->szEst;
116127  pCol->affinity = sqlite3ExprAffinity(p);
116128  if( zType && (m = sqlite3Strlen30(zType))>0 ){
116129  n = sqlite3Strlen30(pCol->zName);
116130  pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
116131  if( pCol->zName ){
116132  memcpy(&pCol->zName[n+1], zType, m+1);
116133  pCol->colFlags |= COLFLAG_HASTYPE;
116134  }
116135  }
116136  if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
116137  pColl = sqlite3ExprCollSeq(pParse, p);
116138  if( pColl && pCol->zColl==0 ){
116139  pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
116140  }
116141  }
116142  pTab->szTabRow = sqlite3LogEst(szAll*4);
116143 }
116144 
116145 /*
116146 ** Given a SELECT statement, generate a Table structure that describes
116147 ** the result set of that SELECT.
116148 */
116149 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
116150  Table *pTab;
116151  sqlite3 *db = pParse->db;
116152  int savedFlags;
116153 
116154  savedFlags = db->flags;
116155  db->flags &= ~SQLITE_FullColNames;
116156  db->flags |= SQLITE_ShortColNames;
116157  sqlite3SelectPrep(pParse, pSelect, 0);
116158  if( pParse->nErr ) return 0;
116159  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
116160  db->flags = savedFlags;
116161  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
116162  if( pTab==0 ){
116163  return 0;
116164  }
116165  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
116166  ** is disabled */
116167  assert( db->lookaside.bDisable );
116168  pTab->nRef = 1;
116169  pTab->zName = 0;
116170  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
116171  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
116172  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
116173  pTab->iPKey = -1;
116174  if( db->mallocFailed ){
116175  sqlite3DeleteTable(db, pTab);
116176  return 0;
116177  }
116178  return pTab;
116179 }
116180 
116181 /*
116182 ** Get a VDBE for the given parser context. Create a new one if necessary.
116183 ** If an error occurs, return NULL and leave a message in pParse.
116184 */
116185 static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
116186  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
116187  if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1);
116188  if( pParse->pToplevel==0
116189  && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
116190  ){
116191  pParse->okConstFactor = 1;
116192  }
116193  return v;
116194 }
116195 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
116196  Vdbe *v = pParse->pVdbe;
116197  return v ? v : allocVdbe(pParse);
116198 }
116199 
116200 
116201 /*
116202 ** Compute the iLimit and iOffset fields of the SELECT based on the
116203 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
116204 ** that appear in the original SQL statement after the LIMIT and OFFSET
116205 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
116206 ** are the integer memory register numbers for counters used to compute
116207 ** the limit and offset. If there is no limit and/or offset, then
116208 ** iLimit and iOffset are negative.
116209 **
116210 ** This routine changes the values of iLimit and iOffset only if
116211 ** a limit or offset is defined by pLimit and pOffset. iLimit and
116212 ** iOffset should have been preset to appropriate default values (zero)
116213 ** prior to calling this routine.
116214 **
116215 ** The iOffset register (if it exists) is initialized to the value
116216 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
116217 ** iOffset+1 is initialized to LIMIT+OFFSET.
116218 **
116219 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
116220 ** redefined. The UNION ALL operator uses this property to force
116221 ** the reuse of the same limit and offset registers across multiple
116222 ** SELECT statements.
116223 */
116224 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
116225  Vdbe *v = 0;
116226  int iLimit = 0;
116227  int iOffset;
116228  int n;
116229  if( p->iLimit ) return;
116230 
116231  /*
116232  ** "LIMIT -1" always shows all rows. There is some
116233  ** controversy about what the correct behavior should be.
116234  ** The current implementation interprets "LIMIT 0" to mean
116235  ** no rows.
116236  */
116237  sqlite3ExprCacheClear(pParse);
116238  assert( p->pOffset==0 || p->pLimit!=0 );
116239  if( p->pLimit ){
116240  p->iLimit = iLimit = ++pParse->nMem;
116241  v = sqlite3GetVdbe(pParse);
116242  assert( v!=0 );
116243  if( sqlite3ExprIsInteger(p->pLimit, &n) ){
116244  sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
116245  VdbeComment((v, "LIMIT counter"));
116246  if( n==0 ){
116247  sqlite3VdbeGoto(v, iBreak);
116248  }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
116249  p->nSelectRow = sqlite3LogEst((u64)n);
116250  p->selFlags |= SF_FixedLimit;
116251  }
116252  }else{
116253  sqlite3ExprCode(pParse, p->pLimit, iLimit);
116254  sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
116255  VdbeComment((v, "LIMIT counter"));
116256  sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
116257  }
116258  if( p->pOffset ){
116259  p->iOffset = iOffset = ++pParse->nMem;
116260  pParse->nMem++; /* Allocate an extra register for limit+offset */
116261  sqlite3ExprCode(pParse, p->pOffset, iOffset);
116262  sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
116263  VdbeComment((v, "OFFSET counter"));
116264  sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
116265  VdbeComment((v, "LIMIT+OFFSET"));
116266  }
116267  }
116268 }
116269 
116270 #ifndef SQLITE_OMIT_COMPOUND_SELECT
116271 /*
116272 ** Return the appropriate collating sequence for the iCol-th column of
116273 ** the result set for the compound-select statement "p". Return NULL if
116274 ** the column has no default collating sequence.
116275 **
116276 ** The collating sequence for the compound select is taken from the
116277 ** left-most term of the select that has a collating sequence.
116278 */
116279 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
116280  CollSeq *pRet;
116281  if( p->pPrior ){
116282  pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
116283  }else{
116284  pRet = 0;
116285  }
116286  assert( iCol>=0 );
116287  /* iCol must be less than p->pEList->nExpr. Otherwise an error would
116288  ** have been thrown during name resolution and we would not have gotten
116289  ** this far */
116290  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
116291  pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
116292  }
116293  return pRet;
116294 }
116295 
116296 /*
116297 ** The select statement passed as the second parameter is a compound SELECT
116298 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
116299 ** structure suitable for implementing the ORDER BY.
116300 **
116301 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
116302 ** function is responsible for ensuring that this structure is eventually
116303 ** freed.
116304 */
116305 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
116306  ExprList *pOrderBy = p->pOrderBy;
116307  int nOrderBy = p->pOrderBy->nExpr;
116308  sqlite3 *db = pParse->db;
116309  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
116310  if( pRet ){
116311  int i;
116312  for(i=0; i<nOrderBy; i++){
116313  struct ExprList_item *pItem = &pOrderBy->a[i];
116314  Expr *pTerm = pItem->pExpr;
116315  CollSeq *pColl;
116316 
116317  if( pTerm->flags & EP_Collate ){
116318  pColl = sqlite3ExprCollSeq(pParse, pTerm);
116319  }else{
116320  pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
116321  if( pColl==0 ) pColl = db->pDfltColl;
116322  pOrderBy->a[i].pExpr =
116323  sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
116324  }
116325  assert( sqlite3KeyInfoIsWriteable(pRet) );
116326  pRet->aColl[i] = pColl;
116327  pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
116328  }
116329  }
116330 
116331  return pRet;
116332 }
116333 
116334 #ifndef SQLITE_OMIT_CTE
116335 /*
116336 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
116337 ** query of the form:
116338 **
116339 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
116340 ** \___________/ \_______________/
116341 ** p->pPrior p
116342 **
116343 **
116344 ** There is exactly one reference to the recursive-table in the FROM clause
116345 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
116346 **
116347 ** The setup-query runs once to generate an initial set of rows that go
116348 ** into a Queue table. Rows are extracted from the Queue table one by
116349 ** one. Each row extracted from Queue is output to pDest. Then the single
116350 ** extracted row (now in the iCurrent table) becomes the content of the
116351 ** recursive-table for a recursive-query run. The output of the recursive-query
116352 ** is added back into the Queue table. Then another row is extracted from Queue
116353 ** and the iteration continues until the Queue table is empty.
116354 **
116355 ** If the compound query operator is UNION then no duplicate rows are ever
116356 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
116357 ** that have ever been inserted into Queue and causes duplicates to be
116358 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
116359 **
116360 ** If the query has an ORDER BY, then entries in the Queue table are kept in
116361 ** ORDER BY order and the first entry is extracted for each cycle. Without
116362 ** an ORDER BY, the Queue table is just a FIFO.
116363 **
116364 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
116365 ** have been output to pDest. A LIMIT of zero means to output no rows and a
116366 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
116367 ** with a positive value, then the first OFFSET outputs are discarded rather
116368 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
116369 ** rows have been skipped.
116370 */
116371 static void generateWithRecursiveQuery(
116372  Parse *pParse, /* Parsing context */
116373  Select *p, /* The recursive SELECT to be coded */
116374  SelectDest *pDest /* What to do with query results */
116375 ){
116376  SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
116377  int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
116378  Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
116379  Select *pSetup = p->pPrior; /* The setup query */
116380  int addrTop; /* Top of the loop */
116381  int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
116382  int iCurrent = 0; /* The Current table */
116383  int regCurrent; /* Register holding Current table */
116384  int iQueue; /* The Queue table */
116385  int iDistinct = 0; /* To ensure unique results if UNION */
116386  int eDest = SRT_Fifo; /* How to write to Queue */
116387  SelectDest destQueue; /* SelectDest targetting the Queue table */
116388  int i; /* Loop counter */
116389  int rc; /* Result code */
116390  ExprList *pOrderBy; /* The ORDER BY clause */
116391  Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
116392  int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
116393 
116394  /* Obtain authorization to do a recursive query */
116395  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
116396 
116397  /* Process the LIMIT and OFFSET clauses, if they exist */
116398  addrBreak = sqlite3VdbeMakeLabel(v);
116399  computeLimitRegisters(pParse, p, addrBreak);
116400  pLimit = p->pLimit;
116401  pOffset = p->pOffset;
116402  regLimit = p->iLimit;
116403  regOffset = p->iOffset;
116404  p->pLimit = p->pOffset = 0;
116405  p->iLimit = p->iOffset = 0;
116406  pOrderBy = p->pOrderBy;
116407 
116408  /* Locate the cursor number of the Current table */
116409  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
116410  if( pSrc->a[i].fg.isRecursive ){
116411  iCurrent = pSrc->a[i].iCursor;
116412  break;
116413  }
116414  }
116415 
116416  /* Allocate cursors numbers for Queue and Distinct. The cursor number for
116417  ** the Distinct table must be exactly one greater than Queue in order
116418  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
116419  iQueue = pParse->nTab++;
116420  if( p->op==TK_UNION ){
116421  eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
116422  iDistinct = pParse->nTab++;
116423  }else{
116424  eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
116425  }
116426  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
116427 
116428  /* Allocate cursors for Current, Queue, and Distinct. */
116429  regCurrent = ++pParse->nMem;
116430  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
116431  if( pOrderBy ){
116432  KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
116433  sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
116434  (char*)pKeyInfo, P4_KEYINFO);
116435  destQueue.pOrderBy = pOrderBy;
116436  }else{
116437  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
116438  }
116439  VdbeComment((v, "Queue table"));
116440  if( iDistinct ){
116441  p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
116442  p->selFlags |= SF_UsesEphemeral;
116443  }
116444 
116445  /* Detach the ORDER BY clause from the compound SELECT */
116446  p->pOrderBy = 0;
116447 
116448  /* Store the results of the setup-query in Queue. */
116449  pSetup->pNext = 0;
116450  rc = sqlite3Select(pParse, pSetup, &destQueue);
116451  pSetup->pNext = p;
116452  if( rc ) goto end_of_recursive_query;
116453 
116454  /* Find the next row in the Queue and output that row */
116455  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
116456 
116457  /* Transfer the next row in Queue over to Current */
116458  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
116459  if( pOrderBy ){
116460  sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
116461  }else{
116462  sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
116463  }
116464  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
116465 
116466  /* Output the single row in Current */
116467  addrCont = sqlite3VdbeMakeLabel(v);
116468  codeOffset(v, regOffset, addrCont);
116469  selectInnerLoop(pParse, p, p->pEList, iCurrent,
116470  0, 0, pDest, addrCont, addrBreak);
116471  if( regLimit ){
116472  sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
116473  VdbeCoverage(v);
116474  }
116475  sqlite3VdbeResolveLabel(v, addrCont);
116476 
116477  /* Execute the recursive SELECT taking the single row in Current as
116478  ** the value for the recursive-table. Store the results in the Queue.
116479  */
116480  if( p->selFlags & SF_Aggregate ){
116481  sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
116482  }else{
116483  p->pPrior = 0;
116484  sqlite3Select(pParse, p, &destQueue);
116485  assert( p->pPrior==0 );
116486  p->pPrior = pSetup;
116487  }
116488 
116489  /* Keep running the loop until the Queue is empty */
116490  sqlite3VdbeGoto(v, addrTop);
116491  sqlite3VdbeResolveLabel(v, addrBreak);
116492 
116493 end_of_recursive_query:
116494  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
116495  p->pOrderBy = pOrderBy;
116496  p->pLimit = pLimit;
116497  p->pOffset = pOffset;
116498  return;
116499 }
116500 #endif /* SQLITE_OMIT_CTE */
116501 
116502 /* Forward references */
116503 static int multiSelectOrderBy(
116504  Parse *pParse, /* Parsing context */
116505  Select *p, /* The right-most of SELECTs to be coded */
116506  SelectDest *pDest /* What to do with query results */
116507 );
116508 
116509 /*
116510 ** Handle the special case of a compound-select that originates from a
116511 ** VALUES clause. By handling this as a special case, we avoid deep
116512 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
116513 ** on a VALUES clause.
116514 **
116515 ** Because the Select object originates from a VALUES clause:
116516 ** (1) It has no LIMIT or OFFSET
116517 ** (2) All terms are UNION ALL
116518 ** (3) There is no ORDER BY clause
116519 */
116520 static int multiSelectValues(
116521  Parse *pParse, /* Parsing context */
116522  Select *p, /* The right-most of SELECTs to be coded */
116523  SelectDest *pDest /* What to do with query results */
116524 ){
116525  Select *pPrior;
116526  int nRow = 1;
116527  int rc = 0;
116528  assert( p->selFlags & SF_MultiValue );
116529  do{
116530  assert( p->selFlags & SF_Values );
116531  assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
116532  assert( p->pLimit==0 );
116533  assert( p->pOffset==0 );
116534  assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
116535  if( p->pPrior==0 ) break;
116536  assert( p->pPrior->pNext==p );
116537  p = p->pPrior;
116538  nRow++;
116539  }while(1);
116540  while( p ){
116541  pPrior = p->pPrior;
116542  p->pPrior = 0;
116543  rc = sqlite3Select(pParse, p, pDest);
116544  p->pPrior = pPrior;
116545  if( rc ) break;
116546  p->nSelectRow = nRow;
116547  p = p->pNext;
116548  }
116549  return rc;
116550 }
116551 
116552 /*
116553 ** This routine is called to process a compound query form from
116554 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
116555 ** INTERSECT
116556 **
116557 ** "p" points to the right-most of the two queries. the query on the
116558 ** left is p->pPrior. The left query could also be a compound query
116559 ** in which case this routine will be called recursively.
116560 **
116561 ** The results of the total query are to be written into a destination
116562 ** of type eDest with parameter iParm.
116563 **
116564 ** Example 1: Consider a three-way compound SQL statement.
116565 **
116566 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
116567 **
116568 ** This statement is parsed up as follows:
116569 **
116570 ** SELECT c FROM t3
116571 ** |
116572 ** `-----> SELECT b FROM t2
116573 ** |
116574 ** `------> SELECT a FROM t1
116575 **
116576 ** The arrows in the diagram above represent the Select.pPrior pointer.
116577 ** So if this routine is called with p equal to the t3 query, then
116578 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
116579 **
116580 ** Notice that because of the way SQLite parses compound SELECTs, the
116581 ** individual selects always group from left to right.
116582 */
116583 static int multiSelect(
116584  Parse *pParse, /* Parsing context */
116585  Select *p, /* The right-most of SELECTs to be coded */
116586  SelectDest *pDest /* What to do with query results */
116587 ){
116588  int rc = SQLITE_OK; /* Success code from a subroutine */
116589  Select *pPrior; /* Another SELECT immediately to our left */
116590  Vdbe *v; /* Generate code to this VDBE */
116591  SelectDest dest; /* Alternative data destination */
116592  Select *pDelete = 0; /* Chain of simple selects to delete */
116593  sqlite3 *db; /* Database connection */
116594 #ifndef SQLITE_OMIT_EXPLAIN
116595  int iSub1 = 0; /* EQP id of left-hand query */
116596  int iSub2 = 0; /* EQP id of right-hand query */
116597 #endif
116598 
116599  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
116600  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
116601  */
116602  assert( p && p->pPrior ); /* Calling function guarantees this much */
116603  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
116604  db = pParse->db;
116605  pPrior = p->pPrior;
116606  dest = *pDest;
116607  if( pPrior->pOrderBy ){
116608  sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
116609  selectOpName(p->op));
116610  rc = 1;
116611  goto multi_select_end;
116612  }
116613  if( pPrior->pLimit ){
116614  sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
116615  selectOpName(p->op));
116616  rc = 1;
116617  goto multi_select_end;
116618  }
116619 
116620  v = sqlite3GetVdbe(pParse);
116621  assert( v!=0 ); /* The VDBE already created by calling function */
116622 
116623  /* Create the destination temporary table if necessary
116624  */
116625  if( dest.eDest==SRT_EphemTab ){
116626  assert( p->pEList );
116627  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
116628  dest.eDest = SRT_Table;
116629  }
116630 
116631  /* Special handling for a compound-select that originates as a VALUES clause.
116632  */
116633  if( p->selFlags & SF_MultiValue ){
116634  rc = multiSelectValues(pParse, p, &dest);
116635  goto multi_select_end;
116636  }
116637 
116638  /* Make sure all SELECTs in the statement have the same number of elements
116639  ** in their result sets.
116640  */
116641  assert( p->pEList && pPrior->pEList );
116642  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
116643 
116644 #ifndef SQLITE_OMIT_CTE
116645  if( p->selFlags & SF_Recursive ){
116646  generateWithRecursiveQuery(pParse, p, &dest);
116647  }else
116648 #endif
116649 
116650  /* Compound SELECTs that have an ORDER BY clause are handled separately.
116651  */
116652  if( p->pOrderBy ){
116653  return multiSelectOrderBy(pParse, p, pDest);
116654  }else
116655 
116656  /* Generate code for the left and right SELECT statements.
116657  */
116658  switch( p->op ){
116659  case TK_ALL: {
116660  int addr = 0;
116661  int nLimit;
116662  assert( !pPrior->pLimit );
116663  pPrior->iLimit = p->iLimit;
116664  pPrior->iOffset = p->iOffset;
116665  pPrior->pLimit = p->pLimit;
116666  pPrior->pOffset = p->pOffset;
116667  explainSetInteger(iSub1, pParse->iNextSelectId);
116668  rc = sqlite3Select(pParse, pPrior, &dest);
116669  p->pLimit = 0;
116670  p->pOffset = 0;
116671  if( rc ){
116672  goto multi_select_end;
116673  }
116674  p->pPrior = 0;
116675  p->iLimit = pPrior->iLimit;
116676  p->iOffset = pPrior->iOffset;
116677  if( p->iLimit ){
116678  addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
116679  VdbeComment((v, "Jump ahead if LIMIT reached"));
116680  if( p->iOffset ){
116681  sqlite3VdbeAddOp3(v, OP_OffsetLimit,
116682  p->iLimit, p->iOffset+1, p->iOffset);
116683  }
116684  }
116685  explainSetInteger(iSub2, pParse->iNextSelectId);
116686  rc = sqlite3Select(pParse, p, &dest);
116687  testcase( rc!=SQLITE_OK );
116688  pDelete = p->pPrior;
116689  p->pPrior = pPrior;
116690  p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
116691  if( pPrior->pLimit
116692  && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
116693  && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
116694  ){
116695  p->nSelectRow = sqlite3LogEst((u64)nLimit);
116696  }
116697  if( addr ){
116698  sqlite3VdbeJumpHere(v, addr);
116699  }
116700  break;
116701  }
116702  case TK_EXCEPT:
116703  case TK_UNION: {
116704  int unionTab; /* Cursor number of the temporary table holding result */
116705  u8 op = 0; /* One of the SRT_ operations to apply to self */
116706  int priorOp; /* The SRT_ operation to apply to prior selects */
116707  Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
116708  int addr;
116709  SelectDest uniondest;
116710 
116711  testcase( p->op==TK_EXCEPT );
116712  testcase( p->op==TK_UNION );
116713  priorOp = SRT_Union;
116714  if( dest.eDest==priorOp ){
116715  /* We can reuse a temporary table generated by a SELECT to our
116716  ** right.
116717  */
116718  assert( p->pLimit==0 ); /* Not allowed on leftward elements */
116719  assert( p->pOffset==0 ); /* Not allowed on leftward elements */
116720  unionTab = dest.iSDParm;
116721  }else{
116722  /* We will need to create our own temporary table to hold the
116723  ** intermediate results.
116724  */
116725  unionTab = pParse->nTab++;
116726  assert( p->pOrderBy==0 );
116727  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
116728  assert( p->addrOpenEphm[0] == -1 );
116729  p->addrOpenEphm[0] = addr;
116730  findRightmost(p)->selFlags |= SF_UsesEphemeral;
116731  assert( p->pEList );
116732  }
116733 
116734  /* Code the SELECT statements to our left
116735  */
116736  assert( !pPrior->pOrderBy );
116737  sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
116738  explainSetInteger(iSub1, pParse->iNextSelectId);
116739  rc = sqlite3Select(pParse, pPrior, &uniondest);
116740  if( rc ){
116741  goto multi_select_end;
116742  }
116743 
116744  /* Code the current SELECT statement
116745  */
116746  if( p->op==TK_EXCEPT ){
116747  op = SRT_Except;
116748  }else{
116749  assert( p->op==TK_UNION );
116750  op = SRT_Union;
116751  }
116752  p->pPrior = 0;
116753  pLimit = p->pLimit;
116754  p->pLimit = 0;
116755  pOffset = p->pOffset;
116756  p->pOffset = 0;
116757  uniondest.eDest = op;
116758  explainSetInteger(iSub2, pParse->iNextSelectId);
116759  rc = sqlite3Select(pParse, p, &uniondest);
116760  testcase( rc!=SQLITE_OK );
116761  /* Query flattening in sqlite3Select() might refill p->pOrderBy.
116762  ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
116763  sqlite3ExprListDelete(db, p->pOrderBy);
116764  pDelete = p->pPrior;
116765  p->pPrior = pPrior;
116766  p->pOrderBy = 0;
116767  if( p->op==TK_UNION ){
116768  p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
116769  }
116770  sqlite3ExprDelete(db, p->pLimit);
116771  p->pLimit = pLimit;
116772  p->pOffset = pOffset;
116773  p->iLimit = 0;
116774  p->iOffset = 0;
116775 
116776  /* Convert the data in the temporary table into whatever form
116777  ** it is that we currently need.
116778  */
116779  assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
116780  if( dest.eDest!=priorOp ){
116781  int iCont, iBreak, iStart;
116782  assert( p->pEList );
116783  if( dest.eDest==SRT_Output ){
116784  Select *pFirst = p;
116785  while( pFirst->pPrior ) pFirst = pFirst->pPrior;
116786  generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
116787  }
116788  iBreak = sqlite3VdbeMakeLabel(v);
116789  iCont = sqlite3VdbeMakeLabel(v);
116790  computeLimitRegisters(pParse, p, iBreak);
116791  sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
116792  iStart = sqlite3VdbeCurrentAddr(v);
116793  selectInnerLoop(pParse, p, p->pEList, unionTab,
116794  0, 0, &dest, iCont, iBreak);
116795  sqlite3VdbeResolveLabel(v, iCont);
116796  sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
116797  sqlite3VdbeResolveLabel(v, iBreak);
116798  sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
116799  }
116800  break;
116801  }
116802  default: assert( p->op==TK_INTERSECT ); {
116803  int tab1, tab2;
116804  int iCont, iBreak, iStart;
116805  Expr *pLimit, *pOffset;
116806  int addr;
116807  SelectDest intersectdest;
116808  int r1;
116809 
116810  /* INTERSECT is different from the others since it requires
116811  ** two temporary tables. Hence it has its own case. Begin
116812  ** by allocating the tables we will need.
116813  */
116814  tab1 = pParse->nTab++;
116815  tab2 = pParse->nTab++;
116816  assert( p->pOrderBy==0 );
116817 
116818  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
116819  assert( p->addrOpenEphm[0] == -1 );
116820  p->addrOpenEphm[0] = addr;
116821  findRightmost(p)->selFlags |= SF_UsesEphemeral;
116822  assert( p->pEList );
116823 
116824  /* Code the SELECTs to our left into temporary table "tab1".
116825  */
116826  sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
116827  explainSetInteger(iSub1, pParse->iNextSelectId);
116828  rc = sqlite3Select(pParse, pPrior, &intersectdest);
116829  if( rc ){
116830  goto multi_select_end;
116831  }
116832 
116833  /* Code the current SELECT into temporary table "tab2"
116834  */
116835  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
116836  assert( p->addrOpenEphm[1] == -1 );
116837  p->addrOpenEphm[1] = addr;
116838  p->pPrior = 0;
116839  pLimit = p->pLimit;
116840  p->pLimit = 0;
116841  pOffset = p->pOffset;
116842  p->pOffset = 0;
116843  intersectdest.iSDParm = tab2;
116844  explainSetInteger(iSub2, pParse->iNextSelectId);
116845  rc = sqlite3Select(pParse, p, &intersectdest);
116846  testcase( rc!=SQLITE_OK );
116847  pDelete = p->pPrior;
116848  p->pPrior = pPrior;
116849  if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
116850  sqlite3ExprDelete(db, p->pLimit);
116851  p->pLimit = pLimit;
116852  p->pOffset = pOffset;
116853 
116854  /* Generate code to take the intersection of the two temporary
116855  ** tables.
116856  */
116857  assert( p->pEList );
116858  if( dest.eDest==SRT_Output ){
116859  Select *pFirst = p;
116860  while( pFirst->pPrior ) pFirst = pFirst->pPrior;
116861  generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
116862  }
116863  iBreak = sqlite3VdbeMakeLabel(v);
116864  iCont = sqlite3VdbeMakeLabel(v);
116865  computeLimitRegisters(pParse, p, iBreak);
116866  sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
116867  r1 = sqlite3GetTempReg(pParse);
116868  iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
116869  sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
116870  sqlite3ReleaseTempReg(pParse, r1);
116871  selectInnerLoop(pParse, p, p->pEList, tab1,
116872  0, 0, &dest, iCont, iBreak);
116873  sqlite3VdbeResolveLabel(v, iCont);
116874  sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
116875  sqlite3VdbeResolveLabel(v, iBreak);
116876  sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
116877  sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
116878  break;
116879  }
116880  }
116881 
116882  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
116883 
116884  /* Compute collating sequences used by
116885  ** temporary tables needed to implement the compound select.
116886  ** Attach the KeyInfo structure to all temporary tables.
116887  **
116888  ** This section is run by the right-most SELECT statement only.
116889  ** SELECT statements to the left always skip this part. The right-most
116890  ** SELECT might also skip this part if it has no ORDER BY clause and
116891  ** no temp tables are required.
116892  */
116893  if( p->selFlags & SF_UsesEphemeral ){
116894  int i; /* Loop counter */
116895  KeyInfo *pKeyInfo; /* Collating sequence for the result set */
116896  Select *pLoop; /* For looping through SELECT statements */
116897  CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
116898  int nCol; /* Number of columns in result set */
116899 
116900  assert( p->pNext==0 );
116901  nCol = p->pEList->nExpr;
116902  pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
116903  if( !pKeyInfo ){
116904  rc = SQLITE_NOMEM_BKPT;
116905  goto multi_select_end;
116906  }
116907  for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
116908  *apColl = multiSelectCollSeq(pParse, p, i);
116909  if( 0==*apColl ){
116910  *apColl = db->pDfltColl;
116911  }
116912  }
116913 
116914  for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
116915  for(i=0; i<2; i++){
116916  int addr = pLoop->addrOpenEphm[i];
116917  if( addr<0 ){
116918  /* If [0] is unused then [1] is also unused. So we can
116919  ** always safely abort as soon as the first unused slot is found */
116920  assert( pLoop->addrOpenEphm[1]<0 );
116921  break;
116922  }
116923  sqlite3VdbeChangeP2(v, addr, nCol);
116924  sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
116925  P4_KEYINFO);
116926  pLoop->addrOpenEphm[i] = -1;
116927  }
116928  }
116929  sqlite3KeyInfoUnref(pKeyInfo);
116930  }
116931 
116932 multi_select_end:
116933  pDest->iSdst = dest.iSdst;
116934  pDest->nSdst = dest.nSdst;
116935  sqlite3SelectDelete(db, pDelete);
116936  return rc;
116937 }
116938 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
116939 
116940 /*
116941 ** Error message for when two or more terms of a compound select have different
116942 ** size result sets.
116943 */
116944 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
116945  if( p->selFlags & SF_Values ){
116946  sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
116947  }else{
116948  sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
116949  " do not have the same number of result columns", selectOpName(p->op));
116950  }
116951 }
116952 
116953 /*
116954 ** Code an output subroutine for a coroutine implementation of a
116955 ** SELECT statment.
116956 **
116957 ** The data to be output is contained in pIn->iSdst. There are
116958 ** pIn->nSdst columns to be output. pDest is where the output should
116959 ** be sent.
116960 **
116961 ** regReturn is the number of the register holding the subroutine
116962 ** return address.
116963 **
116964 ** If regPrev>0 then it is the first register in a vector that
116965 ** records the previous output. mem[regPrev] is a flag that is false
116966 ** if there has been no previous output. If regPrev>0 then code is
116967 ** generated to suppress duplicates. pKeyInfo is used for comparing
116968 ** keys.
116969 **
116970 ** If the LIMIT found in p->iLimit is reached, jump immediately to
116971 ** iBreak.
116972 */
116973 static int generateOutputSubroutine(
116974  Parse *pParse, /* Parsing context */
116975  Select *p, /* The SELECT statement */
116976  SelectDest *pIn, /* Coroutine supplying data */
116977  SelectDest *pDest, /* Where to send the data */
116978  int regReturn, /* The return address register */
116979  int regPrev, /* Previous result register. No uniqueness if 0 */
116980  KeyInfo *pKeyInfo, /* For comparing with previous entry */
116981  int iBreak /* Jump here if we hit the LIMIT */
116982 ){
116983  Vdbe *v = pParse->pVdbe;
116984  int iContinue;
116985  int addr;
116986 
116987  addr = sqlite3VdbeCurrentAddr(v);
116988  iContinue = sqlite3VdbeMakeLabel(v);
116989 
116990  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
116991  */
116992  if( regPrev ){
116993  int addr1, addr2;
116994  addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
116995  addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
116996  (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
116997  sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
116998  sqlite3VdbeJumpHere(v, addr1);
116999  sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
117000  sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
117001  }
117002  if( pParse->db->mallocFailed ) return 0;
117003 
117004  /* Suppress the first OFFSET entries if there is an OFFSET clause
117005  */
117006  codeOffset(v, p->iOffset, iContinue);
117007 
117008  assert( pDest->eDest!=SRT_Exists );
117009  assert( pDest->eDest!=SRT_Table );
117010  switch( pDest->eDest ){
117011  /* Store the result as data using a unique key.
117012  */
117013  case SRT_EphemTab: {
117014  int r1 = sqlite3GetTempReg(pParse);
117015  int r2 = sqlite3GetTempReg(pParse);
117016  sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
117017  sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
117018  sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
117019  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
117020  sqlite3ReleaseTempReg(pParse, r2);
117021  sqlite3ReleaseTempReg(pParse, r1);
117022  break;
117023  }
117024 
117025 #ifndef SQLITE_OMIT_SUBQUERY
117026  /* If we are creating a set for an "expr IN (SELECT ...)".
117027  */
117028  case SRT_Set: {
117029  int r1;
117030  testcase( pIn->nSdst>1 );
117031  r1 = sqlite3GetTempReg(pParse);
117032  sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
117033  r1, pDest->zAffSdst, pIn->nSdst);
117034  sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
117035  sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
117036  sqlite3ReleaseTempReg(pParse, r1);
117037  break;
117038  }
117039 
117040  /* If this is a scalar select that is part of an expression, then
117041  ** store the results in the appropriate memory cell and break out
117042  ** of the scan loop.
117043  */
117044  case SRT_Mem: {
117045  assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
117046  sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
117047  /* The LIMIT clause will jump out of the loop for us */
117048  break;
117049  }
117050 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
117051 
117052  /* The results are stored in a sequence of registers
117053  ** starting at pDest->iSdst. Then the co-routine yields.
117054  */
117055  case SRT_Coroutine: {
117056  if( pDest->iSdst==0 ){
117057  pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
117058  pDest->nSdst = pIn->nSdst;
117059  }
117060  sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
117061  sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
117062  break;
117063  }
117064 
117065  /* If none of the above, then the result destination must be
117066  ** SRT_Output. This routine is never called with any other
117067  ** destination other than the ones handled above or SRT_Output.
117068  **
117069  ** For SRT_Output, results are stored in a sequence of registers.
117070  ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
117071  ** return the next row of result.
117072  */
117073  default: {
117074  assert( pDest->eDest==SRT_Output );
117075  sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
117076  sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
117077  break;
117078  }
117079  }
117080 
117081  /* Jump to the end of the loop if the LIMIT is reached.
117082  */
117083  if( p->iLimit ){
117084  sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
117085  }
117086 
117087  /* Generate the subroutine return
117088  */
117089  sqlite3VdbeResolveLabel(v, iContinue);
117090  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
117091 
117092  return addr;
117093 }
117094 
117095 /*
117096 ** Alternative compound select code generator for cases when there
117097 ** is an ORDER BY clause.
117098 **
117099 ** We assume a query of the following form:
117100 **
117101 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
117102 **
117103 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
117104 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
117105 ** co-routines. Then run the co-routines in parallel and merge the results
117106 ** into the output. In addition to the two coroutines (called selectA and
117107 ** selectB) there are 7 subroutines:
117108 **
117109 ** outA: Move the output of the selectA coroutine into the output
117110 ** of the compound query.
117111 **
117112 ** outB: Move the output of the selectB coroutine into the output
117113 ** of the compound query. (Only generated for UNION and
117114 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
117115 ** appears only in B.)
117116 **
117117 ** AltB: Called when there is data from both coroutines and A<B.
117118 **
117119 ** AeqB: Called when there is data from both coroutines and A==B.
117120 **
117121 ** AgtB: Called when there is data from both coroutines and A>B.
117122 **
117123 ** EofA: Called when data is exhausted from selectA.
117124 **
117125 ** EofB: Called when data is exhausted from selectB.
117126 **
117127 ** The implementation of the latter five subroutines depend on which
117128 ** <operator> is used:
117129 **
117130 **
117131 ** UNION ALL UNION EXCEPT INTERSECT
117132 ** ------------- ----------------- -------------- -----------------
117133 ** AltB: outA, nextA outA, nextA outA, nextA nextA
117134 **
117135 ** AeqB: outA, nextA nextA nextA outA, nextA
117136 **
117137 ** AgtB: outB, nextB outB, nextB nextB nextB
117138 **
117139 ** EofA: outB, nextB outB, nextB halt halt
117140 **
117141 ** EofB: outA, nextA outA, nextA outA, nextA halt
117142 **
117143 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
117144 ** causes an immediate jump to EofA and an EOF on B following nextB causes
117145 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
117146 ** following nextX causes a jump to the end of the select processing.
117147 **
117148 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
117149 ** within the output subroutine. The regPrev register set holds the previously
117150 ** output value. A comparison is made against this value and the output
117151 ** is skipped if the next results would be the same as the previous.
117152 **
117153 ** The implementation plan is to implement the two coroutines and seven
117154 ** subroutines first, then put the control logic at the bottom. Like this:
117155 **
117156 ** goto Init
117157 ** coA: coroutine for left query (A)
117158 ** coB: coroutine for right query (B)
117159 ** outA: output one row of A
117160 ** outB: output one row of B (UNION and UNION ALL only)
117161 ** EofA: ...
117162 ** EofB: ...
117163 ** AltB: ...
117164 ** AeqB: ...
117165 ** AgtB: ...
117166 ** Init: initialize coroutine registers
117167 ** yield coA
117168 ** if eof(A) goto EofA
117169 ** yield coB
117170 ** if eof(B) goto EofB
117171 ** Cmpr: Compare A, B
117172 ** Jump AltB, AeqB, AgtB
117173 ** End: ...
117174 **
117175 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
117176 ** actually called using Gosub and they do not Return. EofA and EofB loop
117177 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
117178 ** and AgtB jump to either L2 or to one of EofA or EofB.
117179 */
117180 #ifndef SQLITE_OMIT_COMPOUND_SELECT
117181 static int multiSelectOrderBy(
117182  Parse *pParse, /* Parsing context */
117183  Select *p, /* The right-most of SELECTs to be coded */
117184  SelectDest *pDest /* What to do with query results */
117185 ){
117186  int i, j; /* Loop counters */
117187  Select *pPrior; /* Another SELECT immediately to our left */
117188  Vdbe *v; /* Generate code to this VDBE */
117189  SelectDest destA; /* Destination for coroutine A */
117190  SelectDest destB; /* Destination for coroutine B */
117191  int regAddrA; /* Address register for select-A coroutine */
117192  int regAddrB; /* Address register for select-B coroutine */
117193  int addrSelectA; /* Address of the select-A coroutine */
117194  int addrSelectB; /* Address of the select-B coroutine */
117195  int regOutA; /* Address register for the output-A subroutine */
117196  int regOutB; /* Address register for the output-B subroutine */
117197  int addrOutA; /* Address of the output-A subroutine */
117198  int addrOutB = 0; /* Address of the output-B subroutine */
117199  int addrEofA; /* Address of the select-A-exhausted subroutine */
117200  int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
117201  int addrEofB; /* Address of the select-B-exhausted subroutine */
117202  int addrAltB; /* Address of the A<B subroutine */
117203  int addrAeqB; /* Address of the A==B subroutine */
117204  int addrAgtB; /* Address of the A>B subroutine */
117205  int regLimitA; /* Limit register for select-A */
117206  int regLimitB; /* Limit register for select-A */
117207  int regPrev; /* A range of registers to hold previous output */
117208  int savedLimit; /* Saved value of p->iLimit */
117209  int savedOffset; /* Saved value of p->iOffset */
117210  int labelCmpr; /* Label for the start of the merge algorithm */
117211  int labelEnd; /* Label for the end of the overall SELECT stmt */
117212  int addr1; /* Jump instructions that get retargetted */
117213  int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
117214  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
117215  KeyInfo *pKeyMerge; /* Comparison information for merging rows */
117216  sqlite3 *db; /* Database connection */
117217  ExprList *pOrderBy; /* The ORDER BY clause */
117218  int nOrderBy; /* Number of terms in the ORDER BY clause */
117219  int *aPermute; /* Mapping from ORDER BY terms to result set columns */
117220 #ifndef SQLITE_OMIT_EXPLAIN
117221  int iSub1; /* EQP id of left-hand query */
117222  int iSub2; /* EQP id of right-hand query */
117223 #endif
117224 
117225  assert( p->pOrderBy!=0 );
117226  assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
117227  db = pParse->db;
117228  v = pParse->pVdbe;
117229  assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
117230  labelEnd = sqlite3VdbeMakeLabel(v);
117231  labelCmpr = sqlite3VdbeMakeLabel(v);
117232 
117233 
117234  /* Patch up the ORDER BY clause
117235  */
117236  op = p->op;
117237  pPrior = p->pPrior;
117238  assert( pPrior->pOrderBy==0 );
117239  pOrderBy = p->pOrderBy;
117240  assert( pOrderBy );
117241  nOrderBy = pOrderBy->nExpr;
117242 
117243  /* For operators other than UNION ALL we have to make sure that
117244  ** the ORDER BY clause covers every term of the result set. Add
117245  ** terms to the ORDER BY clause as necessary.
117246  */
117247  if( op!=TK_ALL ){
117248  for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
117249  struct ExprList_item *pItem;
117250  for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
117251  assert( pItem->u.x.iOrderByCol>0 );
117252  if( pItem->u.x.iOrderByCol==i ) break;
117253  }
117254  if( j==nOrderBy ){
117255  Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
117256  if( pNew==0 ) return SQLITE_NOMEM_BKPT;
117257  pNew->flags |= EP_IntValue;
117258  pNew->u.iValue = i;
117259  pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
117260  if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
117261  }
117262  }
117263  }
117264 
117265  /* Compute the comparison permutation and keyinfo that is used with
117266  ** the permutation used to determine if the next
117267  ** row of results comes from selectA or selectB. Also add explicit
117268  ** collations to the ORDER BY clause terms so that when the subqueries
117269  ** to the right and the left are evaluated, they use the correct
117270  ** collation.
117271  */
117272  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
117273  if( aPermute ){
117274  struct ExprList_item *pItem;
117275  aPermute[0] = nOrderBy;
117276  for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
117277  assert( pItem->u.x.iOrderByCol>0 );
117278  assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
117279  aPermute[i] = pItem->u.x.iOrderByCol - 1;
117280  }
117281  pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
117282  }else{
117283  pKeyMerge = 0;
117284  }
117285 
117286  /* Reattach the ORDER BY clause to the query.
117287  */
117288  p->pOrderBy = pOrderBy;
117289  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
117290 
117291  /* Allocate a range of temporary registers and the KeyInfo needed
117292  ** for the logic that removes duplicate result rows when the
117293  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
117294  */
117295  if( op==TK_ALL ){
117296  regPrev = 0;
117297  }else{
117298  int nExpr = p->pEList->nExpr;
117299  assert( nOrderBy>=nExpr || db->mallocFailed );
117300  regPrev = pParse->nMem+1;
117301  pParse->nMem += nExpr+1;
117302  sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
117303  pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
117304  if( pKeyDup ){
117305  assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
117306  for(i=0; i<nExpr; i++){
117307  pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
117308  pKeyDup->aSortOrder[i] = 0;
117309  }
117310  }
117311  }
117312 
117313  /* Separate the left and the right query from one another
117314  */
117315  p->pPrior = 0;
117316  pPrior->pNext = 0;
117317  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
117318  if( pPrior->pPrior==0 ){
117319  sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
117320  }
117321 
117322  /* Compute the limit registers */
117323  computeLimitRegisters(pParse, p, labelEnd);
117324  if( p->iLimit && op==TK_ALL ){
117325  regLimitA = ++pParse->nMem;
117326  regLimitB = ++pParse->nMem;
117327  sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
117328  regLimitA);
117329  sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
117330  }else{
117331  regLimitA = regLimitB = 0;
117332  }
117333  sqlite3ExprDelete(db, p->pLimit);
117334  p->pLimit = 0;
117335  sqlite3ExprDelete(db, p->pOffset);
117336  p->pOffset = 0;
117337 
117338  regAddrA = ++pParse->nMem;
117339  regAddrB = ++pParse->nMem;
117340  regOutA = ++pParse->nMem;
117341  regOutB = ++pParse->nMem;
117342  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
117343  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
117344 
117345  /* Generate a coroutine to evaluate the SELECT statement to the
117346  ** left of the compound operator - the "A" select.
117347  */
117348  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
117349  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
117350  VdbeComment((v, "left SELECT"));
117351  pPrior->iLimit = regLimitA;
117352  explainSetInteger(iSub1, pParse->iNextSelectId);
117353  sqlite3Select(pParse, pPrior, &destA);
117354  sqlite3VdbeEndCoroutine(v, regAddrA);
117355  sqlite3VdbeJumpHere(v, addr1);
117356 
117357  /* Generate a coroutine to evaluate the SELECT statement on
117358  ** the right - the "B" select
117359  */
117360  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
117361  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
117362  VdbeComment((v, "right SELECT"));
117363  savedLimit = p->iLimit;
117364  savedOffset = p->iOffset;
117365  p->iLimit = regLimitB;
117366  p->iOffset = 0;
117367  explainSetInteger(iSub2, pParse->iNextSelectId);
117368  sqlite3Select(pParse, p, &destB);
117369  p->iLimit = savedLimit;
117370  p->iOffset = savedOffset;
117371  sqlite3VdbeEndCoroutine(v, regAddrB);
117372 
117373  /* Generate a subroutine that outputs the current row of the A
117374  ** select as the next output row of the compound select.
117375  */
117376  VdbeNoopComment((v, "Output routine for A"));
117377  addrOutA = generateOutputSubroutine(pParse,
117378  p, &destA, pDest, regOutA,
117379  regPrev, pKeyDup, labelEnd);
117380 
117381  /* Generate a subroutine that outputs the current row of the B
117382  ** select as the next output row of the compound select.
117383  */
117384  if( op==TK_ALL || op==TK_UNION ){
117385  VdbeNoopComment((v, "Output routine for B"));
117386  addrOutB = generateOutputSubroutine(pParse,
117387  p, &destB, pDest, regOutB,
117388  regPrev, pKeyDup, labelEnd);
117389  }
117390  sqlite3KeyInfoUnref(pKeyDup);
117391 
117392  /* Generate a subroutine to run when the results from select A
117393  ** are exhausted and only data in select B remains.
117394  */
117395  if( op==TK_EXCEPT || op==TK_INTERSECT ){
117396  addrEofA_noB = addrEofA = labelEnd;
117397  }else{
117398  VdbeNoopComment((v, "eof-A subroutine"));
117399  addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
117400  addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
117401  VdbeCoverage(v);
117402  sqlite3VdbeGoto(v, addrEofA);
117403  p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
117404  }
117405 
117406  /* Generate a subroutine to run when the results from select B
117407  ** are exhausted and only data in select A remains.
117408  */
117409  if( op==TK_INTERSECT ){
117410  addrEofB = addrEofA;
117411  if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
117412  }else{
117413  VdbeNoopComment((v, "eof-B subroutine"));
117414  addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
117415  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
117416  sqlite3VdbeGoto(v, addrEofB);
117417  }
117418 
117419  /* Generate code to handle the case of A<B
117420  */
117421  VdbeNoopComment((v, "A-lt-B subroutine"));
117422  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
117423  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
117424  sqlite3VdbeGoto(v, labelCmpr);
117425 
117426  /* Generate code to handle the case of A==B
117427  */
117428  if( op==TK_ALL ){
117429  addrAeqB = addrAltB;
117430  }else if( op==TK_INTERSECT ){
117431  addrAeqB = addrAltB;
117432  addrAltB++;
117433  }else{
117434  VdbeNoopComment((v, "A-eq-B subroutine"));
117435  addrAeqB =
117436  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
117437  sqlite3VdbeGoto(v, labelCmpr);
117438  }
117439 
117440  /* Generate code to handle the case of A>B
117441  */
117442  VdbeNoopComment((v, "A-gt-B subroutine"));
117443  addrAgtB = sqlite3VdbeCurrentAddr(v);
117444  if( op==TK_ALL || op==TK_UNION ){
117445  sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
117446  }
117447  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
117448  sqlite3VdbeGoto(v, labelCmpr);
117449 
117450  /* This code runs once to initialize everything.
117451  */
117452  sqlite3VdbeJumpHere(v, addr1);
117453  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
117454  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
117455 
117456  /* Implement the main merge loop
117457  */
117458  sqlite3VdbeResolveLabel(v, labelCmpr);
117459  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
117460  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
117461  (char*)pKeyMerge, P4_KEYINFO);
117462  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
117463  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
117464 
117465  /* Jump to the this point in order to terminate the query.
117466  */
117467  sqlite3VdbeResolveLabel(v, labelEnd);
117468 
117469  /* Set the number of output columns
117470  */
117471  if( pDest->eDest==SRT_Output ){
117472  Select *pFirst = pPrior;
117473  while( pFirst->pPrior ) pFirst = pFirst->pPrior;
117474  generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
117475  }
117476 
117477  /* Reassembly the compound query so that it will be freed correctly
117478  ** by the calling function */
117479  if( p->pPrior ){
117480  sqlite3SelectDelete(db, p->pPrior);
117481  }
117482  p->pPrior = pPrior;
117483  pPrior->pNext = p;
117484 
117485  /*** TBD: Insert subroutine calls to close cursors on incomplete
117486  **** subqueries ****/
117487  explainComposite(pParse, p->op, iSub1, iSub2, 0);
117488  return pParse->nErr!=0;
117489 }
117490 #endif
117491 
117492 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
117493 /* Forward Declarations */
117494 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
117495 static void substSelect(sqlite3*, Select *, int, ExprList*, int);
117496 
117497 /*
117498 ** Scan through the expression pExpr. Replace every reference to
117499 ** a column in table number iTable with a copy of the iColumn-th
117500 ** entry in pEList. (But leave references to the ROWID column
117501 ** unchanged.)
117502 **
117503 ** This routine is part of the flattening procedure. A subquery
117504 ** whose result set is defined by pEList appears as entry in the
117505 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
117506 ** FORM clause entry is iTable. This routine make the necessary
117507 ** changes to pExpr so that it refers directly to the source table
117508 ** of the subquery rather the result set of the subquery.
117509 */
117510 static Expr *substExpr(
117511  sqlite3 *db, /* Report malloc errors to this connection */
117512  Expr *pExpr, /* Expr in which substitution occurs */
117513  int iTable, /* Table to be substituted */
117514  ExprList *pEList /* Substitute expressions */
117515 ){
117516  if( pExpr==0 ) return 0;
117517  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
117518  if( pExpr->iColumn<0 ){
117519  pExpr->op = TK_NULL;
117520  }else{
117521  Expr *pNew;
117522  assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
117523  assert( pExpr->pLeft==0 && pExpr->pRight==0 );
117524  pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
117525  sqlite3ExprDelete(db, pExpr);
117526  pExpr = pNew;
117527  }
117528  }else{
117529  pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
117530  pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
117531  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
117532  substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
117533  }else{
117534  substExprList(db, pExpr->x.pList, iTable, pEList);
117535  }
117536  }
117537  return pExpr;
117538 }
117539 static void substExprList(
117540  sqlite3 *db, /* Report malloc errors here */
117541  ExprList *pList, /* List to scan and in which to make substitutes */
117542  int iTable, /* Table to be substituted */
117543  ExprList *pEList /* Substitute values */
117544 ){
117545  int i;
117546  if( pList==0 ) return;
117547  for(i=0; i<pList->nExpr; i++){
117548  pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
117549  }
117550 }
117551 static void substSelect(
117552  sqlite3 *db, /* Report malloc errors here */
117553  Select *p, /* SELECT statement in which to make substitutions */
117554  int iTable, /* Table to be replaced */
117555  ExprList *pEList, /* Substitute values */
117556  int doPrior /* Do substitutes on p->pPrior too */
117557 ){
117558  SrcList *pSrc;
117559  struct SrcList_item *pItem;
117560  int i;
117561  if( !p ) return;
117562  do{
117563  substExprList(db, p->pEList, iTable, pEList);
117564  substExprList(db, p->pGroupBy, iTable, pEList);
117565  substExprList(db, p->pOrderBy, iTable, pEList);
117566  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
117567  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
117568  pSrc = p->pSrc;
117569  assert( pSrc!=0 );
117570  for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
117571  substSelect(db, pItem->pSelect, iTable, pEList, 1);
117572  if( pItem->fg.isTabFunc ){
117573  substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
117574  }
117575  }
117576  }while( doPrior && (p = p->pPrior)!=0 );
117577 }
117578 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
117579 
117580 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
117581 /*
117582 ** This routine attempts to flatten subqueries as a performance optimization.
117583 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
117584 **
117585 ** To understand the concept of flattening, consider the following
117586 ** query:
117587 **
117588 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
117589 **
117590 ** The default way of implementing this query is to execute the
117591 ** subquery first and store the results in a temporary table, then
117592 ** run the outer query on that temporary table. This requires two
117593 ** passes over the data. Furthermore, because the temporary table
117594 ** has no indices, the WHERE clause on the outer query cannot be
117595 ** optimized.
117596 **
117597 ** This routine attempts to rewrite queries such as the above into
117598 ** a single flat select, like this:
117599 **
117600 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
117601 **
117602 ** The code generated for this simplification gives the same result
117603 ** but only has to scan the data once. And because indices might
117604 ** exist on the table t1, a complete scan of the data might be
117605 ** avoided.
117606 **
117607 ** Flattening is only attempted if all of the following are true:
117608 **
117609 ** (1) The subquery and the outer query do not both use aggregates.
117610 **
117611 ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
117612 ** and (2b) the outer query does not use subqueries other than the one
117613 ** FROM-clause subquery that is a candidate for flattening. (2b is
117614 ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
117615 **
117616 ** (3) The subquery is not the right operand of a left outer join
117617 ** (Originally ticket #306. Strengthened by ticket #3300)
117618 **
117619 ** (4) The subquery is not DISTINCT.
117620 **
117621 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
117622 ** sub-queries that were excluded from this optimization. Restriction
117623 ** (4) has since been expanded to exclude all DISTINCT subqueries.
117624 **
117625 ** (6) The subquery does not use aggregates or the outer query is not
117626 ** DISTINCT.
117627 **
117628 ** (7) The subquery has a FROM clause. TODO: For subqueries without
117629 ** A FROM clause, consider adding a FROM close with the special
117630 ** table sqlite_once that consists of a single row containing a
117631 ** single NULL.
117632 **
117633 ** (8) The subquery does not use LIMIT or the outer query is not a join.
117634 **
117635 ** (9) The subquery does not use LIMIT or the outer query does not use
117636 ** aggregates.
117637 **
117638 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
117639 ** accidently carried the comment forward until 2014-09-15. Original
117640 ** text: "The subquery does not use aggregates or the outer query
117641 ** does not use LIMIT."
117642 **
117643 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
117644 **
117645 ** (**) Not implemented. Subsumed into restriction (3). Was previously
117646 ** a separate restriction deriving from ticket #350.
117647 **
117648 ** (13) The subquery and outer query do not both use LIMIT.
117649 **
117650 ** (14) The subquery does not use OFFSET.
117651 **
117652 ** (15) The outer query is not part of a compound select or the
117653 ** subquery does not have a LIMIT clause.
117654 ** (See ticket #2339 and ticket [02a8e81d44]).
117655 **
117656 ** (16) The outer query is not an aggregate or the subquery does
117657 ** not contain ORDER BY. (Ticket #2942) This used to not matter
117658 ** until we introduced the group_concat() function.
117659 **
117660 ** (17) The sub-query is not a compound select, or it is a UNION ALL
117661 ** compound clause made up entirely of non-aggregate queries, and
117662 ** the parent query:
117663 **
117664 ** * is not itself part of a compound select,
117665 ** * is not an aggregate or DISTINCT query, and
117666 ** * is not a join
117667 **
117668 ** The parent and sub-query may contain WHERE clauses. Subject to
117669 ** rules (11), (13) and (14), they may also contain ORDER BY,
117670 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
117671 ** operator other than UNION ALL because all the other compound
117672 ** operators have an implied DISTINCT which is disallowed by
117673 ** restriction (4).
117674 **
117675 ** Also, each component of the sub-query must return the same number
117676 ** of result columns. This is actually a requirement for any compound
117677 ** SELECT statement, but all the code here does is make sure that no
117678 ** such (illegal) sub-query is flattened. The caller will detect the
117679 ** syntax error and return a detailed message.
117680 **
117681 ** (18) If the sub-query is a compound select, then all terms of the
117682 ** ORDER by clause of the parent must be simple references to
117683 ** columns of the sub-query.
117684 **
117685 ** (19) The subquery does not use LIMIT or the outer query does not
117686 ** have a WHERE clause.
117687 **
117688 ** (20) If the sub-query is a compound select, then it must not use
117689 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
117690 ** somewhat by saying that the terms of the ORDER BY clause must
117691 ** appear as unmodified result columns in the outer query. But we
117692 ** have other optimizations in mind to deal with that case.
117693 **
117694 ** (21) The subquery does not use LIMIT or the outer query is not
117695 ** DISTINCT. (See ticket [752e1646fc]).
117696 **
117697 ** (22) The subquery is not a recursive CTE.
117698 **
117699 ** (23) The parent is not a recursive CTE, or the sub-query is not a
117700 ** compound query. This restriction is because transforming the
117701 ** parent to a compound query confuses the code that handles
117702 ** recursive queries in multiSelect().
117703 **
117704 ** (24) The subquery is not an aggregate that uses the built-in min() or
117705 ** or max() functions. (Without this restriction, a query like:
117706 ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
117707 ** return the value X for which Y was maximal.)
117708 **
117709 **
117710 ** In this routine, the "p" parameter is a pointer to the outer query.
117711 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
117712 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
117713 **
117714 ** If flattening is not attempted, this routine is a no-op and returns 0.
117715 ** If flattening is attempted this routine returns 1.
117716 **
117717 ** All of the expression analysis must occur on both the outer query and
117718 ** the subquery before this routine runs.
117719 */
117720 static int flattenSubquery(
117721  Parse *pParse, /* Parsing context */
117722  Select *p, /* The parent or outer SELECT statement */
117723  int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
117724  int isAgg, /* True if outer SELECT uses aggregate functions */
117725  int subqueryIsAgg /* True if the subquery uses aggregate functions */
117726 ){
117727  const char *zSavedAuthContext = pParse->zAuthContext;
117728  Select *pParent; /* Current UNION ALL term of the other query */
117729  Select *pSub; /* The inner query or "subquery" */
117730  Select *pSub1; /* Pointer to the rightmost select in sub-query */
117731  SrcList *pSrc; /* The FROM clause of the outer query */
117732  SrcList *pSubSrc; /* The FROM clause of the subquery */
117733  ExprList *pList; /* The result set of the outer query */
117734  int iParent; /* VDBE cursor number of the pSub result set temp table */
117735  int i; /* Loop counter */
117736  Expr *pWhere; /* The WHERE clause */
117737  struct SrcList_item *pSubitem; /* The subquery */
117738  sqlite3 *db = pParse->db;
117739 
117740  /* Check to see if flattening is permitted. Return 0 if not.
117741  */
117742  assert( p!=0 );
117743  assert( p->pPrior==0 ); /* Unable to flatten compound queries */
117744  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
117745  pSrc = p->pSrc;
117746  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
117747  pSubitem = &pSrc->a[iFrom];
117748  iParent = pSubitem->iCursor;
117749  pSub = pSubitem->pSelect;
117750  assert( pSub!=0 );
117751  if( subqueryIsAgg ){
117752  if( isAgg ) return 0; /* Restriction (1) */
117753  if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
117754  if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
117755  || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
117756  || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
117757  ){
117758  return 0; /* Restriction (2b) */
117759  }
117760  }
117761 
117762  pSubSrc = pSub->pSrc;
117763  assert( pSubSrc );
117764  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
117765  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
117766  ** because they could be computed at compile-time. But when LIMIT and OFFSET
117767  ** became arbitrary expressions, we were forced to add restrictions (13)
117768  ** and (14). */
117769  if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
117770  if( pSub->pOffset ) return 0; /* Restriction (14) */
117771  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
117772  return 0; /* Restriction (15) */
117773  }
117774  if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
117775  if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
117776  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
117777  return 0; /* Restrictions (8)(9) */
117778  }
117779  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
117780  return 0; /* Restriction (6) */
117781  }
117782  if( p->pOrderBy && pSub->pOrderBy ){
117783  return 0; /* Restriction (11) */
117784  }
117785  if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
117786  if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
117787  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
117788  return 0; /* Restriction (21) */
117789  }
117790  testcase( pSub->selFlags & SF_Recursive );
117791  testcase( pSub->selFlags & SF_MinMaxAgg );
117792  if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
117793  return 0; /* Restrictions (22) and (24) */
117794  }
117795  if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
117796  return 0; /* Restriction (23) */
117797  }
117798 
117799  /* OBSOLETE COMMENT 1:
117800  ** Restriction 3: If the subquery is a join, make sure the subquery is
117801  ** not used as the right operand of an outer join. Examples of why this
117802  ** is not allowed:
117803  **
117804  ** t1 LEFT OUTER JOIN (t2 JOIN t3)
117805  **
117806  ** If we flatten the above, we would get
117807  **
117808  ** (t1 LEFT OUTER JOIN t2) JOIN t3
117809  **
117810  ** which is not at all the same thing.
117811  **
117812  ** OBSOLETE COMMENT 2:
117813  ** Restriction 12: If the subquery is the right operand of a left outer
117814  ** join, make sure the subquery has no WHERE clause.
117815  ** An examples of why this is not allowed:
117816  **
117817  ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
117818  **
117819  ** If we flatten the above, we would get
117820  **
117821  ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
117822  **
117823  ** But the t2.x>0 test will always fail on a NULL row of t2, which
117824  ** effectively converts the OUTER JOIN into an INNER JOIN.
117825  **
117826  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
117827  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
117828  ** is fraught with danger. Best to avoid the whole thing. If the
117829  ** subquery is the right term of a LEFT JOIN, then do not flatten.
117830  */
117831  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
117832  return 0;
117833  }
117834 
117835  /* Restriction 17: If the sub-query is a compound SELECT, then it must
117836  ** use only the UNION ALL operator. And none of the simple select queries
117837  ** that make up the compound SELECT are allowed to be aggregate or distinct
117838  ** queries.
117839  */
117840  if( pSub->pPrior ){
117841  if( pSub->pOrderBy ){
117842  return 0; /* Restriction 20 */
117843  }
117844  if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
117845  return 0;
117846  }
117847  for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
117848  testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
117849  testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
117850  assert( pSub->pSrc!=0 );
117851  assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
117852  if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
117853  || (pSub1->pPrior && pSub1->op!=TK_ALL)
117854  || pSub1->pSrc->nSrc<1
117855  ){
117856  return 0;
117857  }
117858  testcase( pSub1->pSrc->nSrc>1 );
117859  }
117860 
117861  /* Restriction 18. */
117862  if( p->pOrderBy ){
117863  int ii;
117864  for(ii=0; ii<p->pOrderBy->nExpr; ii++){
117865  if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
117866  }
117867  }
117868  }
117869 
117870  /***** If we reach this point, flattening is permitted. *****/
117871  SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
117872  pSub->zSelName, pSub, iFrom));
117873 
117874  /* Authorize the subquery */
117875  pParse->zAuthContext = pSubitem->zName;
117876  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
117877  testcase( i==SQLITE_DENY );
117878  pParse->zAuthContext = zSavedAuthContext;
117879 
117880  /* If the sub-query is a compound SELECT statement, then (by restrictions
117881  ** 17 and 18 above) it must be a UNION ALL and the parent query must
117882  ** be of the form:
117883  **
117884  ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
117885  **
117886  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
117887  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
117888  ** OFFSET clauses and joins them to the left-hand-side of the original
117889  ** using UNION ALL operators. In this case N is the number of simple
117890  ** select statements in the compound sub-query.
117891  **
117892  ** Example:
117893  **
117894  ** SELECT a+1 FROM (
117895  ** SELECT x FROM tab
117896  ** UNION ALL
117897  ** SELECT y FROM tab
117898  ** UNION ALL
117899  ** SELECT abs(z*2) FROM tab2
117900  ** ) WHERE a!=5 ORDER BY 1
117901  **
117902  ** Transformed into:
117903  **
117904  ** SELECT x+1 FROM tab WHERE x+1!=5
117905  ** UNION ALL
117906  ** SELECT y+1 FROM tab WHERE y+1!=5
117907  ** UNION ALL
117908  ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
117909  ** ORDER BY 1
117910  **
117911  ** We call this the "compound-subquery flattening".
117912  */
117913  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
117914  Select *pNew;
117915  ExprList *pOrderBy = p->pOrderBy;
117916  Expr *pLimit = p->pLimit;
117917  Expr *pOffset = p->pOffset;
117918  Select *pPrior = p->pPrior;
117919  p->pOrderBy = 0;
117920  p->pSrc = 0;
117921  p->pPrior = 0;
117922  p->pLimit = 0;
117923  p->pOffset = 0;
117924  pNew = sqlite3SelectDup(db, p, 0);
117925  sqlite3SelectSetName(pNew, pSub->zSelName);
117926  p->pOffset = pOffset;
117927  p->pLimit = pLimit;
117928  p->pOrderBy = pOrderBy;
117929  p->pSrc = pSrc;
117930  p->op = TK_ALL;
117931  if( pNew==0 ){
117932  p->pPrior = pPrior;
117933  }else{
117934  pNew->pPrior = pPrior;
117935  if( pPrior ) pPrior->pNext = pNew;
117936  pNew->pNext = p;
117937  p->pPrior = pNew;
117938  SELECTTRACE(2,pParse,p,
117939  ("compound-subquery flattener creates %s.%p as peer\n",
117940  pNew->zSelName, pNew));
117941  }
117942  if( db->mallocFailed ) return 1;
117943  }
117944 
117945  /* Begin flattening the iFrom-th entry of the FROM clause
117946  ** in the outer query.
117947  */
117948  pSub = pSub1 = pSubitem->pSelect;
117949 
117950  /* Delete the transient table structure associated with the
117951  ** subquery
117952  */
117953  sqlite3DbFree(db, pSubitem->zDatabase);
117954  sqlite3DbFree(db, pSubitem->zName);
117955  sqlite3DbFree(db, pSubitem->zAlias);
117956  pSubitem->zDatabase = 0;
117957  pSubitem->zName = 0;
117958  pSubitem->zAlias = 0;
117959  pSubitem->pSelect = 0;
117960 
117961  /* Defer deleting the Table object associated with the
117962  ** subquery until code generation is
117963  ** complete, since there may still exist Expr.pTab entries that
117964  ** refer to the subquery even after flattening. Ticket #3346.
117965  **
117966  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
117967  */
117968  if( ALWAYS(pSubitem->pTab!=0) ){
117969  Table *pTabToDel = pSubitem->pTab;
117970  if( pTabToDel->nRef==1 ){
117971  Parse *pToplevel = sqlite3ParseToplevel(pParse);
117972  pTabToDel->pNextZombie = pToplevel->pZombieTab;
117973  pToplevel->pZombieTab = pTabToDel;
117974  }else{
117975  pTabToDel->nRef--;
117976  }
117977  pSubitem->pTab = 0;
117978  }
117979 
117980  /* The following loop runs once for each term in a compound-subquery
117981  ** flattening (as described above). If we are doing a different kind
117982  ** of flattening - a flattening other than a compound-subquery flattening -
117983  ** then this loop only runs once.
117984  **
117985  ** This loop moves all of the FROM elements of the subquery into the
117986  ** the FROM clause of the outer query. Before doing this, remember
117987  ** the cursor number for the original outer query FROM element in
117988  ** iParent. The iParent cursor will never be used. Subsequent code
117989  ** will scan expressions looking for iParent references and replace
117990  ** those references with expressions that resolve to the subquery FROM
117991  ** elements we are now copying in.
117992  */
117993  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
117994  int nSubSrc;
117995  u8 jointype = 0;
117996  pSubSrc = pSub->pSrc; /* FROM clause of subquery */
117997  nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
117998  pSrc = pParent->pSrc; /* FROM clause of the outer query */
117999 
118000  if( pSrc ){
118001  assert( pParent==p ); /* First time through the loop */
118002  jointype = pSubitem->fg.jointype;
118003  }else{
118004  assert( pParent!=p ); /* 2nd and subsequent times through the loop */
118005  pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
118006  if( pSrc==0 ){
118007  assert( db->mallocFailed );
118008  break;
118009  }
118010  }
118011 
118012  /* The subquery uses a single slot of the FROM clause of the outer
118013  ** query. If the subquery has more than one element in its FROM clause,
118014  ** then expand the outer query to make space for it to hold all elements
118015  ** of the subquery.
118016  **
118017  ** Example:
118018  **
118019  ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
118020  **
118021  ** The outer query has 3 slots in its FROM clause. One slot of the
118022  ** outer query (the middle slot) is used by the subquery. The next
118023  ** block of code will expand the outer query FROM clause to 4 slots.
118024  ** The middle slot is expanded to two slots in order to make space
118025  ** for the two elements in the FROM clause of the subquery.
118026  */
118027  if( nSubSrc>1 ){
118028  pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
118029  if( db->mallocFailed ){
118030  break;
118031  }
118032  }
118033 
118034  /* Transfer the FROM clause terms from the subquery into the
118035  ** outer query.
118036  */
118037  for(i=0; i<nSubSrc; i++){
118038  sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
118039  assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
118040  pSrc->a[i+iFrom] = pSubSrc->a[i];
118041  memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
118042  }
118043  pSrc->a[iFrom].fg.jointype = jointype;
118044 
118045  /* Now begin substituting subquery result set expressions for
118046  ** references to the iParent in the outer query.
118047  **
118048  ** Example:
118049  **
118050  ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
118051  ** \ \_____________ subquery __________/ /
118052  ** \_____________________ outer query ______________________________/
118053  **
118054  ** We look at every expression in the outer query and every place we see
118055  ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
118056  */
118057  pList = pParent->pEList;
118058  for(i=0; i<pList->nExpr; i++){
118059  if( pList->a[i].zName==0 ){
118060  char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
118061  sqlite3Dequote(zName);
118062  pList->a[i].zName = zName;
118063  }
118064  }
118065  if( pSub->pOrderBy ){
118066  /* At this point, any non-zero iOrderByCol values indicate that the
118067  ** ORDER BY column expression is identical to the iOrderByCol'th
118068  ** expression returned by SELECT statement pSub. Since these values
118069  ** do not necessarily correspond to columns in SELECT statement pParent,
118070  ** zero them before transfering the ORDER BY clause.
118071  **
118072  ** Not doing this may cause an error if a subsequent call to this
118073  ** function attempts to flatten a compound sub-query into pParent
118074  ** (the only way this can happen is if the compound sub-query is
118075  ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
118076  ExprList *pOrderBy = pSub->pOrderBy;
118077  for(i=0; i<pOrderBy->nExpr; i++){
118078  pOrderBy->a[i].u.x.iOrderByCol = 0;
118079  }
118080  assert( pParent->pOrderBy==0 );
118081  assert( pSub->pPrior==0 );
118082  pParent->pOrderBy = pOrderBy;
118083  pSub->pOrderBy = 0;
118084  }
118085  pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
118086  if( subqueryIsAgg ){
118087  assert( pParent->pHaving==0 );
118088  pParent->pHaving = pParent->pWhere;
118089  pParent->pWhere = pWhere;
118090  pParent->pHaving = sqlite3ExprAnd(db,
118091  sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving
118092  );
118093  assert( pParent->pGroupBy==0 );
118094  pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
118095  }else{
118096  pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
118097  }
118098  substSelect(db, pParent, iParent, pSub->pEList, 0);
118099 
118100  /* The flattened query is distinct if either the inner or the
118101  ** outer query is distinct.
118102  */
118103  pParent->selFlags |= pSub->selFlags & SF_Distinct;
118104 
118105  /*
118106  ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
118107  **
118108  ** One is tempted to try to add a and b to combine the limits. But this
118109  ** does not work if either limit is negative.
118110  */
118111  if( pSub->pLimit ){
118112  pParent->pLimit = pSub->pLimit;
118113  pSub->pLimit = 0;
118114  }
118115  }
118116 
118117  /* Finially, delete what is left of the subquery and return
118118  ** success.
118119  */
118120  sqlite3SelectDelete(db, pSub1);
118121 
118122 #if SELECTTRACE_ENABLED
118123  if( sqlite3SelectTrace & 0x100 ){
118124  SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
118125  sqlite3TreeViewSelect(0, p, 0);
118126  }
118127 #endif
118128 
118129  return 1;
118130 }
118131 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
118132 
118133 
118134 
118135 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
118136 /*
118137 ** Make copies of relevant WHERE clause terms of the outer query into
118138 ** the WHERE clause of subquery. Example:
118139 **
118140 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
118141 **
118142 ** Transformed into:
118143 **
118144 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
118145 ** WHERE x=5 AND y=10;
118146 **
118147 ** The hope is that the terms added to the inner query will make it more
118148 ** efficient.
118149 **
118150 ** Do not attempt this optimization if:
118151 **
118152 ** (1) The inner query is an aggregate. (In that case, we'd really want
118153 ** to copy the outer WHERE-clause terms onto the HAVING clause of the
118154 ** inner query. But they probably won't help there so do not bother.)
118155 **
118156 ** (2) The inner query is the recursive part of a common table expression.
118157 **
118158 ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
118159 ** close would change the meaning of the LIMIT).
118160 **
118161 ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
118162 ** enforces this restriction since this routine does not have enough
118163 ** information to know.)
118164 **
118165 ** (5) The WHERE clause expression originates in the ON or USING clause
118166 ** of a LEFT JOIN.
118167 **
118168 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
118169 ** terms are duplicated into the subquery.
118170 */
118171 static int pushDownWhereTerms(
118172  sqlite3 *db, /* The database connection (for malloc()) */
118173  Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
118174  Expr *pWhere, /* The WHERE clause of the outer query */
118175  int iCursor /* Cursor number of the subquery */
118176 ){
118177  Expr *pNew;
118178  int nChng = 0;
118179  Select *pX; /* For looping over compound SELECTs in pSubq */
118180  if( pWhere==0 ) return 0;
118181  for(pX=pSubq; pX; pX=pX->pPrior){
118182  if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
118183  testcase( pX->selFlags & SF_Aggregate );
118184  testcase( pX->selFlags & SF_Recursive );
118185  testcase( pX!=pSubq );
118186  return 0; /* restrictions (1) and (2) */
118187  }
118188  }
118189  if( pSubq->pLimit!=0 ){
118190  return 0; /* restriction (3) */
118191  }
118192  while( pWhere->op==TK_AND ){
118193  nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
118194  pWhere = pWhere->pLeft;
118195  }
118196  if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
118197  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
118198  nChng++;
118199  while( pSubq ){
118200  pNew = sqlite3ExprDup(db, pWhere, 0);
118201  pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
118202  pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
118203  pSubq = pSubq->pPrior;
118204  }
118205  }
118206  return nChng;
118207 }
118208 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
118209 
118210 /*
118211 ** Based on the contents of the AggInfo structure indicated by the first
118212 ** argument, this function checks if the following are true:
118213 **
118214 ** * the query contains just a single aggregate function,
118215 ** * the aggregate function is either min() or max(), and
118216 ** * the argument to the aggregate function is a column value.
118217 **
118218 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
118219 ** is returned as appropriate. Also, *ppMinMax is set to point to the
118220 ** list of arguments passed to the aggregate before returning.
118221 **
118222 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
118223 ** WHERE_ORDERBY_NORMAL is returned.
118224 */
118225 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
118226  int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
118227 
118228  *ppMinMax = 0;
118229  if( pAggInfo->nFunc==1 ){
118230  Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
118231  ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
118232 
118233  assert( pExpr->op==TK_AGG_FUNCTION );
118234  if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
118235  const char *zFunc = pExpr->u.zToken;
118236  if( sqlite3StrICmp(zFunc, "min")==0 ){
118237  eRet = WHERE_ORDERBY_MIN;
118238  *ppMinMax = pEList;
118239  }else if( sqlite3StrICmp(zFunc, "max")==0 ){
118240  eRet = WHERE_ORDERBY_MAX;
118241  *ppMinMax = pEList;
118242  }
118243  }
118244  }
118245 
118246  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
118247  return eRet;
118248 }
118249 
118250 /*
118251 ** The select statement passed as the first argument is an aggregate query.
118252 ** The second argument is the associated aggregate-info object. This
118253 ** function tests if the SELECT is of the form:
118254 **
118255 ** SELECT count(*) FROM <tbl>
118256 **
118257 ** where table is a database table, not a sub-select or view. If the query
118258 ** does match this pattern, then a pointer to the Table object representing
118259 ** <tbl> is returned. Otherwise, 0 is returned.
118260 */
118261 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
118262  Table *pTab;
118263  Expr *pExpr;
118264 
118265  assert( !p->pGroupBy );
118266 
118267  if( p->pWhere || p->pEList->nExpr!=1
118268  || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
118269  ){
118270  return 0;
118271  }
118272  pTab = p->pSrc->a[0].pTab;
118273  pExpr = p->pEList->a[0].pExpr;
118274  assert( pTab && !pTab->pSelect && pExpr );
118275 
118276  if( IsVirtual(pTab) ) return 0;
118277  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
118278  if( NEVER(pAggInfo->nFunc==0) ) return 0;
118279  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
118280  if( pExpr->flags&EP_Distinct ) return 0;
118281 
118282  return pTab;
118283 }
118284 
118285 /*
118286 ** If the source-list item passed as an argument was augmented with an
118287 ** INDEXED BY clause, then try to locate the specified index. If there
118288 ** was such a clause and the named index cannot be found, return
118289 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
118290 ** pFrom->pIndex and return SQLITE_OK.
118291 */
118292 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
118293  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
118294  Table *pTab = pFrom->pTab;
118295  char *zIndexedBy = pFrom->u1.zIndexedBy;
118296  Index *pIdx;
118297  for(pIdx=pTab->pIndex;
118298  pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
118299  pIdx=pIdx->pNext
118300  );
118301  if( !pIdx ){
118302  sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
118303  pParse->checkSchema = 1;
118304  return SQLITE_ERROR;
118305  }
118306  pFrom->pIBIndex = pIdx;
118307  }
118308  return SQLITE_OK;
118309 }
118310 /*
118311 ** Detect compound SELECT statements that use an ORDER BY clause with
118312 ** an alternative collating sequence.
118313 **
118314 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
118315 **
118316 ** These are rewritten as a subquery:
118317 **
118318 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
118319 ** ORDER BY ... COLLATE ...
118320 **
118321 ** This transformation is necessary because the multiSelectOrderBy() routine
118322 ** above that generates the code for a compound SELECT with an ORDER BY clause
118323 ** uses a merge algorithm that requires the same collating sequence on the
118324 ** result columns as on the ORDER BY clause. See ticket
118325 ** http://www.sqlite.org/src/info/6709574d2a
118326 **
118327 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
118328 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
118329 ** there are COLLATE terms in the ORDER BY.
118330 */
118331 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
118332  int i;
118333  Select *pNew;
118334  Select *pX;
118335  sqlite3 *db;
118336  struct ExprList_item *a;
118337  SrcList *pNewSrc;
118338  Parse *pParse;
118339  Token dummy;
118340 
118341  if( p->pPrior==0 ) return WRC_Continue;
118342  if( p->pOrderBy==0 ) return WRC_Continue;
118343  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
118344  if( pX==0 ) return WRC_Continue;
118345  a = p->pOrderBy->a;
118346  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
118347  if( a[i].pExpr->flags & EP_Collate ) break;
118348  }
118349  if( i<0 ) return WRC_Continue;
118350 
118351  /* If we reach this point, that means the transformation is required. */
118352 
118353  pParse = pWalker->pParse;
118354  db = pParse->db;
118355  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
118356  if( pNew==0 ) return WRC_Abort;
118357  memset(&dummy, 0, sizeof(dummy));
118358  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
118359  if( pNewSrc==0 ) return WRC_Abort;
118360  *pNew = *p;
118361  p->pSrc = pNewSrc;
118362  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
118363  p->op = TK_SELECT;
118364  p->pWhere = 0;
118365  pNew->pGroupBy = 0;
118366  pNew->pHaving = 0;
118367  pNew->pOrderBy = 0;
118368  p->pPrior = 0;
118369  p->pNext = 0;
118370  p->pWith = 0;
118371  p->selFlags &= ~SF_Compound;
118372  assert( (p->selFlags & SF_Converted)==0 );
118373  p->selFlags |= SF_Converted;
118374  assert( pNew->pPrior!=0 );
118375  pNew->pPrior->pNext = pNew;
118376  pNew->pLimit = 0;
118377  pNew->pOffset = 0;
118378  return WRC_Continue;
118379 }
118380 
118381 /*
118382 ** Check to see if the FROM clause term pFrom has table-valued function
118383 ** arguments. If it does, leave an error message in pParse and return
118384 ** non-zero, since pFrom is not allowed to be a table-valued function.
118385 */
118386 static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
118387  if( pFrom->fg.isTabFunc ){
118388  sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
118389  return 1;
118390  }
118391  return 0;
118392 }
118393 
118394 #ifndef SQLITE_OMIT_CTE
118395 /*
118396 ** Argument pWith (which may be NULL) points to a linked list of nested
118397 ** WITH contexts, from inner to outermost. If the table identified by
118398 ** FROM clause element pItem is really a common-table-expression (CTE)
118399 ** then return a pointer to the CTE definition for that table. Otherwise
118400 ** return NULL.
118401 **
118402 ** If a non-NULL value is returned, set *ppContext to point to the With
118403 ** object that the returned CTE belongs to.
118404 */
118405 static struct Cte *searchWith(
118406  With *pWith, /* Current innermost WITH clause */
118407  struct SrcList_item *pItem, /* FROM clause element to resolve */
118408  With **ppContext /* OUT: WITH clause return value belongs to */
118409 ){
118410  const char *zName;
118411  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
118412  With *p;
118413  for(p=pWith; p; p=p->pOuter){
118414  int i;
118415  for(i=0; i<p->nCte; i++){
118416  if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
118417  *ppContext = p;
118418  return &p->a[i];
118419  }
118420  }
118421  }
118422  }
118423  return 0;
118424 }
118425 
118426 /* The code generator maintains a stack of active WITH clauses
118427 ** with the inner-most WITH clause being at the top of the stack.
118428 **
118429 ** This routine pushes the WITH clause passed as the second argument
118430 ** onto the top of the stack. If argument bFree is true, then this
118431 ** WITH clause will never be popped from the stack. In this case it
118432 ** should be freed along with the Parse object. In other cases, when
118433 ** bFree==0, the With object will be freed along with the SELECT
118434 ** statement with which it is associated.
118435 */
118436 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
118437  assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
118438  if( pWith ){
118439  assert( pParse->pWith!=pWith );
118440  pWith->pOuter = pParse->pWith;
118441  pParse->pWith = pWith;
118442  if( bFree ) pParse->pWithToFree = pWith;
118443  }
118444 }
118445 
118446 /*
118447 ** This function checks if argument pFrom refers to a CTE declared by
118448 ** a WITH clause on the stack currently maintained by the parser. And,
118449 ** if currently processing a CTE expression, if it is a recursive
118450 ** reference to the current CTE.
118451 **
118452 ** If pFrom falls into either of the two categories above, pFrom->pTab
118453 ** and other fields are populated accordingly. The caller should check
118454 ** (pFrom->pTab!=0) to determine whether or not a successful match
118455 ** was found.
118456 **
118457 ** Whether or not a match is found, SQLITE_OK is returned if no error
118458 ** occurs. If an error does occur, an error message is stored in the
118459 ** parser and some error code other than SQLITE_OK returned.
118460 */
118461 static int withExpand(
118462  Walker *pWalker,
118463  struct SrcList_item *pFrom
118464 ){
118465  Parse *pParse = pWalker->pParse;
118466  sqlite3 *db = pParse->db;
118467  struct Cte *pCte; /* Matched CTE (or NULL if no match) */
118468  With *pWith; /* WITH clause that pCte belongs to */
118469 
118470  assert( pFrom->pTab==0 );
118471 
118472  pCte = searchWith(pParse->pWith, pFrom, &pWith);
118473  if( pCte ){
118474  Table *pTab;
118475  ExprList *pEList;
118476  Select *pSel;
118477  Select *pLeft; /* Left-most SELECT statement */
118478  int bMayRecursive; /* True if compound joined by UNION [ALL] */
118479  With *pSavedWith; /* Initial value of pParse->pWith */
118480 
118481  /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
118482  ** recursive reference to CTE pCte. Leave an error in pParse and return
118483  ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
118484  ** In this case, proceed. */
118485  if( pCte->zCteErr ){
118486  sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
118487  return SQLITE_ERROR;
118488  }
118489  if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
118490 
118491  assert( pFrom->pTab==0 );
118492  pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
118493  if( pTab==0 ) return WRC_Abort;
118494  pTab->nRef = 1;
118495  pTab->zName = sqlite3DbStrDup(db, pCte->zName);
118496  pTab->iPKey = -1;
118497  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
118498  pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
118499  pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
118500  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
118501  assert( pFrom->pSelect );
118502 
118503  /* Check if this is a recursive CTE. */
118504  pSel = pFrom->pSelect;
118505  bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
118506  if( bMayRecursive ){
118507  int i;
118508  SrcList *pSrc = pFrom->pSelect->pSrc;
118509  for(i=0; i<pSrc->nSrc; i++){
118510  struct SrcList_item *pItem = &pSrc->a[i];
118511  if( pItem->zDatabase==0
118512  && pItem->zName!=0
118513  && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
118514  ){
118515  pItem->pTab = pTab;
118516  pItem->fg.isRecursive = 1;
118517  pTab->nRef++;
118518  pSel->selFlags |= SF_Recursive;
118519  }
118520  }
118521  }
118522 
118523  /* Only one recursive reference is permitted. */
118524  if( pTab->nRef>2 ){
118525  sqlite3ErrorMsg(
118526  pParse, "multiple references to recursive table: %s", pCte->zName
118527  );
118528  return SQLITE_ERROR;
118529  }
118530  assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
118531 
118532  pCte->zCteErr = "circular reference: %s";
118533  pSavedWith = pParse->pWith;
118534  pParse->pWith = pWith;
118535  sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
118536  pParse->pWith = pWith;
118537 
118538  for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
118539  pEList = pLeft->pEList;
118540  if( pCte->pCols ){
118541  if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
118542  sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
118543  pCte->zName, pEList->nExpr, pCte->pCols->nExpr
118544  );
118545  pParse->pWith = pSavedWith;
118546  return SQLITE_ERROR;
118547  }
118548  pEList = pCte->pCols;
118549  }
118550 
118551  sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
118552  if( bMayRecursive ){
118553  if( pSel->selFlags & SF_Recursive ){
118554  pCte->zCteErr = "multiple recursive references: %s";
118555  }else{
118556  pCte->zCteErr = "recursive reference in a subquery: %s";
118557  }
118558  sqlite3WalkSelect(pWalker, pSel);
118559  }
118560  pCte->zCteErr = 0;
118561  pParse->pWith = pSavedWith;
118562  }
118563 
118564  return SQLITE_OK;
118565 }
118566 #endif
118567 
118568 #ifndef SQLITE_OMIT_CTE
118569 /*
118570 ** If the SELECT passed as the second argument has an associated WITH
118571 ** clause, pop it from the stack stored as part of the Parse object.
118572 **
118573 ** This function is used as the xSelectCallback2() callback by
118574 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
118575 ** names and other FROM clause elements.
118576 */
118577 static void selectPopWith(Walker *pWalker, Select *p){
118578  Parse *pParse = pWalker->pParse;
118579  With *pWith = findRightmost(p)->pWith;
118580  if( pWith!=0 ){
118581  assert( pParse->pWith==pWith );
118582  pParse->pWith = pWith->pOuter;
118583  }
118584 }
118585 #else
118586 #define selectPopWith 0
118587 #endif
118588 
118589 /*
118590 ** This routine is a Walker callback for "expanding" a SELECT statement.
118591 ** "Expanding" means to do the following:
118592 **
118593 ** (1) Make sure VDBE cursor numbers have been assigned to every
118594 ** element of the FROM clause.
118595 **
118596 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
118597 ** defines FROM clause. When views appear in the FROM clause,
118598 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
118599 ** that implements the view. A copy is made of the view's SELECT
118600 ** statement so that we can freely modify or delete that statement
118601 ** without worrying about messing up the persistent representation
118602 ** of the view.
118603 **
118604 ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
118605 ** on joins and the ON and USING clause of joins.
118606 **
118607 ** (4) Scan the list of columns in the result set (pEList) looking
118608 ** for instances of the "*" operator or the TABLE.* operator.
118609 ** If found, expand each "*" to be every column in every table
118610 ** and TABLE.* to be every column in TABLE.
118611 **
118612 */
118613 static int selectExpander(Walker *pWalker, Select *p){
118614  Parse *pParse = pWalker->pParse;
118615  int i, j, k;
118616  SrcList *pTabList;
118617  ExprList *pEList;
118618  struct SrcList_item *pFrom;
118619  sqlite3 *db = pParse->db;
118620  Expr *pE, *pRight, *pExpr;
118621  u16 selFlags = p->selFlags;
118622 
118623  p->selFlags |= SF_Expanded;
118624  if( db->mallocFailed ){
118625  return WRC_Abort;
118626  }
118627  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
118628  return WRC_Prune;
118629  }
118630  pTabList = p->pSrc;
118631  pEList = p->pEList;
118632  if( pWalker->xSelectCallback2==selectPopWith ){
118633  sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
118634  }
118635 
118636  /* Make sure cursor numbers have been assigned to all entries in
118637  ** the FROM clause of the SELECT statement.
118638  */
118639  sqlite3SrcListAssignCursors(pParse, pTabList);
118640 
118641  /* Look up every table named in the FROM clause of the select. If
118642  ** an entry of the FROM clause is a subquery instead of a table or view,
118643  ** then create a transient table structure to describe the subquery.
118644  */
118645  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
118646  Table *pTab;
118647  assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
118648  if( pFrom->fg.isRecursive ) continue;
118649  assert( pFrom->pTab==0 );
118650 #ifndef SQLITE_OMIT_CTE
118651  if( withExpand(pWalker, pFrom) ) return WRC_Abort;
118652  if( pFrom->pTab ) {} else
118653 #endif
118654  if( pFrom->zName==0 ){
118655 #ifndef SQLITE_OMIT_SUBQUERY
118656  Select *pSel = pFrom->pSelect;
118657  /* A sub-query in the FROM clause of a SELECT */
118658  assert( pSel!=0 );
118659  assert( pFrom->pTab==0 );
118660  if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
118661  pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
118662  if( pTab==0 ) return WRC_Abort;
118663  pTab->nRef = 1;
118664  pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
118665  while( pSel->pPrior ){ pSel = pSel->pPrior; }
118666  sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
118667  pTab->iPKey = -1;
118668  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
118669  pTab->tabFlags |= TF_Ephemeral;
118670 #endif
118671  }else{
118672  /* An ordinary table or view name in the FROM clause */
118673  assert( pFrom->pTab==0 );
118674  pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
118675  if( pTab==0 ) return WRC_Abort;
118676  if( pTab->nRef==0xffff ){
118677  sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
118678  pTab->zName);
118679  pFrom->pTab = 0;
118680  return WRC_Abort;
118681  }
118682  pTab->nRef++;
118683  if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
118684  return WRC_Abort;
118685  }
118686 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
118687  if( IsVirtual(pTab) || pTab->pSelect ){
118688  i16 nCol;
118689  if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
118690  assert( pFrom->pSelect==0 );
118691  pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
118692  sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
118693  nCol = pTab->nCol;
118694  pTab->nCol = -1;
118695  sqlite3WalkSelect(pWalker, pFrom->pSelect);
118696  pTab->nCol = nCol;
118697  }
118698 #endif
118699  }
118700 
118701  /* Locate the index named by the INDEXED BY clause, if any. */
118702  if( sqlite3IndexedByLookup(pParse, pFrom) ){
118703  return WRC_Abort;
118704  }
118705  }
118706 
118707  /* Process NATURAL keywords, and ON and USING clauses of joins.
118708  */
118709  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
118710  return WRC_Abort;
118711  }
118712 
118713  /* For every "*" that occurs in the column list, insert the names of
118714  ** all columns in all tables. And for every TABLE.* insert the names
118715  ** of all columns in TABLE. The parser inserted a special expression
118716  ** with the TK_ASTERISK operator for each "*" that it found in the column
118717  ** list. The following code just has to locate the TK_ASTERISK
118718  ** expressions and expand each one to the list of all columns in
118719  ** all tables.
118720  **
118721  ** The first loop just checks to see if there are any "*" operators
118722  ** that need expanding.
118723  */
118724  for(k=0; k<pEList->nExpr; k++){
118725  pE = pEList->a[k].pExpr;
118726  if( pE->op==TK_ASTERISK ) break;
118727  assert( pE->op!=TK_DOT || pE->pRight!=0 );
118728  assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
118729  if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
118730  }
118731  if( k<pEList->nExpr ){
118732  /*
118733  ** If we get here it means the result set contains one or more "*"
118734  ** operators that need to be expanded. Loop through each expression
118735  ** in the result set and expand them one by one.
118736  */
118737  struct ExprList_item *a = pEList->a;
118738  ExprList *pNew = 0;
118739  int flags = pParse->db->flags;
118740  int longNames = (flags & SQLITE_FullColNames)!=0
118741  && (flags & SQLITE_ShortColNames)==0;
118742 
118743  for(k=0; k<pEList->nExpr; k++){
118744  pE = a[k].pExpr;
118745  pRight = pE->pRight;
118746  assert( pE->op!=TK_DOT || pRight!=0 );
118747  if( pE->op!=TK_ASTERISK
118748  && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
118749  ){
118750  /* This particular expression does not need to be expanded.
118751  */
118752  pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
118753  if( pNew ){
118754  pNew->a[pNew->nExpr-1].zName = a[k].zName;
118755  pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
118756  a[k].zName = 0;
118757  a[k].zSpan = 0;
118758  }
118759  a[k].pExpr = 0;
118760  }else{
118761  /* This expression is a "*" or a "TABLE.*" and needs to be
118762  ** expanded. */
118763  int tableSeen = 0; /* Set to 1 when TABLE matches */
118764  char *zTName = 0; /* text of name of TABLE */
118765  if( pE->op==TK_DOT ){
118766  assert( pE->pLeft!=0 );
118767  assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
118768  zTName = pE->pLeft->u.zToken;
118769  }
118770  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
118771  Table *pTab = pFrom->pTab;
118772  Select *pSub = pFrom->pSelect;
118773  char *zTabName = pFrom->zAlias;
118774  const char *zSchemaName = 0;
118775  int iDb;
118776  if( zTabName==0 ){
118777  zTabName = pTab->zName;
118778  }
118779  if( db->mallocFailed ) break;
118780  if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
118781  pSub = 0;
118782  if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
118783  continue;
118784  }
118785  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
118786  zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
118787  }
118788  for(j=0; j<pTab->nCol; j++){
118789  char *zName = pTab->aCol[j].zName;
118790  char *zColname; /* The computed column name */
118791  char *zToFree; /* Malloced string that needs to be freed */
118792  Token sColname; /* Computed column name as a token */
118793 
118794  assert( zName );
118795  if( zTName && pSub
118796  && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
118797  ){
118798  continue;
118799  }
118800 
118801  /* If a column is marked as 'hidden', omit it from the expanded
118802  ** result-set list unless the SELECT has the SF_IncludeHidden
118803  ** bit set.
118804  */
118805  if( (p->selFlags & SF_IncludeHidden)==0
118806  && IsHiddenColumn(&pTab->aCol[j])
118807  ){
118808  continue;
118809  }
118810  tableSeen = 1;
118811 
118812  if( i>0 && zTName==0 ){
118813  if( (pFrom->fg.jointype & JT_NATURAL)!=0
118814  && tableAndColumnIndex(pTabList, i, zName, 0, 0)
118815  ){
118816  /* In a NATURAL join, omit the join columns from the
118817  ** table to the right of the join */
118818  continue;
118819  }
118820  if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
118821  /* In a join with a USING clause, omit columns in the
118822  ** using clause from the table on the right. */
118823  continue;
118824  }
118825  }
118826  pRight = sqlite3Expr(db, TK_ID, zName);
118827  zColname = zName;
118828  zToFree = 0;
118829  if( longNames || pTabList->nSrc>1 ){
118830  Expr *pLeft;
118831  pLeft = sqlite3Expr(db, TK_ID, zTabName);
118832  pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
118833  if( zSchemaName ){
118834  pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
118835  pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
118836  }
118837  if( longNames ){
118838  zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
118839  zToFree = zColname;
118840  }
118841  }else{
118842  pExpr = pRight;
118843  }
118844  pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
118845  sqlite3TokenInit(&sColname, zColname);
118846  sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
118847  if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
118848  struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
118849  if( pSub ){
118850  pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
118851  testcase( pX->zSpan==0 );
118852  }else{
118853  pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
118854  zSchemaName, zTabName, zColname);
118855  testcase( pX->zSpan==0 );
118856  }
118857  pX->bSpanIsTab = 1;
118858  }
118859  sqlite3DbFree(db, zToFree);
118860  }
118861  }
118862  if( !tableSeen ){
118863  if( zTName ){
118864  sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
118865  }else{
118866  sqlite3ErrorMsg(pParse, "no tables specified");
118867  }
118868  }
118869  }
118870  }
118871  sqlite3ExprListDelete(db, pEList);
118872  p->pEList = pNew;
118873  }
118874 #if SQLITE_MAX_COLUMN
118875  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
118876  sqlite3ErrorMsg(pParse, "too many columns in result set");
118877  return WRC_Abort;
118878  }
118879 #endif
118880  return WRC_Continue;
118881 }
118882 
118883 /*
118884 ** No-op routine for the parse-tree walker.
118885 **
118886 ** When this routine is the Walker.xExprCallback then expression trees
118887 ** are walked without any actions being taken at each node. Presumably,
118888 ** when this routine is used for Walker.xExprCallback then
118889 ** Walker.xSelectCallback is set to do something useful for every
118890 ** subquery in the parser tree.
118891 */
118892 SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
118893  UNUSED_PARAMETER2(NotUsed, NotUsed2);
118894  return WRC_Continue;
118895 }
118896 
118897 /*
118898 ** This routine "expands" a SELECT statement and all of its subqueries.
118899 ** For additional information on what it means to "expand" a SELECT
118900 ** statement, see the comment on the selectExpand worker callback above.
118901 **
118902 ** Expanding a SELECT statement is the first step in processing a
118903 ** SELECT statement. The SELECT statement must be expanded before
118904 ** name resolution is performed.
118905 **
118906 ** If anything goes wrong, an error message is written into pParse.
118907 ** The calling function can detect the problem by looking at pParse->nErr
118908 ** and/or pParse->db->mallocFailed.
118909 */
118910 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
118911  Walker w;
118912  memset(&w, 0, sizeof(w));
118913  w.xExprCallback = sqlite3ExprWalkNoop;
118914  w.pParse = pParse;
118915  if( pParse->hasCompound ){
118916  w.xSelectCallback = convertCompoundSelectToSubquery;
118917  sqlite3WalkSelect(&w, pSelect);
118918  }
118919  w.xSelectCallback = selectExpander;
118920  if( (pSelect->selFlags & SF_MultiValue)==0 ){
118921  w.xSelectCallback2 = selectPopWith;
118922  }
118923  sqlite3WalkSelect(&w, pSelect);
118924 }
118925 
118926 
118927 #ifndef SQLITE_OMIT_SUBQUERY
118928 /*
118929 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
118930 ** interface.
118931 **
118932 ** For each FROM-clause subquery, add Column.zType and Column.zColl
118933 ** information to the Table structure that represents the result set
118934 ** of that subquery.
118935 **
118936 ** The Table structure that represents the result set was constructed
118937 ** by selectExpander() but the type and collation information was omitted
118938 ** at that point because identifiers had not yet been resolved. This
118939 ** routine is called after identifier resolution.
118940 */
118941 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
118942  Parse *pParse;
118943  int i;
118944  SrcList *pTabList;
118945  struct SrcList_item *pFrom;
118946 
118947  assert( p->selFlags & SF_Resolved );
118948  assert( (p->selFlags & SF_HasTypeInfo)==0 );
118949  p->selFlags |= SF_HasTypeInfo;
118950  pParse = pWalker->pParse;
118951  pTabList = p->pSrc;
118952  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
118953  Table *pTab = pFrom->pTab;
118954  assert( pTab!=0 );
118955  if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
118956  /* A sub-query in the FROM clause of a SELECT */
118957  Select *pSel = pFrom->pSelect;
118958  if( pSel ){
118959  while( pSel->pPrior ) pSel = pSel->pPrior;
118960  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
118961  }
118962  }
118963  }
118964 }
118965 #endif
118966 
118967 
118968 /*
118969 ** This routine adds datatype and collating sequence information to
118970 ** the Table structures of all FROM-clause subqueries in a
118971 ** SELECT statement.
118972 **
118973 ** Use this routine after name resolution.
118974 */
118975 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
118976 #ifndef SQLITE_OMIT_SUBQUERY
118977  Walker w;
118978  memset(&w, 0, sizeof(w));
118979  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
118980  w.xExprCallback = sqlite3ExprWalkNoop;
118981  w.pParse = pParse;
118982  sqlite3WalkSelect(&w, pSelect);
118983 #endif
118984 }
118985 
118986 
118987 /*
118988 ** This routine sets up a SELECT statement for processing. The
118989 ** following is accomplished:
118990 **
118991 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
118992 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
118993 ** * ON and USING clauses are shifted into WHERE statements
118994 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
118995 ** * Identifiers in expression are matched to tables.
118996 **
118997 ** This routine acts recursively on all subqueries within the SELECT.
118998 */
118999 SQLITE_PRIVATE void sqlite3SelectPrep(
119000  Parse *pParse, /* The parser context */
119001  Select *p, /* The SELECT statement being coded. */
119002  NameContext *pOuterNC /* Name context for container */
119003 ){
119004  sqlite3 *db;
119005  if( NEVER(p==0) ) return;
119006  db = pParse->db;
119007  if( db->mallocFailed ) return;
119008  if( p->selFlags & SF_HasTypeInfo ) return;
119009  sqlite3SelectExpand(pParse, p);
119010  if( pParse->nErr || db->mallocFailed ) return;
119011  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
119012  if( pParse->nErr || db->mallocFailed ) return;
119013  sqlite3SelectAddTypeInfo(pParse, p);
119014 }
119015 
119016 /*
119017 ** Reset the aggregate accumulator.
119018 **
119019 ** The aggregate accumulator is a set of memory cells that hold
119020 ** intermediate results while calculating an aggregate. This
119021 ** routine generates code that stores NULLs in all of those memory
119022 ** cells.
119023 */
119024 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
119025  Vdbe *v = pParse->pVdbe;
119026  int i;
119027  struct AggInfo_func *pFunc;
119028  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
119029  if( nReg==0 ) return;
119030 #ifdef SQLITE_DEBUG
119031  /* Verify that all AggInfo registers are within the range specified by
119032  ** AggInfo.mnReg..AggInfo.mxReg */
119033  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
119034  for(i=0; i<pAggInfo->nColumn; i++){
119035  assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
119036  && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
119037  }
119038  for(i=0; i<pAggInfo->nFunc; i++){
119039  assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
119040  && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
119041  }
119042 #endif
119043  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
119044  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
119045  if( pFunc->iDistinct>=0 ){
119046  Expr *pE = pFunc->pExpr;
119047  assert( !ExprHasProperty(pE, EP_xIsSelect) );
119048  if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
119049  sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
119050  "argument");
119051  pFunc->iDistinct = -1;
119052  }else{
119053  KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
119054  sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
119055  (char*)pKeyInfo, P4_KEYINFO);
119056  }
119057  }
119058  }
119059 }
119060 
119061 /*
119062 ** Invoke the OP_AggFinalize opcode for every aggregate function
119063 ** in the AggInfo structure.
119064 */
119065 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
119066  Vdbe *v = pParse->pVdbe;
119067  int i;
119068  struct AggInfo_func *pF;
119069  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
119070  ExprList *pList = pF->pExpr->x.pList;
119071  assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
119072  sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
119073  (void*)pF->pFunc, P4_FUNCDEF);
119074  }
119075 }
119076 
119077 /*
119078 ** Update the accumulator memory cells for an aggregate based on
119079 ** the current cursor position.
119080 */
119081 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
119082  Vdbe *v = pParse->pVdbe;
119083  int i;
119084  int regHit = 0;
119085  int addrHitTest = 0;
119086  struct AggInfo_func *pF;
119087  struct AggInfo_col *pC;
119088 
119089  pAggInfo->directMode = 1;
119090  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
119091  int nArg;
119092  int addrNext = 0;
119093  int regAgg;
119094  ExprList *pList = pF->pExpr->x.pList;
119095  assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
119096  if( pList ){
119097  nArg = pList->nExpr;
119098  regAgg = sqlite3GetTempRange(pParse, nArg);
119099  sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
119100  }else{
119101  nArg = 0;
119102  regAgg = 0;
119103  }
119104  if( pF->iDistinct>=0 ){
119105  addrNext = sqlite3VdbeMakeLabel(v);
119106  testcase( nArg==0 ); /* Error condition */
119107  testcase( nArg>1 ); /* Also an error */
119108  codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
119109  }
119110  if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
119111  CollSeq *pColl = 0;
119112  struct ExprList_item *pItem;
119113  int j;
119114  assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
119115  for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
119116  pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
119117  }
119118  if( !pColl ){
119119  pColl = pParse->db->pDfltColl;
119120  }
119121  if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
119122  sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
119123  }
119124  sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
119125  (void*)pF->pFunc, P4_FUNCDEF);
119126  sqlite3VdbeChangeP5(v, (u8)nArg);
119127  sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
119128  sqlite3ReleaseTempRange(pParse, regAgg, nArg);
119129  if( addrNext ){
119130  sqlite3VdbeResolveLabel(v, addrNext);
119131  sqlite3ExprCacheClear(pParse);
119132  }
119133  }
119134 
119135  /* Before populating the accumulator registers, clear the column cache.
119136  ** Otherwise, if any of the required column values are already present
119137  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
119138  ** to pC->iMem. But by the time the value is used, the original register
119139  ** may have been used, invalidating the underlying buffer holding the
119140  ** text or blob value. See ticket [883034dcb5].
119141  **
119142  ** Another solution would be to change the OP_SCopy used to copy cached
119143  ** values to an OP_Copy.
119144  */
119145  if( regHit ){
119146  addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
119147  }
119148  sqlite3ExprCacheClear(pParse);
119149  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
119150  sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
119151  }
119152  pAggInfo->directMode = 0;
119153  sqlite3ExprCacheClear(pParse);
119154  if( addrHitTest ){
119155  sqlite3VdbeJumpHere(v, addrHitTest);
119156  }
119157 }
119158 
119159 /*
119160 ** Add a single OP_Explain instruction to the VDBE to explain a simple
119161 ** count(*) query ("SELECT count(*) FROM pTab").
119162 */
119163 #ifndef SQLITE_OMIT_EXPLAIN
119164 static void explainSimpleCount(
119165  Parse *pParse, /* Parse context */
119166  Table *pTab, /* Table being queried */
119167  Index *pIdx /* Index used to optimize scan, or NULL */
119168 ){
119169  if( pParse->explain==2 ){
119170  int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
119171  char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
119172  pTab->zName,
119173  bCover ? " USING COVERING INDEX " : "",
119174  bCover ? pIdx->zName : ""
119175  );
119176  sqlite3VdbeAddOp4(
119177  pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
119178  );
119179  }
119180 }
119181 #else
119182 # define explainSimpleCount(a,b,c)
119183 #endif
119184 
119185 /*
119186 ** Generate code for the SELECT statement given in the p argument.
119187 **
119188 ** The results are returned according to the SelectDest structure.
119189 ** See comments in sqliteInt.h for further information.
119190 **
119191 ** This routine returns the number of errors. If any errors are
119192 ** encountered, then an appropriate error message is left in
119193 ** pParse->zErrMsg.
119194 **
119195 ** This routine does NOT free the Select structure passed in. The
119196 ** calling function needs to do that.
119197 */
119198 SQLITE_PRIVATE int sqlite3Select(
119199  Parse *pParse, /* The parser context */
119200  Select *p, /* The SELECT statement being coded. */
119201  SelectDest *pDest /* What to do with the query results */
119202 ){
119203  int i, j; /* Loop counters */
119204  WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
119205  Vdbe *v; /* The virtual machine under construction */
119206  int isAgg; /* True for select lists like "count(*)" */
119207  ExprList *pEList = 0; /* List of columns to extract. */
119208  SrcList *pTabList; /* List of tables to select from */
119209  Expr *pWhere; /* The WHERE clause. May be NULL */
119210  ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
119211  Expr *pHaving; /* The HAVING clause. May be NULL */
119212  int rc = 1; /* Value to return from this function */
119213  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
119214  SortCtx sSort; /* Info on how to code the ORDER BY clause */
119215  AggInfo sAggInfo; /* Information used by aggregate queries */
119216  int iEnd; /* Address of the end of the query */
119217  sqlite3 *db; /* The database connection */
119218 
119219 #ifndef SQLITE_OMIT_EXPLAIN
119220  int iRestoreSelectId = pParse->iSelectId;
119221  pParse->iSelectId = pParse->iNextSelectId++;
119222 #endif
119223 
119224  db = pParse->db;
119225  if( p==0 || db->mallocFailed || pParse->nErr ){
119226  return 1;
119227  }
119228  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
119229  memset(&sAggInfo, 0, sizeof(sAggInfo));
119230 #if SELECTTRACE_ENABLED
119231  pParse->nSelectIndent++;
119232  SELECTTRACE(1,pParse,p, ("begin processing:\n"));
119233  if( sqlite3SelectTrace & 0x100 ){
119234  sqlite3TreeViewSelect(0, p, 0);
119235  }
119236 #endif
119237 
119238  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
119239  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
119240  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
119241  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
119242  if( IgnorableOrderby(pDest) ){
119243  assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
119244  pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
119245  pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
119246  pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
119247  /* If ORDER BY makes no difference in the output then neither does
119248  ** DISTINCT so it can be removed too. */
119249  sqlite3ExprListDelete(db, p->pOrderBy);
119250  p->pOrderBy = 0;
119251  p->selFlags &= ~SF_Distinct;
119252  }
119253  sqlite3SelectPrep(pParse, p, 0);
119254  memset(&sSort, 0, sizeof(sSort));
119255  sSort.pOrderBy = p->pOrderBy;
119256  pTabList = p->pSrc;
119257  if( pParse->nErr || db->mallocFailed ){
119258  goto select_end;
119259  }
119260  assert( p->pEList!=0 );
119261  isAgg = (p->selFlags & SF_Aggregate)!=0;
119262 #if SELECTTRACE_ENABLED
119263  if( sqlite3SelectTrace & 0x100 ){
119264  SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
119265  sqlite3TreeViewSelect(0, p, 0);
119266  }
119267 #endif
119268 
119269  /* Try to flatten subqueries in the FROM clause up into the main query
119270  */
119271 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
119272  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
119273  struct SrcList_item *pItem = &pTabList->a[i];
119274  Select *pSub = pItem->pSelect;
119275  int isAggSub;
119276  Table *pTab = pItem->pTab;
119277  if( pSub==0 ) continue;
119278 
119279  /* Catch mismatch in the declared columns of a view and the number of
119280  ** columns in the SELECT on the RHS */
119281  if( pTab->nCol!=pSub->pEList->nExpr ){
119282  sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
119283  pTab->nCol, pTab->zName, pSub->pEList->nExpr);
119284  goto select_end;
119285  }
119286 
119287  isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
119288  if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
119289  /* This subquery can be absorbed into its parent. */
119290  if( isAggSub ){
119291  isAgg = 1;
119292  p->selFlags |= SF_Aggregate;
119293  }
119294  i = -1;
119295  }
119296  pTabList = p->pSrc;
119297  if( db->mallocFailed ) goto select_end;
119298  if( !IgnorableOrderby(pDest) ){
119299  sSort.pOrderBy = p->pOrderBy;
119300  }
119301  }
119302 #endif
119303 
119304  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
119305  ** does not already exist */
119306  v = sqlite3GetVdbe(pParse);
119307  if( v==0 ) goto select_end;
119308 
119309 #ifndef SQLITE_OMIT_COMPOUND_SELECT
119310  /* Handle compound SELECT statements using the separate multiSelect()
119311  ** procedure.
119312  */
119313  if( p->pPrior ){
119314  rc = multiSelect(pParse, p, pDest);
119315  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
119316 #if SELECTTRACE_ENABLED
119317  SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
119318  pParse->nSelectIndent--;
119319 #endif
119320  return rc;
119321  }
119322 #endif
119323 
119324  /* Generate code for all sub-queries in the FROM clause
119325  */
119326 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
119327  for(i=0; i<pTabList->nSrc; i++){
119328  struct SrcList_item *pItem = &pTabList->a[i];
119329  SelectDest dest;
119330  Select *pSub = pItem->pSelect;
119331  if( pSub==0 ) continue;
119332 
119333  /* Sometimes the code for a subquery will be generated more than
119334  ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
119335  ** for example. In that case, do not regenerate the code to manifest
119336  ** a view or the co-routine to implement a view. The first instance
119337  ** is sufficient, though the subroutine to manifest the view does need
119338  ** to be invoked again. */
119339  if( pItem->addrFillSub ){
119340  if( pItem->fg.viaCoroutine==0 ){
119341  sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
119342  }
119343  continue;
119344  }
119345 
119346  /* Increment Parse.nHeight by the height of the largest expression
119347  ** tree referred to by this, the parent select. The child select
119348  ** may contain expression trees of at most
119349  ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
119350  ** more conservative than necessary, but much easier than enforcing
119351  ** an exact limit.
119352  */
119353  pParse->nHeight += sqlite3SelectExprHeight(p);
119354 
119355  /* Make copies of constant WHERE-clause terms in the outer query down
119356  ** inside the subquery. This can help the subquery to run more efficiently.
119357  */
119358  if( (pItem->fg.jointype & JT_OUTER)==0
119359  && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
119360  ){
119361 #if SELECTTRACE_ENABLED
119362  if( sqlite3SelectTrace & 0x100 ){
119363  SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
119364  sqlite3TreeViewSelect(0, p, 0);
119365  }
119366 #endif
119367  }
119368 
119369  /* Generate code to implement the subquery
119370  **
119371  ** The subquery is implemented as a co-routine if all of these are true:
119372  ** (1) The subquery is guaranteed to be the outer loop (so that it
119373  ** does not need to be computed more than once)
119374  ** (2) The ALL keyword after SELECT is omitted. (Applications are
119375  ** allowed to say "SELECT ALL" instead of just "SELECT" to disable
119376  ** the use of co-routines.)
119377  ** (3) Co-routines are not disabled using sqlite3_test_control()
119378  ** with SQLITE_TESTCTRL_OPTIMIZATIONS.
119379  **
119380  ** TODO: Are there other reasons beside (1) to use a co-routine
119381  ** implementation?
119382  */
119383  if( i==0
119384  && (pTabList->nSrc==1
119385  || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
119386  && (p->selFlags & SF_All)==0 /* (2) */
119387  && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */
119388  ){
119389  /* Implement a co-routine that will return a single row of the result
119390  ** set on each invocation.
119391  */
119392  int addrTop = sqlite3VdbeCurrentAddr(v)+1;
119393  pItem->regReturn = ++pParse->nMem;
119394  sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
119395  VdbeComment((v, "%s", pItem->pTab->zName));
119396  pItem->addrFillSub = addrTop;
119397  sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
119398  explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
119399  sqlite3Select(pParse, pSub, &dest);
119400  pItem->pTab->nRowLogEst = pSub->nSelectRow;
119401  pItem->fg.viaCoroutine = 1;
119402  pItem->regResult = dest.iSdst;
119403  sqlite3VdbeEndCoroutine(v, pItem->regReturn);
119404  sqlite3VdbeJumpHere(v, addrTop-1);
119405  sqlite3ClearTempRegCache(pParse);
119406  }else{
119407  /* Generate a subroutine that will fill an ephemeral table with
119408  ** the content of this subquery. pItem->addrFillSub will point
119409  ** to the address of the generated subroutine. pItem->regReturn
119410  ** is a register allocated to hold the subroutine return address
119411  */
119412  int topAddr;
119413  int onceAddr = 0;
119414  int retAddr;
119415  assert( pItem->addrFillSub==0 );
119416  pItem->regReturn = ++pParse->nMem;
119417  topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
119418  pItem->addrFillSub = topAddr+1;
119419  if( pItem->fg.isCorrelated==0 ){
119420  /* If the subquery is not correlated and if we are not inside of
119421  ** a trigger, then we only need to compute the value of the subquery
119422  ** once. */
119423  onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
119424  VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
119425  }else{
119426  VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
119427  }
119428  sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
119429  explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
119430  sqlite3Select(pParse, pSub, &dest);
119431  pItem->pTab->nRowLogEst = pSub->nSelectRow;
119432  if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
119433  retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
119434  VdbeComment((v, "end %s", pItem->pTab->zName));
119435  sqlite3VdbeChangeP1(v, topAddr, retAddr);
119436  sqlite3ClearTempRegCache(pParse);
119437  }
119438  if( db->mallocFailed ) goto select_end;
119439  pParse->nHeight -= sqlite3SelectExprHeight(p);
119440  }
119441 #endif
119442 
119443  /* Various elements of the SELECT copied into local variables for
119444  ** convenience */
119445  pEList = p->pEList;
119446  pWhere = p->pWhere;
119447  pGroupBy = p->pGroupBy;
119448  pHaving = p->pHaving;
119449  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
119450 
119451 #if SELECTTRACE_ENABLED
119452  if( sqlite3SelectTrace & 0x400 ){
119453  SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
119454  sqlite3TreeViewSelect(0, p, 0);
119455  }
119456 #endif
119457 
119458  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
119459  ** if the select-list is the same as the ORDER BY list, then this query
119460  ** can be rewritten as a GROUP BY. In other words, this:
119461  **
119462  ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
119463  **
119464  ** is transformed to:
119465  **
119466  ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
119467  **
119468  ** The second form is preferred as a single index (or temp-table) may be
119469  ** used for both the ORDER BY and DISTINCT processing. As originally
119470  ** written the query must use a temp-table for at least one of the ORDER
119471  ** BY and DISTINCT, and an index or separate temp-table for the other.
119472  */
119473  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
119474  && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
119475  ){
119476  p->selFlags &= ~SF_Distinct;
119477  pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
119478  /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
119479  ** the sDistinct.isTnct is still set. Hence, isTnct represents the
119480  ** original setting of the SF_Distinct flag, not the current setting */
119481  assert( sDistinct.isTnct );
119482 
119483 #if SELECTTRACE_ENABLED
119484  if( sqlite3SelectTrace & 0x400 ){
119485  SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
119486  sqlite3TreeViewSelect(0, p, 0);
119487  }
119488 #endif
119489  }
119490 
119491  /* If there is an ORDER BY clause, then create an ephemeral index to
119492  ** do the sorting. But this sorting ephemeral index might end up
119493  ** being unused if the data can be extracted in pre-sorted order.
119494  ** If that is the case, then the OP_OpenEphemeral instruction will be
119495  ** changed to an OP_Noop once we figure out that the sorting index is
119496  ** not needed. The sSort.addrSortIndex variable is used to facilitate
119497  ** that change.
119498  */
119499  if( sSort.pOrderBy ){
119500  KeyInfo *pKeyInfo;
119501  pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
119502  sSort.iECursor = pParse->nTab++;
119503  sSort.addrSortIndex =
119504  sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
119505  sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
119506  (char*)pKeyInfo, P4_KEYINFO
119507  );
119508  }else{
119509  sSort.addrSortIndex = -1;
119510  }
119511 
119512  /* If the output is destined for a temporary table, open that table.
119513  */
119514  if( pDest->eDest==SRT_EphemTab ){
119515  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
119516  }
119517 
119518  /* Set the limiter.
119519  */
119520  iEnd = sqlite3VdbeMakeLabel(v);
119521  p->nSelectRow = 320; /* 4 billion rows */
119522  computeLimitRegisters(pParse, p, iEnd);
119523  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
119524  sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
119525  sSort.sortFlags |= SORTFLAG_UseSorter;
119526  }
119527 
119528  /* Open an ephemeral index to use for the distinct set.
119529  */
119530  if( p->selFlags & SF_Distinct ){
119531  sDistinct.tabTnct = pParse->nTab++;
119532  sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
119533  sDistinct.tabTnct, 0, 0,
119534  (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
119535  P4_KEYINFO);
119536  sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
119537  sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
119538  }else{
119539  sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
119540  }
119541 
119542  if( !isAgg && pGroupBy==0 ){
119543  /* No aggregate functions and no GROUP BY clause */
119544  u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
119545  assert( WHERE_USE_LIMIT==SF_FixedLimit );
119546  wctrlFlags |= p->selFlags & SF_FixedLimit;
119547 
119548  /* Begin the database scan. */
119549  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
119550  p->pEList, wctrlFlags, p->nSelectRow);
119551  if( pWInfo==0 ) goto select_end;
119552  if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
119553  p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
119554  }
119555  if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
119556  sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
119557  }
119558  if( sSort.pOrderBy ){
119559  sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
119560  sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
119561  if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
119562  sSort.pOrderBy = 0;
119563  }
119564  }
119565 
119566  /* If sorting index that was created by a prior OP_OpenEphemeral
119567  ** instruction ended up not being needed, then change the OP_OpenEphemeral
119568  ** into an OP_Noop.
119569  */
119570  if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
119571  sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
119572  }
119573 
119574  /* Use the standard inner loop. */
119575  selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
119576  sqlite3WhereContinueLabel(pWInfo),
119577  sqlite3WhereBreakLabel(pWInfo));
119578 
119579  /* End the database scan loop.
119580  */
119581  sqlite3WhereEnd(pWInfo);
119582  }else{
119583  /* This case when there exist aggregate functions or a GROUP BY clause
119584  ** or both */
119585  NameContext sNC; /* Name context for processing aggregate information */
119586  int iAMem; /* First Mem address for storing current GROUP BY */
119587  int iBMem; /* First Mem address for previous GROUP BY */
119588  int iUseFlag; /* Mem address holding flag indicating that at least
119589  ** one row of the input to the aggregator has been
119590  ** processed */
119591  int iAbortFlag; /* Mem address which causes query abort if positive */
119592  int groupBySort; /* Rows come from source in GROUP BY order */
119593  int addrEnd; /* End of processing for this SELECT */
119594  int sortPTab = 0; /* Pseudotable used to decode sorting results */
119595  int sortOut = 0; /* Output register from the sorter */
119596  int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
119597 
119598  /* Remove any and all aliases between the result set and the
119599  ** GROUP BY clause.
119600  */
119601  if( pGroupBy ){
119602  int k; /* Loop counter */
119603  struct ExprList_item *pItem; /* For looping over expression in a list */
119604 
119605  for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
119606  pItem->u.x.iAlias = 0;
119607  }
119608  for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
119609  pItem->u.x.iAlias = 0;
119610  }
119611  assert( 66==sqlite3LogEst(100) );
119612  if( p->nSelectRow>66 ) p->nSelectRow = 66;
119613  }else{
119614  assert( 0==sqlite3LogEst(1) );
119615  p->nSelectRow = 0;
119616  }
119617 
119618  /* If there is both a GROUP BY and an ORDER BY clause and they are
119619  ** identical, then it may be possible to disable the ORDER BY clause
119620  ** on the grounds that the GROUP BY will cause elements to come out
119621  ** in the correct order. It also may not - the GROUP BY might use a
119622  ** database index that causes rows to be grouped together as required
119623  ** but not actually sorted. Either way, record the fact that the
119624  ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
119625  ** variable. */
119626  if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
119627  orderByGrp = 1;
119628  }
119629 
119630  /* Create a label to jump to when we want to abort the query */
119631  addrEnd = sqlite3VdbeMakeLabel(v);
119632 
119633  /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
119634  ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
119635  ** SELECT statement.
119636  */
119637  memset(&sNC, 0, sizeof(sNC));
119638  sNC.pParse = pParse;
119639  sNC.pSrcList = pTabList;
119640  sNC.pAggInfo = &sAggInfo;
119641  sAggInfo.mnReg = pParse->nMem+1;
119642  sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
119643  sAggInfo.pGroupBy = pGroupBy;
119644  sqlite3ExprAnalyzeAggList(&sNC, pEList);
119645  sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
119646  if( pHaving ){
119647  sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
119648  }
119649  sAggInfo.nAccumulator = sAggInfo.nColumn;
119650  for(i=0; i<sAggInfo.nFunc; i++){
119651  assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
119652  sNC.ncFlags |= NC_InAggFunc;
119653  sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
119654  sNC.ncFlags &= ~NC_InAggFunc;
119655  }
119656  sAggInfo.mxReg = pParse->nMem;
119657  if( db->mallocFailed ) goto select_end;
119658 
119659  /* Processing for aggregates with GROUP BY is very different and
119660  ** much more complex than aggregates without a GROUP BY.
119661  */
119662  if( pGroupBy ){
119663  KeyInfo *pKeyInfo; /* Keying information for the group by clause */
119664  int addr1; /* A-vs-B comparision jump */
119665  int addrOutputRow; /* Start of subroutine that outputs a result row */
119666  int regOutputRow; /* Return address register for output subroutine */
119667  int addrSetAbort; /* Set the abort flag and return */
119668  int addrTopOfLoop; /* Top of the input loop */
119669  int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
119670  int addrReset; /* Subroutine for resetting the accumulator */
119671  int regReset; /* Return address register for reset subroutine */
119672 
119673  /* If there is a GROUP BY clause we might need a sorting index to
119674  ** implement it. Allocate that sorting index now. If it turns out
119675  ** that we do not need it after all, the OP_SorterOpen instruction
119676  ** will be converted into a Noop.
119677  */
119678  sAggInfo.sortingIdx = pParse->nTab++;
119679  pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
119680  addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
119681  sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
119682  0, (char*)pKeyInfo, P4_KEYINFO);
119683 
119684  /* Initialize memory locations used by GROUP BY aggregate processing
119685  */
119686  iUseFlag = ++pParse->nMem;
119687  iAbortFlag = ++pParse->nMem;
119688  regOutputRow = ++pParse->nMem;
119689  addrOutputRow = sqlite3VdbeMakeLabel(v);
119690  regReset = ++pParse->nMem;
119691  addrReset = sqlite3VdbeMakeLabel(v);
119692  iAMem = pParse->nMem + 1;
119693  pParse->nMem += pGroupBy->nExpr;
119694  iBMem = pParse->nMem + 1;
119695  pParse->nMem += pGroupBy->nExpr;
119696  sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
119697  VdbeComment((v, "clear abort flag"));
119698  sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
119699  VdbeComment((v, "indicate accumulator empty"));
119700  sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
119701 
119702  /* Begin a loop that will extract all source rows in GROUP BY order.
119703  ** This might involve two separate loops with an OP_Sort in between, or
119704  ** it might be a single loop that uses an index to extract information
119705  ** in the right order to begin with.
119706  */
119707  sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
119708  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
119709  WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
119710  );
119711  if( pWInfo==0 ) goto select_end;
119712  if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
119713  /* The optimizer is able to deliver rows in group by order so
119714  ** we do not have to sort. The OP_OpenEphemeral table will be
119715  ** cancelled later because we still need to use the pKeyInfo
119716  */
119717  groupBySort = 0;
119718  }else{
119719  /* Rows are coming out in undetermined order. We have to push
119720  ** each row into a sorting index, terminate the first loop,
119721  ** then loop over the sorting index in order to get the output
119722  ** in sorted order
119723  */
119724  int regBase;
119725  int regRecord;
119726  int nCol;
119727  int nGroupBy;
119728 
119729  explainTempTable(pParse,
119730  (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
119731  "DISTINCT" : "GROUP BY");
119732 
119733  groupBySort = 1;
119734  nGroupBy = pGroupBy->nExpr;
119735  nCol = nGroupBy;
119736  j = nGroupBy;
119737  for(i=0; i<sAggInfo.nColumn; i++){
119738  if( sAggInfo.aCol[i].iSorterColumn>=j ){
119739  nCol++;
119740  j++;
119741  }
119742  }
119743  regBase = sqlite3GetTempRange(pParse, nCol);
119744  sqlite3ExprCacheClear(pParse);
119745  sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
119746  j = nGroupBy;
119747  for(i=0; i<sAggInfo.nColumn; i++){
119748  struct AggInfo_col *pCol = &sAggInfo.aCol[i];
119749  if( pCol->iSorterColumn>=j ){
119750  int r1 = j + regBase;
119751  sqlite3ExprCodeGetColumnToReg(pParse,
119752  pCol->pTab, pCol->iColumn, pCol->iTable, r1);
119753  j++;
119754  }
119755  }
119756  regRecord = sqlite3GetTempReg(pParse);
119757  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
119758  sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
119759  sqlite3ReleaseTempReg(pParse, regRecord);
119760  sqlite3ReleaseTempRange(pParse, regBase, nCol);
119761  sqlite3WhereEnd(pWInfo);
119762  sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
119763  sortOut = sqlite3GetTempReg(pParse);
119764  sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
119765  sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
119766  VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
119767  sAggInfo.useSortingIdx = 1;
119768  sqlite3ExprCacheClear(pParse);
119769 
119770  }
119771 
119772  /* If the index or temporary table used by the GROUP BY sort
119773  ** will naturally deliver rows in the order required by the ORDER BY
119774  ** clause, cancel the ephemeral table open coded earlier.
119775  **
119776  ** This is an optimization - the correct answer should result regardless.
119777  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
119778  ** disable this optimization for testing purposes. */
119779  if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
119780  && (groupBySort || sqlite3WhereIsSorted(pWInfo))
119781  ){
119782  sSort.pOrderBy = 0;
119783  sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
119784  }
119785 
119786  /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
119787  ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
119788  ** Then compare the current GROUP BY terms against the GROUP BY terms
119789  ** from the previous row currently stored in a0, a1, a2...
119790  */
119791  addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
119792  sqlite3ExprCacheClear(pParse);
119793  if( groupBySort ){
119794  sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
119795  sortOut, sortPTab);
119796  }
119797  for(j=0; j<pGroupBy->nExpr; j++){
119798  if( groupBySort ){
119799  sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
119800  }else{
119801  sAggInfo.directMode = 1;
119802  sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
119803  }
119804  }
119805  sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
119806  (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
119807  addr1 = sqlite3VdbeCurrentAddr(v);
119808  sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
119809 
119810  /* Generate code that runs whenever the GROUP BY changes.
119811  ** Changes in the GROUP BY are detected by the previous code
119812  ** block. If there were no changes, this block is skipped.
119813  **
119814  ** This code copies current group by terms in b0,b1,b2,...
119815  ** over to a0,a1,a2. It then calls the output subroutine
119816  ** and resets the aggregate accumulator registers in preparation
119817  ** for the next GROUP BY batch.
119818  */
119819  sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
119820  sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
119821  VdbeComment((v, "output one row"));
119822  sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
119823  VdbeComment((v, "check abort flag"));
119824  sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
119825  VdbeComment((v, "reset accumulator"));
119826 
119827  /* Update the aggregate accumulators based on the content of
119828  ** the current row
119829  */
119830  sqlite3VdbeJumpHere(v, addr1);
119831  updateAccumulator(pParse, &sAggInfo);
119832  sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
119833  VdbeComment((v, "indicate data in accumulator"));
119834 
119835  /* End of the loop
119836  */
119837  if( groupBySort ){
119838  sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
119839  VdbeCoverage(v);
119840  }else{
119841  sqlite3WhereEnd(pWInfo);
119842  sqlite3VdbeChangeToNoop(v, addrSortingIdx);
119843  }
119844 
119845  /* Output the final row of result
119846  */
119847  sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
119848  VdbeComment((v, "output final row"));
119849 
119850  /* Jump over the subroutines
119851  */
119852  sqlite3VdbeGoto(v, addrEnd);
119853 
119854  /* Generate a subroutine that outputs a single row of the result
119855  ** set. This subroutine first looks at the iUseFlag. If iUseFlag
119856  ** is less than or equal to zero, the subroutine is a no-op. If
119857  ** the processing calls for the query to abort, this subroutine
119858  ** increments the iAbortFlag memory location before returning in
119859  ** order to signal the caller to abort.
119860  */
119861  addrSetAbort = sqlite3VdbeCurrentAddr(v);
119862  sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
119863  VdbeComment((v, "set abort flag"));
119864  sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119865  sqlite3VdbeResolveLabel(v, addrOutputRow);
119866  addrOutputRow = sqlite3VdbeCurrentAddr(v);
119867  sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
119868  VdbeCoverage(v);
119869  VdbeComment((v, "Groupby result generator entry point"));
119870  sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119871  finalizeAggFunctions(pParse, &sAggInfo);
119872  sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
119873  selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
119874  &sDistinct, pDest,
119875  addrOutputRow+1, addrSetAbort);
119876  sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119877  VdbeComment((v, "end groupby result generator"));
119878 
119879  /* Generate a subroutine that will reset the group-by accumulator
119880  */
119881  sqlite3VdbeResolveLabel(v, addrReset);
119882  resetAccumulator(pParse, &sAggInfo);
119883  sqlite3VdbeAddOp1(v, OP_Return, regReset);
119884 
119885  } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
119886  else {
119887  ExprList *pDel = 0;
119888 #ifndef SQLITE_OMIT_BTREECOUNT
119889  Table *pTab;
119890  if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
119891  /* If isSimpleCount() returns a pointer to a Table structure, then
119892  ** the SQL statement is of the form:
119893  **
119894  ** SELECT count(*) FROM <tbl>
119895  **
119896  ** where the Table structure returned represents table <tbl>.
119897  **
119898  ** This statement is so common that it is optimized specially. The
119899  ** OP_Count instruction is executed either on the intkey table that
119900  ** contains the data for table <tbl> or on one of its indexes. It
119901  ** is better to execute the op on an index, as indexes are almost
119902  ** always spread across less pages than their corresponding tables.
119903  */
119904  const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
119905  const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
119906  Index *pIdx; /* Iterator variable */
119907  KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
119908  Index *pBest = 0; /* Best index found so far */
119909  int iRoot = pTab->tnum; /* Root page of scanned b-tree */
119910 
119911  sqlite3CodeVerifySchema(pParse, iDb);
119912  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
119913 
119914  /* Search for the index that has the lowest scan cost.
119915  **
119916  ** (2011-04-15) Do not do a full scan of an unordered index.
119917  **
119918  ** (2013-10-03) Do not count the entries in a partial index.
119919  **
119920  ** In practice the KeyInfo structure will not be used. It is only
119921  ** passed to keep OP_OpenRead happy.
119922  */
119923  if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
119924  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119925  if( pIdx->bUnordered==0
119926  && pIdx->szIdxRow<pTab->szTabRow
119927  && pIdx->pPartIdxWhere==0
119928  && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
119929  ){
119930  pBest = pIdx;
119931  }
119932  }
119933  if( pBest ){
119934  iRoot = pBest->tnum;
119935  pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
119936  }
119937 
119938  /* Open a read-only cursor, execute the OP_Count, close the cursor. */
119939  sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
119940  if( pKeyInfo ){
119941  sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
119942  }
119943  sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
119944  sqlite3VdbeAddOp1(v, OP_Close, iCsr);
119945  explainSimpleCount(pParse, pTab, pBest);
119946  }else
119947 #endif /* SQLITE_OMIT_BTREECOUNT */
119948  {
119949  /* Check if the query is of one of the following forms:
119950  **
119951  ** SELECT min(x) FROM ...
119952  ** SELECT max(x) FROM ...
119953  **
119954  ** If it is, then ask the code in where.c to attempt to sort results
119955  ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
119956  ** If where.c is able to produce results sorted in this order, then
119957  ** add vdbe code to break out of the processing loop after the
119958  ** first iteration (since the first iteration of the loop is
119959  ** guaranteed to operate on the row with the minimum or maximum
119960  ** value of x, the only row required).
119961  **
119962  ** A special flag must be passed to sqlite3WhereBegin() to slightly
119963  ** modify behavior as follows:
119964  **
119965  ** + If the query is a "SELECT min(x)", then the loop coded by
119966  ** where.c should not iterate over any values with a NULL value
119967  ** for x.
119968  **
119969  ** + The optimizer code in where.c (the thing that decides which
119970  ** index or indices to use) should place a different priority on
119971  ** satisfying the 'ORDER BY' clause than it does in other cases.
119972  ** Refer to code and comments in where.c for details.
119973  */
119974  ExprList *pMinMax = 0;
119975  u8 flag = WHERE_ORDERBY_NORMAL;
119976 
119977  assert( p->pGroupBy==0 );
119978  assert( flag==0 );
119979  if( p->pHaving==0 ){
119980  flag = minMaxQuery(&sAggInfo, &pMinMax);
119981  }
119982  assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
119983 
119984  if( flag ){
119985  pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
119986  pDel = pMinMax;
119987  assert( db->mallocFailed || pMinMax!=0 );
119988  if( !db->mallocFailed ){
119989  pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
119990  pMinMax->a[0].pExpr->op = TK_COLUMN;
119991  }
119992  }
119993 
119994  /* This case runs if the aggregate has no GROUP BY clause. The
119995  ** processing is much simpler since there is only a single row
119996  ** of output.
119997  */
119998  resetAccumulator(pParse, &sAggInfo);
119999  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
120000  if( pWInfo==0 ){
120001  sqlite3ExprListDelete(db, pDel);
120002  goto select_end;
120003  }
120004  updateAccumulator(pParse, &sAggInfo);
120005  assert( pMinMax==0 || pMinMax->nExpr==1 );
120006  if( sqlite3WhereIsOrdered(pWInfo)>0 ){
120007  sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
120008  VdbeComment((v, "%s() by index",
120009  (flag==WHERE_ORDERBY_MIN?"min":"max")));
120010  }
120011  sqlite3WhereEnd(pWInfo);
120012  finalizeAggFunctions(pParse, &sAggInfo);
120013  }
120014 
120015  sSort.pOrderBy = 0;
120016  sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
120017  selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
120018  pDest, addrEnd, addrEnd);
120019  sqlite3ExprListDelete(db, pDel);
120020  }
120021  sqlite3VdbeResolveLabel(v, addrEnd);
120022 
120023  } /* endif aggregate query */
120024 
120025  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
120026  explainTempTable(pParse, "DISTINCT");
120027  }
120028 
120029  /* If there is an ORDER BY clause, then we need to sort the results
120030  ** and send them to the callback one by one.
120031  */
120032  if( sSort.pOrderBy ){
120033  explainTempTable(pParse,
120034  sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
120035  generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
120036  }
120037 
120038  /* Jump here to skip this query
120039  */
120040  sqlite3VdbeResolveLabel(v, iEnd);
120041 
120042  /* The SELECT has been coded. If there is an error in the Parse structure,
120043  ** set the return code to 1. Otherwise 0. */
120044  rc = (pParse->nErr>0);
120045 
120046  /* Control jumps to here if an error is encountered above, or upon
120047  ** successful coding of the SELECT.
120048  */
120049 select_end:
120050  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
120051 
120052  /* Identify column names if results of the SELECT are to be output.
120053  */
120054  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
120055  generateColumnNames(pParse, pTabList, pEList);
120056  }
120057 
120058  sqlite3DbFree(db, sAggInfo.aCol);
120059  sqlite3DbFree(db, sAggInfo.aFunc);
120060 #if SELECTTRACE_ENABLED
120061  SELECTTRACE(1,pParse,p,("end processing\n"));
120062  pParse->nSelectIndent--;
120063 #endif
120064  return rc;
120065 }
120066 
120067 /************** End of select.c **********************************************/
120068 /************** Begin file table.c *******************************************/
120069 /*
120070 ** 2001 September 15
120071 **
120072 ** The author disclaims copyright to this source code. In place of
120073 ** a legal notice, here is a blessing:
120074 **
120075 ** May you do good and not evil.
120076 ** May you find forgiveness for yourself and forgive others.
120077 ** May you share freely, never taking more than you give.
120078 **
120079 *************************************************************************
120080 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
120081 ** interface routines. These are just wrappers around the main
120082 ** interface routine of sqlite3_exec().
120083 **
120084 ** These routines are in a separate files so that they will not be linked
120085 ** if they are not used.
120086 */
120087 /* #include "sqliteInt.h" */
120088 /* #include <stdlib.h> */
120089 /* #include <string.h> */
120090 
120091 #ifndef SQLITE_OMIT_GET_TABLE
120092 
120093 /*
120094 ** This structure is used to pass data from sqlite3_get_table() through
120095 ** to the callback function is uses to build the result.
120096 */
120097 typedef struct TabResult {
120098  char **azResult; /* Accumulated output */
120099  char *zErrMsg; /* Error message text, if an error occurs */
120100  u32 nAlloc; /* Slots allocated for azResult[] */
120101  u32 nRow; /* Number of rows in the result */
120102  u32 nColumn; /* Number of columns in the result */
120103  u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
120104  int rc; /* Return code from sqlite3_exec() */
120105 } TabResult;
120106 
120107 /*
120108 ** This routine is called once for each row in the result table. Its job
120109 ** is to fill in the TabResult structure appropriately, allocating new
120110 ** memory as necessary.
120111 */
120112 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
120113  TabResult *p = (TabResult*)pArg; /* Result accumulator */
120114  int need; /* Slots needed in p->azResult[] */
120115  int i; /* Loop counter */
120116  char *z; /* A single column of result */
120117 
120118  /* Make sure there is enough space in p->azResult to hold everything
120119  ** we need to remember from this invocation of the callback.
120120  */
120121  if( p->nRow==0 && argv!=0 ){
120122  need = nCol*2;
120123  }else{
120124  need = nCol;
120125  }
120126  if( p->nData + need > p->nAlloc ){
120127  char **azNew;
120128  p->nAlloc = p->nAlloc*2 + need;
120129  azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
120130  if( azNew==0 ) goto malloc_failed;
120131  p->azResult = azNew;
120132  }
120133 
120134  /* If this is the first row, then generate an extra row containing
120135  ** the names of all columns.
120136  */
120137  if( p->nRow==0 ){
120138  p->nColumn = nCol;
120139  for(i=0; i<nCol; i++){
120140  z = sqlite3_mprintf("%s", colv[i]);
120141  if( z==0 ) goto malloc_failed;
120142  p->azResult[p->nData++] = z;
120143  }
120144  }else if( (int)p->nColumn!=nCol ){
120145  sqlite3_free(p->zErrMsg);
120146  p->zErrMsg = sqlite3_mprintf(
120147  "sqlite3_get_table() called with two or more incompatible queries"
120148  );
120149  p->rc = SQLITE_ERROR;
120150  return 1;
120151  }
120152 
120153  /* Copy over the row data
120154  */
120155  if( argv!=0 ){
120156  for(i=0; i<nCol; i++){
120157  if( argv[i]==0 ){
120158  z = 0;
120159  }else{
120160  int n = sqlite3Strlen30(argv[i])+1;
120161  z = sqlite3_malloc64( n );
120162  if( z==0 ) goto malloc_failed;
120163  memcpy(z, argv[i], n);
120164  }
120165  p->azResult[p->nData++] = z;
120166  }
120167  p->nRow++;
120168  }
120169  return 0;
120170 
120171 malloc_failed:
120172  p->rc = SQLITE_NOMEM_BKPT;
120173  return 1;
120174 }
120175 
120176 /*
120177 ** Query the database. But instead of invoking a callback for each row,
120178 ** malloc() for space to hold the result and return the entire results
120179 ** at the conclusion of the call.
120180 **
120181 ** The result that is written to ***pazResult is held in memory obtained
120182 ** from malloc(). But the caller cannot free this memory directly.
120183 ** Instead, the entire table should be passed to sqlite3_free_table() when
120184 ** the calling procedure is finished using it.
120185 */
120186 SQLITE_API int sqlite3_get_table(
120187  sqlite3 *db, /* The database on which the SQL executes */
120188  const char *zSql, /* The SQL to be executed */
120189  char ***pazResult, /* Write the result table here */
120190  int *pnRow, /* Write the number of rows in the result here */
120191  int *pnColumn, /* Write the number of columns of result here */
120192  char **pzErrMsg /* Write error messages here */
120193 ){
120194  int rc;
120195  TabResult res;
120196 
120197 #ifdef SQLITE_ENABLE_API_ARMOR
120198  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
120199 #endif
120200  *pazResult = 0;
120201  if( pnColumn ) *pnColumn = 0;
120202  if( pnRow ) *pnRow = 0;
120203  if( pzErrMsg ) *pzErrMsg = 0;
120204  res.zErrMsg = 0;
120205  res.nRow = 0;
120206  res.nColumn = 0;
120207  res.nData = 1;
120208  res.nAlloc = 20;
120209  res.rc = SQLITE_OK;
120210  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
120211  if( res.azResult==0 ){
120212  db->errCode = SQLITE_NOMEM;
120213  return SQLITE_NOMEM_BKPT;
120214  }
120215  res.azResult[0] = 0;
120216  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
120217  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
120218  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
120219  if( (rc&0xff)==SQLITE_ABORT ){
120220  sqlite3_free_table(&res.azResult[1]);
120221  if( res.zErrMsg ){
120222  if( pzErrMsg ){
120223  sqlite3_free(*pzErrMsg);
120224  *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
120225  }
120226  sqlite3_free(res.zErrMsg);
120227  }
120228  db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
120229  return res.rc;
120230  }
120231  sqlite3_free(res.zErrMsg);
120232  if( rc!=SQLITE_OK ){
120233  sqlite3_free_table(&res.azResult[1]);
120234  return rc;
120235  }
120236  if( res.nAlloc>res.nData ){
120237  char **azNew;
120238  azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
120239  if( azNew==0 ){
120240  sqlite3_free_table(&res.azResult[1]);
120241  db->errCode = SQLITE_NOMEM;
120242  return SQLITE_NOMEM_BKPT;
120243  }
120244  res.azResult = azNew;
120245  }
120246  *pazResult = &res.azResult[1];
120247  if( pnColumn ) *pnColumn = res.nColumn;
120248  if( pnRow ) *pnRow = res.nRow;
120249  return rc;
120250 }
120251 
120252 /*
120253 ** This routine frees the space the sqlite3_get_table() malloced.
120254 */
120255 SQLITE_API void sqlite3_free_table(
120256  char **azResult /* Result returned from sqlite3_get_table() */
120257 ){
120258  if( azResult ){
120259  int i, n;
120260  azResult--;
120261  assert( azResult!=0 );
120262  n = SQLITE_PTR_TO_INT(azResult[0]);
120263  for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
120264  sqlite3_free(azResult);
120265  }
120266 }
120267 
120268 #endif /* SQLITE_OMIT_GET_TABLE */
120269 
120270 /************** End of table.c ***********************************************/
120271 /************** Begin file trigger.c *****************************************/
120272 /*
120273 **
120274 ** The author disclaims copyright to this source code. In place of
120275 ** a legal notice, here is a blessing:
120276 **
120277 ** May you do good and not evil.
120278 ** May you find forgiveness for yourself and forgive others.
120279 ** May you share freely, never taking more than you give.
120280 **
120281 *************************************************************************
120282 ** This file contains the implementation for TRIGGERs
120283 */
120284 /* #include "sqliteInt.h" */
120285 
120286 #ifndef SQLITE_OMIT_TRIGGER
120287 /*
120288 ** Delete a linked list of TriggerStep structures.
120289 */
120290 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
120291  while( pTriggerStep ){
120292  TriggerStep * pTmp = pTriggerStep;
120293  pTriggerStep = pTriggerStep->pNext;
120294 
120295  sqlite3ExprDelete(db, pTmp->pWhere);
120296  sqlite3ExprListDelete(db, pTmp->pExprList);
120297  sqlite3SelectDelete(db, pTmp->pSelect);
120298  sqlite3IdListDelete(db, pTmp->pIdList);
120299 
120300  sqlite3DbFree(db, pTmp);
120301  }
120302 }
120303 
120304 /*
120305 ** Given table pTab, return a list of all the triggers attached to
120306 ** the table. The list is connected by Trigger.pNext pointers.
120307 **
120308 ** All of the triggers on pTab that are in the same database as pTab
120309 ** are already attached to pTab->pTrigger. But there might be additional
120310 ** triggers on pTab in the TEMP schema. This routine prepends all
120311 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
120312 ** and returns the combined list.
120313 **
120314 ** To state it another way: This routine returns a list of all triggers
120315 ** that fire off of pTab. The list will include any TEMP triggers on
120316 ** pTab as well as the triggers lised in pTab->pTrigger.
120317 */
120318 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
120319  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
120320  Trigger *pList = 0; /* List of triggers to return */
120321 
120322  if( pParse->disableTriggers ){
120323  return 0;
120324  }
120325 
120326  if( pTmpSchema!=pTab->pSchema ){
120327  HashElem *p;
120328  assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
120329  for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
120330  Trigger *pTrig = (Trigger *)sqliteHashData(p);
120331  if( pTrig->pTabSchema==pTab->pSchema
120332  && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
120333  ){
120334  pTrig->pNext = (pList ? pList : pTab->pTrigger);
120335  pList = pTrig;
120336  }
120337  }
120338  }
120339 
120340  return (pList ? pList : pTab->pTrigger);
120341 }
120342 
120343 /*
120344 ** This is called by the parser when it sees a CREATE TRIGGER statement
120345 ** up to the point of the BEGIN before the trigger actions. A Trigger
120346 ** structure is generated based on the information available and stored
120347 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
120348 ** sqlite3FinishTrigger() function is called to complete the trigger
120349 ** construction process.
120350 */
120351 SQLITE_PRIVATE void sqlite3BeginTrigger(
120352  Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
120353  Token *pName1, /* The name of the trigger */
120354  Token *pName2, /* The name of the trigger */
120355  int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
120356  int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
120357  IdList *pColumns, /* column list if this is an UPDATE OF trigger */
120358  SrcList *pTableName,/* The name of the table/view the trigger applies to */
120359  Expr *pWhen, /* WHEN clause */
120360  int isTemp, /* True if the TEMPORARY keyword is present */
120361  int noErr /* Suppress errors if the trigger already exists */
120362 ){
120363  Trigger *pTrigger = 0; /* The new trigger */
120364  Table *pTab; /* Table that the trigger fires off of */
120365  char *zName = 0; /* Name of the trigger */
120366  sqlite3 *db = pParse->db; /* The database connection */
120367  int iDb; /* The database to store the trigger in */
120368  Token *pName; /* The unqualified db name */
120369  DbFixer sFix; /* State vector for the DB fixer */
120370 
120371  assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
120372  assert( pName2!=0 );
120373  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
120374  assert( op>0 && op<0xff );
120375  if( isTemp ){
120376  /* If TEMP was specified, then the trigger name may not be qualified. */
120377  if( pName2->n>0 ){
120378  sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
120379  goto trigger_cleanup;
120380  }
120381  iDb = 1;
120382  pName = pName1;
120383  }else{
120384  /* Figure out the db that the trigger will be created in */
120385  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
120386  if( iDb<0 ){
120387  goto trigger_cleanup;
120388  }
120389  }
120390  if( !pTableName || db->mallocFailed ){
120391  goto trigger_cleanup;
120392  }
120393 
120394  /* A long-standing parser bug is that this syntax was allowed:
120395  **
120396  ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
120397  ** ^^^^^^^^
120398  **
120399  ** To maintain backwards compatibility, ignore the database
120400  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
120401  */
120402  if( db->init.busy && iDb!=1 ){
120403  sqlite3DbFree(db, pTableName->a[0].zDatabase);
120404  pTableName->a[0].zDatabase = 0;
120405  }
120406 
120407  /* If the trigger name was unqualified, and the table is a temp table,
120408  ** then set iDb to 1 to create the trigger in the temporary database.
120409  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
120410  ** exist, the error is caught by the block below.
120411  */
120412  pTab = sqlite3SrcListLookup(pParse, pTableName);
120413  if( db->init.busy==0 && pName2->n==0 && pTab
120414  && pTab->pSchema==db->aDb[1].pSchema ){
120415  iDb = 1;
120416  }
120417 
120418  /* Ensure the table name matches database name and that the table exists */
120419  if( db->mallocFailed ) goto trigger_cleanup;
120420  assert( pTableName->nSrc==1 );
120421  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
120422  if( sqlite3FixSrcList(&sFix, pTableName) ){
120423  goto trigger_cleanup;
120424  }
120425  pTab = sqlite3SrcListLookup(pParse, pTableName);
120426  if( !pTab ){
120427  /* The table does not exist. */
120428  if( db->init.iDb==1 ){
120429  /* Ticket #3810.
120430  ** Normally, whenever a table is dropped, all associated triggers are
120431  ** dropped too. But if a TEMP trigger is created on a non-TEMP table
120432  ** and the table is dropped by a different database connection, the
120433  ** trigger is not visible to the database connection that does the
120434  ** drop so the trigger cannot be dropped. This results in an
120435  ** "orphaned trigger" - a trigger whose associated table is missing.
120436  */
120437  db->init.orphanTrigger = 1;
120438  }
120439  goto trigger_cleanup;
120440  }
120441  if( IsVirtual(pTab) ){
120442  sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
120443  goto trigger_cleanup;
120444  }
120445 
120446  /* Check that the trigger name is not reserved and that no trigger of the
120447  ** specified name exists */
120448  zName = sqlite3NameFromToken(db, pName);
120449  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
120450  goto trigger_cleanup;
120451  }
120452  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
120453  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
120454  if( !noErr ){
120455  sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
120456  }else{
120457  assert( !db->init.busy );
120458  sqlite3CodeVerifySchema(pParse, iDb);
120459  }
120460  goto trigger_cleanup;
120461  }
120462 
120463  /* Do not create a trigger on a system table */
120464  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
120465  sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
120466  goto trigger_cleanup;
120467  }
120468 
120469  /* INSTEAD of triggers are only for views and views only support INSTEAD
120470  ** of triggers.
120471  */
120472  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
120473  sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
120474  (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
120475  goto trigger_cleanup;
120476  }
120477  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
120478  sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
120479  " trigger on table: %S", pTableName, 0);
120480  goto trigger_cleanup;
120481  }
120482 
120483 #ifndef SQLITE_OMIT_AUTHORIZATION
120484  {
120485  int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
120486  int code = SQLITE_CREATE_TRIGGER;
120487  const char *zDb = db->aDb[iTabDb].zDbSName;
120488  const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
120489  if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
120490  if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
120491  goto trigger_cleanup;
120492  }
120493  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
120494  goto trigger_cleanup;
120495  }
120496  }
120497 #endif
120498 
120499  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
120500  ** cannot appear on views. So we might as well translate every
120501  ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
120502  ** elsewhere.
120503  */
120504  if (tr_tm == TK_INSTEAD){
120505  tr_tm = TK_BEFORE;
120506  }
120507 
120508  /* Build the Trigger object */
120509  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
120510  if( pTrigger==0 ) goto trigger_cleanup;
120511  pTrigger->zName = zName;
120512  zName = 0;
120513  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
120514  pTrigger->pSchema = db->aDb[iDb].pSchema;
120515  pTrigger->pTabSchema = pTab->pSchema;
120516  pTrigger->op = (u8)op;
120517  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
120518  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
120519  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
120520  assert( pParse->pNewTrigger==0 );
120521  pParse->pNewTrigger = pTrigger;
120522 
120523 trigger_cleanup:
120524  sqlite3DbFree(db, zName);
120525  sqlite3SrcListDelete(db, pTableName);
120526  sqlite3IdListDelete(db, pColumns);
120527  sqlite3ExprDelete(db, pWhen);
120528  if( !pParse->pNewTrigger ){
120529  sqlite3DeleteTrigger(db, pTrigger);
120530  }else{
120531  assert( pParse->pNewTrigger==pTrigger );
120532  }
120533 }
120534 
120535 /*
120536 ** This routine is called after all of the trigger actions have been parsed
120537 ** in order to complete the process of building the trigger.
120538 */
120539 SQLITE_PRIVATE void sqlite3FinishTrigger(
120540  Parse *pParse, /* Parser context */
120541  TriggerStep *pStepList, /* The triggered program */
120542  Token *pAll /* Token that describes the complete CREATE TRIGGER */
120543 ){
120544  Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
120545  char *zName; /* Name of trigger */
120546  sqlite3 *db = pParse->db; /* The database */
120547  DbFixer sFix; /* Fixer object */
120548  int iDb; /* Database containing the trigger */
120549  Token nameToken; /* Trigger name for error reporting */
120550 
120551  pParse->pNewTrigger = 0;
120552  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
120553  zName = pTrig->zName;
120554  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
120555  pTrig->step_list = pStepList;
120556  while( pStepList ){
120557  pStepList->pTrig = pTrig;
120558  pStepList = pStepList->pNext;
120559  }
120560  sqlite3TokenInit(&nameToken, pTrig->zName);
120561  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
120562  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
120563  || sqlite3FixExpr(&sFix, pTrig->pWhen)
120564  ){
120565  goto triggerfinish_cleanup;
120566  }
120567 
120568  /* if we are not initializing,
120569  ** build the sqlite_master entry
120570  */
120571  if( !db->init.busy ){
120572  Vdbe *v;
120573  char *z;
120574 
120575  /* Make an entry in the sqlite_master table */
120576  v = sqlite3GetVdbe(pParse);
120577  if( v==0 ) goto triggerfinish_cleanup;
120578  sqlite3BeginWriteOperation(pParse, 0, iDb);
120579  z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
120580  sqlite3NestedParse(pParse,
120581  "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
120582  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), zName,
120583  pTrig->table, z);
120584  sqlite3DbFree(db, z);
120585  sqlite3ChangeCookie(pParse, iDb);
120586  sqlite3VdbeAddParseSchemaOp(v, iDb,
120587  sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
120588  }
120589 
120590  if( db->init.busy ){
120591  Trigger *pLink = pTrig;
120592  Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
120593  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
120594  pTrig = sqlite3HashInsert(pHash, zName, pTrig);
120595  if( pTrig ){
120596  sqlite3OomFault(db);
120597  }else if( pLink->pSchema==pLink->pTabSchema ){
120598  Table *pTab;
120599  pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
120600  assert( pTab!=0 );
120601  pLink->pNext = pTab->pTrigger;
120602  pTab->pTrigger = pLink;
120603  }
120604  }
120605 
120606 triggerfinish_cleanup:
120607  sqlite3DeleteTrigger(db, pTrig);
120608  assert( !pParse->pNewTrigger );
120609  sqlite3DeleteTriggerStep(db, pStepList);
120610 }
120611 
120612 /*
120613 ** Turn a SELECT statement (that the pSelect parameter points to) into
120614 ** a trigger step. Return a pointer to a TriggerStep structure.
120615 **
120616 ** The parser calls this routine when it finds a SELECT statement in
120617 ** body of a TRIGGER.
120618 */
120619 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
120620  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
120621  if( pTriggerStep==0 ) {
120622  sqlite3SelectDelete(db, pSelect);
120623  return 0;
120624  }
120625  pTriggerStep->op = TK_SELECT;
120626  pTriggerStep->pSelect = pSelect;
120627  pTriggerStep->orconf = OE_Default;
120628  return pTriggerStep;
120629 }
120630 
120631 /*
120632 ** Allocate space to hold a new trigger step. The allocated space
120633 ** holds both the TriggerStep object and the TriggerStep.target.z string.
120634 **
120635 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
120636 */
120637 static TriggerStep *triggerStepAllocate(
120638  sqlite3 *db, /* Database connection */
120639  u8 op, /* Trigger opcode */
120640  Token *pName /* The target name */
120641 ){
120642  TriggerStep *pTriggerStep;
120643 
120644  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
120645  if( pTriggerStep ){
120646  char *z = (char*)&pTriggerStep[1];
120647  memcpy(z, pName->z, pName->n);
120648  sqlite3Dequote(z);
120649  pTriggerStep->zTarget = z;
120650  pTriggerStep->op = op;
120651  }
120652  return pTriggerStep;
120653 }
120654 
120655 /*
120656 ** Build a trigger step out of an INSERT statement. Return a pointer
120657 ** to the new trigger step.
120658 **
120659 ** The parser calls this routine when it sees an INSERT inside the
120660 ** body of a trigger.
120661 */
120662 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
120663  sqlite3 *db, /* The database connection */
120664  Token *pTableName, /* Name of the table into which we insert */
120665  IdList *pColumn, /* List of columns in pTableName to insert into */
120666  Select *pSelect, /* A SELECT statement that supplies values */
120667  u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
120668 ){
120669  TriggerStep *pTriggerStep;
120670 
120671  assert(pSelect != 0 || db->mallocFailed);
120672 
120673  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
120674  if( pTriggerStep ){
120675  pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
120676  pTriggerStep->pIdList = pColumn;
120677  pTriggerStep->orconf = orconf;
120678  }else{
120679  sqlite3IdListDelete(db, pColumn);
120680  }
120681  sqlite3SelectDelete(db, pSelect);
120682 
120683  return pTriggerStep;
120684 }
120685 
120686 /*
120687 ** Construct a trigger step that implements an UPDATE statement and return
120688 ** a pointer to that trigger step. The parser calls this routine when it
120689 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
120690 */
120691 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
120692  sqlite3 *db, /* The database connection */
120693  Token *pTableName, /* Name of the table to be updated */
120694  ExprList *pEList, /* The SET clause: list of column and new values */
120695  Expr *pWhere, /* The WHERE clause */
120696  u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
120697 ){
120698  TriggerStep *pTriggerStep;
120699 
120700  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
120701  if( pTriggerStep ){
120702  pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
120703  pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
120704  pTriggerStep->orconf = orconf;
120705  }
120706  sqlite3ExprListDelete(db, pEList);
120707  sqlite3ExprDelete(db, pWhere);
120708  return pTriggerStep;
120709 }
120710 
120711 /*
120712 ** Construct a trigger step that implements a DELETE statement and return
120713 ** a pointer to that trigger step. The parser calls this routine when it
120714 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
120715 */
120716 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
120717  sqlite3 *db, /* Database connection */
120718  Token *pTableName, /* The table from which rows are deleted */
120719  Expr *pWhere /* The WHERE clause */
120720 ){
120721  TriggerStep *pTriggerStep;
120722 
120723  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
120724  if( pTriggerStep ){
120725  pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
120726  pTriggerStep->orconf = OE_Default;
120727  }
120728  sqlite3ExprDelete(db, pWhere);
120729  return pTriggerStep;
120730 }
120731 
120732 /*
120733 ** Recursively delete a Trigger structure
120734 */
120735 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
120736  if( pTrigger==0 ) return;
120737  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
120738  sqlite3DbFree(db, pTrigger->zName);
120739  sqlite3DbFree(db, pTrigger->table);
120740  sqlite3ExprDelete(db, pTrigger->pWhen);
120741  sqlite3IdListDelete(db, pTrigger->pColumns);
120742  sqlite3DbFree(db, pTrigger);
120743 }
120744 
120745 /*
120746 ** This function is called to drop a trigger from the database schema.
120747 **
120748 ** This may be called directly from the parser and therefore identifies
120749 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
120750 ** same job as this routine except it takes a pointer to the trigger
120751 ** instead of the trigger name.
120752 **/
120753 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
120754  Trigger *pTrigger = 0;
120755  int i;
120756  const char *zDb;
120757  const char *zName;
120758  sqlite3 *db = pParse->db;
120759 
120760  if( db->mallocFailed ) goto drop_trigger_cleanup;
120761  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
120762  goto drop_trigger_cleanup;
120763  }
120764 
120765  assert( pName->nSrc==1 );
120766  zDb = pName->a[0].zDatabase;
120767  zName = pName->a[0].zName;
120768  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
120769  for(i=OMIT_TEMPDB; i<db->nDb; i++){
120770  int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
120771  if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
120772  assert( sqlite3SchemaMutexHeld(db, j, 0) );
120773  pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
120774  if( pTrigger ) break;
120775  }
120776  if( !pTrigger ){
120777  if( !noErr ){
120778  sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
120779  }else{
120780  sqlite3CodeVerifyNamedSchema(pParse, zDb);
120781  }
120782  pParse->checkSchema = 1;
120783  goto drop_trigger_cleanup;
120784  }
120785  sqlite3DropTriggerPtr(pParse, pTrigger);
120786 
120787 drop_trigger_cleanup:
120788  sqlite3SrcListDelete(db, pName);
120789 }
120790 
120791 /*
120792 ** Return a pointer to the Table structure for the table that a trigger
120793 ** is set on.
120794 */
120795 static Table *tableOfTrigger(Trigger *pTrigger){
120796  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
120797 }
120798 
120799 
120800 /*
120801 ** Drop a trigger given a pointer to that trigger.
120802 */
120803 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
120804  Table *pTable;
120805  Vdbe *v;
120806  sqlite3 *db = pParse->db;
120807  int iDb;
120808 
120809  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
120810  assert( iDb>=0 && iDb<db->nDb );
120811  pTable = tableOfTrigger(pTrigger);
120812  assert( pTable );
120813  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
120814 #ifndef SQLITE_OMIT_AUTHORIZATION
120815  {
120816  int code = SQLITE_DROP_TRIGGER;
120817  const char *zDb = db->aDb[iDb].zDbSName;
120818  const char *zTab = SCHEMA_TABLE(iDb);
120819  if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
120820  if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
120821  sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
120822  return;
120823  }
120824  }
120825 #endif
120826 
120827  /* Generate code to destroy the database record of the trigger.
120828  */
120829  assert( pTable!=0 );
120830  if( (v = sqlite3GetVdbe(pParse))!=0 ){
120831  sqlite3NestedParse(pParse,
120832  "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
120833  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pTrigger->zName
120834  );
120835  sqlite3ChangeCookie(pParse, iDb);
120836  sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
120837  }
120838 }
120839 
120840 /*
120841 ** Remove a trigger from the hash tables of the sqlite* pointer.
120842 */
120843 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
120844  Trigger *pTrigger;
120845  Hash *pHash;
120846 
120847  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
120848  pHash = &(db->aDb[iDb].pSchema->trigHash);
120849  pTrigger = sqlite3HashInsert(pHash, zName, 0);
120850  if( ALWAYS(pTrigger) ){
120851  if( pTrigger->pSchema==pTrigger->pTabSchema ){
120852  Table *pTab = tableOfTrigger(pTrigger);
120853  Trigger **pp;
120854  for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
120855  *pp = (*pp)->pNext;
120856  }
120857  sqlite3DeleteTrigger(db, pTrigger);
120858  db->flags |= SQLITE_InternChanges;
120859  }
120860 }
120861 
120862 /*
120863 ** pEList is the SET clause of an UPDATE statement. Each entry
120864 ** in pEList is of the format <id>=<expr>. If any of the entries
120865 ** in pEList have an <id> which matches an identifier in pIdList,
120866 ** then return TRUE. If pIdList==NULL, then it is considered a
120867 ** wildcard that matches anything. Likewise if pEList==NULL then
120868 ** it matches anything so always return true. Return false only
120869 ** if there is no match.
120870 */
120871 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
120872  int e;
120873  if( pIdList==0 || NEVER(pEList==0) ) return 1;
120874  for(e=0; e<pEList->nExpr; e++){
120875  if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
120876  }
120877  return 0;
120878 }
120879 
120880 /*
120881 ** Return a list of all triggers on table pTab if there exists at least
120882 ** one trigger that must be fired when an operation of type 'op' is
120883 ** performed on the table, and, if that operation is an UPDATE, if at
120884 ** least one of the columns in pChanges is being modified.
120885 */
120886 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
120887  Parse *pParse, /* Parse context */
120888  Table *pTab, /* The table the contains the triggers */
120889  int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
120890  ExprList *pChanges, /* Columns that change in an UPDATE statement */
120891  int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120892 ){
120893  int mask = 0;
120894  Trigger *pList = 0;
120895  Trigger *p;
120896 
120897  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
120898  pList = sqlite3TriggerList(pParse, pTab);
120899  }
120900  assert( pList==0 || IsVirtual(pTab)==0 );
120901  for(p=pList; p; p=p->pNext){
120902  if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
120903  mask |= p->tr_tm;
120904  }
120905  }
120906  if( pMask ){
120907  *pMask = mask;
120908  }
120909  return (mask ? pList : 0);
120910 }
120911 
120912 /*
120913 ** Convert the pStep->zTarget string into a SrcList and return a pointer
120914 ** to that SrcList.
120915 **
120916 ** This routine adds a specific database name, if needed, to the target when
120917 ** forming the SrcList. This prevents a trigger in one database from
120918 ** referring to a target in another database. An exception is when the
120919 ** trigger is in TEMP in which case it can refer to any other database it
120920 ** wants.
120921 */
120922 static SrcList *targetSrcList(
120923  Parse *pParse, /* The parsing context */
120924  TriggerStep *pStep /* The trigger containing the target token */
120925 ){
120926  sqlite3 *db = pParse->db;
120927  int iDb; /* Index of the database to use */
120928  SrcList *pSrc; /* SrcList to be returned */
120929 
120930  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
120931  if( pSrc ){
120932  assert( pSrc->nSrc>0 );
120933  pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
120934  iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
120935  if( iDb==0 || iDb>=2 ){
120936  const char *zDb;
120937  assert( iDb<db->nDb );
120938  zDb = db->aDb[iDb].zDbSName;
120939  pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
120940  }
120941  }
120942  return pSrc;
120943 }
120944 
120945 /*
120946 ** Generate VDBE code for the statements inside the body of a single
120947 ** trigger.
120948 */
120949 static int codeTriggerProgram(
120950  Parse *pParse, /* The parser context */
120951  TriggerStep *pStepList, /* List of statements inside the trigger body */
120952  int orconf /* Conflict algorithm. (OE_Abort, etc) */
120953 ){
120954  TriggerStep *pStep;
120955  Vdbe *v = pParse->pVdbe;
120956  sqlite3 *db = pParse->db;
120957 
120958  assert( pParse->pTriggerTab && pParse->pToplevel );
120959  assert( pStepList );
120960  assert( v!=0 );
120961  for(pStep=pStepList; pStep; pStep=pStep->pNext){
120962  /* Figure out the ON CONFLICT policy that will be used for this step
120963  ** of the trigger program. If the statement that caused this trigger
120964  ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
120965  ** the ON CONFLICT policy that was specified as part of the trigger
120966  ** step statement. Example:
120967  **
120968  ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
120969  ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
120970  ** END;
120971  **
120972  ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
120973  ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
120974  */
120975  pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
120976  assert( pParse->okConstFactor==0 );
120977 
120978  switch( pStep->op ){
120979  case TK_UPDATE: {
120980  sqlite3Update(pParse,
120981  targetSrcList(pParse, pStep),
120982  sqlite3ExprListDup(db, pStep->pExprList, 0),
120983  sqlite3ExprDup(db, pStep->pWhere, 0),
120984  pParse->eOrconf
120985  );
120986  break;
120987  }
120988  case TK_INSERT: {
120989  sqlite3Insert(pParse,
120990  targetSrcList(pParse, pStep),
120991  sqlite3SelectDup(db, pStep->pSelect, 0),
120992  sqlite3IdListDup(db, pStep->pIdList),
120993  pParse->eOrconf
120994  );
120995  break;
120996  }
120997  case TK_DELETE: {
120998  sqlite3DeleteFrom(pParse,
120999  targetSrcList(pParse, pStep),
121000  sqlite3ExprDup(db, pStep->pWhere, 0)
121001  );
121002  break;
121003  }
121004  default: assert( pStep->op==TK_SELECT ); {
121005  SelectDest sDest;
121006  Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
121007  sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
121008  sqlite3Select(pParse, pSelect, &sDest);
121009  sqlite3SelectDelete(db, pSelect);
121010  break;
121011  }
121012  }
121013  if( pStep->op!=TK_SELECT ){
121014  sqlite3VdbeAddOp0(v, OP_ResetCount);
121015  }
121016  }
121017 
121018  return 0;
121019 }
121020 
121021 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
121022 /*
121023 ** This function is used to add VdbeComment() annotations to a VDBE
121024 ** program. It is not used in production code, only for debugging.
121025 */
121026 static const char *onErrorText(int onError){
121027  switch( onError ){
121028  case OE_Abort: return "abort";
121029  case OE_Rollback: return "rollback";
121030  case OE_Fail: return "fail";
121031  case OE_Replace: return "replace";
121032  case OE_Ignore: return "ignore";
121033  case OE_Default: return "default";
121034  }
121035  return "n/a";
121036 }
121037 #endif
121038 
121039 /*
121040 ** Parse context structure pFrom has just been used to create a sub-vdbe
121041 ** (trigger program). If an error has occurred, transfer error information
121042 ** from pFrom to pTo.
121043 */
121044 static void transferParseError(Parse *pTo, Parse *pFrom){
121045  assert( pFrom->zErrMsg==0 || pFrom->nErr );
121046  assert( pTo->zErrMsg==0 || pTo->nErr );
121047  if( pTo->nErr==0 ){
121048  pTo->zErrMsg = pFrom->zErrMsg;
121049  pTo->nErr = pFrom->nErr;
121050  pTo->rc = pFrom->rc;
121051  }else{
121052  sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
121053  }
121054 }
121055 
121056 /*
121057 ** Create and populate a new TriggerPrg object with a sub-program
121058 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
121059 */
121060 static TriggerPrg *codeRowTrigger(
121061  Parse *pParse, /* Current parse context */
121062  Trigger *pTrigger, /* Trigger to code */
121063  Table *pTab, /* The table pTrigger is attached to */
121064  int orconf /* ON CONFLICT policy to code trigger program with */
121065 ){
121066  Parse *pTop = sqlite3ParseToplevel(pParse);
121067  sqlite3 *db = pParse->db; /* Database handle */
121068  TriggerPrg *pPrg; /* Value to return */
121069  Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
121070  Vdbe *v; /* Temporary VM */
121071  NameContext sNC; /* Name context for sub-vdbe */
121072  SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
121073  Parse *pSubParse; /* Parse context for sub-vdbe */
121074  int iEndTrigger = 0; /* Label to jump to if WHEN is false */
121075 
121076  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
121077  assert( pTop->pVdbe );
121078 
121079  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
121080  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
121081  ** list of the top-level Parse object sooner rather than later. */
121082  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
121083  if( !pPrg ) return 0;
121084  pPrg->pNext = pTop->pTriggerPrg;
121085  pTop->pTriggerPrg = pPrg;
121086  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
121087  if( !pProgram ) return 0;
121088  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
121089  pPrg->pTrigger = pTrigger;
121090  pPrg->orconf = orconf;
121091  pPrg->aColmask[0] = 0xffffffff;
121092  pPrg->aColmask[1] = 0xffffffff;
121093 
121094  /* Allocate and populate a new Parse context to use for coding the
121095  ** trigger sub-program. */
121096  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
121097  if( !pSubParse ) return 0;
121098  memset(&sNC, 0, sizeof(sNC));
121099  sNC.pParse = pSubParse;
121100  pSubParse->db = db;
121101  pSubParse->pTriggerTab = pTab;
121102  pSubParse->pToplevel = pTop;
121103  pSubParse->zAuthContext = pTrigger->zName;
121104  pSubParse->eTriggerOp = pTrigger->op;
121105  pSubParse->nQueryLoop = pParse->nQueryLoop;
121106 
121107  v = sqlite3GetVdbe(pSubParse);
121108  if( v ){
121109  VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
121110  pTrigger->zName, onErrorText(orconf),
121111  (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
121112  (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
121113  (pTrigger->op==TK_INSERT ? "INSERT" : ""),
121114  (pTrigger->op==TK_DELETE ? "DELETE" : ""),
121115  pTab->zName
121116  ));
121117 #ifndef SQLITE_OMIT_TRACE
121118  sqlite3VdbeChangeP4(v, -1,
121119  sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
121120  );
121121 #endif
121122 
121123  /* If one was specified, code the WHEN clause. If it evaluates to false
121124  ** (or NULL) the sub-vdbe is immediately halted by jumping to the
121125  ** OP_Halt inserted at the end of the program. */
121126  if( pTrigger->pWhen ){
121127  pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
121128  if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
121129  && db->mallocFailed==0
121130  ){
121131  iEndTrigger = sqlite3VdbeMakeLabel(v);
121132  sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
121133  }
121134  sqlite3ExprDelete(db, pWhen);
121135  }
121136 
121137  /* Code the trigger program into the sub-vdbe. */
121138  codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
121139 
121140  /* Insert an OP_Halt at the end of the sub-program. */
121141  if( iEndTrigger ){
121142  sqlite3VdbeResolveLabel(v, iEndTrigger);
121143  }
121144  sqlite3VdbeAddOp0(v, OP_Halt);
121145  VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
121146 
121147  transferParseError(pParse, pSubParse);
121148  if( db->mallocFailed==0 ){
121149  pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
121150  }
121151  pProgram->nMem = pSubParse->nMem;
121152  pProgram->nCsr = pSubParse->nTab;
121153  pProgram->token = (void *)pTrigger;
121154  pPrg->aColmask[0] = pSubParse->oldmask;
121155  pPrg->aColmask[1] = pSubParse->newmask;
121156  sqlite3VdbeDelete(v);
121157  }
121158 
121159  assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
121160  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
121161  sqlite3ParserReset(pSubParse);
121162  sqlite3StackFree(db, pSubParse);
121163 
121164  return pPrg;
121165 }
121166 
121167 /*
121168 ** Return a pointer to a TriggerPrg object containing the sub-program for
121169 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
121170 ** TriggerPrg object exists, a new object is allocated and populated before
121171 ** being returned.
121172 */
121173 static TriggerPrg *getRowTrigger(
121174  Parse *pParse, /* Current parse context */
121175  Trigger *pTrigger, /* Trigger to code */
121176  Table *pTab, /* The table trigger pTrigger is attached to */
121177  int orconf /* ON CONFLICT algorithm. */
121178 ){
121179  Parse *pRoot = sqlite3ParseToplevel(pParse);
121180  TriggerPrg *pPrg;
121181 
121182  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
121183 
121184  /* It may be that this trigger has already been coded (or is in the
121185  ** process of being coded). If this is the case, then an entry with
121186  ** a matching TriggerPrg.pTrigger field will be present somewhere
121187  ** in the Parse.pTriggerPrg list. Search for such an entry. */
121188  for(pPrg=pRoot->pTriggerPrg;
121189  pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
121190  pPrg=pPrg->pNext
121191  );
121192 
121193  /* If an existing TriggerPrg could not be located, create a new one. */
121194  if( !pPrg ){
121195  pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
121196  }
121197 
121198  return pPrg;
121199 }
121200 
121201 /*
121202 ** Generate code for the trigger program associated with trigger p on
121203 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
121204 ** function are the same as those described in the header function for
121205 ** sqlite3CodeRowTrigger()
121206 */
121207 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
121208  Parse *pParse, /* Parse context */
121209  Trigger *p, /* Trigger to code */
121210  Table *pTab, /* The table to code triggers from */
121211  int reg, /* Reg array containing OLD.* and NEW.* values */
121212  int orconf, /* ON CONFLICT policy */
121213  int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
121214 ){
121215  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
121216  TriggerPrg *pPrg;
121217  pPrg = getRowTrigger(pParse, p, pTab, orconf);
121218  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
121219 
121220  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
121221  ** is a pointer to the sub-vdbe containing the trigger program. */
121222  if( pPrg ){
121223  int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
121224 
121225  sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
121226  (const char *)pPrg->pProgram, P4_SUBPROGRAM);
121227  VdbeComment(
121228  (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
121229 
121230  /* Set the P5 operand of the OP_Program instruction to non-zero if
121231  ** recursive invocation of this trigger program is disallowed. Recursive
121232  ** invocation is disallowed if (a) the sub-program is really a trigger,
121233  ** not a foreign key action, and (b) the flag to enable recursive triggers
121234  ** is clear. */
121235  sqlite3VdbeChangeP5(v, (u8)bRecursive);
121236  }
121237 }
121238 
121239 /*
121240 ** This is called to code the required FOR EACH ROW triggers for an operation
121241 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
121242 ** is given by the op parameter. The tr_tm parameter determines whether the
121243 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
121244 ** parameter pChanges is passed the list of columns being modified.
121245 **
121246 ** If there are no triggers that fire at the specified time for the specified
121247 ** operation on pTab, this function is a no-op.
121248 **
121249 ** The reg argument is the address of the first in an array of registers
121250 ** that contain the values substituted for the new.* and old.* references
121251 ** in the trigger program. If N is the number of columns in table pTab
121252 ** (a copy of pTab->nCol), then registers are populated as follows:
121253 **
121254 ** Register Contains
121255 ** ------------------------------------------------------
121256 ** reg+0 OLD.rowid
121257 ** reg+1 OLD.* value of left-most column of pTab
121258 ** ... ...
121259 ** reg+N OLD.* value of right-most column of pTab
121260 ** reg+N+1 NEW.rowid
121261 ** reg+N+2 OLD.* value of left-most column of pTab
121262 ** ... ...
121263 ** reg+N+N+1 NEW.* value of right-most column of pTab
121264 **
121265 ** For ON DELETE triggers, the registers containing the NEW.* values will
121266 ** never be accessed by the trigger program, so they are not allocated or
121267 ** populated by the caller (there is no data to populate them with anyway).
121268 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
121269 ** are never accessed, and so are not allocated by the caller. So, for an
121270 ** ON INSERT trigger, the value passed to this function as parameter reg
121271 ** is not a readable register, although registers (reg+N) through
121272 ** (reg+N+N+1) are.
121273 **
121274 ** Parameter orconf is the default conflict resolution algorithm for the
121275 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
121276 ** is the instruction that control should jump to if a trigger program
121277 ** raises an IGNORE exception.
121278 */
121279 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
121280  Parse *pParse, /* Parse context */
121281  Trigger *pTrigger, /* List of triggers on table pTab */
121282  int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
121283  ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
121284  int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
121285  Table *pTab, /* The table to code triggers from */
121286  int reg, /* The first in an array of registers (see above) */
121287  int orconf, /* ON CONFLICT policy */
121288  int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
121289 ){
121290  Trigger *p; /* Used to iterate through pTrigger list */
121291 
121292  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
121293  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
121294  assert( (op==TK_UPDATE)==(pChanges!=0) );
121295 
121296  for(p=pTrigger; p; p=p->pNext){
121297 
121298  /* Sanity checking: The schema for the trigger and for the table are
121299  ** always defined. The trigger must be in the same schema as the table
121300  ** or else it must be a TEMP trigger. */
121301  assert( p->pSchema!=0 );
121302  assert( p->pTabSchema!=0 );
121303  assert( p->pSchema==p->pTabSchema
121304  || p->pSchema==pParse->db->aDb[1].pSchema );
121305 
121306  /* Determine whether we should code this trigger */
121307  if( p->op==op
121308  && p->tr_tm==tr_tm
121309  && checkColumnOverlap(p->pColumns, pChanges)
121310  ){
121311  sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
121312  }
121313  }
121314 }
121315 
121316 /*
121317 ** Triggers may access values stored in the old.* or new.* pseudo-table.
121318 ** This function returns a 32-bit bitmask indicating which columns of the
121319 ** old.* or new.* tables actually are used by triggers. This information
121320 ** may be used by the caller, for example, to avoid having to load the entire
121321 ** old.* record into memory when executing an UPDATE or DELETE command.
121322 **
121323 ** Bit 0 of the returned mask is set if the left-most column of the
121324 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
121325 ** the second leftmost column value is required, and so on. If there
121326 ** are more than 32 columns in the table, and at least one of the columns
121327 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
121328 **
121329 ** It is not possible to determine if the old.rowid or new.rowid column is
121330 ** accessed by triggers. The caller must always assume that it is.
121331 **
121332 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
121333 ** applies to the old.* table. If 1, the new.* table.
121334 **
121335 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
121336 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
121337 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
121338 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
121339 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
121340 */
121341 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
121342  Parse *pParse, /* Parse context */
121343  Trigger *pTrigger, /* List of triggers on table pTab */
121344  ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
121345  int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
121346  int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
121347  Table *pTab, /* The table to code triggers from */
121348  int orconf /* Default ON CONFLICT policy for trigger steps */
121349 ){
121350  const int op = pChanges ? TK_UPDATE : TK_DELETE;
121351  u32 mask = 0;
121352  Trigger *p;
121353 
121354  assert( isNew==1 || isNew==0 );
121355  for(p=pTrigger; p; p=p->pNext){
121356  if( p->op==op && (tr_tm&p->tr_tm)
121357  && checkColumnOverlap(p->pColumns,pChanges)
121358  ){
121359  TriggerPrg *pPrg;
121360  pPrg = getRowTrigger(pParse, p, pTab, orconf);
121361  if( pPrg ){
121362  mask |= pPrg->aColmask[isNew];
121363  }
121364  }
121365  }
121366 
121367  return mask;
121368 }
121369 
121370 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
121371 
121372 /************** End of trigger.c *********************************************/
121373 /************** Begin file update.c ******************************************/
121374 /*
121375 ** 2001 September 15
121376 **
121377 ** The author disclaims copyright to this source code. In place of
121378 ** a legal notice, here is a blessing:
121379 **
121380 ** May you do good and not evil.
121381 ** May you find forgiveness for yourself and forgive others.
121382 ** May you share freely, never taking more than you give.
121383 **
121384 *************************************************************************
121385 ** This file contains C code routines that are called by the parser
121386 ** to handle UPDATE statements.
121387 */
121388 /* #include "sqliteInt.h" */
121389 
121390 #ifndef SQLITE_OMIT_VIRTUALTABLE
121391 /* Forward declaration */
121392 static void updateVirtualTable(
121393  Parse *pParse, /* The parsing context */
121394  SrcList *pSrc, /* The virtual table to be modified */
121395  Table *pTab, /* The virtual table */
121396  ExprList *pChanges, /* The columns to change in the UPDATE statement */
121397  Expr *pRowidExpr, /* Expression used to recompute the rowid */
121398  int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
121399  Expr *pWhere, /* WHERE clause of the UPDATE statement */
121400  int onError /* ON CONFLICT strategy */
121401 );
121402 #endif /* SQLITE_OMIT_VIRTUALTABLE */
121403 
121404 /*
121405 ** The most recently coded instruction was an OP_Column to retrieve the
121406 ** i-th column of table pTab. This routine sets the P4 parameter of the
121407 ** OP_Column to the default value, if any.
121408 **
121409 ** The default value of a column is specified by a DEFAULT clause in the
121410 ** column definition. This was either supplied by the user when the table
121411 ** was created, or added later to the table definition by an ALTER TABLE
121412 ** command. If the latter, then the row-records in the table btree on disk
121413 ** may not contain a value for the column and the default value, taken
121414 ** from the P4 parameter of the OP_Column instruction, is returned instead.
121415 ** If the former, then all row-records are guaranteed to include a value
121416 ** for the column and the P4 value is not required.
121417 **
121418 ** Column definitions created by an ALTER TABLE command may only have
121419 ** literal default values specified: a number, null or a string. (If a more
121420 ** complicated default expression value was provided, it is evaluated
121421 ** when the ALTER TABLE is executed and one of the literal values written
121422 ** into the sqlite_master table.)
121423 **
121424 ** Therefore, the P4 parameter is only required if the default value for
121425 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
121426 ** function is capable of transforming these types of expressions into
121427 ** sqlite3_value objects.
121428 **
121429 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
121430 ** on register iReg. This is used when an equivalent integer value is
121431 ** stored in place of an 8-byte floating point value in order to save
121432 ** space.
121433 */
121434 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
121435  assert( pTab!=0 );
121436  if( !pTab->pSelect ){
121437  sqlite3_value *pValue = 0;
121438  u8 enc = ENC(sqlite3VdbeDb(v));
121439  Column *pCol = &pTab->aCol[i];
121440  VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
121441  assert( i<pTab->nCol );
121442  sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
121443  pCol->affinity, &pValue);
121444  if( pValue ){
121445  sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
121446  }
121447 #ifndef SQLITE_OMIT_FLOATING_POINT
121448  if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
121449  sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
121450  }
121451 #endif
121452  }
121453 }
121454 
121455 /*
121456 ** Process an UPDATE statement.
121457 **
121458 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
121459 ** \_______/ \________/ \______/ \________________/
121460 * onError pTabList pChanges pWhere
121461 */
121462 SQLITE_PRIVATE void sqlite3Update(
121463  Parse *pParse, /* The parser context */
121464  SrcList *pTabList, /* The table in which we should change things */
121465  ExprList *pChanges, /* Things to be changed */
121466  Expr *pWhere, /* The WHERE clause. May be null */
121467  int onError /* How to handle constraint errors */
121468 ){
121469  int i, j; /* Loop counters */
121470  Table *pTab; /* The table to be updated */
121471  int addrTop = 0; /* VDBE instruction address of the start of the loop */
121472  WhereInfo *pWInfo; /* Information about the WHERE clause */
121473  Vdbe *v; /* The virtual database engine */
121474  Index *pIdx; /* For looping over indices */
121475  Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
121476  int nIdx; /* Number of indices that need updating */
121477  int iBaseCur; /* Base cursor number */
121478  int iDataCur; /* Cursor for the canonical data btree */
121479  int iIdxCur; /* Cursor for the first index */
121480  sqlite3 *db; /* The database structure */
121481  int *aRegIdx = 0; /* One register assigned to each index to be updated */
121482  int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
121483  ** an expression for the i-th column of the table.
121484  ** aXRef[i]==-1 if the i-th column is not changed. */
121485  u8 *aToOpen; /* 1 for tables and indices to be opened */
121486  u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
121487  u8 chngRowid; /* Rowid changed in a normal table */
121488  u8 chngKey; /* Either chngPk or chngRowid */
121489  Expr *pRowidExpr = 0; /* Expression defining the new record number */
121490  AuthContext sContext; /* The authorization context */
121491  NameContext sNC; /* The name-context to resolve expressions in */
121492  int iDb; /* Database containing the table being updated */
121493  int okOnePass; /* True for one-pass algorithm without the FIFO */
121494  int hasFK; /* True if foreign key processing is required */
121495  int labelBreak; /* Jump here to break out of UPDATE loop */
121496  int labelContinue; /* Jump here to continue next step of UPDATE loop */
121497 
121498 #ifndef SQLITE_OMIT_TRIGGER
121499  int isView; /* True when updating a view (INSTEAD OF trigger) */
121500  Trigger *pTrigger; /* List of triggers on pTab, if required */
121501  int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
121502 #endif
121503  int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
121504  int iEph = 0; /* Ephemeral table holding all primary key values */
121505  int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
121506  int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
121507 
121508  /* Register Allocations */
121509  int regRowCount = 0; /* A count of rows changed */
121510  int regOldRowid = 0; /* The old rowid */
121511  int regNewRowid = 0; /* The new rowid */
121512  int regNew = 0; /* Content of the NEW.* table in triggers */
121513  int regOld = 0; /* Content of OLD.* table in triggers */
121514  int regRowSet = 0; /* Rowset of rows to be updated */
121515  int regKey = 0; /* composite PRIMARY KEY value */
121516 
121517  memset(&sContext, 0, sizeof(sContext));
121518  db = pParse->db;
121519  if( pParse->nErr || db->mallocFailed ){
121520  goto update_cleanup;
121521  }
121522  assert( pTabList->nSrc==1 );
121523 
121524  /* Locate the table which we want to update.
121525  */
121526  pTab = sqlite3SrcListLookup(pParse, pTabList);
121527  if( pTab==0 ) goto update_cleanup;
121528  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
121529 
121530  /* Figure out if we have any triggers and if the table being
121531  ** updated is a view.
121532  */
121533 #ifndef SQLITE_OMIT_TRIGGER
121534  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
121535  isView = pTab->pSelect!=0;
121536  assert( pTrigger || tmask==0 );
121537 #else
121538 # define pTrigger 0
121539 # define isView 0
121540 # define tmask 0
121541 #endif
121542 #ifdef SQLITE_OMIT_VIEW
121543 # undef isView
121544 # define isView 0
121545 #endif
121546 
121547  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
121548  goto update_cleanup;
121549  }
121550  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
121551  goto update_cleanup;
121552  }
121553 
121554  /* Allocate a cursors for the main database table and for all indices.
121555  ** The index cursors might not be used, but if they are used they
121556  ** need to occur right after the database cursor. So go ahead and
121557  ** allocate enough space, just in case.
121558  */
121559  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
121560  iIdxCur = iDataCur+1;
121561  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
121562  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
121563  if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
121564  iDataCur = pParse->nTab;
121565  pTabList->a[0].iCursor = iDataCur;
121566  }
121567  pParse->nTab++;
121568  }
121569 
121570  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
121571  ** Initialize aXRef[] and aToOpen[] to their default values.
121572  */
121573  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
121574  if( aXRef==0 ) goto update_cleanup;
121575  aRegIdx = aXRef+pTab->nCol;
121576  aToOpen = (u8*)(aRegIdx+nIdx);
121577  memset(aToOpen, 1, nIdx+1);
121578  aToOpen[nIdx+1] = 0;
121579  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
121580 
121581  /* Initialize the name-context */
121582  memset(&sNC, 0, sizeof(sNC));
121583  sNC.pParse = pParse;
121584  sNC.pSrcList = pTabList;
121585 
121586  /* Resolve the column names in all the expressions of the
121587  ** of the UPDATE statement. Also find the column index
121588  ** for each column to be updated in the pChanges array. For each
121589  ** column to be updated, make sure we have authorization to change
121590  ** that column.
121591  */
121592  chngRowid = chngPk = 0;
121593  for(i=0; i<pChanges->nExpr; i++){
121594  if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
121595  goto update_cleanup;
121596  }
121597  for(j=0; j<pTab->nCol; j++){
121598  if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
121599  if( j==pTab->iPKey ){
121600  chngRowid = 1;
121601  pRowidExpr = pChanges->a[i].pExpr;
121602  }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
121603  chngPk = 1;
121604  }
121605  aXRef[j] = i;
121606  break;
121607  }
121608  }
121609  if( j>=pTab->nCol ){
121610  if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
121611  j = -1;
121612  chngRowid = 1;
121613  pRowidExpr = pChanges->a[i].pExpr;
121614  }else{
121615  sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
121616  pParse->checkSchema = 1;
121617  goto update_cleanup;
121618  }
121619  }
121620 #ifndef SQLITE_OMIT_AUTHORIZATION
121621  {
121622  int rc;
121623  rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
121624  j<0 ? "ROWID" : pTab->aCol[j].zName,
121625  db->aDb[iDb].zDbSName);
121626  if( rc==SQLITE_DENY ){
121627  goto update_cleanup;
121628  }else if( rc==SQLITE_IGNORE ){
121629  aXRef[j] = -1;
121630  }
121631  }
121632 #endif
121633  }
121634  assert( (chngRowid & chngPk)==0 );
121635  assert( chngRowid==0 || chngRowid==1 );
121636  assert( chngPk==0 || chngPk==1 );
121637  chngKey = chngRowid + chngPk;
121638 
121639  /* The SET expressions are not actually used inside the WHERE loop.
121640  ** So reset the colUsed mask. Unless this is a virtual table. In that
121641  ** case, set all bits of the colUsed mask (to ensure that the virtual
121642  ** table implementation makes all columns available).
121643  */
121644  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
121645 
121646  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
121647 
121648  /* There is one entry in the aRegIdx[] array for each index on the table
121649  ** being updated. Fill in aRegIdx[] with a register number that will hold
121650  ** the key for accessing each index.
121651  **
121652  ** FIXME: Be smarter about omitting indexes that use expressions.
121653  */
121654  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
121655  int reg;
121656  if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
121657  reg = ++pParse->nMem;
121658  }else{
121659  reg = 0;
121660  for(i=0; i<pIdx->nKeyCol; i++){
121661  i16 iIdxCol = pIdx->aiColumn[i];
121662  if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
121663  reg = ++pParse->nMem;
121664  break;
121665  }
121666  }
121667  }
121668  if( reg==0 ) aToOpen[j+1] = 0;
121669  aRegIdx[j] = reg;
121670  }
121671 
121672  /* Begin generating code. */
121673  v = sqlite3GetVdbe(pParse);
121674  if( v==0 ) goto update_cleanup;
121675  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
121676  sqlite3BeginWriteOperation(pParse, 1, iDb);
121677 
121678  /* Allocate required registers. */
121679  if( !IsVirtual(pTab) ){
121680  regRowSet = ++pParse->nMem;
121681  regOldRowid = regNewRowid = ++pParse->nMem;
121682  if( chngPk || pTrigger || hasFK ){
121683  regOld = pParse->nMem + 1;
121684  pParse->nMem += pTab->nCol;
121685  }
121686  if( chngKey || pTrigger || hasFK ){
121687  regNewRowid = ++pParse->nMem;
121688  }
121689  regNew = pParse->nMem + 1;
121690  pParse->nMem += pTab->nCol;
121691  }
121692 
121693  /* Start the view context. */
121694  if( isView ){
121695  sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
121696  }
121697 
121698  /* If we are trying to update a view, realize that view into
121699  ** an ephemeral table.
121700  */
121701 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
121702  if( isView ){
121703  sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
121704  }
121705 #endif
121706 
121707  /* Resolve the column names in all the expressions in the
121708  ** WHERE clause.
121709  */
121710  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
121711  goto update_cleanup;
121712  }
121713 
121714 #ifndef SQLITE_OMIT_VIRTUALTABLE
121715  /* Virtual tables must be handled separately */
121716  if( IsVirtual(pTab) ){
121717  updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
121718  pWhere, onError);
121719  goto update_cleanup;
121720  }
121721 #endif
121722 
121723  /* Begin the database scan
121724  */
121725  if( HasRowid(pTab) ){
121726  sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
121727  pWInfo = sqlite3WhereBegin(
121728  pParse, pTabList, pWhere, 0, 0,
121729  WHERE_ONEPASS_DESIRED | WHERE_SEEK_TABLE, iIdxCur
121730  );
121731  if( pWInfo==0 ) goto update_cleanup;
121732  okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
121733 
121734  /* Remember the rowid of every item to be updated.
121735  */
121736  sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
121737  if( !okOnePass ){
121738  sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
121739  }
121740 
121741  /* End the database scan loop.
121742  */
121743  sqlite3WhereEnd(pWInfo);
121744  }else{
121745  int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
121746  i16 nPk; /* Number of components of the PRIMARY KEY */
121747  int addrOpen; /* Address of the OpenEphemeral instruction */
121748 
121749  assert( pPk!=0 );
121750  nPk = pPk->nKeyCol;
121751  iPk = pParse->nMem+1;
121752  pParse->nMem += nPk;
121753  regKey = ++pParse->nMem;
121754  iEph = pParse->nTab++;
121755  sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
121756  addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
121757  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
121758  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
121759  WHERE_ONEPASS_DESIRED, iIdxCur);
121760  if( pWInfo==0 ) goto update_cleanup;
121761  okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
121762  for(i=0; i<nPk; i++){
121763  assert( pPk->aiColumn[i]>=0 );
121764  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
121765  iPk+i);
121766  }
121767  if( okOnePass ){
121768  sqlite3VdbeChangeToNoop(v, addrOpen);
121769  nKey = nPk;
121770  regKey = iPk;
121771  }else{
121772  sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
121773  sqlite3IndexAffinityStr(db, pPk), nPk);
121774  sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
121775  }
121776  sqlite3WhereEnd(pWInfo);
121777  }
121778 
121779  /* Initialize the count of updated rows
121780  */
121781  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
121782  regRowCount = ++pParse->nMem;
121783  sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
121784  }
121785 
121786  labelBreak = sqlite3VdbeMakeLabel(v);
121787  if( !isView ){
121788  /*
121789  ** Open every index that needs updating. Note that if any
121790  ** index could potentially invoke a REPLACE conflict resolution
121791  ** action, then we need to open all indices because we might need
121792  ** to be deleting some records.
121793  */
121794  if( onError==OE_Replace ){
121795  memset(aToOpen, 1, nIdx+1);
121796  }else{
121797  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
121798  if( pIdx->onError==OE_Replace ){
121799  memset(aToOpen, 1, nIdx+1);
121800  break;
121801  }
121802  }
121803  }
121804  if( okOnePass ){
121805  if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
121806  if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
121807  }
121808  sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
121809  0, 0);
121810  }
121811 
121812  /* Top of the update loop */
121813  if( okOnePass ){
121814  if( aToOpen[iDataCur-iBaseCur] && !isView ){
121815  assert( pPk );
121816  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
121817  VdbeCoverageNeverTaken(v);
121818  }
121819  labelContinue = labelBreak;
121820  sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
121821  VdbeCoverageIf(v, pPk==0);
121822  VdbeCoverageIf(v, pPk!=0);
121823  }else if( pPk ){
121824  labelContinue = sqlite3VdbeMakeLabel(v);
121825  sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
121826  addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
121827  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
121828  VdbeCoverage(v);
121829  }else{
121830  labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
121831  regOldRowid);
121832  VdbeCoverage(v);
121833  sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
121834  VdbeCoverage(v);
121835  }
121836 
121837  /* If the record number will change, set register regNewRowid to
121838  ** contain the new value. If the record number is not being modified,
121839  ** then regNewRowid is the same register as regOldRowid, which is
121840  ** already populated. */
121841  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
121842  if( chngRowid ){
121843  sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
121844  sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
121845  }
121846 
121847  /* Compute the old pre-UPDATE content of the row being changed, if that
121848  ** information is needed */
121849  if( chngPk || hasFK || pTrigger ){
121850  u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
121851  oldmask |= sqlite3TriggerColmask(pParse,
121852  pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
121853  );
121854  for(i=0; i<pTab->nCol; i++){
121855  if( oldmask==0xffffffff
121856  || (i<32 && (oldmask & MASKBIT32(i))!=0)
121857  || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
121858  ){
121859  testcase( oldmask!=0xffffffff && i==31 );
121860  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
121861  }else{
121862  sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
121863  }
121864  }
121865  if( chngRowid==0 && pPk==0 ){
121866  sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
121867  }
121868  }
121869 
121870  /* Populate the array of registers beginning at regNew with the new
121871  ** row data. This array is used to check constants, create the new
121872  ** table and index records, and as the values for any new.* references
121873  ** made by triggers.
121874  **
121875  ** If there are one or more BEFORE triggers, then do not populate the
121876  ** registers associated with columns that are (a) not modified by
121877  ** this UPDATE statement and (b) not accessed by new.* references. The
121878  ** values for registers not modified by the UPDATE must be reloaded from
121879  ** the database after the BEFORE triggers are fired anyway (as the trigger
121880  ** may have modified them). So not loading those that are not going to
121881  ** be used eliminates some redundant opcodes.
121882  */
121883  newmask = sqlite3TriggerColmask(
121884  pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
121885  );
121886  for(i=0; i<pTab->nCol; i++){
121887  if( i==pTab->iPKey ){
121888  sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
121889  }else{
121890  j = aXRef[i];
121891  if( j>=0 ){
121892  sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
121893  }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
121894  /* This branch loads the value of a column that will not be changed
121895  ** into a register. This is done if there are no BEFORE triggers, or
121896  ** if there are one or more BEFORE triggers that use this value via
121897  ** a new.* reference in a trigger program.
121898  */
121899  testcase( i==31 );
121900  testcase( i==32 );
121901  sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
121902  }else{
121903  sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
121904  }
121905  }
121906  }
121907 
121908  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
121909  ** verified. One could argue that this is wrong.
121910  */
121911  if( tmask&TRIGGER_BEFORE ){
121912  sqlite3TableAffinity(v, pTab, regNew);
121913  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
121914  TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
121915 
121916  /* The row-trigger may have deleted the row being updated. In this
121917  ** case, jump to the next row. No updates or AFTER triggers are
121918  ** required. This behavior - what happens when the row being updated
121919  ** is deleted or renamed by a BEFORE trigger - is left undefined in the
121920  ** documentation.
121921  */
121922  if( pPk ){
121923  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
121924  VdbeCoverage(v);
121925  }else{
121926  sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
121927  VdbeCoverage(v);
121928  }
121929 
121930  /* If it did not delete it, the row-trigger may still have modified
121931  ** some of the columns of the row being updated. Load the values for
121932  ** all columns not modified by the update statement into their
121933  ** registers in case this has happened.
121934  */
121935  for(i=0; i<pTab->nCol; i++){
121936  if( aXRef[i]<0 && i!=pTab->iPKey ){
121937  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
121938  }
121939  }
121940  }
121941 
121942  if( !isView ){
121943  int addr1 = 0; /* Address of jump instruction */
121944  int bReplace = 0; /* True if REPLACE conflict resolution might happen */
121945 
121946  /* Do constraint checks. */
121947  assert( regOldRowid>0 );
121948  sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
121949  regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
121950  aXRef);
121951 
121952  /* Do FK constraint checks. */
121953  if( hasFK ){
121954  sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
121955  }
121956 
121957  /* Delete the index entries associated with the current record. */
121958  if( bReplace || chngKey ){
121959  if( pPk ){
121960  addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
121961  }else{
121962  addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
121963  }
121964  VdbeCoverageNeverTaken(v);
121965  }
121966  sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
121967 
121968  /* If changing the rowid value, or if there are foreign key constraints
121969  ** to process, delete the old record. Otherwise, add a noop OP_Delete
121970  ** to invoke the pre-update hook.
121971  **
121972  ** That (regNew==regnewRowid+1) is true is also important for the
121973  ** pre-update hook. If the caller invokes preupdate_new(), the returned
121974  ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
121975  ** is the column index supplied by the user.
121976  */
121977  assert( regNew==regNewRowid+1 );
121978 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
121979  sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
121980  OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP),
121981  regNewRowid
121982  );
121983  if( !pParse->nested ){
121984  sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
121985  }
121986 #else
121987  if( hasFK || chngKey || pPk!=0 ){
121988  sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
121989  }
121990 #endif
121991  if( bReplace || chngKey ){
121992  sqlite3VdbeJumpHere(v, addr1);
121993  }
121994 
121995  if( hasFK ){
121996  sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
121997  }
121998 
121999  /* Insert the new index entries and the new record. */
122000  sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
122001  regNewRowid, aRegIdx, 1, 0, 0);
122002 
122003  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
122004  ** handle rows (possibly in other tables) that refer via a foreign key
122005  ** to the row just updated. */
122006  if( hasFK ){
122007  sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
122008  }
122009  }
122010 
122011  /* Increment the row counter
122012  */
122013  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
122014  sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
122015  }
122016 
122017  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
122018  TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
122019 
122020  /* Repeat the above with the next record to be updated, until
122021  ** all record selected by the WHERE clause have been updated.
122022  */
122023  if( okOnePass ){
122024  /* Nothing to do at end-of-loop for a single-pass */
122025  }else if( pPk ){
122026  sqlite3VdbeResolveLabel(v, labelContinue);
122027  sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
122028  }else{
122029  sqlite3VdbeGoto(v, labelContinue);
122030  }
122031  sqlite3VdbeResolveLabel(v, labelBreak);
122032 
122033  /* Close all tables */
122034  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
122035  assert( aRegIdx );
122036  if( aToOpen[i+1] ){
122037  sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
122038  }
122039  }
122040  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
122041 
122042  /* Update the sqlite_sequence table by storing the content of the
122043  ** maximum rowid counter values recorded while inserting into
122044  ** autoincrement tables.
122045  */
122046  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
122047  sqlite3AutoincrementEnd(pParse);
122048  }
122049 
122050  /*
122051  ** Return the number of rows that were changed. If this routine is
122052  ** generating code because of a call to sqlite3NestedParse(), do not
122053  ** invoke the callback function.
122054  */
122055  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
122056  sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
122057  sqlite3VdbeSetNumCols(v, 1);
122058  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
122059  }
122060 
122061 update_cleanup:
122062  sqlite3AuthContextPop(&sContext);
122063  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
122064  sqlite3SrcListDelete(db, pTabList);
122065  sqlite3ExprListDelete(db, pChanges);
122066  sqlite3ExprDelete(db, pWhere);
122067  return;
122068 }
122069 /* Make sure "isView" and other macros defined above are undefined. Otherwise
122070 ** they may interfere with compilation of other functions in this file
122071 ** (or in another file, if this file becomes part of the amalgamation). */
122072 #ifdef isView
122073  #undef isView
122074 #endif
122075 #ifdef pTrigger
122076  #undef pTrigger
122077 #endif
122078 
122079 #ifndef SQLITE_OMIT_VIRTUALTABLE
122080 /*
122081 ** Generate code for an UPDATE of a virtual table.
122082 **
122083 ** There are two possible strategies - the default and the special
122084 ** "onepass" strategy. Onepass is only used if the virtual table
122085 ** implementation indicates that pWhere may match at most one row.
122086 **
122087 ** The default strategy is to create an ephemeral table that contains
122088 ** for each row to be changed:
122089 **
122090 ** (A) The original rowid of that row.
122091 ** (B) The revised rowid for the row.
122092 ** (C) The content of every column in the row.
122093 **
122094 ** Then loop through the contents of this ephemeral table executing a
122095 ** VUpdate for each row. When finished, drop the ephemeral table.
122096 **
122097 ** The "onepass" strategy does not use an ephemeral table. Instead, it
122098 ** stores the same values (A, B and C above) in a register array and
122099 ** makes a single invocation of VUpdate.
122100 */
122101 static void updateVirtualTable(
122102  Parse *pParse, /* The parsing context */
122103  SrcList *pSrc, /* The virtual table to be modified */
122104  Table *pTab, /* The virtual table */
122105  ExprList *pChanges, /* The columns to change in the UPDATE statement */
122106  Expr *pRowid, /* Expression used to recompute the rowid */
122107  int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
122108  Expr *pWhere, /* WHERE clause of the UPDATE statement */
122109  int onError /* ON CONFLICT strategy */
122110 ){
122111  Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
122112  int ephemTab; /* Table holding the result of the SELECT */
122113  int i; /* Loop counter */
122114  sqlite3 *db = pParse->db; /* Database connection */
122115  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
122116  WhereInfo *pWInfo;
122117  int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
122118  int regArg; /* First register in VUpdate arg array */
122119  int regRec; /* Register in which to assemble record */
122120  int regRowid; /* Register for ephem table rowid */
122121  int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
122122  int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
122123  int bOnePass; /* True to use onepass strategy */
122124  int addr; /* Address of OP_OpenEphemeral */
122125 
122126  /* Allocate nArg registers to martial the arguments to VUpdate. Then
122127  ** create and open the ephemeral table in which the records created from
122128  ** these arguments will be temporarily stored. */
122129  assert( v );
122130  ephemTab = pParse->nTab++;
122131  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
122132  regArg = pParse->nMem + 1;
122133  pParse->nMem += nArg;
122134  regRec = ++pParse->nMem;
122135  regRowid = ++pParse->nMem;
122136 
122137  /* Start scanning the virtual table */
122138  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
122139  if( pWInfo==0 ) return;
122140 
122141  /* Populate the argument registers. */
122142  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
122143  if( pRowid ){
122144  sqlite3ExprCode(pParse, pRowid, regArg+1);
122145  }else{
122146  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
122147  }
122148  for(i=0; i<pTab->nCol; i++){
122149  if( aXRef[i]>=0 ){
122150  sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
122151  }else{
122152  sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
122153  }
122154  }
122155 
122156  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
122157 
122158  if( bOnePass ){
122159  /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
122160  ** above. Also, if this is a top-level parse (not a trigger), clear the
122161  ** multi-write flag so that the VM does not open a statement journal */
122162  sqlite3VdbeChangeToNoop(v, addr);
122163  if( sqlite3IsToplevel(pParse) ){
122164  pParse->isMultiWrite = 0;
122165  }
122166  }else{
122167  /* Create a record from the argument register contents and insert it into
122168  ** the ephemeral table. */
122169  sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
122170  sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
122171  sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
122172  }
122173 
122174 
122175  if( bOnePass==0 ){
122176  /* End the virtual table scan */
122177  sqlite3WhereEnd(pWInfo);
122178 
122179  /* Begin scannning through the ephemeral table. */
122180  addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
122181 
122182  /* Extract arguments from the current row of the ephemeral table and
122183  ** invoke the VUpdate method. */
122184  for(i=0; i<nArg; i++){
122185  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
122186  }
122187  }
122188  sqlite3VtabMakeWritable(pParse, pTab);
122189  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
122190  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
122191  sqlite3MayAbort(pParse);
122192 
122193  /* End of the ephemeral table scan. Or, if using the onepass strategy,
122194  ** jump to here if the scan visited zero rows. */
122195  if( bOnePass==0 ){
122196  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
122197  sqlite3VdbeJumpHere(v, addr);
122198  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
122199  }else{
122200  sqlite3WhereEnd(pWInfo);
122201  }
122202 }
122203 #endif /* SQLITE_OMIT_VIRTUALTABLE */
122204 
122205 /************** End of update.c **********************************************/
122206 /************** Begin file vacuum.c ******************************************/
122207 /*
122208 ** 2003 April 6
122209 **
122210 ** The author disclaims copyright to this source code. In place of
122211 ** a legal notice, here is a blessing:
122212 **
122213 ** May you do good and not evil.
122214 ** May you find forgiveness for yourself and forgive others.
122215 ** May you share freely, never taking more than you give.
122216 **
122217 *************************************************************************
122218 ** This file contains code used to implement the VACUUM command.
122219 **
122220 ** Most of the code in this file may be omitted by defining the
122221 ** SQLITE_OMIT_VACUUM macro.
122222 */
122223 /* #include "sqliteInt.h" */
122224 /* #include "vdbeInt.h" */
122225 
122226 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
122227 
122228 /*
122229 ** Execute zSql on database db.
122230 **
122231 ** If zSql returns rows, then each row will have exactly one
122232 ** column. (This will only happen if zSql begins with "SELECT".)
122233 ** Take each row of result and call execSql() again recursively.
122234 **
122235 ** The execSqlF() routine does the same thing, except it accepts
122236 ** a format string as its third argument
122237 */
122238 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
122239  sqlite3_stmt *pStmt;
122240  int rc;
122241 
122242  /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
122243  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
122244  if( rc!=SQLITE_OK ) return rc;
122245  while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
122246  const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
122247  assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
122248  if( zSubSql ){
122249  assert( zSubSql[0]!='S' );
122250  rc = execSql(db, pzErrMsg, zSubSql);
122251  if( rc!=SQLITE_OK ) break;
122252  }
122253  }
122254  assert( rc!=SQLITE_ROW );
122255  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
122256  if( rc ){
122257  sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
122258  }
122259  (void)sqlite3_finalize(pStmt);
122260  return rc;
122261 }
122262 static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
122263  char *z;
122264  va_list ap;
122265  int rc;
122266  va_start(ap, zSql);
122267  z = sqlite3VMPrintf(db, zSql, ap);
122268  va_end(ap);
122269  if( z==0 ) return SQLITE_NOMEM;
122270  rc = execSql(db, pzErrMsg, z);
122271  sqlite3DbFree(db, z);
122272  return rc;
122273 }
122274 
122275 /*
122276 ** The VACUUM command is used to clean up the database,
122277 ** collapse free space, etc. It is modelled after the VACUUM command
122278 ** in PostgreSQL. The VACUUM command works as follows:
122279 **
122280 ** (1) Create a new transient database file
122281 ** (2) Copy all content from the database being vacuumed into
122282 ** the new transient database file
122283 ** (3) Copy content from the transient database back into the
122284 ** original database.
122285 **
122286 ** The transient database requires temporary disk space approximately
122287 ** equal to the size of the original database. The copy operation of
122288 ** step (3) requires additional temporary disk space approximately equal
122289 ** to the size of the original database for the rollback journal.
122290 ** Hence, temporary disk space that is approximately 2x the size of the
122291 ** original database is required. Every page of the database is written
122292 ** approximately 3 times: Once for step (2) and twice for step (3).
122293 ** Two writes per page are required in step (3) because the original
122294 ** database content must be written into the rollback journal prior to
122295 ** overwriting the database with the vacuumed content.
122296 **
122297 ** Only 1x temporary space and only 1x writes would be required if
122298 ** the copy of step (3) were replaced by deleting the original database
122299 ** and renaming the transient database as the original. But that will
122300 ** not work if other processes are attached to the original database.
122301 ** And a power loss in between deleting the original and renaming the
122302 ** transient would cause the database file to appear to be deleted
122303 ** following reboot.
122304 */
122305 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
122306  Vdbe *v = sqlite3GetVdbe(pParse);
122307  int iDb = pNm ? sqlite3TwoPartName(pParse, pNm, pNm, &pNm) : 0;
122308  if( v && (iDb>=2 || iDb==0) ){
122309  sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
122310  sqlite3VdbeUsesBtree(v, iDb);
122311  }
122312  return;
122313 }
122314 
122315 /*
122316 ** This routine implements the OP_Vacuum opcode of the VDBE.
122317 */
122318 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
122319  int rc = SQLITE_OK; /* Return code from service routines */
122320  Btree *pMain; /* The database being vacuumed */
122321  Btree *pTemp; /* The temporary database we vacuum into */
122322  int saved_flags; /* Saved value of the db->flags */
122323  int saved_nChange; /* Saved value of db->nChange */
122324  int saved_nTotalChange; /* Saved value of db->nTotalChange */
122325  u8 saved_mTrace; /* Saved trace settings */
122326  Db *pDb = 0; /* Database to detach at end of vacuum */
122327  int isMemDb; /* True if vacuuming a :memory: database */
122328  int nRes; /* Bytes of reserved space at the end of each page */
122329  int nDb; /* Number of attached databases */
122330  const char *zDbMain; /* Schema name of database to vacuum */
122331 
122332  if( !db->autoCommit ){
122333  sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
122334  return SQLITE_ERROR;
122335  }
122336  if( db->nVdbeActive>1 ){
122337  sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
122338  return SQLITE_ERROR;
122339  }
122340 
122341  /* Save the current value of the database flags so that it can be
122342  ** restored before returning. Then set the writable-schema flag, and
122343  ** disable CHECK and foreign key constraints. */
122344  saved_flags = db->flags;
122345  saved_nChange = db->nChange;
122346  saved_nTotalChange = db->nTotalChange;
122347  saved_mTrace = db->mTrace;
122348  db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks
122349  | SQLITE_PreferBuiltin | SQLITE_Vacuum);
122350  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
122351  db->mTrace = 0;
122352 
122353  zDbMain = db->aDb[iDb].zDbSName;
122354  pMain = db->aDb[iDb].pBt;
122355  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
122356 
122357  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
122358  ** can be set to 'off' for this file, as it is not recovered if a crash
122359  ** occurs anyway. The integrity of the database is maintained by a
122360  ** (possibly synchronous) transaction opened on the main database before
122361  ** sqlite3BtreeCopyFile() is called.
122362  **
122363  ** An optimisation would be to use a non-journaled pager.
122364  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
122365  ** that actually made the VACUUM run slower. Very little journalling
122366  ** actually occurs when doing a vacuum since the vacuum_db is initially
122367  ** empty. Only the journal header is written. Apparently it takes more
122368  ** time to parse and run the PRAGMA to turn journalling off than it does
122369  ** to write the journal header file.
122370  */
122371  nDb = db->nDb;
122372  rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
122373  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122374  assert( (db->nDb-1)==nDb );
122375  pDb = &db->aDb[nDb];
122376  assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
122377  pTemp = pDb->pBt;
122378 
122379  /* The call to execSql() to attach the temp database has left the file
122380  ** locked (as there was more than one active statement when the transaction
122381  ** to read the schema was concluded. Unlock it here so that this doesn't
122382  ** cause problems for the call to BtreeSetPageSize() below. */
122383  sqlite3BtreeCommit(pTemp);
122384 
122385  nRes = sqlite3BtreeGetOptimalReserve(pMain);
122386 
122387  /* A VACUUM cannot change the pagesize of an encrypted database. */
122388 #ifdef SQLITE_HAS_CODEC
122389  if( db->nextPagesize ){
122390  extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
122391  int nKey;
122392  char *zKey;
122393  sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
122394  if( nKey ) db->nextPagesize = 0;
122395  }
122396 #endif
122397 
122398  sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
122399  sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
122400  sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
122401 
122402  /* Begin a transaction and take an exclusive lock on the main database
122403  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
122404  ** to ensure that we do not try to change the page-size on a WAL database.
122405  */
122406  rc = execSql(db, pzErrMsg, "BEGIN");
122407  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122408  rc = sqlite3BtreeBeginTrans(pMain, 2);
122409  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122410 
122411  /* Do not attempt to change the page size for a WAL database */
122412  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
122413  ==PAGER_JOURNALMODE_WAL ){
122414  db->nextPagesize = 0;
122415  }
122416 
122417  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
122418  || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
122419  || NEVER(db->mallocFailed)
122420  ){
122421  rc = SQLITE_NOMEM_BKPT;
122422  goto end_of_vacuum;
122423  }
122424 
122425 #ifndef SQLITE_OMIT_AUTOVACUUM
122426  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
122427  sqlite3BtreeGetAutoVacuum(pMain));
122428 #endif
122429 
122430  /* Query the schema of the main database. Create a mirror schema
122431  ** in the temporary database.
122432  */
122433  db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
122434  rc = execSqlF(db, pzErrMsg,
122435  "SELECT sql FROM \"%w\".sqlite_master"
122436  " WHERE type='table'AND name<>'sqlite_sequence'"
122437  " AND coalesce(rootpage,1)>0",
122438  zDbMain
122439  );
122440  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122441  rc = execSqlF(db, pzErrMsg,
122442  "SELECT sql FROM \"%w\".sqlite_master"
122443  " WHERE type='index' AND length(sql)>10",
122444  zDbMain
122445  );
122446  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122447  db->init.iDb = 0;
122448 
122449  /* Loop through the tables in the main database. For each, do
122450  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
122451  ** the contents to the temporary database.
122452  */
122453  rc = execSqlF(db, pzErrMsg,
122454  "SELECT'INSERT INTO vacuum_db.'||quote(name)"
122455  "||' SELECT*FROM\"%w\".'||quote(name)"
122456  "FROM vacuum_db.sqlite_master "
122457  "WHERE type='table'AND coalesce(rootpage,1)>0",
122458  zDbMain
122459  );
122460  assert( (db->flags & SQLITE_Vacuum)!=0 );
122461  db->flags &= ~SQLITE_Vacuum;
122462  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122463 
122464  /* Copy the triggers, views, and virtual tables from the main database
122465  ** over to the temporary database. None of these objects has any
122466  ** associated storage, so all we have to do is copy their entries
122467  ** from the SQLITE_MASTER table.
122468  */
122469  rc = execSqlF(db, pzErrMsg,
122470  "INSERT INTO vacuum_db.sqlite_master"
122471  " SELECT*FROM \"%w\".sqlite_master"
122472  " WHERE type IN('view','trigger')"
122473  " OR(type='table'AND rootpage=0)",
122474  zDbMain
122475  );
122476  if( rc ) goto end_of_vacuum;
122477 
122478  /* At this point, there is a write transaction open on both the
122479  ** vacuum database and the main database. Assuming no error occurs,
122480  ** both transactions are closed by this block - the main database
122481  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
122482  ** call to sqlite3BtreeCommit().
122483  */
122484  {
122485  u32 meta;
122486  int i;
122487 
122488  /* This array determines which meta meta values are preserved in the
122489  ** vacuum. Even entries are the meta value number and odd entries
122490  ** are an increment to apply to the meta value after the vacuum.
122491  ** The increment is used to increase the schema cookie so that other
122492  ** connections to the same database will know to reread the schema.
122493  */
122494  static const unsigned char aCopy[] = {
122495  BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
122496  BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
122497  BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
122498  BTREE_USER_VERSION, 0, /* Preserve the user version */
122499  BTREE_APPLICATION_ID, 0, /* Preserve the application id */
122500  };
122501 
122502  assert( 1==sqlite3BtreeIsInTrans(pTemp) );
122503  assert( 1==sqlite3BtreeIsInTrans(pMain) );
122504 
122505  /* Copy Btree meta values */
122506  for(i=0; i<ArraySize(aCopy); i+=2){
122507  /* GetMeta() and UpdateMeta() cannot fail in this context because
122508  ** we already have page 1 loaded into cache and marked dirty. */
122509  sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
122510  rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
122511  if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
122512  }
122513 
122514  rc = sqlite3BtreeCopyFile(pMain, pTemp);
122515  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122516  rc = sqlite3BtreeCommit(pTemp);
122517  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122518 #ifndef SQLITE_OMIT_AUTOVACUUM
122519  sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
122520 #endif
122521  }
122522 
122523  assert( rc==SQLITE_OK );
122524  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
122525 
122526 end_of_vacuum:
122527  /* Restore the original value of db->flags */
122528  db->init.iDb = 0;
122529  db->flags = saved_flags;
122530  db->nChange = saved_nChange;
122531  db->nTotalChange = saved_nTotalChange;
122532  db->mTrace = saved_mTrace;
122533  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
122534 
122535  /* Currently there is an SQL level transaction open on the vacuum
122536  ** database. No locks are held on any other files (since the main file
122537  ** was committed at the btree level). So it safe to end the transaction
122538  ** by manually setting the autoCommit flag to true and detaching the
122539  ** vacuum database. The vacuum_db journal file is deleted when the pager
122540  ** is closed by the DETACH.
122541  */
122542  db->autoCommit = 1;
122543 
122544  if( pDb ){
122545  sqlite3BtreeClose(pDb->pBt);
122546  pDb->pBt = 0;
122547  pDb->pSchema = 0;
122548  }
122549 
122550  /* This both clears the schemas and reduces the size of the db->aDb[]
122551  ** array. */
122552  sqlite3ResetAllSchemasOfConnection(db);
122553 
122554  return rc;
122555 }
122556 
122557 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
122558 
122559 /************** End of vacuum.c **********************************************/
122560 /************** Begin file vtab.c ********************************************/
122561 /*
122562 ** 2006 June 10
122563 **
122564 ** The author disclaims copyright to this source code. In place of
122565 ** a legal notice, here is a blessing:
122566 **
122567 ** May you do good and not evil.
122568 ** May you find forgiveness for yourself and forgive others.
122569 ** May you share freely, never taking more than you give.
122570 **
122571 *************************************************************************
122572 ** This file contains code used to help implement virtual tables.
122573 */
122574 #ifndef SQLITE_OMIT_VIRTUALTABLE
122575 /* #include "sqliteInt.h" */
122576 
122577 /*
122578 ** Before a virtual table xCreate() or xConnect() method is invoked, the
122579 ** sqlite3.pVtabCtx member variable is set to point to an instance of
122580 ** this struct allocated on the stack. It is used by the implementation of
122581 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
122582 ** are invoked only from within xCreate and xConnect methods.
122583 */
122584 struct VtabCtx {
122585  VTable *pVTable; /* The virtual table being constructed */
122586  Table *pTab; /* The Table object to which the virtual table belongs */
122587  VtabCtx *pPrior; /* Parent context (if any) */
122588  int bDeclared; /* True after sqlite3_declare_vtab() is called */
122589 };
122590 
122591 /*
122592 ** The actual function that does the work of creating a new module.
122593 ** This function implements the sqlite3_create_module() and
122594 ** sqlite3_create_module_v2() interfaces.
122595 */
122596 static int createModule(
122597  sqlite3 *db, /* Database in which module is registered */
122598  const char *zName, /* Name assigned to this module */
122599  const sqlite3_module *pModule, /* The definition of the module */
122600  void *pAux, /* Context pointer for xCreate/xConnect */
122601  void (*xDestroy)(void *) /* Module destructor function */
122602 ){
122603  int rc = SQLITE_OK;
122604  int nName;
122605 
122606  sqlite3_mutex_enter(db->mutex);
122607  nName = sqlite3Strlen30(zName);
122608  if( sqlite3HashFind(&db->aModule, zName) ){
122609  rc = SQLITE_MISUSE_BKPT;
122610  }else{
122611  Module *pMod;
122612  pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
122613  if( pMod ){
122614  Module *pDel;
122615  char *zCopy = (char *)(&pMod[1]);
122616  memcpy(zCopy, zName, nName+1);
122617  pMod->zName = zCopy;
122618  pMod->pModule = pModule;
122619  pMod->pAux = pAux;
122620  pMod->xDestroy = xDestroy;
122621  pMod->pEpoTab = 0;
122622  pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
122623  assert( pDel==0 || pDel==pMod );
122624  if( pDel ){
122625  sqlite3OomFault(db);
122626  sqlite3DbFree(db, pDel);
122627  }
122628  }
122629  }
122630  rc = sqlite3ApiExit(db, rc);
122631  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
122632 
122633  sqlite3_mutex_leave(db->mutex);
122634  return rc;
122635 }
122636 
122637 
122638 /*
122639 ** External API function used to create a new virtual-table module.
122640 */
122641 SQLITE_API int sqlite3_create_module(
122642  sqlite3 *db, /* Database in which module is registered */
122643  const char *zName, /* Name assigned to this module */
122644  const sqlite3_module *pModule, /* The definition of the module */
122645  void *pAux /* Context pointer for xCreate/xConnect */
122646 ){
122647 #ifdef SQLITE_ENABLE_API_ARMOR
122648  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
122649 #endif
122650  return createModule(db, zName, pModule, pAux, 0);
122651 }
122652 
122653 /*
122654 ** External API function used to create a new virtual-table module.
122655 */
122656 SQLITE_API int sqlite3_create_module_v2(
122657  sqlite3 *db, /* Database in which module is registered */
122658  const char *zName, /* Name assigned to this module */
122659  const sqlite3_module *pModule, /* The definition of the module */
122660  void *pAux, /* Context pointer for xCreate/xConnect */
122661  void (*xDestroy)(void *) /* Module destructor function */
122662 ){
122663 #ifdef SQLITE_ENABLE_API_ARMOR
122664  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
122665 #endif
122666  return createModule(db, zName, pModule, pAux, xDestroy);
122667 }
122668 
122669 /*
122670 ** Lock the virtual table so that it cannot be disconnected.
122671 ** Locks nest. Every lock should have a corresponding unlock.
122672 ** If an unlock is omitted, resources leaks will occur.
122673 **
122674 ** If a disconnect is attempted while a virtual table is locked,
122675 ** the disconnect is deferred until all locks have been removed.
122676 */
122677 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
122678  pVTab->nRef++;
122679 }
122680 
122681 
122682 /*
122683 ** pTab is a pointer to a Table structure representing a virtual-table.
122684 ** Return a pointer to the VTable object used by connection db to access
122685 ** this virtual-table, if one has been created, or NULL otherwise.
122686 */
122687 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
122688  VTable *pVtab;
122689  assert( IsVirtual(pTab) );
122690  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
122691  return pVtab;
122692 }
122693 
122694 /*
122695 ** Decrement the ref-count on a virtual table object. When the ref-count
122696 ** reaches zero, call the xDisconnect() method to delete the object.
122697 */
122698 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
122699  sqlite3 *db = pVTab->db;
122700 
122701  assert( db );
122702  assert( pVTab->nRef>0 );
122703  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
122704 
122705  pVTab->nRef--;
122706  if( pVTab->nRef==0 ){
122707  sqlite3_vtab *p = pVTab->pVtab;
122708  if( p ){
122709  p->pModule->xDisconnect(p);
122710  }
122711  sqlite3DbFree(db, pVTab);
122712  }
122713 }
122714 
122715 /*
122716 ** Table p is a virtual table. This function moves all elements in the
122717 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
122718 ** database connections to be disconnected at the next opportunity.
122719 ** Except, if argument db is not NULL, then the entry associated with
122720 ** connection db is left in the p->pVTable list.
122721 */
122722 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
122723  VTable *pRet = 0;
122724  VTable *pVTable = p->pVTable;
122725  p->pVTable = 0;
122726 
122727  /* Assert that the mutex (if any) associated with the BtShared database
122728  ** that contains table p is held by the caller. See header comments
122729  ** above function sqlite3VtabUnlockList() for an explanation of why
122730  ** this makes it safe to access the sqlite3.pDisconnect list of any
122731  ** database connection that may have an entry in the p->pVTable list.
122732  */
122733  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
122734 
122735  while( pVTable ){
122736  sqlite3 *db2 = pVTable->db;
122737  VTable *pNext = pVTable->pNext;
122738  assert( db2 );
122739  if( db2==db ){
122740  pRet = pVTable;
122741  p->pVTable = pRet;
122742  pRet->pNext = 0;
122743  }else{
122744  pVTable->pNext = db2->pDisconnect;
122745  db2->pDisconnect = pVTable;
122746  }
122747  pVTable = pNext;
122748  }
122749 
122750  assert( !db || pRet );
122751  return pRet;
122752 }
122753 
122754 /*
122755 ** Table *p is a virtual table. This function removes the VTable object
122756 ** for table *p associated with database connection db from the linked
122757 ** list in p->pVTab. It also decrements the VTable ref count. This is
122758 ** used when closing database connection db to free all of its VTable
122759 ** objects without disturbing the rest of the Schema object (which may
122760 ** be being used by other shared-cache connections).
122761 */
122762 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
122763  VTable **ppVTab;
122764 
122765  assert( IsVirtual(p) );
122766  assert( sqlite3BtreeHoldsAllMutexes(db) );
122767  assert( sqlite3_mutex_held(db->mutex) );
122768 
122769  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
122770  if( (*ppVTab)->db==db ){
122771  VTable *pVTab = *ppVTab;
122772  *ppVTab = pVTab->pNext;
122773  sqlite3VtabUnlock(pVTab);
122774  break;
122775  }
122776  }
122777 }
122778 
122779 
122780 /*
122781 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
122782 **
122783 ** This function may only be called when the mutexes associated with all
122784 ** shared b-tree databases opened using connection db are held by the
122785 ** caller. This is done to protect the sqlite3.pDisconnect list. The
122786 ** sqlite3.pDisconnect list is accessed only as follows:
122787 **
122788 ** 1) By this function. In this case, all BtShared mutexes and the mutex
122789 ** associated with the database handle itself must be held.
122790 **
122791 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
122792 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
122793 ** associated with the database the virtual table is stored in is held
122794 ** or, if the virtual table is stored in a non-sharable database, then
122795 ** the database handle mutex is held.
122796 **
122797 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
122798 ** by multiple threads. It is thread-safe.
122799 */
122800 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
122801  VTable *p = db->pDisconnect;
122802  db->pDisconnect = 0;
122803 
122804  assert( sqlite3BtreeHoldsAllMutexes(db) );
122805  assert( sqlite3_mutex_held(db->mutex) );
122806 
122807  if( p ){
122808  sqlite3ExpirePreparedStatements(db);
122809  do {
122810  VTable *pNext = p->pNext;
122811  sqlite3VtabUnlock(p);
122812  p = pNext;
122813  }while( p );
122814  }
122815 }
122816 
122817 /*
122818 ** Clear any and all virtual-table information from the Table record.
122819 ** This routine is called, for example, just before deleting the Table
122820 ** record.
122821 **
122822 ** Since it is a virtual-table, the Table structure contains a pointer
122823 ** to the head of a linked list of VTable structures. Each VTable
122824 ** structure is associated with a single sqlite3* user of the schema.
122825 ** The reference count of the VTable structure associated with database
122826 ** connection db is decremented immediately (which may lead to the
122827 ** structure being xDisconnected and free). Any other VTable structures
122828 ** in the list are moved to the sqlite3.pDisconnect list of the associated
122829 ** database connection.
122830 */
122831 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
122832  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
122833  if( p->azModuleArg ){
122834  int i;
122835  for(i=0; i<p->nModuleArg; i++){
122836  if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
122837  }
122838  sqlite3DbFree(db, p->azModuleArg);
122839  }
122840 }
122841 
122842 /*
122843 ** Add a new module argument to pTable->azModuleArg[].
122844 ** The string is not copied - the pointer is stored. The
122845 ** string will be freed automatically when the table is
122846 ** deleted.
122847 */
122848 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
122849  int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
122850  char **azModuleArg;
122851  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
122852  if( azModuleArg==0 ){
122853  sqlite3DbFree(db, zArg);
122854  }else{
122855  int i = pTable->nModuleArg++;
122856  azModuleArg[i] = zArg;
122857  azModuleArg[i+1] = 0;
122858  pTable->azModuleArg = azModuleArg;
122859  }
122860 }
122861 
122862 /*
122863 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
122864 ** statement. The module name has been parsed, but the optional list
122865 ** of parameters that follow the module name are still pending.
122866 */
122867 SQLITE_PRIVATE void sqlite3VtabBeginParse(
122868  Parse *pParse, /* Parsing context */
122869  Token *pName1, /* Name of new table, or database name */
122870  Token *pName2, /* Name of new table or NULL */
122871  Token *pModuleName, /* Name of the module for the virtual table */
122872  int ifNotExists /* No error if the table already exists */
122873 ){
122874  int iDb; /* The database the table is being created in */
122875  Table *pTable; /* The new virtual table */
122876  sqlite3 *db; /* Database connection */
122877 
122878  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
122879  pTable = pParse->pNewTable;
122880  if( pTable==0 ) return;
122881  assert( 0==pTable->pIndex );
122882 
122883  db = pParse->db;
122884  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
122885  assert( iDb>=0 );
122886 
122887  pTable->tabFlags |= TF_Virtual;
122888  pTable->nModuleArg = 0;
122889  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
122890  addModuleArgument(db, pTable, 0);
122891  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
122892  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
122893  || (pParse->sNameToken.z==pName1->z && pName2->z==0)
122894  );
122895  pParse->sNameToken.n = (int)(
122896  &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
122897  );
122898 
122899 #ifndef SQLITE_OMIT_AUTHORIZATION
122900  /* Creating a virtual table invokes the authorization callback twice.
122901  ** The first invocation, to obtain permission to INSERT a row into the
122902  ** sqlite_master table, has already been made by sqlite3StartTable().
122903  ** The second call, to obtain permission to create the table, is made now.
122904  */
122905  if( pTable->azModuleArg ){
122906  sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
122907  pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
122908  }
122909 #endif
122910 }
122911 
122912 /*
122913 ** This routine takes the module argument that has been accumulating
122914 ** in pParse->zArg[] and appends it to the list of arguments on the
122915 ** virtual table currently under construction in pParse->pTable.
122916 */
122917 static void addArgumentToVtab(Parse *pParse){
122918  if( pParse->sArg.z && pParse->pNewTable ){
122919  const char *z = (const char*)pParse->sArg.z;
122920  int n = pParse->sArg.n;
122921  sqlite3 *db = pParse->db;
122922  addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
122923  }
122924 }
122925 
122926 /*
122927 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
122928 ** has been completely parsed.
122929 */
122930 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
122931  Table *pTab = pParse->pNewTable; /* The table being constructed */
122932  sqlite3 *db = pParse->db; /* The database connection */
122933 
122934  if( pTab==0 ) return;
122935  addArgumentToVtab(pParse);
122936  pParse->sArg.z = 0;
122937  if( pTab->nModuleArg<1 ) return;
122938 
122939  /* If the CREATE VIRTUAL TABLE statement is being entered for the
122940  ** first time (in other words if the virtual table is actually being
122941  ** created now instead of just being read out of sqlite_master) then
122942  ** do additional initialization work and store the statement text
122943  ** in the sqlite_master table.
122944  */
122945  if( !db->init.busy ){
122946  char *zStmt;
122947  char *zWhere;
122948  int iDb;
122949  int iReg;
122950  Vdbe *v;
122951 
122952  /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
122953  if( pEnd ){
122954  pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
122955  }
122956  zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
122957 
122958  /* A slot for the record has already been allocated in the
122959  ** SQLITE_MASTER table. We just need to update that slot with all
122960  ** the information we've collected.
122961  **
122962  ** The VM register number pParse->regRowid holds the rowid of an
122963  ** entry in the sqlite_master table tht was created for this vtab
122964  ** by sqlite3StartTable().
122965  */
122966  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122967  sqlite3NestedParse(pParse,
122968  "UPDATE %Q.%s "
122969  "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
122970  "WHERE rowid=#%d",
122971  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb),
122972  pTab->zName,
122973  pTab->zName,
122974  zStmt,
122975  pParse->regRowid
122976  );
122977  sqlite3DbFree(db, zStmt);
122978  v = sqlite3GetVdbe(pParse);
122979  sqlite3ChangeCookie(pParse, iDb);
122980 
122981  sqlite3VdbeAddOp0(v, OP_Expire);
122982  zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
122983  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
122984 
122985  iReg = ++pParse->nMem;
122986  sqlite3VdbeLoadString(v, iReg, pTab->zName);
122987  sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
122988  }
122989 
122990  /* If we are rereading the sqlite_master table create the in-memory
122991  ** record of the table. The xConnect() method is not called until
122992  ** the first time the virtual table is used in an SQL statement. This
122993  ** allows a schema that contains virtual tables to be loaded before
122994  ** the required virtual table implementations are registered. */
122995  else {
122996  Table *pOld;
122997  Schema *pSchema = pTab->pSchema;
122998  const char *zName = pTab->zName;
122999  assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
123000  pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
123001  if( pOld ){
123002  sqlite3OomFault(db);
123003  assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
123004  return;
123005  }
123006  pParse->pNewTable = 0;
123007  }
123008 }
123009 
123010 /*
123011 ** The parser calls this routine when it sees the first token
123012 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
123013 */
123014 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
123015  addArgumentToVtab(pParse);
123016  pParse->sArg.z = 0;
123017  pParse->sArg.n = 0;
123018 }
123019 
123020 /*
123021 ** The parser calls this routine for each token after the first token
123022 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
123023 */
123024 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
123025  Token *pArg = &pParse->sArg;
123026  if( pArg->z==0 ){
123027  pArg->z = p->z;
123028  pArg->n = p->n;
123029  }else{
123030  assert(pArg->z <= p->z);
123031  pArg->n = (int)(&p->z[p->n] - pArg->z);
123032  }
123033 }
123034 
123035 /*
123036 ** Invoke a virtual table constructor (either xCreate or xConnect). The
123037 ** pointer to the function to invoke is passed as the fourth parameter
123038 ** to this procedure.
123039 */
123040 static int vtabCallConstructor(
123041  sqlite3 *db,
123042  Table *pTab,
123043  Module *pMod,
123044  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
123045  char **pzErr
123046 ){
123047  VtabCtx sCtx;
123048  VTable *pVTable;
123049  int rc;
123050  const char *const*azArg = (const char *const*)pTab->azModuleArg;
123051  int nArg = pTab->nModuleArg;
123052  char *zErr = 0;
123053  char *zModuleName;
123054  int iDb;
123055  VtabCtx *pCtx;
123056 
123057  /* Check that the virtual-table is not already being initialized */
123058  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
123059  if( pCtx->pTab==pTab ){
123060  *pzErr = sqlite3MPrintf(db,
123061  "vtable constructor called recursively: %s", pTab->zName
123062  );
123063  return SQLITE_LOCKED;
123064  }
123065  }
123066 
123067  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
123068  if( !zModuleName ){
123069  return SQLITE_NOMEM_BKPT;
123070  }
123071 
123072  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
123073  if( !pVTable ){
123074  sqlite3DbFree(db, zModuleName);
123075  return SQLITE_NOMEM_BKPT;
123076  }
123077  pVTable->db = db;
123078  pVTable->pMod = pMod;
123079 
123080  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
123081  pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
123082 
123083  /* Invoke the virtual table constructor */
123084  assert( &db->pVtabCtx );
123085  assert( xConstruct );
123086  sCtx.pTab = pTab;
123087  sCtx.pVTable = pVTable;
123088  sCtx.pPrior = db->pVtabCtx;
123089  sCtx.bDeclared = 0;
123090  db->pVtabCtx = &sCtx;
123091  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
123092  db->pVtabCtx = sCtx.pPrior;
123093  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
123094  assert( sCtx.pTab==pTab );
123095 
123096  if( SQLITE_OK!=rc ){
123097  if( zErr==0 ){
123098  *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
123099  }else {
123100  *pzErr = sqlite3MPrintf(db, "%s", zErr);
123101  sqlite3_free(zErr);
123102  }
123103  sqlite3DbFree(db, pVTable);
123104  }else if( ALWAYS(pVTable->pVtab) ){
123105  /* Justification of ALWAYS(): A correct vtab constructor must allocate
123106  ** the sqlite3_vtab object if successful. */
123107  memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
123108  pVTable->pVtab->pModule = pMod->pModule;
123109  pVTable->nRef = 1;
123110  if( sCtx.bDeclared==0 ){
123111  const char *zFormat = "vtable constructor did not declare schema: %s";
123112  *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
123113  sqlite3VtabUnlock(pVTable);
123114  rc = SQLITE_ERROR;
123115  }else{
123116  int iCol;
123117  u8 oooHidden = 0;
123118  /* If everything went according to plan, link the new VTable structure
123119  ** into the linked list headed by pTab->pVTable. Then loop through the
123120  ** columns of the table to see if any of them contain the token "hidden".
123121  ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
123122  ** the type string. */
123123  pVTable->pNext = pTab->pVTable;
123124  pTab->pVTable = pVTable;
123125 
123126  for(iCol=0; iCol<pTab->nCol; iCol++){
123127  char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
123128  int nType;
123129  int i = 0;
123130  nType = sqlite3Strlen30(zType);
123131  for(i=0; i<nType; i++){
123132  if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
123133  && (i==0 || zType[i-1]==' ')
123134  && (zType[i+6]=='\0' || zType[i+6]==' ')
123135  ){
123136  break;
123137  }
123138  }
123139  if( i<nType ){
123140  int j;
123141  int nDel = 6 + (zType[i+6] ? 1 : 0);
123142  for(j=i; (j+nDel)<=nType; j++){
123143  zType[j] = zType[j+nDel];
123144  }
123145  if( zType[i]=='\0' && i>0 ){
123146  assert(zType[i-1]==' ');
123147  zType[i-1] = '\0';
123148  }
123149  pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
123150  oooHidden = TF_OOOHidden;
123151  }else{
123152  pTab->tabFlags |= oooHidden;
123153  }
123154  }
123155  }
123156  }
123157 
123158  sqlite3DbFree(db, zModuleName);
123159  return rc;
123160 }
123161 
123162 /*
123163 ** This function is invoked by the parser to call the xConnect() method
123164 ** of the virtual table pTab. If an error occurs, an error code is returned
123165 ** and an error left in pParse.
123166 **
123167 ** This call is a no-op if table pTab is not a virtual table.
123168 */
123169 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
123170  sqlite3 *db = pParse->db;
123171  const char *zMod;
123172  Module *pMod;
123173  int rc;
123174 
123175  assert( pTab );
123176  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
123177  return SQLITE_OK;
123178  }
123179 
123180  /* Locate the required virtual table module */
123181  zMod = pTab->azModuleArg[0];
123182  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
123183 
123184  if( !pMod ){
123185  const char *zModule = pTab->azModuleArg[0];
123186  sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
123187  rc = SQLITE_ERROR;
123188  }else{
123189  char *zErr = 0;
123190  rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
123191  if( rc!=SQLITE_OK ){
123192  sqlite3ErrorMsg(pParse, "%s", zErr);
123193  }
123194  sqlite3DbFree(db, zErr);
123195  }
123196 
123197  return rc;
123198 }
123199 /*
123200 ** Grow the db->aVTrans[] array so that there is room for at least one
123201 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
123202 */
123203 static int growVTrans(sqlite3 *db){
123204  const int ARRAY_INCR = 5;
123205 
123206  /* Grow the sqlite3.aVTrans array if required */
123207  if( (db->nVTrans%ARRAY_INCR)==0 ){
123208  VTable **aVTrans;
123209  int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
123210  aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
123211  if( !aVTrans ){
123212  return SQLITE_NOMEM_BKPT;
123213  }
123214  memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
123215  db->aVTrans = aVTrans;
123216  }
123217 
123218  return SQLITE_OK;
123219 }
123220 
123221 /*
123222 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
123223 ** have already been reserved using growVTrans().
123224 */
123225 static void addToVTrans(sqlite3 *db, VTable *pVTab){
123226  /* Add pVtab to the end of sqlite3.aVTrans */
123227  db->aVTrans[db->nVTrans++] = pVTab;
123228  sqlite3VtabLock(pVTab);
123229 }
123230 
123231 /*
123232 ** This function is invoked by the vdbe to call the xCreate method
123233 ** of the virtual table named zTab in database iDb.
123234 **
123235 ** If an error occurs, *pzErr is set to point to an English language
123236 ** description of the error and an SQLITE_XXX error code is returned.
123237 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
123238 */
123239 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
123240  int rc = SQLITE_OK;
123241  Table *pTab;
123242  Module *pMod;
123243  const char *zMod;
123244 
123245  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
123246  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
123247 
123248  /* Locate the required virtual table module */
123249  zMod = pTab->azModuleArg[0];
123250  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
123251 
123252  /* If the module has been registered and includes a Create method,
123253  ** invoke it now. If the module has not been registered, return an
123254  ** error. Otherwise, do nothing.
123255  */
123256  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
123257  *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
123258  rc = SQLITE_ERROR;
123259  }else{
123260  rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
123261  }
123262 
123263  /* Justification of ALWAYS(): The xConstructor method is required to
123264  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
123265  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
123266  rc = growVTrans(db);
123267  if( rc==SQLITE_OK ){
123268  addToVTrans(db, sqlite3GetVTable(db, pTab));
123269  }
123270  }
123271 
123272  return rc;
123273 }
123274 
123275 /*
123276 ** This function is used to set the schema of a virtual table. It is only
123277 ** valid to call this function from within the xCreate() or xConnect() of a
123278 ** virtual table module.
123279 */
123280 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
123281  VtabCtx *pCtx;
123282  Parse *pParse;
123283  int rc = SQLITE_OK;
123284  Table *pTab;
123285  char *zErr = 0;
123286 
123287 #ifdef SQLITE_ENABLE_API_ARMOR
123288  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
123289  return SQLITE_MISUSE_BKPT;
123290  }
123291 #endif
123292  sqlite3_mutex_enter(db->mutex);
123293  pCtx = db->pVtabCtx;
123294  if( !pCtx || pCtx->bDeclared ){
123295  sqlite3Error(db, SQLITE_MISUSE);
123296  sqlite3_mutex_leave(db->mutex);
123297  return SQLITE_MISUSE_BKPT;
123298  }
123299  pTab = pCtx->pTab;
123300  assert( (pTab->tabFlags & TF_Virtual)!=0 );
123301 
123302  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
123303  if( pParse==0 ){
123304  rc = SQLITE_NOMEM_BKPT;
123305  }else{
123306  pParse->declareVtab = 1;
123307  pParse->db = db;
123308  pParse->nQueryLoop = 1;
123309 
123310  if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
123311  && pParse->pNewTable
123312  && !db->mallocFailed
123313  && !pParse->pNewTable->pSelect
123314  && (pParse->pNewTable->tabFlags & TF_Virtual)==0
123315  ){
123316  if( !pTab->aCol ){
123317  Table *pNew = pParse->pNewTable;
123318  Index *pIdx;
123319  pTab->aCol = pNew->aCol;
123320  pTab->nCol = pNew->nCol;
123321  pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
123322  pNew->nCol = 0;
123323  pNew->aCol = 0;
123324  assert( pTab->pIndex==0 );
123325  if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){
123326  rc = SQLITE_ERROR;
123327  }
123328  pIdx = pNew->pIndex;
123329  if( pIdx ){
123330  assert( pIdx->pNext==0 );
123331  pTab->pIndex = pIdx;
123332  pNew->pIndex = 0;
123333  pIdx->pTable = pTab;
123334  }
123335  }
123336  pCtx->bDeclared = 1;
123337  }else{
123338  sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
123339  sqlite3DbFree(db, zErr);
123340  rc = SQLITE_ERROR;
123341  }
123342  pParse->declareVtab = 0;
123343 
123344  if( pParse->pVdbe ){
123345  sqlite3VdbeFinalize(pParse->pVdbe);
123346  }
123347  sqlite3DeleteTable(db, pParse->pNewTable);
123348  sqlite3ParserReset(pParse);
123349  sqlite3StackFree(db, pParse);
123350  }
123351 
123352  assert( (rc&0xff)==rc );
123353  rc = sqlite3ApiExit(db, rc);
123354  sqlite3_mutex_leave(db->mutex);
123355  return rc;
123356 }
123357 
123358 /*
123359 ** This function is invoked by the vdbe to call the xDestroy method
123360 ** of the virtual table named zTab in database iDb. This occurs
123361 ** when a DROP TABLE is mentioned.
123362 **
123363 ** This call is a no-op if zTab is not a virtual table.
123364 */
123365 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
123366  int rc = SQLITE_OK;
123367  Table *pTab;
123368 
123369  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
123370  if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
123371  VTable *p;
123372  int (*xDestroy)(sqlite3_vtab *);
123373  for(p=pTab->pVTable; p; p=p->pNext){
123374  assert( p->pVtab );
123375  if( p->pVtab->nRef>0 ){
123376  return SQLITE_LOCKED;
123377  }
123378  }
123379  p = vtabDisconnectAll(db, pTab);
123380  xDestroy = p->pMod->pModule->xDestroy;
123381  assert( xDestroy!=0 ); /* Checked before the virtual table is created */
123382  rc = xDestroy(p->pVtab);
123383  /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
123384  if( rc==SQLITE_OK ){
123385  assert( pTab->pVTable==p && p->pNext==0 );
123386  p->pVtab = 0;
123387  pTab->pVTable = 0;
123388  sqlite3VtabUnlock(p);
123389  }
123390  }
123391 
123392  return rc;
123393 }
123394 
123395 /*
123396 ** This function invokes either the xRollback or xCommit method
123397 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
123398 ** called is identified by the second argument, "offset", which is
123399 ** the offset of the method to call in the sqlite3_module structure.
123400 **
123401 ** The array is cleared after invoking the callbacks.
123402 */
123403 static void callFinaliser(sqlite3 *db, int offset){
123404  int i;
123405  if( db->aVTrans ){
123406  VTable **aVTrans = db->aVTrans;
123407  db->aVTrans = 0;
123408  for(i=0; i<db->nVTrans; i++){
123409  VTable *pVTab = aVTrans[i];
123410  sqlite3_vtab *p = pVTab->pVtab;
123411  if( p ){
123412  int (*x)(sqlite3_vtab *);
123413  x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
123414  if( x ) x(p);
123415  }
123416  pVTab->iSavepoint = 0;
123417  sqlite3VtabUnlock(pVTab);
123418  }
123419  sqlite3DbFree(db, aVTrans);
123420  db->nVTrans = 0;
123421  }
123422 }
123423 
123424 /*
123425 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
123426 ** array. Return the error code for the first error that occurs, or
123427 ** SQLITE_OK if all xSync operations are successful.
123428 **
123429 ** If an error message is available, leave it in p->zErrMsg.
123430 */
123431 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
123432  int i;
123433  int rc = SQLITE_OK;
123434  VTable **aVTrans = db->aVTrans;
123435 
123436  db->aVTrans = 0;
123437  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
123438  int (*x)(sqlite3_vtab *);
123439  sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
123440  if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
123441  rc = x(pVtab);
123442  sqlite3VtabImportErrmsg(p, pVtab);
123443  }
123444  }
123445  db->aVTrans = aVTrans;
123446  return rc;
123447 }
123448 
123449 /*
123450 ** Invoke the xRollback method of all virtual tables in the
123451 ** sqlite3.aVTrans array. Then clear the array itself.
123452 */
123453 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
123454  callFinaliser(db, offsetof(sqlite3_module,xRollback));
123455  return SQLITE_OK;
123456 }
123457 
123458 /*
123459 ** Invoke the xCommit method of all virtual tables in the
123460 ** sqlite3.aVTrans array. Then clear the array itself.
123461 */
123462 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
123463  callFinaliser(db, offsetof(sqlite3_module,xCommit));
123464  return SQLITE_OK;
123465 }
123466 
123467 /*
123468 ** If the virtual table pVtab supports the transaction interface
123469 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
123470 ** not currently open, invoke the xBegin method now.
123471 **
123472 ** If the xBegin call is successful, place the sqlite3_vtab pointer
123473 ** in the sqlite3.aVTrans array.
123474 */
123475 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
123476  int rc = SQLITE_OK;
123477  const sqlite3_module *pModule;
123478 
123479  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
123480  ** than zero, then this function is being called from within a
123481  ** virtual module xSync() callback. It is illegal to write to
123482  ** virtual module tables in this case, so return SQLITE_LOCKED.
123483  */
123484  if( sqlite3VtabInSync(db) ){
123485  return SQLITE_LOCKED;
123486  }
123487  if( !pVTab ){
123488  return SQLITE_OK;
123489  }
123490  pModule = pVTab->pVtab->pModule;
123491 
123492  if( pModule->xBegin ){
123493  int i;
123494 
123495  /* If pVtab is already in the aVTrans array, return early */
123496  for(i=0; i<db->nVTrans; i++){
123497  if( db->aVTrans[i]==pVTab ){
123498  return SQLITE_OK;
123499  }
123500  }
123501 
123502  /* Invoke the xBegin method. If successful, add the vtab to the
123503  ** sqlite3.aVTrans[] array. */
123504  rc = growVTrans(db);
123505  if( rc==SQLITE_OK ){
123506  rc = pModule->xBegin(pVTab->pVtab);
123507  if( rc==SQLITE_OK ){
123508  int iSvpt = db->nStatement + db->nSavepoint;
123509  addToVTrans(db, pVTab);
123510  if( iSvpt && pModule->xSavepoint ){
123511  pVTab->iSavepoint = iSvpt;
123512  rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
123513  }
123514  }
123515  }
123516  }
123517  return rc;
123518 }
123519 
123520 /*
123521 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
123522 ** virtual tables that currently have an open transaction. Pass iSavepoint
123523 ** as the second argument to the virtual table method invoked.
123524 **
123525 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
123526 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
123527 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
123528 ** an open transaction is invoked.
123529 **
123530 ** If any virtual table method returns an error code other than SQLITE_OK,
123531 ** processing is abandoned and the error returned to the caller of this
123532 ** function immediately. If all calls to virtual table methods are successful,
123533 ** SQLITE_OK is returned.
123534 */
123535 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
123536  int rc = SQLITE_OK;
123537 
123538  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
123539  assert( iSavepoint>=-1 );
123540  if( db->aVTrans ){
123541  int i;
123542  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
123543  VTable *pVTab = db->aVTrans[i];
123544  const sqlite3_module *pMod = pVTab->pMod->pModule;
123545  if( pVTab->pVtab && pMod->iVersion>=2 ){
123546  int (*xMethod)(sqlite3_vtab *, int);
123547  switch( op ){
123548  case SAVEPOINT_BEGIN:
123549  xMethod = pMod->xSavepoint;
123550  pVTab->iSavepoint = iSavepoint+1;
123551  break;
123552  case SAVEPOINT_ROLLBACK:
123553  xMethod = pMod->xRollbackTo;
123554  break;
123555  default:
123556  xMethod = pMod->xRelease;
123557  break;
123558  }
123559  if( xMethod && pVTab->iSavepoint>iSavepoint ){
123560  rc = xMethod(pVTab->pVtab, iSavepoint);
123561  }
123562  }
123563  }
123564  }
123565  return rc;
123566 }
123567 
123568 /*
123569 ** The first parameter (pDef) is a function implementation. The
123570 ** second parameter (pExpr) is the first argument to this function.
123571 ** If pExpr is a column in a virtual table, then let the virtual
123572 ** table implementation have an opportunity to overload the function.
123573 **
123574 ** This routine is used to allow virtual table implementations to
123575 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
123576 **
123577 ** Return either the pDef argument (indicating no change) or a
123578 ** new FuncDef structure that is marked as ephemeral using the
123579 ** SQLITE_FUNC_EPHEM flag.
123580 */
123581 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
123582  sqlite3 *db, /* Database connection for reporting malloc problems */
123583  FuncDef *pDef, /* Function to possibly overload */
123584  int nArg, /* Number of arguments to the function */
123585  Expr *pExpr /* First argument to the function */
123586 ){
123587  Table *pTab;
123588  sqlite3_vtab *pVtab;
123589  sqlite3_module *pMod;
123590  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
123591  void *pArg = 0;
123592  FuncDef *pNew;
123593  int rc = 0;
123594  char *zLowerName;
123595  unsigned char *z;
123596 
123597 
123598  /* Check to see the left operand is a column in a virtual table */
123599  if( NEVER(pExpr==0) ) return pDef;
123600  if( pExpr->op!=TK_COLUMN ) return pDef;
123601  pTab = pExpr->pTab;
123602  if( NEVER(pTab==0) ) return pDef;
123603  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
123604  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
123605  assert( pVtab!=0 );
123606  assert( pVtab->pModule!=0 );
123607  pMod = (sqlite3_module *)pVtab->pModule;
123608  if( pMod->xFindFunction==0 ) return pDef;
123609 
123610  /* Call the xFindFunction method on the virtual table implementation
123611  ** to see if the implementation wants to overload this function
123612  */
123613  zLowerName = sqlite3DbStrDup(db, pDef->zName);
123614  if( zLowerName ){
123615  for(z=(unsigned char*)zLowerName; *z; z++){
123616  *z = sqlite3UpperToLower[*z];
123617  }
123618  rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
123619  sqlite3DbFree(db, zLowerName);
123620  }
123621  if( rc==0 ){
123622  return pDef;
123623  }
123624 
123625  /* Create a new ephemeral function definition for the overloaded
123626  ** function */
123627  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
123628  + sqlite3Strlen30(pDef->zName) + 1);
123629  if( pNew==0 ){
123630  return pDef;
123631  }
123632  *pNew = *pDef;
123633  pNew->zName = (const char*)&pNew[1];
123634  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
123635  pNew->xSFunc = xSFunc;
123636  pNew->pUserData = pArg;
123637  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
123638  return pNew;
123639 }
123640 
123641 /*
123642 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
123643 ** array so that an OP_VBegin will get generated for it. Add pTab to the
123644 ** array if it is missing. If pTab is already in the array, this routine
123645 ** is a no-op.
123646 */
123647 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
123648  Parse *pToplevel = sqlite3ParseToplevel(pParse);
123649  int i, n;
123650  Table **apVtabLock;
123651 
123652  assert( IsVirtual(pTab) );
123653  for(i=0; i<pToplevel->nVtabLock; i++){
123654  if( pTab==pToplevel->apVtabLock[i] ) return;
123655  }
123656  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
123657  apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
123658  if( apVtabLock ){
123659  pToplevel->apVtabLock = apVtabLock;
123660  pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
123661  }else{
123662  sqlite3OomFault(pToplevel->db);
123663  }
123664 }
123665 
123666 /*
123667 ** Check to see if virtual table module pMod can be have an eponymous
123668 ** virtual table instance. If it can, create one if one does not already
123669 ** exist. Return non-zero if the eponymous virtual table instance exists
123670 ** when this routine returns, and return zero if it does not exist.
123671 **
123672 ** An eponymous virtual table instance is one that is named after its
123673 ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
123674 ** statement in order to come into existance. Eponymous virtual table
123675 ** instances always exist. They cannot be DROP-ed.
123676 **
123677 ** Any virtual table module for which xConnect and xCreate are the same
123678 ** method can have an eponymous virtual table instance.
123679 */
123680 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
123681  const sqlite3_module *pModule = pMod->pModule;
123682  Table *pTab;
123683  char *zErr = 0;
123684  int rc;
123685  sqlite3 *db = pParse->db;
123686  if( pMod->pEpoTab ) return 1;
123687  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
123688  pTab = sqlite3DbMallocZero(db, sizeof(Table));
123689  if( pTab==0 ) return 0;
123690  pTab->zName = sqlite3DbStrDup(db, pMod->zName);
123691  if( pTab->zName==0 ){
123692  sqlite3DbFree(db, pTab);
123693  return 0;
123694  }
123695  pMod->pEpoTab = pTab;
123696  pTab->nRef = 1;
123697  pTab->pSchema = db->aDb[0].pSchema;
123698  pTab->tabFlags |= TF_Virtual;
123699  pTab->nModuleArg = 0;
123700  pTab->iPKey = -1;
123701  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
123702  addModuleArgument(db, pTab, 0);
123703  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
123704  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
123705  if( rc ){
123706  sqlite3ErrorMsg(pParse, "%s", zErr);
123707  sqlite3DbFree(db, zErr);
123708  sqlite3VtabEponymousTableClear(db, pMod);
123709  return 0;
123710  }
123711  return 1;
123712 }
123713 
123714 /*
123715 ** Erase the eponymous virtual table instance associated with
123716 ** virtual table module pMod, if it exists.
123717 */
123718 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
123719  Table *pTab = pMod->pEpoTab;
123720  if( pTab!=0 ){
123721  /* Mark the table as Ephemeral prior to deleting it, so that the
123722  ** sqlite3DeleteTable() routine will know that it is not stored in
123723  ** the schema. */
123724  pTab->tabFlags |= TF_Ephemeral;
123725  sqlite3DeleteTable(db, pTab);
123726  pMod->pEpoTab = 0;
123727  }
123728 }
123729 
123730 /*
123731 ** Return the ON CONFLICT resolution mode in effect for the virtual
123732 ** table update operation currently in progress.
123733 **
123734 ** The results of this routine are undefined unless it is called from
123735 ** within an xUpdate method.
123736 */
123737 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
123738  static const unsigned char aMap[] = {
123739  SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
123740  };
123741 #ifdef SQLITE_ENABLE_API_ARMOR
123742  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
123743 #endif
123744  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
123745  assert( OE_Ignore==4 && OE_Replace==5 );
123746  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
123747  return (int)aMap[db->vtabOnConflict-1];
123748 }
123749 
123750 /*
123751 ** Call from within the xCreate() or xConnect() methods to provide
123752 ** the SQLite core with additional information about the behavior
123753 ** of the virtual table being implemented.
123754 */
123755 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
123756  va_list ap;
123757  int rc = SQLITE_OK;
123758 
123759 #ifdef SQLITE_ENABLE_API_ARMOR
123760  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
123761 #endif
123762  sqlite3_mutex_enter(db->mutex);
123763  va_start(ap, op);
123764  switch( op ){
123765  case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
123766  VtabCtx *p = db->pVtabCtx;
123767  if( !p ){
123768  rc = SQLITE_MISUSE_BKPT;
123769  }else{
123770  assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
123771  p->pVTable->bConstraint = (u8)va_arg(ap, int);
123772  }
123773  break;
123774  }
123775  default:
123776  rc = SQLITE_MISUSE_BKPT;
123777  break;
123778  }
123779  va_end(ap);
123780 
123781  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
123782  sqlite3_mutex_leave(db->mutex);
123783  return rc;
123784 }
123785 
123786 #endif /* SQLITE_OMIT_VIRTUALTABLE */
123787 
123788 /************** End of vtab.c ************************************************/
123789 /************** Begin file wherecode.c ***************************************/
123790 /*
123791 ** 2015-06-06
123792 **
123793 ** The author disclaims copyright to this source code. In place of
123794 ** a legal notice, here is a blessing:
123795 **
123796 ** May you do good and not evil.
123797 ** May you find forgiveness for yourself and forgive others.
123798 ** May you share freely, never taking more than you give.
123799 **
123800 *************************************************************************
123801 ** This module contains C code that generates VDBE code used to process
123802 ** the WHERE clause of SQL statements.
123803 **
123804 ** This file was split off from where.c on 2015-06-06 in order to reduce the
123805 ** size of where.c and make it easier to edit. This file contains the routines
123806 ** that actually generate the bulk of the WHERE loop code. The original where.c
123807 ** file retains the code that does query planning and analysis.
123808 */
123809 /* #include "sqliteInt.h" */
123810 /************** Include whereInt.h in the middle of wherecode.c **************/
123811 /************** Begin file whereInt.h ****************************************/
123812 /*
123813 ** 2013-11-12
123814 **
123815 ** The author disclaims copyright to this source code. In place of
123816 ** a legal notice, here is a blessing:
123817 **
123818 ** May you do good and not evil.
123819 ** May you find forgiveness for yourself and forgive others.
123820 ** May you share freely, never taking more than you give.
123821 **
123822 *************************************************************************
123823 **
123824 ** This file contains structure and macro definitions for the query
123825 ** planner logic in "where.c". These definitions are broken out into
123826 ** a separate source file for easier editing.
123827 */
123828 
123829 /*
123830 ** Trace output macros
123831 */
123832 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
123833 /***/ int sqlite3WhereTrace;
123834 #endif
123835 #if defined(SQLITE_DEBUG) \
123836  && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
123837 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
123838 # define WHERETRACE_ENABLED 1
123839 #else
123840 # define WHERETRACE(K,X)
123841 #endif
123842 
123843 /* Forward references
123844 */
123845 typedef struct WhereClause WhereClause;
123846 typedef struct WhereMaskSet WhereMaskSet;
123847 typedef struct WhereOrInfo WhereOrInfo;
123848 typedef struct WhereAndInfo WhereAndInfo;
123849 typedef struct WhereLevel WhereLevel;
123850 typedef struct WhereLoop WhereLoop;
123851 typedef struct WherePath WherePath;
123852 typedef struct WhereTerm WhereTerm;
123853 typedef struct WhereLoopBuilder WhereLoopBuilder;
123854 typedef struct WhereScan WhereScan;
123855 typedef struct WhereOrCost WhereOrCost;
123856 typedef struct WhereOrSet WhereOrSet;
123857 
123858 /*
123859 ** This object contains information needed to implement a single nested
123860 ** loop in WHERE clause.
123861 **
123862 ** Contrast this object with WhereLoop. This object describes the
123863 ** implementation of the loop. WhereLoop describes the algorithm.
123864 ** This object contains a pointer to the WhereLoop algorithm as one of
123865 ** its elements.
123866 **
123867 ** The WhereInfo object contains a single instance of this object for
123868 ** each term in the FROM clause (which is to say, for each of the
123869 ** nested loops as implemented). The order of WhereLevel objects determines
123870 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
123871 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
123872 */
123873 struct WhereLevel {
123874  int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
123875  int iTabCur; /* The VDBE cursor used to access the table */
123876  int iIdxCur; /* The VDBE cursor used to access pIdx */
123877  int addrBrk; /* Jump here to break out of the loop */
123878  int addrNxt; /* Jump here to start the next IN combination */
123879  int addrSkip; /* Jump here for next iteration of skip-scan */
123880  int addrCont; /* Jump here to continue with the next loop cycle */
123881  int addrFirst; /* First instruction of interior of the loop */
123882  int addrBody; /* Beginning of the body of this loop */
123883 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
123884  u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
123885  int addrLikeRep; /* LIKE range processing address */
123886 #endif
123887  u8 iFrom; /* Which entry in the FROM clause */
123888  u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
123889  int p1, p2; /* Operands of the opcode used to ends the loop */
123890  union { /* Information that depends on pWLoop->wsFlags */
123891  struct {
123892  int nIn; /* Number of entries in aInLoop[] */
123893  struct InLoop {
123894  int iCur; /* The VDBE cursor used by this IN operator */
123895  int addrInTop; /* Top of the IN loop */
123896  u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
123897  } *aInLoop; /* Information about each nested IN operator */
123898  } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
123899  Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
123900  } u;
123901  struct WhereLoop *pWLoop; /* The selected WhereLoop object */
123902  Bitmask notReady; /* FROM entries not usable at this level */
123903 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123904  int addrVisit; /* Address at which row is visited */
123905 #endif
123906 };
123907 
123908 /*
123909 ** Each instance of this object represents an algorithm for evaluating one
123910 ** term of a join. Every term of the FROM clause will have at least
123911 ** one corresponding WhereLoop object (unless INDEXED BY constraints
123912 ** prevent a query solution - which is an error) and many terms of the
123913 ** FROM clause will have multiple WhereLoop objects, each describing a
123914 ** potential way of implementing that FROM-clause term, together with
123915 ** dependencies and cost estimates for using the chosen algorithm.
123916 **
123917 ** Query planning consists of building up a collection of these WhereLoop
123918 ** objects, then computing a particular sequence of WhereLoop objects, with
123919 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
123920 ** and that minimize the overall cost.
123921 */
123922 struct WhereLoop {
123923  Bitmask prereq; /* Bitmask of other loops that must run first */
123924  Bitmask maskSelf; /* Bitmask identifying table iTab */
123925 #ifdef SQLITE_DEBUG
123926  char cId; /* Symbolic ID of this loop for debugging use */
123927 #endif
123928  u8 iTab; /* Position in FROM clause of table for this loop */
123929  u8 iSortIdx; /* Sorting index number. 0==None */
123930  LogEst rSetup; /* One-time setup cost (ex: create transient index) */
123931  LogEst rRun; /* Cost of running each loop */
123932  LogEst nOut; /* Estimated number of output rows */
123933  union {
123934  struct { /* Information for internal btree tables */
123935  u16 nEq; /* Number of equality constraints */
123936  u16 nBtm; /* Size of BTM vector */
123937  u16 nTop; /* Size of TOP vector */
123938  Index *pIndex; /* Index used, or NULL */
123939  } btree;
123940  struct { /* Information for virtual tables */
123941  int idxNum; /* Index number */
123942  u8 needFree; /* True if sqlite3_free(idxStr) is needed */
123943  i8 isOrdered; /* True if satisfies ORDER BY */
123944  u16 omitMask; /* Terms that may be omitted */
123945  char *idxStr; /* Index identifier string */
123946  } vtab;
123947  } u;
123948  u32 wsFlags; /* WHERE_* flags describing the plan */
123949  u16 nLTerm; /* Number of entries in aLTerm[] */
123950  u16 nSkip; /* Number of NULL aLTerm[] entries */
123951  /**** whereLoopXfer() copies fields above ***********************/
123952 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
123953  u16 nLSlot; /* Number of slots allocated for aLTerm[] */
123954  WhereTerm **aLTerm; /* WhereTerms used */
123955  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
123956  WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
123957 };
123958 
123959 /* This object holds the prerequisites and the cost of running a
123960 ** subquery on one operand of an OR operator in the WHERE clause.
123961 ** See WhereOrSet for additional information
123962 */
123963 struct WhereOrCost {
123964  Bitmask prereq; /* Prerequisites */
123965  LogEst rRun; /* Cost of running this subquery */
123966  LogEst nOut; /* Number of outputs for this subquery */
123967 };
123968 
123969 /* The WhereOrSet object holds a set of possible WhereOrCosts that
123970 ** correspond to the subquery(s) of OR-clause processing. Only the
123971 ** best N_OR_COST elements are retained.
123972 */
123973 #define N_OR_COST 3
123974 struct WhereOrSet {
123975  u16 n; /* Number of valid a[] entries */
123976  WhereOrCost a[N_OR_COST]; /* Set of best costs */
123977 };
123978 
123979 /*
123980 ** Each instance of this object holds a sequence of WhereLoop objects
123981 ** that implement some or all of a query plan.
123982 **
123983 ** Think of each WhereLoop object as a node in a graph with arcs
123984 ** showing dependencies and costs for travelling between nodes. (That is
123985 ** not a completely accurate description because WhereLoop costs are a
123986 ** vector, not a scalar, and because dependencies are many-to-one, not
123987 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
123988 ** Then a WherePath object is a path through the graph that visits some
123989 ** or all of the WhereLoop objects once.
123990 **
123991 ** The "solver" works by creating the N best WherePath objects of length
123992 ** 1. Then using those as a basis to compute the N best WherePath objects
123993 ** of length 2. And so forth until the length of WherePaths equals the
123994 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
123995 ** at the end is the chosen query plan.
123996 */
123997 struct WherePath {
123998  Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
123999  Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
124000  LogEst nRow; /* Estimated number of rows generated by this path */
124001  LogEst rCost; /* Total cost of this path */
124002  LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
124003  i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
124004  WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
124005 };
124006 
124007 /*
124008 ** The query generator uses an array of instances of this structure to
124009 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
124010 ** clause subexpression is separated from the others by AND operators,
124011 ** usually, or sometimes subexpressions separated by OR.
124012 **
124013 ** All WhereTerms are collected into a single WhereClause structure.
124014 ** The following identity holds:
124015 **
124016 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
124017 **
124018 ** When a term is of the form:
124019 **
124020 ** X <op> <expr>
124021 **
124022 ** where X is a column name and <op> is one of certain operators,
124023 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
124024 ** cursor number and column number for X. WhereTerm.eOperator records
124025 ** the <op> using a bitmask encoding defined by WO_xxx below. The
124026 ** use of a bitmask encoding for the operator allows us to search
124027 ** quickly for terms that match any of several different operators.
124028 **
124029 ** A WhereTerm might also be two or more subterms connected by OR:
124030 **
124031 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
124032 **
124033 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
124034 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
124035 ** is collected about the OR clause.
124036 **
124037 ** If a term in the WHERE clause does not match either of the two previous
124038 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
124039 ** to the original subexpression content and wtFlags is set up appropriately
124040 ** but no other fields in the WhereTerm object are meaningful.
124041 **
124042 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
124043 ** but they do so indirectly. A single WhereMaskSet structure translates
124044 ** cursor number into bits and the translated bit is stored in the prereq
124045 ** fields. The translation is used in order to maximize the number of
124046 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
124047 ** spread out over the non-negative integers. For example, the cursor
124048 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
124049 ** translates these sparse cursor numbers into consecutive integers
124050 ** beginning with 0 in order to make the best possible use of the available
124051 ** bits in the Bitmask. So, in the example above, the cursor numbers
124052 ** would be mapped into integers 0 through 7.
124053 **
124054 ** The number of terms in a join is limited by the number of bits
124055 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
124056 ** is only able to process joins with 64 or fewer tables.
124057 */
124058 struct WhereTerm {
124059  Expr *pExpr; /* Pointer to the subexpression that is this term */
124060  WhereClause *pWC; /* The clause this term is part of */
124061  LogEst truthProb; /* Probability of truth for this expression */
124062  u16 wtFlags; /* TERM_xxx bit flags. See below */
124063  u16 eOperator; /* A WO_xx value describing <op> */
124064  u8 nChild; /* Number of children that must disable us */
124065  u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
124066  int iParent; /* Disable pWC->a[iParent] when this term disabled */
124067  int leftCursor; /* Cursor number of X in "X <op> <expr>" */
124068  int iField; /* Field in (?,?,?) IN (SELECT...) vector */
124069  union {
124070  int leftColumn; /* Column number of X in "X <op> <expr>" */
124071  WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
124072  WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
124073  } u;
124074  Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
124075  Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
124076 };
124077 
124078 /*
124079 ** Allowed values of WhereTerm.wtFlags
124080 */
124081 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
124082 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
124083 #define TERM_CODED 0x04 /* This term is already coded */
124084 #define TERM_COPIED 0x08 /* Has a child */
124085 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
124086 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
124087 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
124088 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
124089 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
124090 #else
124091 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
124092 #endif
124093 #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
124094 #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
124095 #define TERM_LIKE 0x400 /* The original LIKE operator */
124096 #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
124097 
124098 /*
124099 ** An instance of the WhereScan object is used as an iterator for locating
124100 ** terms in the WHERE clause that are useful to the query planner.
124101 */
124102 struct WhereScan {
124103  WhereClause *pOrigWC; /* Original, innermost WhereClause */
124104  WhereClause *pWC; /* WhereClause currently being scanned */
124105  const char *zCollName; /* Required collating sequence, if not NULL */
124106  Expr *pIdxExpr; /* Search for this index expression */
124107  char idxaff; /* Must match this affinity, if zCollName!=NULL */
124108  unsigned char nEquiv; /* Number of entries in aEquiv[] */
124109  unsigned char iEquiv; /* Next unused slot in aEquiv[] */
124110  u32 opMask; /* Acceptable operators */
124111  int k; /* Resume scanning at this->pWC->a[this->k] */
124112  int aiCur[11]; /* Cursors in the equivalence class */
124113  i16 aiColumn[11]; /* Corresponding column number in the eq-class */
124114 };
124115 
124116 /*
124117 ** An instance of the following structure holds all information about a
124118 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
124119 **
124120 ** Explanation of pOuter: For a WHERE clause of the form
124121 **
124122 ** a AND ((b AND c) OR (d AND e)) AND f
124123 **
124124 ** There are separate WhereClause objects for the whole clause and for
124125 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
124126 ** subclauses points to the WhereClause object for the whole clause.
124127 */
124128 struct WhereClause {
124129  WhereInfo *pWInfo; /* WHERE clause processing context */
124130  WhereClause *pOuter; /* Outer conjunction */
124131  u8 op; /* Split operator. TK_AND or TK_OR */
124132  int nTerm; /* Number of terms */
124133  int nSlot; /* Number of entries in a[] */
124134  WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
124135 #if defined(SQLITE_SMALL_STACK)
124136  WhereTerm aStatic[1]; /* Initial static space for a[] */
124137 #else
124138  WhereTerm aStatic[8]; /* Initial static space for a[] */
124139 #endif
124140 };
124141 
124142 /*
124143 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
124144 ** a dynamically allocated instance of the following structure.
124145 */
124146 struct WhereOrInfo {
124147  WhereClause wc; /* Decomposition into subterms */
124148  Bitmask indexable; /* Bitmask of all indexable tables in the clause */
124149 };
124150 
124151 /*
124152 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
124153 ** a dynamically allocated instance of the following structure.
124154 */
124155 struct WhereAndInfo {
124156  WhereClause wc; /* The subexpression broken out */
124157 };
124158 
124159 /*
124160 ** An instance of the following structure keeps track of a mapping
124161 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
124162 **
124163 ** The VDBE cursor numbers are small integers contained in
124164 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
124165 ** clause, the cursor numbers might not begin with 0 and they might
124166 ** contain gaps in the numbering sequence. But we want to make maximum
124167 ** use of the bits in our bitmasks. This structure provides a mapping
124168 ** from the sparse cursor numbers into consecutive integers beginning
124169 ** with 0.
124170 **
124171 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
124172 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
124173 **
124174 ** For example, if the WHERE clause expression used these VDBE
124175 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
124176 ** would map those cursor numbers into bits 0 through 5.
124177 **
124178 ** Note that the mapping is not necessarily ordered. In the example
124179 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
124180 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
124181 ** does not really matter. What is important is that sparse cursor
124182 ** numbers all get mapped into bit numbers that begin with 0 and contain
124183 ** no gaps.
124184 */
124185 struct WhereMaskSet {
124186  int n; /* Number of assigned cursor values */
124187  int ix[BMS]; /* Cursor assigned to each bit */
124188 };
124189 
124190 /*
124191 ** Initialize a WhereMaskSet object
124192 */
124193 #define initMaskSet(P) (P)->n=0
124194 
124195 /*
124196 ** This object is a convenience wrapper holding all information needed
124197 ** to construct WhereLoop objects for a particular query.
124198 */
124199 struct WhereLoopBuilder {
124200  WhereInfo *pWInfo; /* Information about this WHERE */
124201  WhereClause *pWC; /* WHERE clause terms */
124202  ExprList *pOrderBy; /* ORDER BY clause */
124203  WhereLoop *pNew; /* Template WhereLoop */
124204  WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
124205 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
124206  UnpackedRecord *pRec; /* Probe for stat4 (if required) */
124207  int nRecValid; /* Number of valid fields currently in pRec */
124208 #endif
124209 };
124210 
124211 /*
124212 ** The WHERE clause processing routine has two halves. The
124213 ** first part does the start of the WHERE loop and the second
124214 ** half does the tail of the WHERE loop. An instance of
124215 ** this structure is returned by the first half and passed
124216 ** into the second half to give some continuity.
124217 **
124218 ** An instance of this object holds the complete state of the query
124219 ** planner.
124220 */
124221 struct WhereInfo {
124222  Parse *pParse; /* Parsing and code generating context */
124223  SrcList *pTabList; /* List of tables in the join */
124224  ExprList *pOrderBy; /* The ORDER BY clause or NULL */
124225  ExprList *pDistinctSet; /* DISTINCT over all these values */
124226  LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
124227  int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
124228  int iContinue; /* Jump here to continue with next record */
124229  int iBreak; /* Jump here to break out of the loop */
124230  int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
124231  u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
124232  u8 nLevel; /* Number of nested loop */
124233  i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
124234  u8 sorted; /* True if really sorted (not just grouped) */
124235  u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
124236  u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
124237  u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
124238  u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
124239  int iTop; /* The very beginning of the WHERE loop */
124240  WhereLoop *pLoops; /* List of all WhereLoop objects */
124241  Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
124242  LogEst nRowOut; /* Estimated number of output rows */
124243  WhereClause sWC; /* Decomposition of the WHERE clause */
124244  WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
124245  WhereLevel a[1]; /* Information about each nest loop in WHERE */
124246 };
124247 
124248 /*
124249 ** Private interfaces - callable only by other where.c routines.
124250 **
124251 ** where.c:
124252 */
124253 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
124254 #ifdef WHERETRACE_ENABLED
124255 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
124256 #endif
124257 SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
124258  WhereClause *pWC, /* The WHERE clause to be searched */
124259  int iCur, /* Cursor number of LHS */
124260  int iColumn, /* Column number of LHS */
124261  Bitmask notReady, /* RHS must not overlap with this mask */
124262  u32 op, /* Mask of WO_xx values describing operator */
124263  Index *pIdx /* Must be compatible with this index, if not NULL */
124264 );
124265 
124266 /* wherecode.c: */
124267 #ifndef SQLITE_OMIT_EXPLAIN
124268 SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
124269  Parse *pParse, /* Parse context */
124270  SrcList *pTabList, /* Table list this loop refers to */
124271  WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
124272  int iLevel, /* Value for "level" column of output */
124273  int iFrom, /* Value for "from" column of output */
124274  u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
124275 );
124276 #else
124277 # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
124278 #endif /* SQLITE_OMIT_EXPLAIN */
124279 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
124280 SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
124281  Vdbe *v, /* Vdbe to add scanstatus entry to */
124282  SrcList *pSrclist, /* FROM clause pLvl reads data from */
124283  WhereLevel *pLvl, /* Level to add scanstatus() entry for */
124284  int addrExplain /* Address of OP_Explain (or 0) */
124285 );
124286 #else
124287 # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
124288 #endif
124289 SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
124290  WhereInfo *pWInfo, /* Complete information about the WHERE clause */
124291  int iLevel, /* Which level of pWInfo->a[] should be coded */
124292  Bitmask notReady /* Which tables are currently available */
124293 );
124294 
124295 /* whereexpr.c: */
124296 SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
124297 SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
124298 SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
124299 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
124300 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
124301 SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
124302 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
124303 
124304 
124305 
124306 
124307 
124308 /*
124309 ** Bitmasks for the operators on WhereTerm objects. These are all
124310 ** operators that are of interest to the query planner. An
124311 ** OR-ed combination of these values can be used when searching for
124312 ** particular WhereTerms within a WhereClause.
124313 **
124314 ** Value constraints:
124315 ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
124316 ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
124317 ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
124318 ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
124319 ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
124320 ** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
124321 */
124322 #define WO_IN 0x0001
124323 #define WO_EQ 0x0002
124324 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
124325 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
124326 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
124327 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
124328 #define WO_MATCH 0x0040
124329 #define WO_IS 0x0080
124330 #define WO_ISNULL 0x0100
124331 #define WO_OR 0x0200 /* Two or more OR-connected terms */
124332 #define WO_AND 0x0400 /* Two or more AND-connected terms */
124333 #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
124334 #define WO_NOOP 0x1000 /* This term does not restrict search space */
124335 
124336 #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
124337 #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
124338 
124339 /*
124340 ** These are definitions of bits in the WhereLoop.wsFlags field.
124341 ** The particular combination of bits in each WhereLoop help to
124342 ** determine the algorithm that WhereLoop represents.
124343 */
124344 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
124345 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
124346 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
124347 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
124348 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
124349 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
124350 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
124351 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
124352 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
124353 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
124354 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
124355 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
124356 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
124357 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
124358 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
124359 #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
124360 #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
124361 #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
124362 #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
124363 
124364 /************** End of whereInt.h ********************************************/
124365 /************** Continuing where we left off in wherecode.c ******************/
124366 
124367 #ifndef SQLITE_OMIT_EXPLAIN
124368 
124369 /*
124370 ** Return the name of the i-th column of the pIdx index.
124371 */
124372 static const char *explainIndexColumnName(Index *pIdx, int i){
124373  i = pIdx->aiColumn[i];
124374  if( i==XN_EXPR ) return "<expr>";
124375  if( i==XN_ROWID ) return "rowid";
124376  return pIdx->pTable->aCol[i].zName;
124377 }
124378 
124379 /*
124380 ** This routine is a helper for explainIndexRange() below
124381 **
124382 ** pStr holds the text of an expression that we are building up one term
124383 ** at a time. This routine adds a new term to the end of the expression.
124384 ** Terms are separated by AND so add the "AND" text for second and subsequent
124385 ** terms only.
124386 */
124387 static void explainAppendTerm(
124388  StrAccum *pStr, /* The text expression being built */
124389  Index *pIdx, /* Index to read column names from */
124390  int nTerm, /* Number of terms */
124391  int iTerm, /* Zero-based index of first term. */
124392  int bAnd, /* Non-zero to append " AND " */
124393  const char *zOp /* Name of the operator */
124394 ){
124395  int i;
124396 
124397  assert( nTerm>=1 );
124398  if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
124399 
124400  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
124401  for(i=0; i<nTerm; i++){
124402  if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
124403  sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
124404  }
124405  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
124406 
124407  sqlite3StrAccumAppend(pStr, zOp, 1);
124408 
124409  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
124410  for(i=0; i<nTerm; i++){
124411  if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
124412  sqlite3StrAccumAppend(pStr, "?", 1);
124413  }
124414  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
124415 }
124416 
124417 /*
124418 ** Argument pLevel describes a strategy for scanning table pTab. This
124419 ** function appends text to pStr that describes the subset of table
124420 ** rows scanned by the strategy in the form of an SQL expression.
124421 **
124422 ** For example, if the query:
124423 **
124424 ** SELECT * FROM t1 WHERE a=1 AND b>2;
124425 **
124426 ** is run and there is an index on (a, b), then this function returns a
124427 ** string similar to:
124428 **
124429 ** "a=? AND b>?"
124430 */
124431 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
124432  Index *pIndex = pLoop->u.btree.pIndex;
124433  u16 nEq = pLoop->u.btree.nEq;
124434  u16 nSkip = pLoop->nSkip;
124435  int i, j;
124436 
124437  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
124438  sqlite3StrAccumAppend(pStr, " (", 2);
124439  for(i=0; i<nEq; i++){
124440  const char *z = explainIndexColumnName(pIndex, i);
124441  if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
124442  sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
124443  }
124444 
124445  j = i;
124446  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
124447  explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
124448  i = 1;
124449  }
124450  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
124451  explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
124452  }
124453  sqlite3StrAccumAppend(pStr, ")", 1);
124454 }
124455 
124456 /*
124457 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
124458 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
124459 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
124460 ** is added to the output to describe the table scan strategy in pLevel.
124461 **
124462 ** If an OP_Explain opcode is added to the VM, its address is returned.
124463 ** Otherwise, if no OP_Explain is coded, zero is returned.
124464 */
124465 SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
124466  Parse *pParse, /* Parse context */
124467  SrcList *pTabList, /* Table list this loop refers to */
124468  WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
124469  int iLevel, /* Value for "level" column of output */
124470  int iFrom, /* Value for "from" column of output */
124471  u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
124472 ){
124473  int ret = 0;
124474 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
124475  if( pParse->explain==2 )
124476 #endif
124477  {
124478  struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
124479  Vdbe *v = pParse->pVdbe; /* VM being constructed */
124480  sqlite3 *db = pParse->db; /* Database handle */
124481  int iId = pParse->iSelectId; /* Select id (left-most output column) */
124482  int isSearch; /* True for a SEARCH. False for SCAN. */
124483  WhereLoop *pLoop; /* The controlling WhereLoop object */
124484  u32 flags; /* Flags that describe this loop */
124485  char *zMsg; /* Text to add to EQP output */
124486  StrAccum str; /* EQP output string */
124487  char zBuf[100]; /* Initial space for EQP output string */
124488 
124489  pLoop = pLevel->pWLoop;
124490  flags = pLoop->wsFlags;
124491  if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
124492 
124493  isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
124494  || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
124495  || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
124496 
124497  sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
124498  sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
124499  if( pItem->pSelect ){
124500  sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
124501  }else{
124502  sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
124503  }
124504 
124505  if( pItem->zAlias ){
124506  sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
124507  }
124508  if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
124509  const char *zFmt = 0;
124510  Index *pIdx;
124511 
124512  assert( pLoop->u.btree.pIndex!=0 );
124513  pIdx = pLoop->u.btree.pIndex;
124514  assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
124515  if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
124516  if( isSearch ){
124517  zFmt = "PRIMARY KEY";
124518  }
124519  }else if( flags & WHERE_PARTIALIDX ){
124520  zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
124521  }else if( flags & WHERE_AUTO_INDEX ){
124522  zFmt = "AUTOMATIC COVERING INDEX";
124523  }else if( flags & WHERE_IDX_ONLY ){
124524  zFmt = "COVERING INDEX %s";
124525  }else{
124526  zFmt = "INDEX %s";
124527  }
124528  if( zFmt ){
124529  sqlite3StrAccumAppend(&str, " USING ", 7);
124530  sqlite3XPrintf(&str, zFmt, pIdx->zName);
124531  explainIndexRange(&str, pLoop);
124532  }
124533  }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
124534  const char *zRangeOp;
124535  if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
124536  zRangeOp = "=";
124537  }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
124538  zRangeOp = ">? AND rowid<";
124539  }else if( flags&WHERE_BTM_LIMIT ){
124540  zRangeOp = ">";
124541  }else{
124542  assert( flags&WHERE_TOP_LIMIT);
124543  zRangeOp = "<";
124544  }
124545  sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
124546  }
124547 #ifndef SQLITE_OMIT_VIRTUALTABLE
124548  else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
124549  sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
124550  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
124551  }
124552 #endif
124553 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
124554  if( pLoop->nOut>=10 ){
124555  sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
124556  }else{
124557  sqlite3StrAccumAppend(&str, " (~1 row)", 9);
124558  }
124559 #endif
124560  zMsg = sqlite3StrAccumFinish(&str);
124561  ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
124562  }
124563  return ret;
124564 }
124565 #endif /* SQLITE_OMIT_EXPLAIN */
124566 
124567 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
124568 /*
124569 ** Configure the VM passed as the first argument with an
124570 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
124571 ** implement level pLvl. Argument pSrclist is a pointer to the FROM
124572 ** clause that the scan reads data from.
124573 **
124574 ** If argument addrExplain is not 0, it must be the address of an
124575 ** OP_Explain instruction that describes the same loop.
124576 */
124577 SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
124578  Vdbe *v, /* Vdbe to add scanstatus entry to */
124579  SrcList *pSrclist, /* FROM clause pLvl reads data from */
124580  WhereLevel *pLvl, /* Level to add scanstatus() entry for */
124581  int addrExplain /* Address of OP_Explain (or 0) */
124582 ){
124583  const char *zObj = 0;
124584  WhereLoop *pLoop = pLvl->pWLoop;
124585  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
124586  zObj = pLoop->u.btree.pIndex->zName;
124587  }else{
124588  zObj = pSrclist->a[pLvl->iFrom].zName;
124589  }
124590  sqlite3VdbeScanStatus(
124591  v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
124592  );
124593 }
124594 #endif
124595 
124596 
124597 /*
124598 ** Disable a term in the WHERE clause. Except, do not disable the term
124599 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
124600 ** or USING clause of that join.
124601 **
124602 ** Consider the term t2.z='ok' in the following queries:
124603 **
124604 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
124605 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
124606 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
124607 **
124608 ** The t2.z='ok' is disabled in the in (2) because it originates
124609 ** in the ON clause. The term is disabled in (3) because it is not part
124610 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
124611 **
124612 ** Disabling a term causes that term to not be tested in the inner loop
124613 ** of the join. Disabling is an optimization. When terms are satisfied
124614 ** by indices, we disable them to prevent redundant tests in the inner
124615 ** loop. We would get the correct results if nothing were ever disabled,
124616 ** but joins might run a little slower. The trick is to disable as much
124617 ** as we can without disabling too much. If we disabled in (1), we'd get
124618 ** the wrong answer. See ticket #813.
124619 **
124620 ** If all the children of a term are disabled, then that term is also
124621 ** automatically disabled. In this way, terms get disabled if derived
124622 ** virtual terms are tested first. For example:
124623 **
124624 ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
124625 ** \___________/ \______/ \_____/
124626 ** parent child1 child2
124627 **
124628 ** Only the parent term was in the original WHERE clause. The child1
124629 ** and child2 terms were added by the LIKE optimization. If both of
124630 ** the virtual child terms are valid, then testing of the parent can be
124631 ** skipped.
124632 **
124633 ** Usually the parent term is marked as TERM_CODED. But if the parent
124634 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
124635 ** The TERM_LIKECOND marking indicates that the term should be coded inside
124636 ** a conditional such that is only evaluated on the second pass of a
124637 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
124638 */
124639 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
124640  int nLoop = 0;
124641  while( ALWAYS(pTerm!=0)
124642  && (pTerm->wtFlags & TERM_CODED)==0
124643  && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
124644  && (pLevel->notReady & pTerm->prereqAll)==0
124645  ){
124646  if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
124647  pTerm->wtFlags |= TERM_LIKECOND;
124648  }else{
124649  pTerm->wtFlags |= TERM_CODED;
124650  }
124651  if( pTerm->iParent<0 ) break;
124652  pTerm = &pTerm->pWC->a[pTerm->iParent];
124653  pTerm->nChild--;
124654  if( pTerm->nChild!=0 ) break;
124655  nLoop++;
124656  }
124657 }
124658 
124659 /*
124660 ** Code an OP_Affinity opcode to apply the column affinity string zAff
124661 ** to the n registers starting at base.
124662 **
124663 ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
124664 ** beginning and end of zAff are ignored. If all entries in zAff are
124665 ** SQLITE_AFF_BLOB, then no code gets generated.
124666 **
124667 ** This routine makes its own copy of zAff so that the caller is free
124668 ** to modify zAff after this routine returns.
124669 */
124670 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
124671  Vdbe *v = pParse->pVdbe;
124672  if( zAff==0 ){
124673  assert( pParse->db->mallocFailed );
124674  return;
124675  }
124676  assert( v!=0 );
124677 
124678  /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
124679  ** and end of the affinity string.
124680  */
124681  while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
124682  n--;
124683  base++;
124684  zAff++;
124685  }
124686  while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
124687  n--;
124688  }
124689 
124690  /* Code the OP_Affinity opcode if there is anything left to do. */
124691  if( n>0 ){
124692  sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
124693  sqlite3ExprCacheAffinityChange(pParse, base, n);
124694  }
124695 }
124696 
124697 /*
124698 ** Expression pRight, which is the RHS of a comparison operation, is
124699 ** either a vector of n elements or, if n==1, a scalar expression.
124700 ** Before the comparison operation, affinity zAff is to be applied
124701 ** to the pRight values. This function modifies characters within the
124702 ** affinity string to SQLITE_AFF_BLOB if either:
124703 **
124704 ** * the comparison will be performed with no affinity, or
124705 ** * the affinity change in zAff is guaranteed not to change the value.
124706 */
124707 static void updateRangeAffinityStr(
124708  Expr *pRight, /* RHS of comparison */
124709  int n, /* Number of vector elements in comparison */
124710  char *zAff /* Affinity string to modify */
124711 ){
124712  int i;
124713  for(i=0; i<n; i++){
124714  Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
124715  if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
124716  || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
124717  ){
124718  zAff[i] = SQLITE_AFF_BLOB;
124719  }
124720  }
124721 }
124722 
124723 /*
124724 ** Generate code for a single equality term of the WHERE clause. An equality
124725 ** term can be either X=expr or X IN (...). pTerm is the term to be
124726 ** coded.
124727 **
124728 ** The current value for the constraint is left in a register, the index
124729 ** of which is returned. An attempt is made store the result in iTarget but
124730 ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
124731 ** constraint is a TK_EQ or TK_IS, then the current value might be left in
124732 ** some other register and it is the caller's responsibility to compensate.
124733 **
124734 ** For a constraint of the form X=expr, the expression is evaluated in
124735 ** straight-line code. For constraints of the form X IN (...)
124736 ** this routine sets up a loop that will iterate over all values of X.
124737 */
124738 static int codeEqualityTerm(
124739  Parse *pParse, /* The parsing context */
124740  WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
124741  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
124742  int iEq, /* Index of the equality term within this level */
124743  int bRev, /* True for reverse-order IN operations */
124744  int iTarget /* Attempt to leave results in this register */
124745 ){
124746  Expr *pX = pTerm->pExpr;
124747  Vdbe *v = pParse->pVdbe;
124748  int iReg; /* Register holding results */
124749 
124750  assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
124751  assert( iTarget>0 );
124752  if( pX->op==TK_EQ || pX->op==TK_IS ){
124753  iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
124754  }else if( pX->op==TK_ISNULL ){
124755  iReg = iTarget;
124756  sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
124757 #ifndef SQLITE_OMIT_SUBQUERY
124758  }else{
124759  int eType = IN_INDEX_NOOP;
124760  int iTab;
124761  struct InLoop *pIn;
124762  WhereLoop *pLoop = pLevel->pWLoop;
124763  int i;
124764  int nEq = 0;
124765  int *aiMap = 0;
124766 
124767  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
124768  && pLoop->u.btree.pIndex!=0
124769  && pLoop->u.btree.pIndex->aSortOrder[iEq]
124770  ){
124771  testcase( iEq==0 );
124772  testcase( bRev );
124773  bRev = !bRev;
124774  }
124775  assert( pX->op==TK_IN );
124776  iReg = iTarget;
124777 
124778  for(i=0; i<iEq; i++){
124779  if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
124780  disableTerm(pLevel, pTerm);
124781  return iTarget;
124782  }
124783  }
124784  for(i=iEq;i<pLoop->nLTerm; i++){
124785  if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
124786  }
124787 
124788  if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
124789  eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
124790  }else{
124791  Select *pSelect = pX->x.pSelect;
124792  sqlite3 *db = pParse->db;
124793  ExprList *pOrigRhs = pSelect->pEList;
124794  ExprList *pOrigLhs = pX->pLeft->x.pList;
124795  ExprList *pRhs = 0; /* New Select.pEList for RHS */
124796  ExprList *pLhs = 0; /* New pX->pLeft vector */
124797 
124798  for(i=iEq;i<pLoop->nLTerm; i++){
124799  if( pLoop->aLTerm[i]->pExpr==pX ){
124800  int iField = pLoop->aLTerm[i]->iField - 1;
124801  Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
124802  Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
124803 
124804  pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
124805  pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
124806  }
124807  }
124808  if( !db->mallocFailed ){
124809  Expr *pLeft = pX->pLeft;
124810 
124811  if( pSelect->pOrderBy ){
124812  /* If the SELECT statement has an ORDER BY clause, zero the
124813  ** iOrderByCol variables. These are set to non-zero when an
124814  ** ORDER BY term exactly matches one of the terms of the
124815  ** result-set. Since the result-set of the SELECT statement may
124816  ** have been modified or reordered, these variables are no longer
124817  ** set correctly. Since setting them is just an optimization,
124818  ** it's easiest just to zero them here. */
124819  ExprList *pOrderBy = pSelect->pOrderBy;
124820  for(i=0; i<pOrderBy->nExpr; i++){
124821  pOrderBy->a[i].u.x.iOrderByCol = 0;
124822  }
124823  }
124824 
124825  /* Take care here not to generate a TK_VECTOR containing only a
124826  ** single value. Since the parser never creates such a vector, some
124827  ** of the subroutines do not handle this case. */
124828  if( pLhs->nExpr==1 ){
124829  pX->pLeft = pLhs->a[0].pExpr;
124830  }else{
124831  pLeft->x.pList = pLhs;
124832  aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
124833  testcase( aiMap==0 );
124834  }
124835  pSelect->pEList = pRhs;
124836  eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
124837  testcase( aiMap!=0 && aiMap[0]!=0 );
124838  pSelect->pEList = pOrigRhs;
124839  pLeft->x.pList = pOrigLhs;
124840  pX->pLeft = pLeft;
124841  }
124842  sqlite3ExprListDelete(pParse->db, pLhs);
124843  sqlite3ExprListDelete(pParse->db, pRhs);
124844  }
124845 
124846  if( eType==IN_INDEX_INDEX_DESC ){
124847  testcase( bRev );
124848  bRev = !bRev;
124849  }
124850  iTab = pX->iTable;
124851  sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
124852  VdbeCoverageIf(v, bRev);
124853  VdbeCoverageIf(v, !bRev);
124854  assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
124855 
124856  pLoop->wsFlags |= WHERE_IN_ABLE;
124857  if( pLevel->u.in.nIn==0 ){
124858  pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
124859  }
124860 
124861  i = pLevel->u.in.nIn;
124862  pLevel->u.in.nIn += nEq;
124863  pLevel->u.in.aInLoop =
124864  sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
124865  sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
124866  pIn = pLevel->u.in.aInLoop;
124867  if( pIn ){
124868  int iMap = 0; /* Index in aiMap[] */
124869  pIn += i;
124870  for(i=iEq;i<pLoop->nLTerm; i++){
124871  if( pLoop->aLTerm[i]->pExpr==pX ){
124872  int iOut = iReg + i - iEq;
124873  if( eType==IN_INDEX_ROWID ){
124874  testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */
124875  pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
124876  }else{
124877  int iCol = aiMap ? aiMap[iMap++] : 0;
124878  pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
124879  }
124880  sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
124881  if( i==iEq ){
124882  pIn->iCur = iTab;
124883  pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
124884  }else{
124885  pIn->eEndLoopOp = OP_Noop;
124886  }
124887  pIn++;
124888  }
124889  }
124890  }else{
124891  pLevel->u.in.nIn = 0;
124892  }
124893  sqlite3DbFree(pParse->db, aiMap);
124894 #endif
124895  }
124896  disableTerm(pLevel, pTerm);
124897  return iReg;
124898 }
124899 
124900 /*
124901 ** Generate code that will evaluate all == and IN constraints for an
124902 ** index scan.
124903 **
124904 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
124905 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
124906 ** The index has as many as three equality constraints, but in this
124907 ** example, the third "c" value is an inequality. So only two
124908 ** constraints are coded. This routine will generate code to evaluate
124909 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
124910 ** in consecutive registers and the index of the first register is returned.
124911 **
124912 ** In the example above nEq==2. But this subroutine works for any value
124913 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
124914 ** The only thing it does is allocate the pLevel->iMem memory cell and
124915 ** compute the affinity string.
124916 **
124917 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
124918 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
124919 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
124920 ** occurs after the nEq quality constraints.
124921 **
124922 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
124923 ** the index of the first memory cell in that range. The code that
124924 ** calls this routine will use that memory range to store keys for
124925 ** start and termination conditions of the loop.
124926 ** key value of the loop. If one or more IN operators appear, then
124927 ** this routine allocates an additional nEq memory cells for internal
124928 ** use.
124929 **
124930 ** Before returning, *pzAff is set to point to a buffer containing a
124931 ** copy of the column affinity string of the index allocated using
124932 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
124933 ** with equality constraints that use BLOB or NONE affinity are set to
124934 ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
124935 **
124936 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
124937 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
124938 **
124939 ** In the example above, the index on t1(a) has TEXT affinity. But since
124940 ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
124941 ** no conversion should be attempted before using a t2.b value as part of
124942 ** a key to search the index. Hence the first byte in the returned affinity
124943 ** string in this example would be set to SQLITE_AFF_BLOB.
124944 */
124945 static int codeAllEqualityTerms(
124946  Parse *pParse, /* Parsing context */
124947  WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
124948  int bRev, /* Reverse the order of IN operators */
124949  int nExtraReg, /* Number of extra registers to allocate */
124950  char **pzAff /* OUT: Set to point to affinity string */
124951 ){
124952  u16 nEq; /* The number of == or IN constraints to code */
124953  u16 nSkip; /* Number of left-most columns to skip */
124954  Vdbe *v = pParse->pVdbe; /* The vm under construction */
124955  Index *pIdx; /* The index being used for this loop */
124956  WhereTerm *pTerm; /* A single constraint term */
124957  WhereLoop *pLoop; /* The WhereLoop object */
124958  int j; /* Loop counter */
124959  int regBase; /* Base register */
124960  int nReg; /* Number of registers to allocate */
124961  char *zAff; /* Affinity string to return */
124962 
124963  /* This module is only called on query plans that use an index. */
124964  pLoop = pLevel->pWLoop;
124965  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
124966  nEq = pLoop->u.btree.nEq;
124967  nSkip = pLoop->nSkip;
124968  pIdx = pLoop->u.btree.pIndex;
124969  assert( pIdx!=0 );
124970 
124971  /* Figure out how many memory cells we will need then allocate them.
124972  */
124973  regBase = pParse->nMem + 1;
124974  nReg = pLoop->u.btree.nEq + nExtraReg;
124975  pParse->nMem += nReg;
124976 
124977  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
124978  assert( zAff!=0 || pParse->db->mallocFailed );
124979 
124980  if( nSkip ){
124981  int iIdxCur = pLevel->iIdxCur;
124982  sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
124983  VdbeCoverageIf(v, bRev==0);
124984  VdbeCoverageIf(v, bRev!=0);
124985  VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
124986  j = sqlite3VdbeAddOp0(v, OP_Goto);
124987  pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
124988  iIdxCur, 0, regBase, nSkip);
124989  VdbeCoverageIf(v, bRev==0);
124990  VdbeCoverageIf(v, bRev!=0);
124991  sqlite3VdbeJumpHere(v, j);
124992  for(j=0; j<nSkip; j++){
124993  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
124994  testcase( pIdx->aiColumn[j]==XN_EXPR );
124995  VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
124996  }
124997  }
124998 
124999  /* Evaluate the equality constraints
125000  */
125001  assert( zAff==0 || (int)strlen(zAff)>=nEq );
125002  for(j=nSkip; j<nEq; j++){
125003  int r1;
125004  pTerm = pLoop->aLTerm[j];
125005  assert( pTerm!=0 );
125006  /* The following testcase is true for indices with redundant columns.
125007  ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
125008  testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
125009  testcase( pTerm->wtFlags & TERM_VIRTUAL );
125010  r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
125011  if( r1!=regBase+j ){
125012  if( nReg==1 ){
125013  sqlite3ReleaseTempReg(pParse, regBase);
125014  regBase = r1;
125015  }else{
125016  sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
125017  }
125018  }
125019  if( pTerm->eOperator & WO_IN ){
125020  if( pTerm->pExpr->flags & EP_xIsSelect ){
125021  /* No affinity ever needs to be (or should be) applied to a value
125022  ** from the RHS of an "? IN (SELECT ...)" expression. The
125023  ** sqlite3FindInIndex() routine has already ensured that the
125024  ** affinity of the comparison has been applied to the value. */
125025  if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
125026  }
125027  }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
125028  Expr *pRight = pTerm->pExpr->pRight;
125029  if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
125030  sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
125031  VdbeCoverage(v);
125032  }
125033  if( zAff ){
125034  if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
125035  zAff[j] = SQLITE_AFF_BLOB;
125036  }
125037  if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
125038  zAff[j] = SQLITE_AFF_BLOB;
125039  }
125040  }
125041  }
125042  }
125043  *pzAff = zAff;
125044  return regBase;
125045 }
125046 
125047 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
125048 /*
125049 ** If the most recently coded instruction is a constant range constraint
125050 ** (a string literal) that originated from the LIKE optimization, then
125051 ** set P3 and P5 on the OP_String opcode so that the string will be cast
125052 ** to a BLOB at appropriate times.
125053 **
125054 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
125055 ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
125056 ** scan loop run twice, once for strings and a second time for BLOBs.
125057 ** The OP_String opcodes on the second pass convert the upper and lower
125058 ** bound string constants to blobs. This routine makes the necessary changes
125059 ** to the OP_String opcodes for that to happen.
125060 **
125061 ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
125062 ** only the one pass through the string space is required, so this routine
125063 ** becomes a no-op.
125064 */
125065 static void whereLikeOptimizationStringFixup(
125066  Vdbe *v, /* prepared statement under construction */
125067  WhereLevel *pLevel, /* The loop that contains the LIKE operator */
125068  WhereTerm *pTerm /* The upper or lower bound just coded */
125069 ){
125070  if( pTerm->wtFlags & TERM_LIKEOPT ){
125071  VdbeOp *pOp;
125072  assert( pLevel->iLikeRepCntr>0 );
125073  pOp = sqlite3VdbeGetOp(v, -1);
125074  assert( pOp!=0 );
125075  assert( pOp->opcode==OP_String8
125076  || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
125077  pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
125078  pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
125079  }
125080 }
125081 #else
125082 # define whereLikeOptimizationStringFixup(A,B,C)
125083 #endif
125084 
125085 #ifdef SQLITE_ENABLE_CURSOR_HINTS
125086 /*
125087 ** Information is passed from codeCursorHint() down to individual nodes of
125088 ** the expression tree (by sqlite3WalkExpr()) using an instance of this
125089 ** structure.
125090 */
125091 struct CCurHint {
125092  int iTabCur; /* Cursor for the main table */
125093  int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
125094  Index *pIdx; /* The index used to access the table */
125095 };
125096 
125097 /*
125098 ** This function is called for every node of an expression that is a candidate
125099 ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
125100 ** the table CCurHint.iTabCur, verify that the same column can be
125101 ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
125102 */
125103 static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
125104  struct CCurHint *pHint = pWalker->u.pCCurHint;
125105  assert( pHint->pIdx!=0 );
125106  if( pExpr->op==TK_COLUMN
125107  && pExpr->iTable==pHint->iTabCur
125108  && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
125109  ){
125110  pWalker->eCode = 1;
125111  }
125112  return WRC_Continue;
125113 }
125114 
125115 /*
125116 ** Test whether or not expression pExpr, which was part of a WHERE clause,
125117 ** should be included in the cursor-hint for a table that is on the rhs
125118 ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
125119 ** expression is not suitable.
125120 **
125121 ** An expression is unsuitable if it might evaluate to non NULL even if
125122 ** a TK_COLUMN node that does affect the value of the expression is set
125123 ** to NULL. For example:
125124 **
125125 ** col IS NULL
125126 ** col IS NOT NULL
125127 ** coalesce(col, 1)
125128 ** CASE WHEN col THEN 0 ELSE 1 END
125129 */
125130 static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
125131  if( pExpr->op==TK_IS
125132  || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
125133  || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
125134  ){
125135  pWalker->eCode = 1;
125136  }else if( pExpr->op==TK_FUNCTION ){
125137  int d1;
125138  char d2[3];
125139  if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
125140  pWalker->eCode = 1;
125141  }
125142  }
125143 
125144  return WRC_Continue;
125145 }
125146 
125147 
125148 /*
125149 ** This function is called on every node of an expression tree used as an
125150 ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
125151 ** that accesses any table other than the one identified by
125152 ** CCurHint.iTabCur, then do the following:
125153 **
125154 ** 1) allocate a register and code an OP_Column instruction to read
125155 ** the specified column into the new register, and
125156 **
125157 ** 2) transform the expression node to a TK_REGISTER node that reads
125158 ** from the newly populated register.
125159 **
125160 ** Also, if the node is a TK_COLUMN that does access the table idenified
125161 ** by pCCurHint.iTabCur, and an index is being used (which we will
125162 ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
125163 ** an access of the index rather than the original table.
125164 */
125165 static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
125166  int rc = WRC_Continue;
125167  struct CCurHint *pHint = pWalker->u.pCCurHint;
125168  if( pExpr->op==TK_COLUMN ){
125169  if( pExpr->iTable!=pHint->iTabCur ){
125170  Vdbe *v = pWalker->pParse->pVdbe;
125171  int reg = ++pWalker->pParse->nMem; /* Register for column value */
125172  sqlite3ExprCodeGetColumnOfTable(
125173  v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
125174  );
125175  pExpr->op = TK_REGISTER;
125176  pExpr->iTable = reg;
125177  }else if( pHint->pIdx!=0 ){
125178  pExpr->iTable = pHint->iIdxCur;
125179  pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
125180  assert( pExpr->iColumn>=0 );
125181  }
125182  }else if( pExpr->op==TK_AGG_FUNCTION ){
125183  /* An aggregate function in the WHERE clause of a query means this must
125184  ** be a correlated sub-query, and expression pExpr is an aggregate from
125185  ** the parent context. Do not walk the function arguments in this case.
125186  **
125187  ** todo: It should be possible to replace this node with a TK_REGISTER
125188  ** expression, as the result of the expression must be stored in a
125189  ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
125190  rc = WRC_Prune;
125191  }
125192  return rc;
125193 }
125194 
125195 /*
125196 ** Insert an OP_CursorHint instruction if it is appropriate to do so.
125197 */
125198 static void codeCursorHint(
125199  struct SrcList_item *pTabItem, /* FROM clause item */
125200  WhereInfo *pWInfo, /* The where clause */
125201  WhereLevel *pLevel, /* Which loop to provide hints for */
125202  WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
125203 ){
125204  Parse *pParse = pWInfo->pParse;
125205  sqlite3 *db = pParse->db;
125206  Vdbe *v = pParse->pVdbe;
125207  Expr *pExpr = 0;
125208  WhereLoop *pLoop = pLevel->pWLoop;
125209  int iCur;
125210  WhereClause *pWC;
125211  WhereTerm *pTerm;
125212  int i, j;
125213  struct CCurHint sHint;
125214  Walker sWalker;
125215 
125216  if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
125217  iCur = pLevel->iTabCur;
125218  assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
125219  sHint.iTabCur = iCur;
125220  sHint.iIdxCur = pLevel->iIdxCur;
125221  sHint.pIdx = pLoop->u.btree.pIndex;
125222  memset(&sWalker, 0, sizeof(sWalker));
125223  sWalker.pParse = pParse;
125224  sWalker.u.pCCurHint = &sHint;
125225  pWC = &pWInfo->sWC;
125226  for(i=0; i<pWC->nTerm; i++){
125227  pTerm = &pWC->a[i];
125228  if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125229  if( pTerm->prereqAll & pLevel->notReady ) continue;
125230 
125231  /* Any terms specified as part of the ON(...) clause for any LEFT
125232  ** JOIN for which the current table is not the rhs are omitted
125233  ** from the cursor-hint.
125234  **
125235  ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
125236  ** that were specified as part of the WHERE clause must be excluded.
125237  ** This is to address the following:
125238  **
125239  ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
125240  **
125241  ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
125242  ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
125243  ** pushed down to the cursor, this row is filtered out, causing
125244  ** SQLite to synthesize a row of NULL values. Which does match the
125245  ** WHERE clause, and so the query returns a row. Which is incorrect.
125246  **
125247  ** For the same reason, WHERE terms such as:
125248  **
125249  ** WHERE 1 = (t2.c IS NULL)
125250  **
125251  ** are also excluded. See codeCursorHintIsOrFunction() for details.
125252  */
125253  if( pTabItem->fg.jointype & JT_LEFT ){
125254  Expr *pExpr = pTerm->pExpr;
125255  if( !ExprHasProperty(pExpr, EP_FromJoin)
125256  || pExpr->iRightJoinTable!=pTabItem->iCursor
125257  ){
125258  sWalker.eCode = 0;
125259  sWalker.xExprCallback = codeCursorHintIsOrFunction;
125260  sqlite3WalkExpr(&sWalker, pTerm->pExpr);
125261  if( sWalker.eCode ) continue;
125262  }
125263  }else{
125264  if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
125265  }
125266 
125267  /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
125268  ** the cursor. These terms are not needed as hints for a pure range
125269  ** scan (that has no == terms) so omit them. */
125270  if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
125271  for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
125272  if( j<pLoop->nLTerm ) continue;
125273  }
125274 
125275  /* No subqueries or non-deterministic functions allowed */
125276  if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
125277 
125278  /* For an index scan, make sure referenced columns are actually in
125279  ** the index. */
125280  if( sHint.pIdx!=0 ){
125281  sWalker.eCode = 0;
125282  sWalker.xExprCallback = codeCursorHintCheckExpr;
125283  sqlite3WalkExpr(&sWalker, pTerm->pExpr);
125284  if( sWalker.eCode ) continue;
125285  }
125286 
125287  /* If we survive all prior tests, that means this term is worth hinting */
125288  pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
125289  }
125290  if( pExpr!=0 ){
125291  sWalker.xExprCallback = codeCursorHintFixExpr;
125292  sqlite3WalkExpr(&sWalker, pExpr);
125293  sqlite3VdbeAddOp4(v, OP_CursorHint,
125294  (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
125295  (const char*)pExpr, P4_EXPR);
125296  }
125297 }
125298 #else
125299 # define codeCursorHint(A,B,C,D) /* No-op */
125300 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
125301 
125302 /*
125303 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
125304 ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
125305 ** function generates code to do a deferred seek of cursor iCur to the
125306 ** rowid stored in register iRowid.
125307 **
125308 ** Normally, this is just:
125309 **
125310 ** OP_Seek $iCur $iRowid
125311 **
125312 ** However, if the scan currently being coded is a branch of an OR-loop and
125313 ** the statement currently being coded is a SELECT, then P3 of the OP_Seek
125314 ** is set to iIdxCur and P4 is set to point to an array of integers
125315 ** containing one entry for each column of the table cursor iCur is open
125316 ** on. For each table column, if the column is the i'th column of the
125317 ** index, then the corresponding array entry is set to (i+1). If the column
125318 ** does not appear in the index at all, the array entry is set to 0.
125319 */
125320 static void codeDeferredSeek(
125321  WhereInfo *pWInfo, /* Where clause context */
125322  Index *pIdx, /* Index scan is using */
125323  int iCur, /* Cursor for IPK b-tree */
125324  int iIdxCur /* Index cursor */
125325 ){
125326  Parse *pParse = pWInfo->pParse; /* Parse context */
125327  Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
125328 
125329  assert( iIdxCur>0 );
125330  assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
125331 
125332  sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
125333  if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
125334  && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
125335  ){
125336  int i;
125337  Table *pTab = pIdx->pTable;
125338  int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
125339  if( ai ){
125340  ai[0] = pTab->nCol;
125341  for(i=0; i<pIdx->nColumn-1; i++){
125342  assert( pIdx->aiColumn[i]<pTab->nCol );
125343  if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
125344  }
125345  sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
125346  }
125347  }
125348 }
125349 
125350 /*
125351 ** If the expression passed as the second argument is a vector, generate
125352 ** code to write the first nReg elements of the vector into an array
125353 ** of registers starting with iReg.
125354 **
125355 ** If the expression is not a vector, then nReg must be passed 1. In
125356 ** this case, generate code to evaluate the expression and leave the
125357 ** result in register iReg.
125358 */
125359 static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
125360  assert( nReg>0 );
125361  if( sqlite3ExprIsVector(p) ){
125362 #ifndef SQLITE_OMIT_SUBQUERY
125363  if( (p->flags & EP_xIsSelect) ){
125364  Vdbe *v = pParse->pVdbe;
125365  int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
125366  sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
125367  }else
125368 #endif
125369  {
125370  int i;
125371  ExprList *pList = p->x.pList;
125372  assert( nReg<=pList->nExpr );
125373  for(i=0; i<nReg; i++){
125374  sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
125375  }
125376  }
125377  }else{
125378  assert( nReg==1 );
125379  sqlite3ExprCode(pParse, p, iReg);
125380  }
125381 }
125382 
125383 /*
125384 ** Generate code for the start of the iLevel-th loop in the WHERE clause
125385 ** implementation described by pWInfo.
125386 */
125387 SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
125388  WhereInfo *pWInfo, /* Complete information about the WHERE clause */
125389  int iLevel, /* Which level of pWInfo->a[] should be coded */
125390  Bitmask notReady /* Which tables are currently available */
125391 ){
125392  int j, k; /* Loop counters */
125393  int iCur; /* The VDBE cursor for the table */
125394  int addrNxt; /* Where to jump to continue with the next IN case */
125395  int omitTable; /* True if we use the index only */
125396  int bRev; /* True if we need to scan in reverse order */
125397  WhereLevel *pLevel; /* The where level to be coded */
125398  WhereLoop *pLoop; /* The WhereLoop object being coded */
125399  WhereClause *pWC; /* Decomposition of the entire WHERE clause */
125400  WhereTerm *pTerm; /* A WHERE clause term */
125401  Parse *pParse; /* Parsing context */
125402  sqlite3 *db; /* Database connection */
125403  Vdbe *v; /* The prepared stmt under constructions */
125404  struct SrcList_item *pTabItem; /* FROM clause term being coded */
125405  int addrBrk; /* Jump here to break out of the loop */
125406  int addrCont; /* Jump here to continue with next cycle */
125407  int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
125408  int iReleaseReg = 0; /* Temp register to free before returning */
125409 
125410  pParse = pWInfo->pParse;
125411  v = pParse->pVdbe;
125412  pWC = &pWInfo->sWC;
125413  db = pParse->db;
125414  pLevel = &pWInfo->a[iLevel];
125415  pLoop = pLevel->pWLoop;
125416  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
125417  iCur = pTabItem->iCursor;
125418  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
125419  bRev = (pWInfo->revMask>>iLevel)&1;
125420  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
125421  && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
125422  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
125423 
125424  /* Create labels for the "break" and "continue" instructions
125425  ** for the current loop. Jump to addrBrk to break out of a loop.
125426  ** Jump to cont to go immediately to the next iteration of the
125427  ** loop.
125428  **
125429  ** When there is an IN operator, we also have a "addrNxt" label that
125430  ** means to continue with the next IN value combination. When
125431  ** there are no IN operators in the constraints, the "addrNxt" label
125432  ** is the same as "addrBrk".
125433  */
125434  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
125435  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
125436 
125437  /* If this is the right table of a LEFT OUTER JOIN, allocate and
125438  ** initialize a memory cell that records if this table matches any
125439  ** row of the left table of the join.
125440  */
125441  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
125442  pLevel->iLeftJoin = ++pParse->nMem;
125443  sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
125444  VdbeComment((v, "init LEFT JOIN no-match flag"));
125445  }
125446 
125447  /* Special case of a FROM clause subquery implemented as a co-routine */
125448  if( pTabItem->fg.viaCoroutine ){
125449  int regYield = pTabItem->regReturn;
125450  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
125451  pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
125452  VdbeCoverage(v);
125453  VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
125454  pLevel->op = OP_Goto;
125455  }else
125456 
125457 #ifndef SQLITE_OMIT_VIRTUALTABLE
125458  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
125459  /* Case 1: The table is a virtual-table. Use the VFilter and VNext
125460  ** to access the data.
125461  */
125462  int iReg; /* P3 Value for OP_VFilter */
125463  int addrNotFound;
125464  int nConstraint = pLoop->nLTerm;
125465  int iIn; /* Counter for IN constraints */
125466 
125467  sqlite3ExprCachePush(pParse);
125468  iReg = sqlite3GetTempRange(pParse, nConstraint+2);
125469  addrNotFound = pLevel->addrBrk;
125470  for(j=0; j<nConstraint; j++){
125471  int iTarget = iReg+j+2;
125472  pTerm = pLoop->aLTerm[j];
125473  if( NEVER(pTerm==0) ) continue;
125474  if( pTerm->eOperator & WO_IN ){
125475  codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
125476  addrNotFound = pLevel->addrNxt;
125477  }else{
125478  Expr *pRight = pTerm->pExpr->pRight;
125479  codeExprOrVector(pParse, pRight, iTarget, 1);
125480  }
125481  }
125482  sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
125483  sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
125484  sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
125485  pLoop->u.vtab.idxStr,
125486  pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
125487  VdbeCoverage(v);
125488  pLoop->u.vtab.needFree = 0;
125489  pLevel->p1 = iCur;
125490  pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
125491  pLevel->p2 = sqlite3VdbeCurrentAddr(v);
125492  iIn = pLevel->u.in.nIn;
125493  for(j=nConstraint-1; j>=0; j--){
125494  pTerm = pLoop->aLTerm[j];
125495  if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
125496  disableTerm(pLevel, pTerm);
125497  }else if( (pTerm->eOperator & WO_IN)!=0 ){
125498  Expr *pCompare; /* The comparison operator */
125499  Expr *pRight; /* RHS of the comparison */
125500  VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
125501 
125502  /* Reload the constraint value into reg[iReg+j+2]. The same value
125503  ** was loaded into the same register prior to the OP_VFilter, but
125504  ** the xFilter implementation might have changed the datatype or
125505  ** encoding of the value in the register, so it *must* be reloaded. */
125506  assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
125507  if( !db->mallocFailed ){
125508  assert( iIn>0 );
125509  pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
125510  assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
125511  assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
125512  assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
125513  testcase( pOp->opcode==OP_Rowid );
125514  sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
125515  }
125516 
125517  /* Generate code that will continue to the next row if
125518  ** the IN constraint is not satisfied */
125519  pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0);
125520  assert( pCompare!=0 || db->mallocFailed );
125521  if( pCompare ){
125522  pCompare->pLeft = pTerm->pExpr->pLeft;
125523  pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
125524  if( pRight ){
125525  pRight->iTable = iReg+j+2;
125526  sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
125527  }
125528  pCompare->pLeft = 0;
125529  sqlite3ExprDelete(db, pCompare);
125530  }
125531  }
125532  }
125533  /* These registers need to be preserved in case there is an IN operator
125534  ** loop. So we could deallocate the registers here (and potentially
125535  ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
125536  ** simpler and safer to simply not reuse the registers.
125537  **
125538  ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
125539  */
125540  sqlite3ExprCachePop(pParse);
125541  }else
125542 #endif /* SQLITE_OMIT_VIRTUALTABLE */
125543 
125544  if( (pLoop->wsFlags & WHERE_IPK)!=0
125545  && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
125546  ){
125547  /* Case 2: We can directly reference a single row using an
125548  ** equality comparison against the ROWID field. Or
125549  ** we reference multiple rows using a "rowid IN (...)"
125550  ** construct.
125551  */
125552  assert( pLoop->u.btree.nEq==1 );
125553  pTerm = pLoop->aLTerm[0];
125554  assert( pTerm!=0 );
125555  assert( pTerm->pExpr!=0 );
125556  assert( omitTable==0 );
125557  testcase( pTerm->wtFlags & TERM_VIRTUAL );
125558  iReleaseReg = ++pParse->nMem;
125559  iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
125560  if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
125561  addrNxt = pLevel->addrNxt;
125562  sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
125563  VdbeCoverage(v);
125564  sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
125565  sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
125566  VdbeComment((v, "pk"));
125567  pLevel->op = OP_Noop;
125568  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
125569  && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
125570  ){
125571  /* Case 3: We have an inequality comparison against the ROWID field.
125572  */
125573  int testOp = OP_Noop;
125574  int start;
125575  int memEndValue = 0;
125576  WhereTerm *pStart, *pEnd;
125577 
125578  assert( omitTable==0 );
125579  j = 0;
125580  pStart = pEnd = 0;
125581  if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
125582  if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
125583  assert( pStart!=0 || pEnd!=0 );
125584  if( bRev ){
125585  pTerm = pStart;
125586  pStart = pEnd;
125587  pEnd = pTerm;
125588  }
125589  codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
125590  if( pStart ){
125591  Expr *pX; /* The expression that defines the start bound */
125592  int r1, rTemp; /* Registers for holding the start boundary */
125593  int op; /* Cursor seek operation */
125594 
125595  /* The following constant maps TK_xx codes into corresponding
125596  ** seek opcodes. It depends on a particular ordering of TK_xx
125597  */
125598  const u8 aMoveOp[] = {
125599  /* TK_GT */ OP_SeekGT,
125600  /* TK_LE */ OP_SeekLE,
125601  /* TK_LT */ OP_SeekLT,
125602  /* TK_GE */ OP_SeekGE
125603  };
125604  assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
125605  assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
125606  assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
125607 
125608  assert( (pStart->wtFlags & TERM_VNULL)==0 );
125609  testcase( pStart->wtFlags & TERM_VIRTUAL );
125610  pX = pStart->pExpr;
125611  assert( pX!=0 );
125612  testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
125613  if( sqlite3ExprIsVector(pX->pRight) ){
125614  r1 = rTemp = sqlite3GetTempReg(pParse);
125615  codeExprOrVector(pParse, pX->pRight, r1, 1);
125616  op = aMoveOp[(pX->op - TK_GT) | 0x0001];
125617  }else{
125618  r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
125619  disableTerm(pLevel, pStart);
125620  op = aMoveOp[(pX->op - TK_GT)];
125621  }
125622  sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
125623  VdbeComment((v, "pk"));
125624  VdbeCoverageIf(v, pX->op==TK_GT);
125625  VdbeCoverageIf(v, pX->op==TK_LE);
125626  VdbeCoverageIf(v, pX->op==TK_LT);
125627  VdbeCoverageIf(v, pX->op==TK_GE);
125628  sqlite3ExprCacheAffinityChange(pParse, r1, 1);
125629  sqlite3ReleaseTempReg(pParse, rTemp);
125630  }else{
125631  sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
125632  VdbeCoverageIf(v, bRev==0);
125633  VdbeCoverageIf(v, bRev!=0);
125634  }
125635  if( pEnd ){
125636  Expr *pX;
125637  pX = pEnd->pExpr;
125638  assert( pX!=0 );
125639  assert( (pEnd->wtFlags & TERM_VNULL)==0 );
125640  testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
125641  testcase( pEnd->wtFlags & TERM_VIRTUAL );
125642  memEndValue = ++pParse->nMem;
125643  codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
125644  if( 0==sqlite3ExprIsVector(pX->pRight)
125645  && (pX->op==TK_LT || pX->op==TK_GT)
125646  ){
125647  testOp = bRev ? OP_Le : OP_Ge;
125648  }else{
125649  testOp = bRev ? OP_Lt : OP_Gt;
125650  }
125651  if( 0==sqlite3ExprIsVector(pX->pRight) ){
125652  disableTerm(pLevel, pEnd);
125653  }
125654  }
125655  start = sqlite3VdbeCurrentAddr(v);
125656  pLevel->op = bRev ? OP_Prev : OP_Next;
125657  pLevel->p1 = iCur;
125658  pLevel->p2 = start;
125659  assert( pLevel->p5==0 );
125660  if( testOp!=OP_Noop ){
125661  iRowidReg = ++pParse->nMem;
125662  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
125663  sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
125664  sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
125665  VdbeCoverageIf(v, testOp==OP_Le);
125666  VdbeCoverageIf(v, testOp==OP_Lt);
125667  VdbeCoverageIf(v, testOp==OP_Ge);
125668  VdbeCoverageIf(v, testOp==OP_Gt);
125669  sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
125670  }
125671  }else if( pLoop->wsFlags & WHERE_INDEXED ){
125672  /* Case 4: A scan using an index.
125673  **
125674  ** The WHERE clause may contain zero or more equality
125675  ** terms ("==" or "IN" operators) that refer to the N
125676  ** left-most columns of the index. It may also contain
125677  ** inequality constraints (>, <, >= or <=) on the indexed
125678  ** column that immediately follows the N equalities. Only
125679  ** the right-most column can be an inequality - the rest must
125680  ** use the "==" and "IN" operators. For example, if the
125681  ** index is on (x,y,z), then the following clauses are all
125682  ** optimized:
125683  **
125684  ** x=5
125685  ** x=5 AND y=10
125686  ** x=5 AND y<10
125687  ** x=5 AND y>5 AND y<10
125688  ** x=5 AND y=5 AND z<=10
125689  **
125690  ** The z<10 term of the following cannot be used, only
125691  ** the x=5 term:
125692  **
125693  ** x=5 AND z<10
125694  **
125695  ** N may be zero if there are inequality constraints.
125696  ** If there are no inequality constraints, then N is at
125697  ** least one.
125698  **
125699  ** This case is also used when there are no WHERE clause
125700  ** constraints but an index is selected anyway, in order
125701  ** to force the output order to conform to an ORDER BY.
125702  */
125703  static const u8 aStartOp[] = {
125704  0,
125705  0,
125706  OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
125707  OP_Last, /* 3: (!start_constraints && startEq && bRev) */
125708  OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
125709  OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
125710  OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
125711  OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
125712  };
125713  static const u8 aEndOp[] = {
125714  OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
125715  OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
125716  OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
125717  OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
125718  };
125719  u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
125720  u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
125721  u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
125722  int regBase; /* Base register holding constraint values */
125723  WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
125724  WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
125725  int startEq; /* True if range start uses ==, >= or <= */
125726  int endEq; /* True if range end uses ==, >= or <= */
125727  int start_constraints; /* Start of range is constrained */
125728  int nConstraint; /* Number of constraint terms */
125729  Index *pIdx; /* The index we will be using */
125730  int iIdxCur; /* The VDBE cursor for the index */
125731  int nExtraReg = 0; /* Number of extra registers needed */
125732  int op; /* Instruction opcode */
125733  char *zStartAff; /* Affinity for start of range constraint */
125734  char *zEndAff = 0; /* Affinity for end of range constraint */
125735  u8 bSeekPastNull = 0; /* True to seek past initial nulls */
125736  u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
125737 
125738  pIdx = pLoop->u.btree.pIndex;
125739  iIdxCur = pLevel->iIdxCur;
125740  assert( nEq>=pLoop->nSkip );
125741 
125742  /* If this loop satisfies a sort order (pOrderBy) request that
125743  ** was passed to this function to implement a "SELECT min(x) ..."
125744  ** query, then the caller will only allow the loop to run for
125745  ** a single iteration. This means that the first row returned
125746  ** should not have a NULL value stored in 'x'. If column 'x' is
125747  ** the first one after the nEq equality constraints in the index,
125748  ** this requires some special handling.
125749  */
125750  assert( pWInfo->pOrderBy==0
125751  || pWInfo->pOrderBy->nExpr==1
125752  || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
125753  if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
125754  && pWInfo->nOBSat>0
125755  && (pIdx->nKeyCol>nEq)
125756  ){
125757  assert( pLoop->nSkip==0 );
125758  bSeekPastNull = 1;
125759  nExtraReg = 1;
125760  }
125761 
125762  /* Find any inequality constraint terms for the start and end
125763  ** of the range.
125764  */
125765  j = nEq;
125766  if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
125767  pRangeStart = pLoop->aLTerm[j++];
125768  nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
125769  /* Like optimization range constraints always occur in pairs */
125770  assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
125771  (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
125772  }
125773  if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
125774  pRangeEnd = pLoop->aLTerm[j++];
125775  nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
125776 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
125777  if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
125778  assert( pRangeStart!=0 ); /* LIKE opt constraints */
125779  assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
125780  pLevel->iLikeRepCntr = (u32)++pParse->nMem;
125781  sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
125782  VdbeComment((v, "LIKE loop counter"));
125783  pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
125784  /* iLikeRepCntr actually stores 2x the counter register number. The
125785  ** bottom bit indicates whether the search order is ASC or DESC. */
125786  testcase( bRev );
125787  testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
125788  assert( (bRev & ~1)==0 );
125789  pLevel->iLikeRepCntr <<=1;
125790  pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
125791  }
125792 #endif
125793  if( pRangeStart==0 ){
125794  j = pIdx->aiColumn[nEq];
125795  if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
125796  bSeekPastNull = 1;
125797  }
125798  }
125799  }
125800  assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
125801 
125802  /* If we are doing a reverse order scan on an ascending index, or
125803  ** a forward order scan on a descending index, interchange the
125804  ** start and end terms (pRangeStart and pRangeEnd).
125805  */
125806  if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
125807  || (bRev && pIdx->nKeyCol==nEq)
125808  ){
125809  SWAP(WhereTerm *, pRangeEnd, pRangeStart);
125810  SWAP(u8, bSeekPastNull, bStopAtNull);
125811  SWAP(u8, nBtm, nTop);
125812  }
125813 
125814  /* Generate code to evaluate all constraint terms using == or IN
125815  ** and store the values of those terms in an array of registers
125816  ** starting at regBase.
125817  */
125818  codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
125819  regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
125820  assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
125821  if( zStartAff && nTop ){
125822  zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
125823  }
125824  addrNxt = pLevel->addrNxt;
125825 
125826  testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
125827  testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
125828  testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
125829  testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
125830  startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
125831  endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
125832  start_constraints = pRangeStart || nEq>0;
125833 
125834  /* Seek the index cursor to the start of the range. */
125835  nConstraint = nEq;
125836  if( pRangeStart ){
125837  Expr *pRight = pRangeStart->pExpr->pRight;
125838  codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
125839  whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
125840  if( (pRangeStart->wtFlags & TERM_VNULL)==0
125841  && sqlite3ExprCanBeNull(pRight)
125842  ){
125843  sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
125844  VdbeCoverage(v);
125845  }
125846  if( zStartAff ){
125847  updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
125848  }
125849  nConstraint += nBtm;
125850  testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
125851  if( sqlite3ExprIsVector(pRight)==0 ){
125852  disableTerm(pLevel, pRangeStart);
125853  }else{
125854  startEq = 1;
125855  }
125856  bSeekPastNull = 0;
125857  }else if( bSeekPastNull ){
125858  sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
125859  nConstraint++;
125860  startEq = 0;
125861  start_constraints = 1;
125862  }
125863  codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
125864  if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
125865  /* The skip-scan logic inside the call to codeAllEqualityConstraints()
125866  ** above has already left the cursor sitting on the correct row,
125867  ** so no further seeking is needed */
125868  }else{
125869  op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
125870  assert( op!=0 );
125871  sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
125872  VdbeCoverage(v);
125873  VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
125874  VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
125875  VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
125876  VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
125877  VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
125878  VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
125879  }
125880 
125881  /* Load the value for the inequality constraint at the end of the
125882  ** range (if any).
125883  */
125884  nConstraint = nEq;
125885  if( pRangeEnd ){
125886  Expr *pRight = pRangeEnd->pExpr->pRight;
125887  sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
125888  codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
125889  whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
125890  if( (pRangeEnd->wtFlags & TERM_VNULL)==0
125891  && sqlite3ExprCanBeNull(pRight)
125892  ){
125893  sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
125894  VdbeCoverage(v);
125895  }
125896  if( zEndAff ){
125897  updateRangeAffinityStr(pRight, nTop, zEndAff);
125898  codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
125899  }else{
125900  assert( pParse->db->mallocFailed );
125901  }
125902  nConstraint += nTop;
125903  testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
125904 
125905  if( sqlite3ExprIsVector(pRight)==0 ){
125906  disableTerm(pLevel, pRangeEnd);
125907  }else{
125908  endEq = 1;
125909  }
125910  }else if( bStopAtNull ){
125911  sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
125912  endEq = 0;
125913  nConstraint++;
125914  }
125915  sqlite3DbFree(db, zStartAff);
125916  sqlite3DbFree(db, zEndAff);
125917 
125918  /* Top of the loop body */
125919  pLevel->p2 = sqlite3VdbeCurrentAddr(v);
125920 
125921  /* Check if the index cursor is past the end of the range. */
125922  if( nConstraint ){
125923  op = aEndOp[bRev*2 + endEq];
125924  sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
125925  testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
125926  testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
125927  testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
125928  testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
125929  }
125930 
125931  /* Seek the table cursor, if required */
125932  if( omitTable ){
125933  /* pIdx is a covering index. No need to access the main table. */
125934  }else if( HasRowid(pIdx->pTable) ){
125935  if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){
125936  iRowidReg = ++pParse->nMem;
125937  sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
125938  sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
125939  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
125940  VdbeCoverage(v);
125941  }else{
125942  codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
125943  }
125944  }else if( iCur!=iIdxCur ){
125945  Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
125946  iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
125947  for(j=0; j<pPk->nKeyCol; j++){
125948  k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
125949  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
125950  }
125951  sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
125952  iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
125953  }
125954 
125955  /* Record the instruction used to terminate the loop. */
125956  if( pLoop->wsFlags & WHERE_ONEROW ){
125957  pLevel->op = OP_Noop;
125958  }else if( bRev ){
125959  pLevel->op = OP_Prev;
125960  }else{
125961  pLevel->op = OP_Next;
125962  }
125963  pLevel->p1 = iIdxCur;
125964  pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
125965  if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
125966  pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
125967  }else{
125968  assert( pLevel->p5==0 );
125969  }
125970  }else
125971 
125972 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
125973  if( pLoop->wsFlags & WHERE_MULTI_OR ){
125974  /* Case 5: Two or more separately indexed terms connected by OR
125975  **
125976  ** Example:
125977  **
125978  ** CREATE TABLE t1(a,b,c,d);
125979  ** CREATE INDEX i1 ON t1(a);
125980  ** CREATE INDEX i2 ON t1(b);
125981  ** CREATE INDEX i3 ON t1(c);
125982  **
125983  ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
125984  **
125985  ** In the example, there are three indexed terms connected by OR.
125986  ** The top of the loop looks like this:
125987  **
125988  ** Null 1 # Zero the rowset in reg 1
125989  **
125990  ** Then, for each indexed term, the following. The arguments to
125991  ** RowSetTest are such that the rowid of the current row is inserted
125992  ** into the RowSet. If it is already present, control skips the
125993  ** Gosub opcode and jumps straight to the code generated by WhereEnd().
125994  **
125995  ** sqlite3WhereBegin(<term>)
125996  ** RowSetTest # Insert rowid into rowset
125997  ** Gosub 2 A
125998  ** sqlite3WhereEnd()
125999  **
126000  ** Following the above, code to terminate the loop. Label A, the target
126001  ** of the Gosub above, jumps to the instruction right after the Goto.
126002  **
126003  ** Null 1 # Zero the rowset in reg 1
126004  ** Goto B # The loop is finished.
126005  **
126006  ** A: <loop body> # Return data, whatever.
126007  **
126008  ** Return 2 # Jump back to the Gosub
126009  **
126010  ** B: <after the loop>
126011  **
126012  ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
126013  ** use an ephemeral index instead of a RowSet to record the primary
126014  ** keys of the rows we have already seen.
126015  **
126016  */
126017  WhereClause *pOrWc; /* The OR-clause broken out into subterms */
126018  SrcList *pOrTab; /* Shortened table list or OR-clause generation */
126019  Index *pCov = 0; /* Potential covering index (or NULL) */
126020  int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
126021 
126022  int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
126023  int regRowset = 0; /* Register for RowSet object */
126024  int regRowid = 0; /* Register holding rowid */
126025  int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
126026  int iRetInit; /* Address of regReturn init */
126027  int untestedTerms = 0; /* Some terms not completely tested */
126028  int ii; /* Loop counter */
126029  u16 wctrlFlags; /* Flags for sub-WHERE clause */
126030  Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
126031  Table *pTab = pTabItem->pTab;
126032 
126033  pTerm = pLoop->aLTerm[0];
126034  assert( pTerm!=0 );
126035  assert( pTerm->eOperator & WO_OR );
126036  assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
126037  pOrWc = &pTerm->u.pOrInfo->wc;
126038  pLevel->op = OP_Return;
126039  pLevel->p1 = regReturn;
126040 
126041  /* Set up a new SrcList in pOrTab containing the table being scanned
126042  ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
126043  ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
126044  */
126045  if( pWInfo->nLevel>1 ){
126046  int nNotReady; /* The number of notReady tables */
126047  struct SrcList_item *origSrc; /* Original list of tables */
126048  nNotReady = pWInfo->nLevel - iLevel - 1;
126049  pOrTab = sqlite3StackAllocRaw(db,
126050  sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
126051  if( pOrTab==0 ) return notReady;
126052  pOrTab->nAlloc = (u8)(nNotReady + 1);
126053  pOrTab->nSrc = pOrTab->nAlloc;
126054  memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
126055  origSrc = pWInfo->pTabList->a;
126056  for(k=1; k<=nNotReady; k++){
126057  memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
126058  }
126059  }else{
126060  pOrTab = pWInfo->pTabList;
126061  }
126062 
126063  /* Initialize the rowset register to contain NULL. An SQL NULL is
126064  ** equivalent to an empty rowset. Or, create an ephemeral index
126065  ** capable of holding primary keys in the case of a WITHOUT ROWID.
126066  **
126067  ** Also initialize regReturn to contain the address of the instruction
126068  ** immediately following the OP_Return at the bottom of the loop. This
126069  ** is required in a few obscure LEFT JOIN cases where control jumps
126070  ** over the top of the loop into the body of it. In this case the
126071  ** correct response for the end-of-loop code (the OP_Return) is to
126072  ** fall through to the next instruction, just as an OP_Next does if
126073  ** called on an uninitialized cursor.
126074  */
126075  if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
126076  if( HasRowid(pTab) ){
126077  regRowset = ++pParse->nMem;
126078  sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
126079  }else{
126080  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
126081  regRowset = pParse->nTab++;
126082  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
126083  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
126084  }
126085  regRowid = ++pParse->nMem;
126086  }
126087  iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
126088 
126089  /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
126090  ** Then for every term xN, evaluate as the subexpression: xN AND z
126091  ** That way, terms in y that are factored into the disjunction will
126092  ** be picked up by the recursive calls to sqlite3WhereBegin() below.
126093  **
126094  ** Actually, each subexpression is converted to "xN AND w" where w is
126095  ** the "interesting" terms of z - terms that did not originate in the
126096  ** ON or USING clause of a LEFT JOIN, and terms that are usable as
126097  ** indices.
126098  **
126099  ** This optimization also only applies if the (x1 OR x2 OR ...) term
126100  ** is not contained in the ON clause of a LEFT JOIN.
126101  ** See ticket http://www.sqlite.org/src/info/f2369304e4
126102  */
126103  if( pWC->nTerm>1 ){
126104  int iTerm;
126105  for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
126106  Expr *pExpr = pWC->a[iTerm].pExpr;
126107  if( &pWC->a[iTerm] == pTerm ) continue;
126108  if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
126109  testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
126110  testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
126111  if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
126112  if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
126113  testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
126114  pExpr = sqlite3ExprDup(db, pExpr, 0);
126115  pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
126116  }
126117  if( pAndExpr ){
126118  pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0);
126119  }
126120  }
126121 
126122  /* Run a separate WHERE clause for each term of the OR clause. After
126123  ** eliminating duplicates from other WHERE clauses, the action for each
126124  ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
126125  */
126126  wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
126127  for(ii=0; ii<pOrWc->nTerm; ii++){
126128  WhereTerm *pOrTerm = &pOrWc->a[ii];
126129  if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
126130  WhereInfo *pSubWInfo; /* Info for single OR-term scan */
126131  Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
126132  int jmp1 = 0; /* Address of jump operation */
126133  if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
126134  pAndExpr->pLeft = pOrExpr;
126135  pOrExpr = pAndExpr;
126136  }
126137  /* Loop through table entries that match term pOrTerm. */
126138  WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
126139  pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
126140  wctrlFlags, iCovCur);
126141  assert( pSubWInfo || pParse->nErr || db->mallocFailed );
126142  if( pSubWInfo ){
126143  WhereLoop *pSubLoop;
126144  int addrExplain = sqlite3WhereExplainOneScan(
126145  pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
126146  );
126147  sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
126148 
126149  /* This is the sub-WHERE clause body. First skip over
126150  ** duplicate rows from prior sub-WHERE clauses, and record the
126151  ** rowid (or PRIMARY KEY) for the current row so that the same
126152  ** row will be skipped in subsequent sub-WHERE clauses.
126153  */
126154  if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
126155  int r;
126156  int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
126157  if( HasRowid(pTab) ){
126158  r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
126159  jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
126160  r,iSet);
126161  VdbeCoverage(v);
126162  }else{
126163  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
126164  int nPk = pPk->nKeyCol;
126165  int iPk;
126166 
126167  /* Read the PK into an array of temp registers. */
126168  r = sqlite3GetTempRange(pParse, nPk);
126169  for(iPk=0; iPk<nPk; iPk++){
126170  int iCol = pPk->aiColumn[iPk];
126171  sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
126172  }
126173 
126174  /* Check if the temp table already contains this key. If so,
126175  ** the row has already been included in the result set and
126176  ** can be ignored (by jumping past the Gosub below). Otherwise,
126177  ** insert the key into the temp table and proceed with processing
126178  ** the row.
126179  **
126180  ** Use some of the same optimizations as OP_RowSetTest: If iSet
126181  ** is zero, assume that the key cannot already be present in
126182  ** the temp table. And if iSet is -1, assume that there is no
126183  ** need to insert the key into the temp table, as it will never
126184  ** be tested for. */
126185  if( iSet ){
126186  jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
126187  VdbeCoverage(v);
126188  }
126189  if( iSet>=0 ){
126190  sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
126191  sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
126192  if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
126193  }
126194 
126195  /* Release the array of temp registers */
126196  sqlite3ReleaseTempRange(pParse, r, nPk);
126197  }
126198  }
126199 
126200  /* Invoke the main loop body as a subroutine */
126201  sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
126202 
126203  /* Jump here (skipping the main loop body subroutine) if the
126204  ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
126205  if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
126206 
126207  /* The pSubWInfo->untestedTerms flag means that this OR term
126208  ** contained one or more AND term from a notReady table. The
126209  ** terms from the notReady table could not be tested and will
126210  ** need to be tested later.
126211  */
126212  if( pSubWInfo->untestedTerms ) untestedTerms = 1;
126213 
126214  /* If all of the OR-connected terms are optimized using the same
126215  ** index, and the index is opened using the same cursor number
126216  ** by each call to sqlite3WhereBegin() made by this loop, it may
126217  ** be possible to use that index as a covering index.
126218  **
126219  ** If the call to sqlite3WhereBegin() above resulted in a scan that
126220  ** uses an index, and this is either the first OR-connected term
126221  ** processed or the index is the same as that used by all previous
126222  ** terms, set pCov to the candidate covering index. Otherwise, set
126223  ** pCov to NULL to indicate that no candidate covering index will
126224  ** be available.
126225  */
126226  pSubLoop = pSubWInfo->a[0].pWLoop;
126227  assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
126228  if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
126229  && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
126230  && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
126231  ){
126232  assert( pSubWInfo->a[0].iIdxCur==iCovCur );
126233  pCov = pSubLoop->u.btree.pIndex;
126234  }else{
126235  pCov = 0;
126236  }
126237 
126238  /* Finish the loop through table entries that match term pOrTerm. */
126239  sqlite3WhereEnd(pSubWInfo);
126240  }
126241  }
126242  }
126243  pLevel->u.pCovidx = pCov;
126244  if( pCov ) pLevel->iIdxCur = iCovCur;
126245  if( pAndExpr ){
126246  pAndExpr->pLeft = 0;
126247  sqlite3ExprDelete(db, pAndExpr);
126248  }
126249  sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
126250  sqlite3VdbeGoto(v, pLevel->addrBrk);
126251  sqlite3VdbeResolveLabel(v, iLoopBody);
126252 
126253  if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
126254  if( !untestedTerms ) disableTerm(pLevel, pTerm);
126255  }else
126256 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
126257 
126258  {
126259  /* Case 6: There is no usable index. We must do a complete
126260  ** scan of the entire table.
126261  */
126262  static const u8 aStep[] = { OP_Next, OP_Prev };
126263  static const u8 aStart[] = { OP_Rewind, OP_Last };
126264  assert( bRev==0 || bRev==1 );
126265  if( pTabItem->fg.isRecursive ){
126266  /* Tables marked isRecursive have only a single row that is stored in
126267  ** a pseudo-cursor. No need to Rewind or Next such cursors. */
126268  pLevel->op = OP_Noop;
126269  }else{
126270  codeCursorHint(pTabItem, pWInfo, pLevel, 0);
126271  pLevel->op = aStep[bRev];
126272  pLevel->p1 = iCur;
126273  pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
126274  VdbeCoverageIf(v, bRev==0);
126275  VdbeCoverageIf(v, bRev!=0);
126276  pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
126277  }
126278  }
126279 
126280 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
126281  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
126282 #endif
126283 
126284  /* Insert code to test every subexpression that can be completely
126285  ** computed using the current set of tables.
126286  */
126287  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
126288  Expr *pE;
126289  int skipLikeAddr = 0;
126290  testcase( pTerm->wtFlags & TERM_VIRTUAL );
126291  testcase( pTerm->wtFlags & TERM_CODED );
126292  if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
126293  if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
126294  testcase( pWInfo->untestedTerms==0
126295  && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
126296  pWInfo->untestedTerms = 1;
126297  continue;
126298  }
126299  pE = pTerm->pExpr;
126300  assert( pE!=0 );
126301  if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
126302  continue;
126303  }
126304  if( pTerm->wtFlags & TERM_LIKECOND ){
126305  /* If the TERM_LIKECOND flag is set, that means that the range search
126306  ** is sufficient to guarantee that the LIKE operator is true, so we
126307  ** can skip the call to the like(A,B) function. But this only works
126308  ** for strings. So do not skip the call to the function on the pass
126309  ** that compares BLOBs. */
126310 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
126311  continue;
126312 #else
126313  u32 x = pLevel->iLikeRepCntr;
126314  assert( x>0 );
126315  skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1));
126316  VdbeCoverage(v);
126317 #endif
126318  }
126319  sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
126320  if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
126321  pTerm->wtFlags |= TERM_CODED;
126322  }
126323 
126324  /* Insert code to test for implied constraints based on transitivity
126325  ** of the "==" operator.
126326  **
126327  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
126328  ** and we are coding the t1 loop and the t2 loop has not yet coded,
126329  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
126330  ** the implied "t1.a=123" constraint.
126331  */
126332  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
126333  Expr *pE, sEAlt;
126334  WhereTerm *pAlt;
126335  if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
126336  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
126337  if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
126338  if( pTerm->leftCursor!=iCur ) continue;
126339  if( pLevel->iLeftJoin ) continue;
126340  pE = pTerm->pExpr;
126341  assert( !ExprHasProperty(pE, EP_FromJoin) );
126342  assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
126343  pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
126344  WO_EQ|WO_IN|WO_IS, 0);
126345  if( pAlt==0 ) continue;
126346  if( pAlt->wtFlags & (TERM_CODED) ) continue;
126347  testcase( pAlt->eOperator & WO_EQ );
126348  testcase( pAlt->eOperator & WO_IS );
126349  testcase( pAlt->eOperator & WO_IN );
126350  VdbeModuleComment((v, "begin transitive constraint"));
126351  sEAlt = *pAlt->pExpr;
126352  sEAlt.pLeft = pE->pLeft;
126353  sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
126354  }
126355 
126356  /* For a LEFT OUTER JOIN, generate code that will record the fact that
126357  ** at least one row of the right table has matched the left table.
126358  */
126359  if( pLevel->iLeftJoin ){
126360  pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
126361  sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
126362  VdbeComment((v, "record LEFT JOIN hit"));
126363  sqlite3ExprCacheClear(pParse);
126364  for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
126365  testcase( pTerm->wtFlags & TERM_VIRTUAL );
126366  testcase( pTerm->wtFlags & TERM_CODED );
126367  if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
126368  if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
126369  assert( pWInfo->untestedTerms );
126370  continue;
126371  }
126372  assert( pTerm->pExpr );
126373  sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
126374  pTerm->wtFlags |= TERM_CODED;
126375  }
126376  }
126377 
126378  return pLevel->notReady;
126379 }
126380 
126381 /************** End of wherecode.c *******************************************/
126382 /************** Begin file whereexpr.c ***************************************/
126383 /*
126384 ** 2015-06-08
126385 **
126386 ** The author disclaims copyright to this source code. In place of
126387 ** a legal notice, here is a blessing:
126388 **
126389 ** May you do good and not evil.
126390 ** May you find forgiveness for yourself and forgive others.
126391 ** May you share freely, never taking more than you give.
126392 **
126393 *************************************************************************
126394 ** This module contains C code that generates VDBE code used to process
126395 ** the WHERE clause of SQL statements.
126396 **
126397 ** This file was originally part of where.c but was split out to improve
126398 ** readability and editabiliity. This file contains utility routines for
126399 ** analyzing Expr objects in the WHERE clause.
126400 */
126401 /* #include "sqliteInt.h" */
126402 /* #include "whereInt.h" */
126403 
126404 /* Forward declarations */
126405 static void exprAnalyze(SrcList*, WhereClause*, int);
126406 
126407 /*
126408 ** Deallocate all memory associated with a WhereOrInfo object.
126409 */
126410 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
126411  sqlite3WhereClauseClear(&p->wc);
126412  sqlite3DbFree(db, p);
126413 }
126414 
126415 /*
126416 ** Deallocate all memory associated with a WhereAndInfo object.
126417 */
126418 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
126419  sqlite3WhereClauseClear(&p->wc);
126420  sqlite3DbFree(db, p);
126421 }
126422 
126423 /*
126424 ** Add a single new WhereTerm entry to the WhereClause object pWC.
126425 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
126426 ** The index in pWC->a[] of the new WhereTerm is returned on success.
126427 ** 0 is returned if the new WhereTerm could not be added due to a memory
126428 ** allocation error. The memory allocation failure will be recorded in
126429 ** the db->mallocFailed flag so that higher-level functions can detect it.
126430 **
126431 ** This routine will increase the size of the pWC->a[] array as necessary.
126432 **
126433 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
126434 ** for freeing the expression p is assumed by the WhereClause object pWC.
126435 ** This is true even if this routine fails to allocate a new WhereTerm.
126436 **
126437 ** WARNING: This routine might reallocate the space used to store
126438 ** WhereTerms. All pointers to WhereTerms should be invalidated after
126439 ** calling this routine. Such pointers may be reinitialized by referencing
126440 ** the pWC->a[] array.
126441 */
126442 static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
126443  WhereTerm *pTerm;
126444  int idx;
126445  testcase( wtFlags & TERM_VIRTUAL );
126446  if( pWC->nTerm>=pWC->nSlot ){
126447  WhereTerm *pOld = pWC->a;
126448  sqlite3 *db = pWC->pWInfo->pParse->db;
126449  pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
126450  if( pWC->a==0 ){
126451  if( wtFlags & TERM_DYNAMIC ){
126452  sqlite3ExprDelete(db, p);
126453  }
126454  pWC->a = pOld;
126455  return 0;
126456  }
126457  memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
126458  if( pOld!=pWC->aStatic ){
126459  sqlite3DbFree(db, pOld);
126460  }
126461  pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
126462  }
126463  pTerm = &pWC->a[idx = pWC->nTerm++];
126464  if( p && ExprHasProperty(p, EP_Unlikely) ){
126465  pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
126466  }else{
126467  pTerm->truthProb = 1;
126468  }
126469  pTerm->pExpr = sqlite3ExprSkipCollate(p);
126470  pTerm->wtFlags = wtFlags;
126471  pTerm->pWC = pWC;
126472  pTerm->iParent = -1;
126473  memset(&pTerm->eOperator, 0,
126474  sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
126475  return idx;
126476 }
126477 
126478 /*
126479 ** Return TRUE if the given operator is one of the operators that is
126480 ** allowed for an indexable WHERE clause term. The allowed operators are
126481 ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
126482 */
126483 static int allowedOp(int op){
126484  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
126485  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
126486  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
126487  assert( TK_GE==TK_EQ+4 );
126488  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
126489 }
126490 
126491 /*
126492 ** Commute a comparison operator. Expressions of the form "X op Y"
126493 ** are converted into "Y op X".
126494 **
126495 ** If left/right precedence rules come into play when determining the
126496 ** collating sequence, then COLLATE operators are adjusted to ensure
126497 ** that the collating sequence does not change. For example:
126498 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
126499 ** the left hand side of a comparison overrides any collation sequence
126500 ** attached to the right. For the same reason the EP_Collate flag
126501 ** is not commuted.
126502 */
126503 static void exprCommute(Parse *pParse, Expr *pExpr){
126504  u16 expRight = (pExpr->pRight->flags & EP_Collate);
126505  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
126506  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
126507  if( expRight==expLeft ){
126508  /* Either X and Y both have COLLATE operator or neither do */
126509  if( expRight ){
126510  /* Both X and Y have COLLATE operators. Make sure X is always
126511  ** used by clearing the EP_Collate flag from Y. */
126512  pExpr->pRight->flags &= ~EP_Collate;
126513  }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
126514  /* Neither X nor Y have COLLATE operators, but X has a non-default
126515  ** collating sequence. So add the EP_Collate marker on X to cause
126516  ** it to be searched first. */
126517  pExpr->pLeft->flags |= EP_Collate;
126518  }
126519  }
126520  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
126521  if( pExpr->op>=TK_GT ){
126522  assert( TK_LT==TK_GT+2 );
126523  assert( TK_GE==TK_LE+2 );
126524  assert( TK_GT>TK_EQ );
126525  assert( TK_GT<TK_LE );
126526  assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
126527  pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
126528  }
126529 }
126530 
126531 /*
126532 ** Translate from TK_xx operator to WO_xx bitmask.
126533 */
126534 static u16 operatorMask(int op){
126535  u16 c;
126536  assert( allowedOp(op) );
126537  if( op==TK_IN ){
126538  c = WO_IN;
126539  }else if( op==TK_ISNULL ){
126540  c = WO_ISNULL;
126541  }else if( op==TK_IS ){
126542  c = WO_IS;
126543  }else{
126544  assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
126545  c = (u16)(WO_EQ<<(op-TK_EQ));
126546  }
126547  assert( op!=TK_ISNULL || c==WO_ISNULL );
126548  assert( op!=TK_IN || c==WO_IN );
126549  assert( op!=TK_EQ || c==WO_EQ );
126550  assert( op!=TK_LT || c==WO_LT );
126551  assert( op!=TK_LE || c==WO_LE );
126552  assert( op!=TK_GT || c==WO_GT );
126553  assert( op!=TK_GE || c==WO_GE );
126554  assert( op!=TK_IS || c==WO_IS );
126555  return c;
126556 }
126557 
126558 
126559 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
126560 /*
126561 ** Check to see if the given expression is a LIKE or GLOB operator that
126562 ** can be optimized using inequality constraints. Return TRUE if it is
126563 ** so and false if not.
126564 **
126565 ** In order for the operator to be optimizible, the RHS must be a string
126566 ** literal that does not begin with a wildcard. The LHS must be a column
126567 ** that may only be NULL, a string, or a BLOB, never a number. (This means
126568 ** that virtual tables cannot participate in the LIKE optimization.) The
126569 ** collating sequence for the column on the LHS must be appropriate for
126570 ** the operator.
126571 */
126572 static int isLikeOrGlob(
126573  Parse *pParse, /* Parsing and code generating context */
126574  Expr *pExpr, /* Test this expression */
126575  Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
126576  int *pisComplete, /* True if the only wildcard is % in the last character */
126577  int *pnoCase /* True if uppercase is equivalent to lowercase */
126578 ){
126579  const char *z = 0; /* String on RHS of LIKE operator */
126580  Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
126581  ExprList *pList; /* List of operands to the LIKE operator */
126582  int c; /* One character in z[] */
126583  int cnt; /* Number of non-wildcard prefix characters */
126584  char wc[3]; /* Wildcard characters */
126585  sqlite3 *db = pParse->db; /* Database connection */
126586  sqlite3_value *pVal = 0;
126587  int op; /* Opcode of pRight */
126588  int rc; /* Result code to return */
126589 
126590  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
126591  return 0;
126592  }
126593 #ifdef SQLITE_EBCDIC
126594  if( *pnoCase ) return 0;
126595 #endif
126596  pList = pExpr->x.pList;
126597  pLeft = pList->a[1].pExpr;
126598  if( pLeft->op!=TK_COLUMN
126599  || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
126600  || IsVirtual(pLeft->pTab) /* Value might be numeric */
126601  ){
126602  /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
126603  ** be the name of an indexed column with TEXT affinity. */
126604  return 0;
126605  }
126606  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
126607 
126608  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
126609  op = pRight->op;
126610  if( op==TK_VARIABLE ){
126611  Vdbe *pReprepare = pParse->pReprepare;
126612  int iCol = pRight->iColumn;
126613  pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
126614  if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
126615  z = (char *)sqlite3_value_text(pVal);
126616  }
126617  sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
126618  assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
126619  }else if( op==TK_STRING ){
126620  z = pRight->u.zToken;
126621  }
126622  if( z ){
126623  cnt = 0;
126624  while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
126625  cnt++;
126626  }
126627  if( cnt!=0 && 255!=(u8)z[cnt-1] ){
126628  Expr *pPrefix;
126629  *pisComplete = c==wc[0] && z[cnt+1]==0;
126630  pPrefix = sqlite3Expr(db, TK_STRING, z);
126631  if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
126632  *ppPrefix = pPrefix;
126633  if( op==TK_VARIABLE ){
126634  Vdbe *v = pParse->pVdbe;
126635  sqlite3VdbeSetVarmask(v, pRight->iColumn);
126636  if( *pisComplete && pRight->u.zToken[1] ){
126637  /* If the rhs of the LIKE expression is a variable, and the current
126638  ** value of the variable means there is no need to invoke the LIKE
126639  ** function, then no OP_Variable will be added to the program.
126640  ** This causes problems for the sqlite3_bind_parameter_name()
126641  ** API. To work around them, add a dummy OP_Variable here.
126642  */
126643  int r1 = sqlite3GetTempReg(pParse);
126644  sqlite3ExprCodeTarget(pParse, pRight, r1);
126645  sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
126646  sqlite3ReleaseTempReg(pParse, r1);
126647  }
126648  }
126649  }else{
126650  z = 0;
126651  }
126652  }
126653 
126654  rc = (z!=0);
126655  sqlite3ValueFree(pVal);
126656  return rc;
126657 }
126658 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
126659 
126660 
126661 #ifndef SQLITE_OMIT_VIRTUALTABLE
126662 /*
126663 ** Check to see if the given expression is of the form
126664 **
126665 ** column OP expr
126666 **
126667 ** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
126668 ** column of a virtual table.
126669 **
126670 ** If it is then return TRUE. If not, return FALSE.
126671 */
126672 static int isMatchOfColumn(
126673  Expr *pExpr, /* Test this expression */
126674  unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */
126675 ){
126676  static const struct Op2 {
126677  const char *zOp;
126678  unsigned char eOp2;
126679  } aOp[] = {
126680  { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
126681  { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
126682  { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
126683  { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
126684  };
126685  ExprList *pList;
126686  Expr *pCol; /* Column reference */
126687  int i;
126688 
126689  if( pExpr->op!=TK_FUNCTION ){
126690  return 0;
126691  }
126692  pList = pExpr->x.pList;
126693  if( pList==0 || pList->nExpr!=2 ){
126694  return 0;
126695  }
126696  pCol = pList->a[1].pExpr;
126697  if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
126698  return 0;
126699  }
126700  for(i=0; i<ArraySize(aOp); i++){
126701  if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
126702  *peOp2 = aOp[i].eOp2;
126703  return 1;
126704  }
126705  }
126706  return 0;
126707 }
126708 #endif /* SQLITE_OMIT_VIRTUALTABLE */
126709 
126710 /*
126711 ** If the pBase expression originated in the ON or USING clause of
126712 ** a join, then transfer the appropriate markings over to derived.
126713 */
126714 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
126715  if( pDerived ){
126716  pDerived->flags |= pBase->flags & EP_FromJoin;
126717  pDerived->iRightJoinTable = pBase->iRightJoinTable;
126718  }
126719 }
126720 
126721 /*
126722 ** Mark term iChild as being a child of term iParent
126723 */
126724 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
126725  pWC->a[iChild].iParent = iParent;
126726  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
126727  pWC->a[iParent].nChild++;
126728 }
126729 
126730 /*
126731 ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
126732 ** a conjunction, then return just pTerm when N==0. If N is exceeds
126733 ** the number of available subterms, return NULL.
126734 */
126735 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
126736  if( pTerm->eOperator!=WO_AND ){
126737  return N==0 ? pTerm : 0;
126738  }
126739  if( N<pTerm->u.pAndInfo->wc.nTerm ){
126740  return &pTerm->u.pAndInfo->wc.a[N];
126741  }
126742  return 0;
126743 }
126744 
126745 /*
126746 ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
126747 ** two subterms are in disjunction - they are OR-ed together.
126748 **
126749 ** If these two terms are both of the form: "A op B" with the same
126750 ** A and B values but different operators and if the operators are
126751 ** compatible (if one is = and the other is <, for example) then
126752 ** add a new virtual AND term to pWC that is the combination of the
126753 ** two.
126754 **
126755 ** Some examples:
126756 **
126757 ** x<y OR x=y --> x<=y
126758 ** x=y OR x=y --> x=y
126759 ** x<=y OR x<y --> x<=y
126760 **
126761 ** The following is NOT generated:
126762 **
126763 ** x<y OR x>y --> x!=y
126764 */
126765 static void whereCombineDisjuncts(
126766  SrcList *pSrc, /* the FROM clause */
126767  WhereClause *pWC, /* The complete WHERE clause */
126768  WhereTerm *pOne, /* First disjunct */
126769  WhereTerm *pTwo /* Second disjunct */
126770 ){
126771  u16 eOp = pOne->eOperator | pTwo->eOperator;
126772  sqlite3 *db; /* Database connection (for malloc) */
126773  Expr *pNew; /* New virtual expression */
126774  int op; /* Operator for the combined expression */
126775  int idxNew; /* Index in pWC of the next virtual term */
126776 
126777  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
126778  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
126779  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
126780  && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
126781  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
126782  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
126783  if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
126784  if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
126785  /* If we reach this point, it means the two subterms can be combined */
126786  if( (eOp & (eOp-1))!=0 ){
126787  if( eOp & (WO_LT|WO_LE) ){
126788  eOp = WO_LE;
126789  }else{
126790  assert( eOp & (WO_GT|WO_GE) );
126791  eOp = WO_GE;
126792  }
126793  }
126794  db = pWC->pWInfo->pParse->db;
126795  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
126796  if( pNew==0 ) return;
126797  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
126798  pNew->op = op;
126799  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
126800  exprAnalyze(pSrc, pWC, idxNew);
126801 }
126802 
126803 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
126804 /*
126805 ** Analyze a term that consists of two or more OR-connected
126806 ** subterms. So in:
126807 **
126808 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
126809 ** ^^^^^^^^^^^^^^^^^^^^
126810 **
126811 ** This routine analyzes terms such as the middle term in the above example.
126812 ** A WhereOrTerm object is computed and attached to the term under
126813 ** analysis, regardless of the outcome of the analysis. Hence:
126814 **
126815 ** WhereTerm.wtFlags |= TERM_ORINFO
126816 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
126817 **
126818 ** The term being analyzed must have two or more of OR-connected subterms.
126819 ** A single subterm might be a set of AND-connected sub-subterms.
126820 ** Examples of terms under analysis:
126821 **
126822 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
126823 ** (B) x=expr1 OR expr2=x OR x=expr3
126824 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
126825 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
126826 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
126827 ** (F) x>A OR (x=A AND y>=B)
126828 **
126829 ** CASE 1:
126830 **
126831 ** If all subterms are of the form T.C=expr for some single column of C and
126832 ** a single table T (as shown in example B above) then create a new virtual
126833 ** term that is an equivalent IN expression. In other words, if the term
126834 ** being analyzed is:
126835 **
126836 ** x = expr1 OR expr2 = x OR x = expr3
126837 **
126838 ** then create a new virtual term like this:
126839 **
126840 ** x IN (expr1,expr2,expr3)
126841 **
126842 ** CASE 2:
126843 **
126844 ** If there are exactly two disjuncts and one side has x>A and the other side
126845 ** has x=A (for the same x and A) then add a new virtual conjunct term to the
126846 ** WHERE clause of the form "x>=A". Example:
126847 **
126848 ** x>A OR (x=A AND y>B) adds: x>=A
126849 **
126850 ** The added conjunct can sometimes be helpful in query planning.
126851 **
126852 ** CASE 3:
126853 **
126854 ** If all subterms are indexable by a single table T, then set
126855 **
126856 ** WhereTerm.eOperator = WO_OR
126857 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
126858 **
126859 ** A subterm is "indexable" if it is of the form
126860 ** "T.C <op> <expr>" where C is any column of table T and
126861 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
126862 ** A subterm is also indexable if it is an AND of two or more
126863 ** subsubterms at least one of which is indexable. Indexable AND
126864 ** subterms have their eOperator set to WO_AND and they have
126865 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
126866 **
126867 ** From another point of view, "indexable" means that the subterm could
126868 ** potentially be used with an index if an appropriate index exists.
126869 ** This analysis does not consider whether or not the index exists; that
126870 ** is decided elsewhere. This analysis only looks at whether subterms
126871 ** appropriate for indexing exist.
126872 **
126873 ** All examples A through E above satisfy case 3. But if a term
126874 ** also satisfies case 1 (such as B) we know that the optimizer will
126875 ** always prefer case 1, so in that case we pretend that case 3 is not
126876 ** satisfied.
126877 **
126878 ** It might be the case that multiple tables are indexable. For example,
126879 ** (E) above is indexable on tables P, Q, and R.
126880 **
126881 ** Terms that satisfy case 3 are candidates for lookup by using
126882 ** separate indices to find rowids for each subterm and composing
126883 ** the union of all rowids using a RowSet object. This is similar
126884 ** to "bitmap indices" in other database engines.
126885 **
126886 ** OTHERWISE:
126887 **
126888 ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
126889 ** zero. This term is not useful for search.
126890 */
126891 static void exprAnalyzeOrTerm(
126892  SrcList *pSrc, /* the FROM clause */
126893  WhereClause *pWC, /* the complete WHERE clause */
126894  int idxTerm /* Index of the OR-term to be analyzed */
126895 ){
126896  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
126897  Parse *pParse = pWInfo->pParse; /* Parser context */
126898  sqlite3 *db = pParse->db; /* Database connection */
126899  WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
126900  Expr *pExpr = pTerm->pExpr; /* The expression of the term */
126901  int i; /* Loop counters */
126902  WhereClause *pOrWc; /* Breakup of pTerm into subterms */
126903  WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
126904  WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
126905  Bitmask chngToIN; /* Tables that might satisfy case 1 */
126906  Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
126907 
126908  /*
126909  ** Break the OR clause into its separate subterms. The subterms are
126910  ** stored in a WhereClause structure containing within the WhereOrInfo
126911  ** object that is attached to the original OR clause term.
126912  */
126913  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
126914  assert( pExpr->op==TK_OR );
126915  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
126916  if( pOrInfo==0 ) return;
126917  pTerm->wtFlags |= TERM_ORINFO;
126918  pOrWc = &pOrInfo->wc;
126919  memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
126920  sqlite3WhereClauseInit(pOrWc, pWInfo);
126921  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
126922  sqlite3WhereExprAnalyze(pSrc, pOrWc);
126923  if( db->mallocFailed ) return;
126924  assert( pOrWc->nTerm>=2 );
126925 
126926  /*
126927  ** Compute the set of tables that might satisfy cases 1 or 3.
126928  */
126929  indexable = ~(Bitmask)0;
126930  chngToIN = ~(Bitmask)0;
126931  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
126932  if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
126933  WhereAndInfo *pAndInfo;
126934  assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
126935  chngToIN = 0;
126936  pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
126937  if( pAndInfo ){
126938  WhereClause *pAndWC;
126939  WhereTerm *pAndTerm;
126940  int j;
126941  Bitmask b = 0;
126942  pOrTerm->u.pAndInfo = pAndInfo;
126943  pOrTerm->wtFlags |= TERM_ANDINFO;
126944  pOrTerm->eOperator = WO_AND;
126945  pAndWC = &pAndInfo->wc;
126946  memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
126947  sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
126948  sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
126949  sqlite3WhereExprAnalyze(pSrc, pAndWC);
126950  pAndWC->pOuter = pWC;
126951  if( !db->mallocFailed ){
126952  for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
126953  assert( pAndTerm->pExpr );
126954  if( allowedOp(pAndTerm->pExpr->op)
126955  || pAndTerm->eOperator==WO_MATCH
126956  ){
126957  b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
126958  }
126959  }
126960  }
126961  indexable &= b;
126962  }
126963  }else if( pOrTerm->wtFlags & TERM_COPIED ){
126964  /* Skip this term for now. We revisit it when we process the
126965  ** corresponding TERM_VIRTUAL term */
126966  }else{
126967  Bitmask b;
126968  b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
126969  if( pOrTerm->wtFlags & TERM_VIRTUAL ){
126970  WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
126971  b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
126972  }
126973  indexable &= b;
126974  if( (pOrTerm->eOperator & WO_EQ)==0 ){
126975  chngToIN = 0;
126976  }else{
126977  chngToIN &= b;
126978  }
126979  }
126980  }
126981 
126982  /*
126983  ** Record the set of tables that satisfy case 3. The set might be
126984  ** empty.
126985  */
126986  pOrInfo->indexable = indexable;
126987  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
126988 
126989  /* For a two-way OR, attempt to implementation case 2.
126990  */
126991  if( indexable && pOrWc->nTerm==2 ){
126992  int iOne = 0;
126993  WhereTerm *pOne;
126994  while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
126995  int iTwo = 0;
126996  WhereTerm *pTwo;
126997  while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
126998  whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
126999  }
127000  }
127001  }
127002 
127003  /*
127004  ** chngToIN holds a set of tables that *might* satisfy case 1. But
127005  ** we have to do some additional checking to see if case 1 really
127006  ** is satisfied.
127007  **
127008  ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
127009  ** that there is no possibility of transforming the OR clause into an
127010  ** IN operator because one or more terms in the OR clause contain
127011  ** something other than == on a column in the single table. The 1-bit
127012  ** case means that every term of the OR clause is of the form
127013  ** "table.column=expr" for some single table. The one bit that is set
127014  ** will correspond to the common table. We still need to check to make
127015  ** sure the same column is used on all terms. The 2-bit case is when
127016  ** the all terms are of the form "table1.column=table2.column". It
127017  ** might be possible to form an IN operator with either table1.column
127018  ** or table2.column as the LHS if either is common to every term of
127019  ** the OR clause.
127020  **
127021  ** Note that terms of the form "table.column1=table.column2" (the
127022  ** same table on both sizes of the ==) cannot be optimized.
127023  */
127024  if( chngToIN ){
127025  int okToChngToIN = 0; /* True if the conversion to IN is valid */
127026  int iColumn = -1; /* Column index on lhs of IN operator */
127027  int iCursor = -1; /* Table cursor common to all terms */
127028  int j = 0; /* Loop counter */
127029 
127030  /* Search for a table and column that appears on one side or the
127031  ** other of the == operator in every subterm. That table and column
127032  ** will be recorded in iCursor and iColumn. There might not be any
127033  ** such table and column. Set okToChngToIN if an appropriate table
127034  ** and column is found but leave okToChngToIN false if not found.
127035  */
127036  for(j=0; j<2 && !okToChngToIN; j++){
127037  pOrTerm = pOrWc->a;
127038  for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
127039  assert( pOrTerm->eOperator & WO_EQ );
127040  pOrTerm->wtFlags &= ~TERM_OR_OK;
127041  if( pOrTerm->leftCursor==iCursor ){
127042  /* This is the 2-bit case and we are on the second iteration and
127043  ** current term is from the first iteration. So skip this term. */
127044  assert( j==1 );
127045  continue;
127046  }
127047  if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
127048  pOrTerm->leftCursor))==0 ){
127049  /* This term must be of the form t1.a==t2.b where t2 is in the
127050  ** chngToIN set but t1 is not. This term will be either preceded
127051  ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
127052  ** and use its inversion. */
127053  testcase( pOrTerm->wtFlags & TERM_COPIED );
127054  testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
127055  assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
127056  continue;
127057  }
127058  iColumn = pOrTerm->u.leftColumn;
127059  iCursor = pOrTerm->leftCursor;
127060  break;
127061  }
127062  if( i<0 ){
127063  /* No candidate table+column was found. This can only occur
127064  ** on the second iteration */
127065  assert( j==1 );
127066  assert( IsPowerOfTwo(chngToIN) );
127067  assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
127068  break;
127069  }
127070  testcase( j==1 );
127071 
127072  /* We have found a candidate table and column. Check to see if that
127073  ** table and column is common to every term in the OR clause */
127074  okToChngToIN = 1;
127075  for(; i>=0 && okToChngToIN; i--, pOrTerm++){
127076  assert( pOrTerm->eOperator & WO_EQ );
127077  if( pOrTerm->leftCursor!=iCursor ){
127078  pOrTerm->wtFlags &= ~TERM_OR_OK;
127079  }else if( pOrTerm->u.leftColumn!=iColumn ){
127080  okToChngToIN = 0;
127081  }else{
127082  int affLeft, affRight;
127083  /* If the right-hand side is also a column, then the affinities
127084  ** of both right and left sides must be such that no type
127085  ** conversions are required on the right. (Ticket #2249)
127086  */
127087  affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
127088  affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
127089  if( affRight!=0 && affRight!=affLeft ){
127090  okToChngToIN = 0;
127091  }else{
127092  pOrTerm->wtFlags |= TERM_OR_OK;
127093  }
127094  }
127095  }
127096  }
127097 
127098  /* At this point, okToChngToIN is true if original pTerm satisfies
127099  ** case 1. In that case, construct a new virtual term that is
127100  ** pTerm converted into an IN operator.
127101  */
127102  if( okToChngToIN ){
127103  Expr *pDup; /* A transient duplicate expression */
127104  ExprList *pList = 0; /* The RHS of the IN operator */
127105  Expr *pLeft = 0; /* The LHS of the IN operator */
127106  Expr *pNew; /* The complete IN operator */
127107 
127108  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
127109  if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
127110  assert( pOrTerm->eOperator & WO_EQ );
127111  assert( pOrTerm->leftCursor==iCursor );
127112  assert( pOrTerm->u.leftColumn==iColumn );
127113  pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
127114  pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
127115  pLeft = pOrTerm->pExpr->pLeft;
127116  }
127117  assert( pLeft!=0 );
127118  pDup = sqlite3ExprDup(db, pLeft, 0);
127119  pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
127120  if( pNew ){
127121  int idxNew;
127122  transferJoinMarkings(pNew, pExpr);
127123  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
127124  pNew->x.pList = pList;
127125  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
127126  testcase( idxNew==0 );
127127  exprAnalyze(pSrc, pWC, idxNew);
127128  pTerm = &pWC->a[idxTerm];
127129  markTermAsChild(pWC, idxNew, idxTerm);
127130  }else{
127131  sqlite3ExprListDelete(db, pList);
127132  }
127133  pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
127134  }
127135  }
127136 }
127137 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
127138 
127139 /*
127140 ** We already know that pExpr is a binary operator where both operands are
127141 ** column references. This routine checks to see if pExpr is an equivalence
127142 ** relation:
127143 ** 1. The SQLITE_Transitive optimization must be enabled
127144 ** 2. Must be either an == or an IS operator
127145 ** 3. Not originating in the ON clause of an OUTER JOIN
127146 ** 4. The affinities of A and B must be compatible
127147 ** 5a. Both operands use the same collating sequence OR
127148 ** 5b. The overall collating sequence is BINARY
127149 ** If this routine returns TRUE, that means that the RHS can be substituted
127150 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
127151 ** This is an optimization. No harm comes from returning 0. But if 1 is
127152 ** returned when it should not be, then incorrect answers might result.
127153 */
127154 static int termIsEquivalence(Parse *pParse, Expr *pExpr){
127155  char aff1, aff2;
127156  CollSeq *pColl;
127157  const char *zColl1, *zColl2;
127158  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
127159  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
127160  if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
127161  aff1 = sqlite3ExprAffinity(pExpr->pLeft);
127162  aff2 = sqlite3ExprAffinity(pExpr->pRight);
127163  if( aff1!=aff2
127164  && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
127165  ){
127166  return 0;
127167  }
127168  pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
127169  if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
127170  pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
127171  zColl1 = pColl ? pColl->zName : 0;
127172  pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
127173  zColl2 = pColl ? pColl->zName : 0;
127174  return sqlite3_stricmp(zColl1, zColl2)==0;
127175 }
127176 
127177 /*
127178 ** Recursively walk the expressions of a SELECT statement and generate
127179 ** a bitmask indicating which tables are used in that expression
127180 ** tree.
127181 */
127182 static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
127183  Bitmask mask = 0;
127184  while( pS ){
127185  SrcList *pSrc = pS->pSrc;
127186  mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
127187  mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
127188  mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
127189  mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
127190  mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
127191  if( ALWAYS(pSrc!=0) ){
127192  int i;
127193  for(i=0; i<pSrc->nSrc; i++){
127194  mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
127195  mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
127196  }
127197  }
127198  pS = pS->pPrior;
127199  }
127200  return mask;
127201 }
127202 
127203 /*
127204 ** Expression pExpr is one operand of a comparison operator that might
127205 ** be useful for indexing. This routine checks to see if pExpr appears
127206 ** in any index. Return TRUE (1) if pExpr is an indexed term and return
127207 ** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor
127208 ** number of the table that is indexed and *piColumn to the column number
127209 ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
127210 ** indexed.
127211 **
127212 ** If pExpr is a TK_COLUMN column reference, then this routine always returns
127213 ** true even if that particular column is not indexed, because the column
127214 ** might be added to an automatic index later.
127215 */
127216 static int exprMightBeIndexed(
127217  SrcList *pFrom, /* The FROM clause */
127218  int op, /* The specific comparison operator */
127219  Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
127220  Expr *pExpr, /* An operand of a comparison operator */
127221  int *piCur, /* Write the referenced table cursor number here */
127222  int *piColumn /* Write the referenced table column number here */
127223 ){
127224  Index *pIdx;
127225  int i;
127226  int iCur;
127227 
127228  /* If this expression is a vector to the left or right of a
127229  ** inequality constraint (>, <, >= or <=), perform the processing
127230  ** on the first element of the vector. */
127231  assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
127232  assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
127233  assert( op<=TK_GE );
127234  if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
127235  pExpr = pExpr->x.pList->a[0].pExpr;
127236  }
127237 
127238  if( pExpr->op==TK_COLUMN ){
127239  *piCur = pExpr->iTable;
127240  *piColumn = pExpr->iColumn;
127241  return 1;
127242  }
127243  if( mPrereq==0 ) return 0; /* No table references */
127244  if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
127245  for(i=0; mPrereq>1; i++, mPrereq>>=1){}
127246  iCur = pFrom->a[i].iCursor;
127247  for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
127248  if( pIdx->aColExpr==0 ) continue;
127249  for(i=0; i<pIdx->nKeyCol; i++){
127250  if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
127251  if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
127252  *piCur = iCur;
127253  *piColumn = XN_EXPR;
127254  return 1;
127255  }
127256  }
127257  }
127258  return 0;
127259 }
127260 
127261 /*
127262 ** The input to this routine is an WhereTerm structure with only the
127263 ** "pExpr" field filled in. The job of this routine is to analyze the
127264 ** subexpression and populate all the other fields of the WhereTerm
127265 ** structure.
127266 **
127267 ** If the expression is of the form "<expr> <op> X" it gets commuted
127268 ** to the standard form of "X <op> <expr>".
127269 **
127270 ** If the expression is of the form "X <op> Y" where both X and Y are
127271 ** columns, then the original expression is unchanged and a new virtual
127272 ** term of the form "Y <op> X" is added to the WHERE clause and
127273 ** analyzed separately. The original term is marked with TERM_COPIED
127274 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
127275 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
127276 ** is a commuted copy of a prior term.) The original term has nChild=1
127277 ** and the copy has idxParent set to the index of the original term.
127278 */
127279 static void exprAnalyze(
127280  SrcList *pSrc, /* the FROM clause */
127281  WhereClause *pWC, /* the WHERE clause */
127282  int idxTerm /* Index of the term to be analyzed */
127283 ){
127284  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
127285  WhereTerm *pTerm; /* The term to be analyzed */
127286  WhereMaskSet *pMaskSet; /* Set of table index masks */
127287  Expr *pExpr; /* The expression to be analyzed */
127288  Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
127289  Bitmask prereqAll; /* Prerequesites of pExpr */
127290  Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
127291  Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
127292  int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
127293  int noCase = 0; /* uppercase equivalent to lowercase */
127294  int op; /* Top-level operator. pExpr->op */
127295  Parse *pParse = pWInfo->pParse; /* Parsing context */
127296  sqlite3 *db = pParse->db; /* Database connection */
127297  unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
127298 
127299  if( db->mallocFailed ){
127300  return;
127301  }
127302  pTerm = &pWC->a[idxTerm];
127303  pMaskSet = &pWInfo->sMaskSet;
127304  pExpr = pTerm->pExpr;
127305  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
127306  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
127307  op = pExpr->op;
127308  if( op==TK_IN ){
127309  assert( pExpr->pRight==0 );
127310  if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
127311  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
127312  pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
127313  }else{
127314  pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
127315  }
127316  }else if( op==TK_ISNULL ){
127317  pTerm->prereqRight = 0;
127318  }else{
127319  pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
127320  }
127321  prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
127322  if( ExprHasProperty(pExpr, EP_FromJoin) ){
127323  Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
127324  prereqAll |= x;
127325  extraRight = x-1; /* ON clause terms may not be used with an index
127326  ** on left table of a LEFT JOIN. Ticket #3015 */
127327  }
127328  pTerm->prereqAll = prereqAll;
127329  pTerm->leftCursor = -1;
127330  pTerm->iParent = -1;
127331  pTerm->eOperator = 0;
127332  if( allowedOp(op) ){
127333  int iCur, iColumn;
127334  Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
127335  Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
127336  u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
127337 
127338  if( pTerm->iField>0 ){
127339  assert( op==TK_IN );
127340  assert( pLeft->op==TK_VECTOR );
127341  pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
127342  }
127343 
127344  if( exprMightBeIndexed(pSrc, op, prereqLeft, pLeft, &iCur, &iColumn) ){
127345  pTerm->leftCursor = iCur;
127346  pTerm->u.leftColumn = iColumn;
127347  pTerm->eOperator = operatorMask(op) & opMask;
127348  }
127349  if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
127350  if( pRight
127351  && exprMightBeIndexed(pSrc, op, pTerm->prereqRight, pRight, &iCur,&iColumn)
127352  ){
127353  WhereTerm *pNew;
127354  Expr *pDup;
127355  u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
127356  assert( pTerm->iField==0 );
127357  if( pTerm->leftCursor>=0 ){
127358  int idxNew;
127359  pDup = sqlite3ExprDup(db, pExpr, 0);
127360  if( db->mallocFailed ){
127361  sqlite3ExprDelete(db, pDup);
127362  return;
127363  }
127364  idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
127365  if( idxNew==0 ) return;
127366  pNew = &pWC->a[idxNew];
127367  markTermAsChild(pWC, idxNew, idxTerm);
127368  if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
127369  pTerm = &pWC->a[idxTerm];
127370  pTerm->wtFlags |= TERM_COPIED;
127371 
127372  if( termIsEquivalence(pParse, pDup) ){
127373  pTerm->eOperator |= WO_EQUIV;
127374  eExtraOp = WO_EQUIV;
127375  }
127376  }else{
127377  pDup = pExpr;
127378  pNew = pTerm;
127379  }
127380  exprCommute(pParse, pDup);
127381  pNew->leftCursor = iCur;
127382  pNew->u.leftColumn = iColumn;
127383  testcase( (prereqLeft | extraRight) != prereqLeft );
127384  pNew->prereqRight = prereqLeft | extraRight;
127385  pNew->prereqAll = prereqAll;
127386  pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
127387  }
127388  }
127389 
127390 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
127391  /* If a term is the BETWEEN operator, create two new virtual terms
127392  ** that define the range that the BETWEEN implements. For example:
127393  **
127394  ** a BETWEEN b AND c
127395  **
127396  ** is converted into:
127397  **
127398  ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
127399  **
127400  ** The two new terms are added onto the end of the WhereClause object.
127401  ** The new terms are "dynamic" and are children of the original BETWEEN
127402  ** term. That means that if the BETWEEN term is coded, the children are
127403  ** skipped. Or, if the children are satisfied by an index, the original
127404  ** BETWEEN term is skipped.
127405  */
127406  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
127407  ExprList *pList = pExpr->x.pList;
127408  int i;
127409  static const u8 ops[] = {TK_GE, TK_LE};
127410  assert( pList!=0 );
127411  assert( pList->nExpr==2 );
127412  for(i=0; i<2; i++){
127413  Expr *pNewExpr;
127414  int idxNew;
127415  pNewExpr = sqlite3PExpr(pParse, ops[i],
127416  sqlite3ExprDup(db, pExpr->pLeft, 0),
127417  sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
127418  transferJoinMarkings(pNewExpr, pExpr);
127419  idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
127420  testcase( idxNew==0 );
127421  exprAnalyze(pSrc, pWC, idxNew);
127422  pTerm = &pWC->a[idxTerm];
127423  markTermAsChild(pWC, idxNew, idxTerm);
127424  }
127425  }
127426 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
127427 
127428 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
127429  /* Analyze a term that is composed of two or more subterms connected by
127430  ** an OR operator.
127431  */
127432  else if( pExpr->op==TK_OR ){
127433  assert( pWC->op==TK_AND );
127434  exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
127435  pTerm = &pWC->a[idxTerm];
127436  }
127437 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
127438 
127439 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
127440  /* Add constraints to reduce the search space on a LIKE or GLOB
127441  ** operator.
127442  **
127443  ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
127444  **
127445  ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
127446  **
127447  ** The last character of the prefix "abc" is incremented to form the
127448  ** termination condition "abd". If case is not significant (the default
127449  ** for LIKE) then the lower-bound is made all uppercase and the upper-
127450  ** bound is made all lowercase so that the bounds also work when comparing
127451  ** BLOBs.
127452  */
127453  if( pWC->op==TK_AND
127454  && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
127455  ){
127456  Expr *pLeft; /* LHS of LIKE/GLOB operator */
127457  Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
127458  Expr *pNewExpr1;
127459  Expr *pNewExpr2;
127460  int idxNew1;
127461  int idxNew2;
127462  const char *zCollSeqName; /* Name of collating sequence */
127463  const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
127464 
127465  pLeft = pExpr->x.pList->a[1].pExpr;
127466  pStr2 = sqlite3ExprDup(db, pStr1, 0);
127467 
127468  /* Convert the lower bound to upper-case and the upper bound to
127469  ** lower-case (upper-case is less than lower-case in ASCII) so that
127470  ** the range constraints also work for BLOBs
127471  */
127472  if( noCase && !pParse->db->mallocFailed ){
127473  int i;
127474  char c;
127475  pTerm->wtFlags |= TERM_LIKE;
127476  for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
127477  pStr1->u.zToken[i] = sqlite3Toupper(c);
127478  pStr2->u.zToken[i] = sqlite3Tolower(c);
127479  }
127480  }
127481 
127482  if( !db->mallocFailed ){
127483  u8 c, *pC; /* Last character before the first wildcard */
127484  pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
127485  c = *pC;
127486  if( noCase ){
127487  /* The point is to increment the last character before the first
127488  ** wildcard. But if we increment '@', that will push it into the
127489  ** alphabetic range where case conversions will mess up the
127490  ** inequality. To avoid this, make sure to also run the full
127491  ** LIKE on all candidate expressions by clearing the isComplete flag
127492  */
127493  if( c=='A'-1 ) isComplete = 0;
127494  c = sqlite3UpperToLower[c];
127495  }
127496  *pC = c + 1;
127497  }
127498  zCollSeqName = noCase ? "NOCASE" : "BINARY";
127499  pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
127500  pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
127501  sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
127502  pStr1, 0);
127503  transferJoinMarkings(pNewExpr1, pExpr);
127504  idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
127505  testcase( idxNew1==0 );
127506  exprAnalyze(pSrc, pWC, idxNew1);
127507  pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
127508  pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
127509  sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
127510  pStr2, 0);
127511  transferJoinMarkings(pNewExpr2, pExpr);
127512  idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
127513  testcase( idxNew2==0 );
127514  exprAnalyze(pSrc, pWC, idxNew2);
127515  pTerm = &pWC->a[idxTerm];
127516  if( isComplete ){
127517  markTermAsChild(pWC, idxNew1, idxTerm);
127518  markTermAsChild(pWC, idxNew2, idxTerm);
127519  }
127520  }
127521 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
127522 
127523 #ifndef SQLITE_OMIT_VIRTUALTABLE
127524  /* Add a WO_MATCH auxiliary term to the constraint set if the
127525  ** current expression is of the form: column MATCH expr.
127526  ** This information is used by the xBestIndex methods of
127527  ** virtual tables. The native query optimizer does not attempt
127528  ** to do anything with MATCH functions.
127529  */
127530  if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
127531  int idxNew;
127532  Expr *pRight, *pLeft;
127533  WhereTerm *pNewTerm;
127534  Bitmask prereqColumn, prereqExpr;
127535 
127536  pRight = pExpr->x.pList->a[0].pExpr;
127537  pLeft = pExpr->x.pList->a[1].pExpr;
127538  prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
127539  prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
127540  if( (prereqExpr & prereqColumn)==0 ){
127541  Expr *pNewExpr;
127542  pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
127543  0, sqlite3ExprDup(db, pRight, 0), 0);
127544  idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
127545  testcase( idxNew==0 );
127546  pNewTerm = &pWC->a[idxNew];
127547  pNewTerm->prereqRight = prereqExpr;
127548  pNewTerm->leftCursor = pLeft->iTable;
127549  pNewTerm->u.leftColumn = pLeft->iColumn;
127550  pNewTerm->eOperator = WO_MATCH;
127551  pNewTerm->eMatchOp = eOp2;
127552  markTermAsChild(pWC, idxNew, idxTerm);
127553  pTerm = &pWC->a[idxTerm];
127554  pTerm->wtFlags |= TERM_COPIED;
127555  pNewTerm->prereqAll = pTerm->prereqAll;
127556  }
127557  }
127558 #endif /* SQLITE_OMIT_VIRTUALTABLE */
127559 
127560  /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
127561  ** new terms for each component comparison - "a = ?" and "b = ?". The
127562  ** new terms completely replace the original vector comparison, which is
127563  ** no longer used.
127564  **
127565  ** This is only required if at least one side of the comparison operation
127566  ** is not a sub-select. */
127567  if( pWC->op==TK_AND
127568  && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
127569  && sqlite3ExprIsVector(pExpr->pLeft)
127570  && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
127571  || (pExpr->pRight->flags & EP_xIsSelect)==0
127572  )){
127573  int nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
127574  int i;
127575  assert( nLeft==sqlite3ExprVectorSize(pExpr->pRight) );
127576  for(i=0; i<nLeft; i++){
127577  int idxNew;
127578  Expr *pNew;
127579  Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
127580  Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
127581 
127582  pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight, 0);
127583  transferJoinMarkings(pNew, pExpr);
127584  idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
127585  exprAnalyze(pSrc, pWC, idxNew);
127586  }
127587  pTerm = &pWC->a[idxTerm];
127588  pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */
127589  pTerm->eOperator = 0;
127590  }
127591 
127592  /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
127593  ** a virtual term for each vector component. The expression object
127594  ** used by each such virtual term is pExpr (the full vector IN(...)
127595  ** expression). The WhereTerm.iField variable identifies the index within
127596  ** the vector on the LHS that the virtual term represents.
127597  **
127598  ** This only works if the RHS is a simple SELECT, not a compound
127599  */
127600  if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
127601  && pExpr->pLeft->op==TK_VECTOR
127602  && pExpr->x.pSelect->pPrior==0
127603  ){
127604  int i;
127605  for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
127606  int idxNew;
127607  idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
127608  pWC->a[idxNew].iField = i+1;
127609  exprAnalyze(pSrc, pWC, idxNew);
127610  markTermAsChild(pWC, idxNew, idxTerm);
127611  }
127612  }
127613 
127614 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127615  /* When sqlite_stat3 histogram data is available an operator of the
127616  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
127617  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
127618  ** virtual term of that form.
127619  **
127620  ** Note that the virtual term must be tagged with TERM_VNULL.
127621  */
127622  if( pExpr->op==TK_NOTNULL
127623  && pExpr->pLeft->op==TK_COLUMN
127624  && pExpr->pLeft->iColumn>=0
127625  && OptimizationEnabled(db, SQLITE_Stat34)
127626  ){
127627  Expr *pNewExpr;
127628  Expr *pLeft = pExpr->pLeft;
127629  int idxNew;
127630  WhereTerm *pNewTerm;
127631 
127632  pNewExpr = sqlite3PExpr(pParse, TK_GT,
127633  sqlite3ExprDup(db, pLeft, 0),
127634  sqlite3ExprAlloc(db, TK_NULL, 0, 0), 0);
127635 
127636  idxNew = whereClauseInsert(pWC, pNewExpr,
127637  TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
127638  if( idxNew ){
127639  pNewTerm = &pWC->a[idxNew];
127640  pNewTerm->prereqRight = 0;
127641  pNewTerm->leftCursor = pLeft->iTable;
127642  pNewTerm->u.leftColumn = pLeft->iColumn;
127643  pNewTerm->eOperator = WO_GT;
127644  markTermAsChild(pWC, idxNew, idxTerm);
127645  pTerm = &pWC->a[idxTerm];
127646  pTerm->wtFlags |= TERM_COPIED;
127647  pNewTerm->prereqAll = pTerm->prereqAll;
127648  }
127649  }
127650 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
127651 
127652  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
127653  ** an index for tables to the left of the join.
127654  */
127655  pTerm->prereqRight |= extraRight;
127656 }
127657 
127658 /***************************************************************************
127659 ** Routines with file scope above. Interface to the rest of the where.c
127660 ** subsystem follows.
127661 ***************************************************************************/
127662 
127663 /*
127664 ** This routine identifies subexpressions in the WHERE clause where
127665 ** each subexpression is separated by the AND operator or some other
127666 ** operator specified in the op parameter. The WhereClause structure
127667 ** is filled with pointers to subexpressions. For example:
127668 **
127669 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
127670 ** \________/ \_______________/ \________________/
127671 ** slot[0] slot[1] slot[2]
127672 **
127673 ** The original WHERE clause in pExpr is unaltered. All this routine
127674 ** does is make slot[] entries point to substructure within pExpr.
127675 **
127676 ** In the previous sentence and in the diagram, "slot[]" refers to
127677 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
127678 ** all terms of the WHERE clause.
127679 */
127680 SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
127681  Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
127682  pWC->op = op;
127683  if( pE2==0 ) return;
127684  if( pE2->op!=op ){
127685  whereClauseInsert(pWC, pExpr, 0);
127686  }else{
127687  sqlite3WhereSplit(pWC, pE2->pLeft, op);
127688  sqlite3WhereSplit(pWC, pE2->pRight, op);
127689  }
127690 }
127691 
127692 /*
127693 ** Initialize a preallocated WhereClause structure.
127694 */
127695 SQLITE_PRIVATE void sqlite3WhereClauseInit(
127696  WhereClause *pWC, /* The WhereClause to be initialized */
127697  WhereInfo *pWInfo /* The WHERE processing context */
127698 ){
127699  pWC->pWInfo = pWInfo;
127700  pWC->pOuter = 0;
127701  pWC->nTerm = 0;
127702  pWC->nSlot = ArraySize(pWC->aStatic);
127703  pWC->a = pWC->aStatic;
127704 }
127705 
127706 /*
127707 ** Deallocate a WhereClause structure. The WhereClause structure
127708 ** itself is not freed. This routine is the inverse of
127709 ** sqlite3WhereClauseInit().
127710 */
127711 SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
127712  int i;
127713  WhereTerm *a;
127714  sqlite3 *db = pWC->pWInfo->pParse->db;
127715  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
127716  if( a->wtFlags & TERM_DYNAMIC ){
127717  sqlite3ExprDelete(db, a->pExpr);
127718  }
127719  if( a->wtFlags & TERM_ORINFO ){
127720  whereOrInfoDelete(db, a->u.pOrInfo);
127721  }else if( a->wtFlags & TERM_ANDINFO ){
127722  whereAndInfoDelete(db, a->u.pAndInfo);
127723  }
127724  }
127725  if( pWC->a!=pWC->aStatic ){
127726  sqlite3DbFree(db, pWC->a);
127727  }
127728 }
127729 
127730 
127731 /*
127732 ** These routines walk (recursively) an expression tree and generate
127733 ** a bitmask indicating which tables are used in that expression
127734 ** tree.
127735 */
127736 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
127737  Bitmask mask;
127738  if( p==0 ) return 0;
127739  if( p->op==TK_COLUMN ){
127740  mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
127741  return mask;
127742  }
127743  assert( !ExprHasProperty(p, EP_TokenOnly) );
127744  mask = p->pRight ? sqlite3WhereExprUsage(pMaskSet, p->pRight) : 0;
127745  if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
127746  if( ExprHasProperty(p, EP_xIsSelect) ){
127747  mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
127748  }else if( p->x.pList ){
127749  mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
127750  }
127751  return mask;
127752 }
127753 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
127754  int i;
127755  Bitmask mask = 0;
127756  if( pList ){
127757  for(i=0; i<pList->nExpr; i++){
127758  mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
127759  }
127760  }
127761  return mask;
127762 }
127763 
127764 
127765 /*
127766 ** Call exprAnalyze on all terms in a WHERE clause.
127767 **
127768 ** Note that exprAnalyze() might add new virtual terms onto the
127769 ** end of the WHERE clause. We do not want to analyze these new
127770 ** virtual terms, so start analyzing at the end and work forward
127771 ** so that the added virtual terms are never processed.
127772 */
127773 SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
127774  SrcList *pTabList, /* the FROM clause */
127775  WhereClause *pWC /* the WHERE clause to be analyzed */
127776 ){
127777  int i;
127778  for(i=pWC->nTerm-1; i>=0; i--){
127779  exprAnalyze(pTabList, pWC, i);
127780  }
127781 }
127782 
127783 /*
127784 ** For table-valued-functions, transform the function arguments into
127785 ** new WHERE clause terms.
127786 **
127787 ** Each function argument translates into an equality constraint against
127788 ** a HIDDEN column in the table.
127789 */
127790 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
127791  Parse *pParse, /* Parsing context */
127792  struct SrcList_item *pItem, /* The FROM clause term to process */
127793  WhereClause *pWC /* Xfer function arguments to here */
127794 ){
127795  Table *pTab;
127796  int j, k;
127797  ExprList *pArgs;
127798  Expr *pColRef;
127799  Expr *pTerm;
127800  if( pItem->fg.isTabFunc==0 ) return;
127801  pTab = pItem->pTab;
127802  assert( pTab!=0 );
127803  pArgs = pItem->u1.pFuncArg;
127804  if( pArgs==0 ) return;
127805  for(j=k=0; j<pArgs->nExpr; j++){
127806  while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
127807  if( k>=pTab->nCol ){
127808  sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
127809  pTab->zName, j);
127810  return;
127811  }
127812  pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
127813  if( pColRef==0 ) return;
127814  pColRef->iTable = pItem->iCursor;
127815  pColRef->iColumn = k++;
127816  pColRef->pTab = pTab;
127817  pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
127818  sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
127819  whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
127820  }
127821 }
127822 
127823 /************** End of whereexpr.c *******************************************/
127824 /************** Begin file where.c *******************************************/
127825 /*
127826 ** 2001 September 15
127827 **
127828 ** The author disclaims copyright to this source code. In place of
127829 ** a legal notice, here is a blessing:
127830 **
127831 ** May you do good and not evil.
127832 ** May you find forgiveness for yourself and forgive others.
127833 ** May you share freely, never taking more than you give.
127834 **
127835 *************************************************************************
127836 ** This module contains C code that generates VDBE code used to process
127837 ** the WHERE clause of SQL statements. This module is responsible for
127838 ** generating the code that loops through a table looking for applicable
127839 ** rows. Indices are selected and used to speed the search when doing
127840 ** so is applicable. Because this module is responsible for selecting
127841 ** indices, you might also think of this module as the "query optimizer".
127842 */
127843 /* #include "sqliteInt.h" */
127844 /* #include "whereInt.h" */
127845 
127846 /* Forward declaration of methods */
127847 static int whereLoopResize(sqlite3*, WhereLoop*, int);
127848 
127849 /* Test variable that can be set to enable WHERE tracing */
127850 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
127851 /***/ int sqlite3WhereTrace = 0;
127852 #endif
127853 
127854 
127855 /*
127856 ** Return the estimated number of output rows from a WHERE clause
127857 */
127858 SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
127859  return pWInfo->nRowOut;
127860 }
127861 
127862 /*
127863 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
127864 ** WHERE clause returns outputs for DISTINCT processing.
127865 */
127866 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
127867  return pWInfo->eDistinct;
127868 }
127869 
127870 /*
127871 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
127872 ** Return FALSE if the output needs to be sorted.
127873 */
127874 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
127875  return pWInfo->nOBSat;
127876 }
127877 
127878 /*
127879 ** Return TRUE if the innermost loop of the WHERE clause implementation
127880 ** returns rows in ORDER BY order for complete run of the inner loop.
127881 **
127882 ** Across multiple iterations of outer loops, the output rows need not be
127883 ** sorted. As long as rows are sorted for just the innermost loop, this
127884 ** routine can return TRUE.
127885 */
127886 SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
127887  return pWInfo->bOrderedInnerLoop;
127888 }
127889 
127890 /*
127891 ** Return the VDBE address or label to jump to in order to continue
127892 ** immediately with the next row of a WHERE clause.
127893 */
127894 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
127895  assert( pWInfo->iContinue!=0 );
127896  return pWInfo->iContinue;
127897 }
127898 
127899 /*
127900 ** Return the VDBE address or label to jump to in order to break
127901 ** out of a WHERE loop.
127902 */
127903 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
127904  return pWInfo->iBreak;
127905 }
127906 
127907 /*
127908 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
127909 ** operate directly on the rowis returned by a WHERE clause. Return
127910 ** ONEPASS_SINGLE (1) if the statement can operation directly because only
127911 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
127912 ** optimization can be used on multiple
127913 **
127914 ** If the ONEPASS optimization is used (if this routine returns true)
127915 ** then also write the indices of open cursors used by ONEPASS
127916 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
127917 ** table and iaCur[1] gets the cursor used by an auxiliary index.
127918 ** Either value may be -1, indicating that cursor is not used.
127919 ** Any cursors returned will have been opened for writing.
127920 **
127921 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
127922 ** unable to use the ONEPASS optimization.
127923 */
127924 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
127925  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
127926 #ifdef WHERETRACE_ENABLED
127927  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
127928  sqlite3DebugPrintf("%s cursors: %d %d\n",
127929  pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
127930  aiCur[0], aiCur[1]);
127931  }
127932 #endif
127933  return pWInfo->eOnePass;
127934 }
127935 
127936 /*
127937 ** Move the content of pSrc into pDest
127938 */
127939 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
127940  pDest->n = pSrc->n;
127941  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
127942 }
127943 
127944 /*
127945 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
127946 **
127947 ** The new entry might overwrite an existing entry, or it might be
127948 ** appended, or it might be discarded. Do whatever is the right thing
127949 ** so that pSet keeps the N_OR_COST best entries seen so far.
127950 */
127951 static int whereOrInsert(
127952  WhereOrSet *pSet, /* The WhereOrSet to be updated */
127953  Bitmask prereq, /* Prerequisites of the new entry */
127954  LogEst rRun, /* Run-cost of the new entry */
127955  LogEst nOut /* Number of outputs for the new entry */
127956 ){
127957  u16 i;
127958  WhereOrCost *p;
127959  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
127960  if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
127961  goto whereOrInsert_done;
127962  }
127963  if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
127964  return 0;
127965  }
127966  }
127967  if( pSet->n<N_OR_COST ){
127968  p = &pSet->a[pSet->n++];
127969  p->nOut = nOut;
127970  }else{
127971  p = pSet->a;
127972  for(i=1; i<pSet->n; i++){
127973  if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
127974  }
127975  if( p->rRun<=rRun ) return 0;
127976  }
127977 whereOrInsert_done:
127978  p->prereq = prereq;
127979  p->rRun = rRun;
127980  if( p->nOut>nOut ) p->nOut = nOut;
127981  return 1;
127982 }
127983 
127984 /*
127985 ** Return the bitmask for the given cursor number. Return 0 if
127986 ** iCursor is not in the set.
127987 */
127988 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
127989  int i;
127990  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
127991  for(i=0; i<pMaskSet->n; i++){
127992  if( pMaskSet->ix[i]==iCursor ){
127993  return MASKBIT(i);
127994  }
127995  }
127996  return 0;
127997 }
127998 
127999 /*
128000 ** Create a new mask for cursor iCursor.
128001 **
128002 ** There is one cursor per table in the FROM clause. The number of
128003 ** tables in the FROM clause is limited by a test early in the
128004 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
128005 ** array will never overflow.
128006 */
128007 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
128008  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
128009  pMaskSet->ix[pMaskSet->n++] = iCursor;
128010 }
128011 
128012 /*
128013 ** Advance to the next WhereTerm that matches according to the criteria
128014 ** established when the pScan object was initialized by whereScanInit().
128015 ** Return NULL if there are no more matching WhereTerms.
128016 */
128017 static WhereTerm *whereScanNext(WhereScan *pScan){
128018  int iCur; /* The cursor on the LHS of the term */
128019  i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
128020  Expr *pX; /* An expression being tested */
128021  WhereClause *pWC; /* Shorthand for pScan->pWC */
128022  WhereTerm *pTerm; /* The term being tested */
128023  int k = pScan->k; /* Where to start scanning */
128024 
128025  while( pScan->iEquiv<=pScan->nEquiv ){
128026  iCur = pScan->aiCur[pScan->iEquiv-1];
128027  iColumn = pScan->aiColumn[pScan->iEquiv-1];
128028  if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
128029  while( (pWC = pScan->pWC)!=0 ){
128030  for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
128031  if( pTerm->leftCursor==iCur
128032  && pTerm->u.leftColumn==iColumn
128033  && (iColumn!=XN_EXPR
128034  || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
128035  && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
128036  ){
128037  if( (pTerm->eOperator & WO_EQUIV)!=0
128038  && pScan->nEquiv<ArraySize(pScan->aiCur)
128039  && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
128040  ){
128041  int j;
128042  for(j=0; j<pScan->nEquiv; j++){
128043  if( pScan->aiCur[j]==pX->iTable
128044  && pScan->aiColumn[j]==pX->iColumn ){
128045  break;
128046  }
128047  }
128048  if( j==pScan->nEquiv ){
128049  pScan->aiCur[j] = pX->iTable;
128050  pScan->aiColumn[j] = pX->iColumn;
128051  pScan->nEquiv++;
128052  }
128053  }
128054  if( (pTerm->eOperator & pScan->opMask)!=0 ){
128055  /* Verify the affinity and collating sequence match */
128056  if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
128057  CollSeq *pColl;
128058  Parse *pParse = pWC->pWInfo->pParse;
128059  pX = pTerm->pExpr;
128060  if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
128061  continue;
128062  }
128063  assert(pX->pLeft);
128064  pColl = sqlite3BinaryCompareCollSeq(pParse,
128065  pX->pLeft, pX->pRight);
128066  if( pColl==0 ) pColl = pParse->db->pDfltColl;
128067  if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
128068  continue;
128069  }
128070  }
128071  if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
128072  && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
128073  && pX->iTable==pScan->aiCur[0]
128074  && pX->iColumn==pScan->aiColumn[0]
128075  ){
128076  testcase( pTerm->eOperator & WO_IS );
128077  continue;
128078  }
128079  pScan->k = k+1;
128080  return pTerm;
128081  }
128082  }
128083  }
128084  pScan->pWC = pScan->pWC->pOuter;
128085  k = 0;
128086  }
128087  pScan->pWC = pScan->pOrigWC;
128088  k = 0;
128089  pScan->iEquiv++;
128090  }
128091  return 0;
128092 }
128093 
128094 /*
128095 ** Initialize a WHERE clause scanner object. Return a pointer to the
128096 ** first match. Return NULL if there are no matches.
128097 **
128098 ** The scanner will be searching the WHERE clause pWC. It will look
128099 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
128100 ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
128101 ** must be one of the indexes of table iCur.
128102 **
128103 ** The <op> must be one of the operators described by opMask.
128104 **
128105 ** If the search is for X and the WHERE clause contains terms of the
128106 ** form X=Y then this routine might also return terms of the form
128107 ** "Y <op> <expr>". The number of levels of transitivity is limited,
128108 ** but is enough to handle most commonly occurring SQL statements.
128109 **
128110 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
128111 ** index pIdx.
128112 */
128113 static WhereTerm *whereScanInit(
128114  WhereScan *pScan, /* The WhereScan object being initialized */
128115  WhereClause *pWC, /* The WHERE clause to be scanned */
128116  int iCur, /* Cursor to scan for */
128117  int iColumn, /* Column to scan for */
128118  u32 opMask, /* Operator(s) to scan for */
128119  Index *pIdx /* Must be compatible with this index */
128120 ){
128121  int j = 0;
128122 
128123  /* memset(pScan, 0, sizeof(*pScan)); */
128124  pScan->pOrigWC = pWC;
128125  pScan->pWC = pWC;
128126  pScan->pIdxExpr = 0;
128127  if( pIdx ){
128128  j = iColumn;
128129  iColumn = pIdx->aiColumn[j];
128130  if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
128131  if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID;
128132  }
128133  if( pIdx && iColumn>=0 ){
128134  pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
128135  pScan->zCollName = pIdx->azColl[j];
128136  }else{
128137  pScan->idxaff = 0;
128138  pScan->zCollName = 0;
128139  }
128140  pScan->opMask = opMask;
128141  pScan->k = 0;
128142  pScan->aiCur[0] = iCur;
128143  pScan->aiColumn[0] = iColumn;
128144  pScan->nEquiv = 1;
128145  pScan->iEquiv = 1;
128146  return whereScanNext(pScan);
128147 }
128148 
128149 /*
128150 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
128151 ** where X is a reference to the iColumn of table iCur or of index pIdx
128152 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
128153 ** the op parameter. Return a pointer to the term. Return 0 if not found.
128154 **
128155 ** If pIdx!=0 then it must be one of the indexes of table iCur.
128156 ** Search for terms matching the iColumn-th column of pIdx
128157 ** rather than the iColumn-th column of table iCur.
128158 **
128159 ** The term returned might by Y=<expr> if there is another constraint in
128160 ** the WHERE clause that specifies that X=Y. Any such constraints will be
128161 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
128162 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
128163 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
128164 ** other equivalent values. Hence a search for X will return <expr> if X=A1
128165 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
128166 **
128167 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
128168 ** then try for the one with no dependencies on <expr> - in other words where
128169 ** <expr> is a constant expression of some kind. Only return entries of
128170 ** the form "X <op> Y" where Y is a column in another table if no terms of
128171 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
128172 ** exist, try to return a term that does not use WO_EQUIV.
128173 */
128174 SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
128175  WhereClause *pWC, /* The WHERE clause to be searched */
128176  int iCur, /* Cursor number of LHS */
128177  int iColumn, /* Column number of LHS */
128178  Bitmask notReady, /* RHS must not overlap with this mask */
128179  u32 op, /* Mask of WO_xx values describing operator */
128180  Index *pIdx /* Must be compatible with this index, if not NULL */
128181 ){
128182  WhereTerm *pResult = 0;
128183  WhereTerm *p;
128184  WhereScan scan;
128185 
128186  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
128187  op &= WO_EQ|WO_IS;
128188  while( p ){
128189  if( (p->prereqRight & notReady)==0 ){
128190  if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
128191  testcase( p->eOperator & WO_IS );
128192  return p;
128193  }
128194  if( pResult==0 ) pResult = p;
128195  }
128196  p = whereScanNext(&scan);
128197  }
128198  return pResult;
128199 }
128200 
128201 /*
128202 ** This function searches pList for an entry that matches the iCol-th column
128203 ** of index pIdx.
128204 **
128205 ** If such an expression is found, its index in pList->a[] is returned. If
128206 ** no expression is found, -1 is returned.
128207 */
128208 static int findIndexCol(
128209  Parse *pParse, /* Parse context */
128210  ExprList *pList, /* Expression list to search */
128211  int iBase, /* Cursor for table associated with pIdx */
128212  Index *pIdx, /* Index to match column of */
128213  int iCol /* Column of index to match */
128214 ){
128215  int i;
128216  const char *zColl = pIdx->azColl[iCol];
128217 
128218  for(i=0; i<pList->nExpr; i++){
128219  Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
128220  if( p->op==TK_COLUMN
128221  && p->iColumn==pIdx->aiColumn[iCol]
128222  && p->iTable==iBase
128223  ){
128224  CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
128225  if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
128226  return i;
128227  }
128228  }
128229  }
128230 
128231  return -1;
128232 }
128233 
128234 /*
128235 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
128236 */
128237 static int indexColumnNotNull(Index *pIdx, int iCol){
128238  int j;
128239  assert( pIdx!=0 );
128240  assert( iCol>=0 && iCol<pIdx->nColumn );
128241  j = pIdx->aiColumn[iCol];
128242  if( j>=0 ){
128243  return pIdx->pTable->aCol[j].notNull;
128244  }else if( j==(-1) ){
128245  return 1;
128246  }else{
128247  assert( j==(-2) );
128248  return 0; /* Assume an indexed expression can always yield a NULL */
128249 
128250  }
128251 }
128252 
128253 /*
128254 ** Return true if the DISTINCT expression-list passed as the third argument
128255 ** is redundant.
128256 **
128257 ** A DISTINCT list is redundant if any subset of the columns in the
128258 ** DISTINCT list are collectively unique and individually non-null.
128259 */
128260 static int isDistinctRedundant(
128261  Parse *pParse, /* Parsing context */
128262  SrcList *pTabList, /* The FROM clause */
128263  WhereClause *pWC, /* The WHERE clause */
128264  ExprList *pDistinct /* The result set that needs to be DISTINCT */
128265 ){
128266  Table *pTab;
128267  Index *pIdx;
128268  int i;
128269  int iBase;
128270 
128271  /* If there is more than one table or sub-select in the FROM clause of
128272  ** this query, then it will not be possible to show that the DISTINCT
128273  ** clause is redundant. */
128274  if( pTabList->nSrc!=1 ) return 0;
128275  iBase = pTabList->a[0].iCursor;
128276  pTab = pTabList->a[0].pTab;
128277 
128278  /* If any of the expressions is an IPK column on table iBase, then return
128279  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
128280  ** current SELECT is a correlated sub-query.
128281  */
128282  for(i=0; i<pDistinct->nExpr; i++){
128283  Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
128284  if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
128285  }
128286 
128287  /* Loop through all indices on the table, checking each to see if it makes
128288  ** the DISTINCT qualifier redundant. It does so if:
128289  **
128290  ** 1. The index is itself UNIQUE, and
128291  **
128292  ** 2. All of the columns in the index are either part of the pDistinct
128293  ** list, or else the WHERE clause contains a term of the form "col=X",
128294  ** where X is a constant value. The collation sequences of the
128295  ** comparison and select-list expressions must match those of the index.
128296  **
128297  ** 3. All of those index columns for which the WHERE clause does not
128298  ** contain a "col=X" term are subject to a NOT NULL constraint.
128299  */
128300  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
128301  if( !IsUniqueIndex(pIdx) ) continue;
128302  for(i=0; i<pIdx->nKeyCol; i++){
128303  if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
128304  if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
128305  if( indexColumnNotNull(pIdx, i)==0 ) break;
128306  }
128307  }
128308  if( i==pIdx->nKeyCol ){
128309  /* This index implies that the DISTINCT qualifier is redundant. */
128310  return 1;
128311  }
128312  }
128313 
128314  return 0;
128315 }
128316 
128317 
128318 /*
128319 ** Estimate the logarithm of the input value to base 2.
128320 */
128321 static LogEst estLog(LogEst N){
128322  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
128323 }
128324 
128325 /*
128326 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
128327 **
128328 ** This routine runs over generated VDBE code and translates OP_Column
128329 ** opcodes into OP_Copy when the table is being accessed via co-routine
128330 ** instead of via table lookup.
128331 **
128332 ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
128333 ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
128334 ** then each OP_Rowid is transformed into an instruction to increment the
128335 ** value stored in its output register.
128336 */
128337 static void translateColumnToCopy(
128338  Vdbe *v, /* The VDBE containing code to translate */
128339  int iStart, /* Translate from this opcode to the end */
128340  int iTabCur, /* OP_Column/OP_Rowid references to this table */
128341  int iRegister, /* The first column is in this register */
128342  int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
128343 ){
128344  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
128345  int iEnd = sqlite3VdbeCurrentAddr(v);
128346  for(; iStart<iEnd; iStart++, pOp++){
128347  if( pOp->p1!=iTabCur ) continue;
128348  if( pOp->opcode==OP_Column ){
128349  pOp->opcode = OP_Copy;
128350  pOp->p1 = pOp->p2 + iRegister;
128351  pOp->p2 = pOp->p3;
128352  pOp->p3 = 0;
128353  }else if( pOp->opcode==OP_Rowid ){
128354  if( bIncrRowid ){
128355  /* Increment the value stored in the P2 operand of the OP_Rowid. */
128356  pOp->opcode = OP_AddImm;
128357  pOp->p1 = pOp->p2;
128358  pOp->p2 = 1;
128359  }else{
128360  pOp->opcode = OP_Null;
128361  pOp->p1 = 0;
128362  pOp->p3 = 0;
128363  }
128364  }
128365  }
128366 }
128367 
128368 /*
128369 ** Two routines for printing the content of an sqlite3_index_info
128370 ** structure. Used for testing and debugging only. If neither
128371 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
128372 ** are no-ops.
128373 */
128374 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
128375 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
128376  int i;
128377  if( !sqlite3WhereTrace ) return;
128378  for(i=0; i<p->nConstraint; i++){
128379  sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
128380  i,
128381  p->aConstraint[i].iColumn,
128382  p->aConstraint[i].iTermOffset,
128383  p->aConstraint[i].op,
128384  p->aConstraint[i].usable);
128385  }
128386  for(i=0; i<p->nOrderBy; i++){
128387  sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
128388  i,
128389  p->aOrderBy[i].iColumn,
128390  p->aOrderBy[i].desc);
128391  }
128392 }
128393 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
128394  int i;
128395  if( !sqlite3WhereTrace ) return;
128396  for(i=0; i<p->nConstraint; i++){
128397  sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
128398  i,
128399  p->aConstraintUsage[i].argvIndex,
128400  p->aConstraintUsage[i].omit);
128401  }
128402  sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
128403  sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
128404  sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
128405  sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
128406  sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
128407 }
128408 #else
128409 #define TRACE_IDX_INPUTS(A)
128410 #define TRACE_IDX_OUTPUTS(A)
128411 #endif
128412 
128413 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
128414 /*
128415 ** Return TRUE if the WHERE clause term pTerm is of a form where it
128416 ** could be used with an index to access pSrc, assuming an appropriate
128417 ** index existed.
128418 */
128419 static int termCanDriveIndex(
128420  WhereTerm *pTerm, /* WHERE clause term to check */
128421  struct SrcList_item *pSrc, /* Table we are trying to access */
128422  Bitmask notReady /* Tables in outer loops of the join */
128423 ){
128424  char aff;
128425  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
128426  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
128427  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
128428  if( pTerm->u.leftColumn<0 ) return 0;
128429  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
128430  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
128431  testcase( pTerm->pExpr->op==TK_IS );
128432  return 1;
128433 }
128434 #endif
128435 
128436 
128437 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
128438 /*
128439 ** Generate code to construct the Index object for an automatic index
128440 ** and to set up the WhereLevel object pLevel so that the code generator
128441 ** makes use of the automatic index.
128442 */
128443 static void constructAutomaticIndex(
128444  Parse *pParse, /* The parsing context */
128445  WhereClause *pWC, /* The WHERE clause */
128446  struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
128447  Bitmask notReady, /* Mask of cursors that are not available */
128448  WhereLevel *pLevel /* Write new index here */
128449 ){
128450  int nKeyCol; /* Number of columns in the constructed index */
128451  WhereTerm *pTerm; /* A single term of the WHERE clause */
128452  WhereTerm *pWCEnd; /* End of pWC->a[] */
128453  Index *pIdx; /* Object describing the transient index */
128454  Vdbe *v; /* Prepared statement under construction */
128455  int addrInit; /* Address of the initialization bypass jump */
128456  Table *pTable; /* The table being indexed */
128457  int addrTop; /* Top of the index fill loop */
128458  int regRecord; /* Register holding an index record */
128459  int n; /* Column counter */
128460  int i; /* Loop counter */
128461  int mxBitCol; /* Maximum column in pSrc->colUsed */
128462  CollSeq *pColl; /* Collating sequence to on a column */
128463  WhereLoop *pLoop; /* The Loop object */
128464  char *zNotUsed; /* Extra space on the end of pIdx */
128465  Bitmask idxCols; /* Bitmap of columns used for indexing */
128466  Bitmask extraCols; /* Bitmap of additional columns */
128467  u8 sentWarning = 0; /* True if a warnning has been issued */
128468  Expr *pPartial = 0; /* Partial Index Expression */
128469  int iContinue = 0; /* Jump here to skip excluded rows */
128470  struct SrcList_item *pTabItem; /* FROM clause term being indexed */
128471  int addrCounter = 0; /* Address where integer counter is initialized */
128472  int regBase; /* Array of registers where record is assembled */
128473 
128474  /* Generate code to skip over the creation and initialization of the
128475  ** transient index on 2nd and subsequent iterations of the loop. */
128476  v = pParse->pVdbe;
128477  assert( v!=0 );
128478  addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
128479 
128480  /* Count the number of columns that will be added to the index
128481  ** and used to match WHERE clause constraints */
128482  nKeyCol = 0;
128483  pTable = pSrc->pTab;
128484  pWCEnd = &pWC->a[pWC->nTerm];
128485  pLoop = pLevel->pWLoop;
128486  idxCols = 0;
128487  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
128488  Expr *pExpr = pTerm->pExpr;
128489  assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
128490  || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
128491  || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
128492  if( pLoop->prereq==0
128493  && (pTerm->wtFlags & TERM_VIRTUAL)==0
128494  && !ExprHasProperty(pExpr, EP_FromJoin)
128495  && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
128496  pPartial = sqlite3ExprAnd(pParse->db, pPartial,
128497  sqlite3ExprDup(pParse->db, pExpr, 0));
128498  }
128499  if( termCanDriveIndex(pTerm, pSrc, notReady) ){
128500  int iCol = pTerm->u.leftColumn;
128501  Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
128502  testcase( iCol==BMS );
128503  testcase( iCol==BMS-1 );
128504  if( !sentWarning ){
128505  sqlite3_log(SQLITE_WARNING_AUTOINDEX,
128506  "automatic index on %s(%s)", pTable->zName,
128507  pTable->aCol[iCol].zName);
128508  sentWarning = 1;
128509  }
128510  if( (idxCols & cMask)==0 ){
128511  if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
128512  goto end_auto_index_create;
128513  }
128514  pLoop->aLTerm[nKeyCol++] = pTerm;
128515  idxCols |= cMask;
128516  }
128517  }
128518  }
128519  assert( nKeyCol>0 );
128520  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
128521  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
128522  | WHERE_AUTO_INDEX;
128523 
128524  /* Count the number of additional columns needed to create a
128525  ** covering index. A "covering index" is an index that contains all
128526  ** columns that are needed by the query. With a covering index, the
128527  ** original table never needs to be accessed. Automatic indices must
128528  ** be a covering index because the index will not be updated if the
128529  ** original table changes and the index and table cannot both be used
128530  ** if they go out of sync.
128531  */
128532  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
128533  mxBitCol = MIN(BMS-1,pTable->nCol);
128534  testcase( pTable->nCol==BMS-1 );
128535  testcase( pTable->nCol==BMS-2 );
128536  for(i=0; i<mxBitCol; i++){
128537  if( extraCols & MASKBIT(i) ) nKeyCol++;
128538  }
128539  if( pSrc->colUsed & MASKBIT(BMS-1) ){
128540  nKeyCol += pTable->nCol - BMS + 1;
128541  }
128542 
128543  /* Construct the Index object to describe this index */
128544  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
128545  if( pIdx==0 ) goto end_auto_index_create;
128546  pLoop->u.btree.pIndex = pIdx;
128547  pIdx->zName = "auto-index";
128548  pIdx->pTable = pTable;
128549  n = 0;
128550  idxCols = 0;
128551  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
128552  if( termCanDriveIndex(pTerm, pSrc, notReady) ){
128553  int iCol = pTerm->u.leftColumn;
128554  Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
128555  testcase( iCol==BMS-1 );
128556  testcase( iCol==BMS );
128557  if( (idxCols & cMask)==0 ){
128558  Expr *pX = pTerm->pExpr;
128559  idxCols |= cMask;
128560  pIdx->aiColumn[n] = pTerm->u.leftColumn;
128561  pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
128562  pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
128563  n++;
128564  }
128565  }
128566  }
128567  assert( (u32)n==pLoop->u.btree.nEq );
128568 
128569  /* Add additional columns needed to make the automatic index into
128570  ** a covering index */
128571  for(i=0; i<mxBitCol; i++){
128572  if( extraCols & MASKBIT(i) ){
128573  pIdx->aiColumn[n] = i;
128574  pIdx->azColl[n] = sqlite3StrBINARY;
128575  n++;
128576  }
128577  }
128578  if( pSrc->colUsed & MASKBIT(BMS-1) ){
128579  for(i=BMS-1; i<pTable->nCol; i++){
128580  pIdx->aiColumn[n] = i;
128581  pIdx->azColl[n] = sqlite3StrBINARY;
128582  n++;
128583  }
128584  }
128585  assert( n==nKeyCol );
128586  pIdx->aiColumn[n] = XN_ROWID;
128587  pIdx->azColl[n] = sqlite3StrBINARY;
128588 
128589  /* Create the automatic index */
128590  assert( pLevel->iIdxCur>=0 );
128591  pLevel->iIdxCur = pParse->nTab++;
128592  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
128593  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
128594  VdbeComment((v, "for %s", pTable->zName));
128595 
128596  /* Fill the automatic index with content */
128597  sqlite3ExprCachePush(pParse);
128598  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
128599  if( pTabItem->fg.viaCoroutine ){
128600  int regYield = pTabItem->regReturn;
128601  addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
128602  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
128603  addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
128604  VdbeCoverage(v);
128605  VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
128606  }else{
128607  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
128608  }
128609  if( pPartial ){
128610  iContinue = sqlite3VdbeMakeLabel(v);
128611  sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
128612  pLoop->wsFlags |= WHERE_PARTIALIDX;
128613  }
128614  regRecord = sqlite3GetTempReg(pParse);
128615  regBase = sqlite3GenerateIndexKey(
128616  pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
128617  );
128618  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
128619  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
128620  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
128621  if( pTabItem->fg.viaCoroutine ){
128622  sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
128623  translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
128624  sqlite3VdbeGoto(v, addrTop);
128625  pTabItem->fg.viaCoroutine = 0;
128626  }else{
128627  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
128628  }
128629  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
128630  sqlite3VdbeJumpHere(v, addrTop);
128631  sqlite3ReleaseTempReg(pParse, regRecord);
128632  sqlite3ExprCachePop(pParse);
128633 
128634  /* Jump here when skipping the initialization */
128635  sqlite3VdbeJumpHere(v, addrInit);
128636 
128637 end_auto_index_create:
128638  sqlite3ExprDelete(pParse->db, pPartial);
128639 }
128640 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
128641 
128642 #ifndef SQLITE_OMIT_VIRTUALTABLE
128643 /*
128644 ** Allocate and populate an sqlite3_index_info structure. It is the
128645 ** responsibility of the caller to eventually release the structure
128646 ** by passing the pointer returned by this function to sqlite3_free().
128647 */
128648 static sqlite3_index_info *allocateIndexInfo(
128649  Parse *pParse,
128650  WhereClause *pWC,
128651  Bitmask mUnusable, /* Ignore terms with these prereqs */
128652  struct SrcList_item *pSrc,
128653  ExprList *pOrderBy,
128654  u16 *pmNoOmit /* Mask of terms not to omit */
128655 ){
128656  int i, j;
128657  int nTerm;
128658  struct sqlite3_index_constraint *pIdxCons;
128659  struct sqlite3_index_orderby *pIdxOrderBy;
128660  struct sqlite3_index_constraint_usage *pUsage;
128661  WhereTerm *pTerm;
128662  int nOrderBy;
128663  sqlite3_index_info *pIdxInfo;
128664  u16 mNoOmit = 0;
128665 
128666  /* Count the number of possible WHERE clause constraints referring
128667  ** to this virtual table */
128668  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
128669  if( pTerm->leftCursor != pSrc->iCursor ) continue;
128670  if( pTerm->prereqRight & mUnusable ) continue;
128671  assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
128672  testcase( pTerm->eOperator & WO_IN );
128673  testcase( pTerm->eOperator & WO_ISNULL );
128674  testcase( pTerm->eOperator & WO_IS );
128675  testcase( pTerm->eOperator & WO_ALL );
128676  if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
128677  if( pTerm->wtFlags & TERM_VNULL ) continue;
128678  assert( pTerm->u.leftColumn>=(-1) );
128679  nTerm++;
128680  }
128681 
128682  /* If the ORDER BY clause contains only columns in the current
128683  ** virtual table then allocate space for the aOrderBy part of
128684  ** the sqlite3_index_info structure.
128685  */
128686  nOrderBy = 0;
128687  if( pOrderBy ){
128688  int n = pOrderBy->nExpr;
128689  for(i=0; i<n; i++){
128690  Expr *pExpr = pOrderBy->a[i].pExpr;
128691  if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
128692  }
128693  if( i==n){
128694  nOrderBy = n;
128695  }
128696  }
128697 
128698  /* Allocate the sqlite3_index_info structure
128699  */
128700  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
128701  + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
128702  + sizeof(*pIdxOrderBy)*nOrderBy );
128703  if( pIdxInfo==0 ){
128704  sqlite3ErrorMsg(pParse, "out of memory");
128705  return 0;
128706  }
128707 
128708  /* Initialize the structure. The sqlite3_index_info structure contains
128709  ** many fields that are declared "const" to prevent xBestIndex from
128710  ** changing them. We have to do some funky casting in order to
128711  ** initialize those fields.
128712  */
128713  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
128714  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
128715  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
128716  *(int*)&pIdxInfo->nConstraint = nTerm;
128717  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
128718  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
128719  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
128720  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
128721  pUsage;
128722 
128723  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
128724  u8 op;
128725  if( pTerm->leftCursor != pSrc->iCursor ) continue;
128726  if( pTerm->prereqRight & mUnusable ) continue;
128727  assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
128728  testcase( pTerm->eOperator & WO_IN );
128729  testcase( pTerm->eOperator & WO_IS );
128730  testcase( pTerm->eOperator & WO_ISNULL );
128731  testcase( pTerm->eOperator & WO_ALL );
128732  if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
128733  if( pTerm->wtFlags & TERM_VNULL ) continue;
128734  assert( pTerm->u.leftColumn>=(-1) );
128735  pIdxCons[j].iColumn = pTerm->u.leftColumn;
128736  pIdxCons[j].iTermOffset = i;
128737  op = (u8)pTerm->eOperator & WO_ALL;
128738  if( op==WO_IN ) op = WO_EQ;
128739  if( op==WO_MATCH ){
128740  op = pTerm->eMatchOp;
128741  }
128742  pIdxCons[j].op = op;
128743  /* The direct assignment in the previous line is possible only because
128744  ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
128745  ** following asserts verify this fact. */
128746  assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
128747  assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
128748  assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
128749  assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
128750  assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
128751  assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
128752  assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
128753 
128754  if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
128755  && sqlite3ExprIsVector(pTerm->pExpr->pRight)
128756  ){
128757  if( i<16 ) mNoOmit |= (1 << i);
128758  if( op==WO_LT ) pIdxCons[j].op = WO_LE;
128759  if( op==WO_GT ) pIdxCons[j].op = WO_GE;
128760  }
128761 
128762  j++;
128763  }
128764  for(i=0; i<nOrderBy; i++){
128765  Expr *pExpr = pOrderBy->a[i].pExpr;
128766  pIdxOrderBy[i].iColumn = pExpr->iColumn;
128767  pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
128768  }
128769 
128770  *pmNoOmit = mNoOmit;
128771  return pIdxInfo;
128772 }
128773 
128774 /*
128775 ** The table object reference passed as the second argument to this function
128776 ** must represent a virtual table. This function invokes the xBestIndex()
128777 ** method of the virtual table with the sqlite3_index_info object that
128778 ** comes in as the 3rd argument to this function.
128779 **
128780 ** If an error occurs, pParse is populated with an error message and a
128781 ** non-zero value is returned. Otherwise, 0 is returned and the output
128782 ** part of the sqlite3_index_info structure is left populated.
128783 **
128784 ** Whether or not an error is returned, it is the responsibility of the
128785 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
128786 ** that this is required.
128787 */
128788 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
128789  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
128790  int rc;
128791 
128792  TRACE_IDX_INPUTS(p);
128793  rc = pVtab->pModule->xBestIndex(pVtab, p);
128794  TRACE_IDX_OUTPUTS(p);
128795 
128796  if( rc!=SQLITE_OK ){
128797  if( rc==SQLITE_NOMEM ){
128798  sqlite3OomFault(pParse->db);
128799  }else if( !pVtab->zErrMsg ){
128800  sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
128801  }else{
128802  sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
128803  }
128804  }
128805  sqlite3_free(pVtab->zErrMsg);
128806  pVtab->zErrMsg = 0;
128807 
128808 #if 0
128809  /* This error is now caught by the caller.
128810  ** Search for "xBestIndex malfunction" below */
128811  for(i=0; i<p->nConstraint; i++){
128812  if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
128813  sqlite3ErrorMsg(pParse,
128814  "table %s: xBestIndex returned an invalid plan", pTab->zName);
128815  }
128816  }
128817 #endif
128818 
128819  return pParse->nErr;
128820 }
128821 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
128822 
128823 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128824 /*
128825 ** Estimate the location of a particular key among all keys in an
128826 ** index. Store the results in aStat as follows:
128827 **
128828 ** aStat[0] Est. number of rows less than pRec
128829 ** aStat[1] Est. number of rows equal to pRec
128830 **
128831 ** Return the index of the sample that is the smallest sample that
128832 ** is greater than or equal to pRec. Note that this index is not an index
128833 ** into the aSample[] array - it is an index into a virtual set of samples
128834 ** based on the contents of aSample[] and the number of fields in record
128835 ** pRec.
128836 */
128837 static int whereKeyStats(
128838  Parse *pParse, /* Database connection */
128839  Index *pIdx, /* Index to consider domain of */
128840  UnpackedRecord *pRec, /* Vector of values to consider */
128841  int roundUp, /* Round up if true. Round down if false */
128842  tRowcnt *aStat /* OUT: stats written here */
128843 ){
128844  IndexSample *aSample = pIdx->aSample;
128845  int iCol; /* Index of required stats in anEq[] etc. */
128846  int i; /* Index of first sample >= pRec */
128847  int iSample; /* Smallest sample larger than or equal to pRec */
128848  int iMin = 0; /* Smallest sample not yet tested */
128849  int iTest; /* Next sample to test */
128850  int res; /* Result of comparison operation */
128851  int nField; /* Number of fields in pRec */
128852  tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
128853 
128854 #ifndef SQLITE_DEBUG
128855  UNUSED_PARAMETER( pParse );
128856 #endif
128857  assert( pRec!=0 );
128858  assert( pIdx->nSample>0 );
128859  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
128860 
128861  /* Do a binary search to find the first sample greater than or equal
128862  ** to pRec. If pRec contains a single field, the set of samples to search
128863  ** is simply the aSample[] array. If the samples in aSample[] contain more
128864  ** than one fields, all fields following the first are ignored.
128865  **
128866  ** If pRec contains N fields, where N is more than one, then as well as the
128867  ** samples in aSample[] (truncated to N fields), the search also has to
128868  ** consider prefixes of those samples. For example, if the set of samples
128869  ** in aSample is:
128870  **
128871  ** aSample[0] = (a, 5)
128872  ** aSample[1] = (a, 10)
128873  ** aSample[2] = (b, 5)
128874  ** aSample[3] = (c, 100)
128875  ** aSample[4] = (c, 105)
128876  **
128877  ** Then the search space should ideally be the samples above and the
128878  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
128879  ** the code actually searches this set:
128880  **
128881  ** 0: (a)
128882  ** 1: (a, 5)
128883  ** 2: (a, 10)
128884  ** 3: (a, 10)
128885  ** 4: (b)
128886  ** 5: (b, 5)
128887  ** 6: (c)
128888  ** 7: (c, 100)
128889  ** 8: (c, 105)
128890  ** 9: (c, 105)
128891  **
128892  ** For each sample in the aSample[] array, N samples are present in the
128893  ** effective sample array. In the above, samples 0 and 1 are based on
128894  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
128895  **
128896  ** Often, sample i of each block of N effective samples has (i+1) fields.
128897  ** Except, each sample may be extended to ensure that it is greater than or
128898  ** equal to the previous sample in the array. For example, in the above,
128899  ** sample 2 is the first sample of a block of N samples, so at first it
128900  ** appears that it should be 1 field in size. However, that would make it
128901  ** smaller than sample 1, so the binary search would not work. As a result,
128902  ** it is extended to two fields. The duplicates that this creates do not
128903  ** cause any problems.
128904  */
128905  nField = pRec->nField;
128906  iCol = 0;
128907  iSample = pIdx->nSample * nField;
128908  do{
128909  int iSamp; /* Index in aSample[] of test sample */
128910  int n; /* Number of fields in test sample */
128911 
128912  iTest = (iMin+iSample)/2;
128913  iSamp = iTest / nField;
128914  if( iSamp>0 ){
128915  /* The proposed effective sample is a prefix of sample aSample[iSamp].
128916  ** Specifically, the shortest prefix of at least (1 + iTest%nField)
128917  ** fields that is greater than the previous effective sample. */
128918  for(n=(iTest % nField) + 1; n<nField; n++){
128919  if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
128920  }
128921  }else{
128922  n = iTest + 1;
128923  }
128924 
128925  pRec->nField = n;
128926  res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
128927  if( res<0 ){
128928  iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
128929  iMin = iTest+1;
128930  }else if( res==0 && n<nField ){
128931  iLower = aSample[iSamp].anLt[n-1];
128932  iMin = iTest+1;
128933  res = -1;
128934  }else{
128935  iSample = iTest;
128936  iCol = n-1;
128937  }
128938  }while( res && iMin<iSample );
128939  i = iSample / nField;
128940 
128941 #ifdef SQLITE_DEBUG
128942  /* The following assert statements check that the binary search code
128943  ** above found the right answer. This block serves no purpose other
128944  ** than to invoke the asserts. */
128945  if( pParse->db->mallocFailed==0 ){
128946  if( res==0 ){
128947  /* If (res==0) is true, then pRec must be equal to sample i. */
128948  assert( i<pIdx->nSample );
128949  assert( iCol==nField-1 );
128950  pRec->nField = nField;
128951  assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
128952  || pParse->db->mallocFailed
128953  );
128954  }else{
128955  /* Unless i==pIdx->nSample, indicating that pRec is larger than
128956  ** all samples in the aSample[] array, pRec must be smaller than the
128957  ** (iCol+1) field prefix of sample i. */
128958  assert( i<=pIdx->nSample && i>=0 );
128959  pRec->nField = iCol+1;
128960  assert( i==pIdx->nSample
128961  || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
128962  || pParse->db->mallocFailed );
128963 
128964  /* if i==0 and iCol==0, then record pRec is smaller than all samples
128965  ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
128966  ** be greater than or equal to the (iCol) field prefix of sample i.
128967  ** If (i>0), then pRec must also be greater than sample (i-1). */
128968  if( iCol>0 ){
128969  pRec->nField = iCol;
128970  assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
128971  || pParse->db->mallocFailed );
128972  }
128973  if( i>0 ){
128974  pRec->nField = nField;
128975  assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
128976  || pParse->db->mallocFailed );
128977  }
128978  }
128979  }
128980 #endif /* ifdef SQLITE_DEBUG */
128981 
128982  if( res==0 ){
128983  /* Record pRec is equal to sample i */
128984  assert( iCol==nField-1 );
128985  aStat[0] = aSample[i].anLt[iCol];
128986  aStat[1] = aSample[i].anEq[iCol];
128987  }else{
128988  /* At this point, the (iCol+1) field prefix of aSample[i] is the first
128989  ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
128990  ** is larger than all samples in the array. */
128991  tRowcnt iUpper, iGap;
128992  if( i>=pIdx->nSample ){
128993  iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
128994  }else{
128995  iUpper = aSample[i].anLt[iCol];
128996  }
128997 
128998  if( iLower>=iUpper ){
128999  iGap = 0;
129000  }else{
129001  iGap = iUpper - iLower;
129002  }
129003  if( roundUp ){
129004  iGap = (iGap*2)/3;
129005  }else{
129006  iGap = iGap/3;
129007  }
129008  aStat[0] = iLower + iGap;
129009  aStat[1] = pIdx->aAvgEq[iCol];
129010  }
129011 
129012  /* Restore the pRec->nField value before returning. */
129013  pRec->nField = nField;
129014  return i;
129015 }
129016 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
129017 
129018 /*
129019 ** If it is not NULL, pTerm is a term that provides an upper or lower
129020 ** bound on a range scan. Without considering pTerm, it is estimated
129021 ** that the scan will visit nNew rows. This function returns the number
129022 ** estimated to be visited after taking pTerm into account.
129023 **
129024 ** If the user explicitly specified a likelihood() value for this term,
129025 ** then the return value is the likelihood multiplied by the number of
129026 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
129027 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
129028 */
129029 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
129030  LogEst nRet = nNew;
129031  if( pTerm ){
129032  if( pTerm->truthProb<=0 ){
129033  nRet += pTerm->truthProb;
129034  }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
129035  nRet -= 20; assert( 20==sqlite3LogEst(4) );
129036  }
129037  }
129038  return nRet;
129039 }
129040 
129041 
129042 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129043 /*
129044 ** Return the affinity for a single column of an index.
129045 */
129046 SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
129047  assert( iCol>=0 && iCol<pIdx->nColumn );
129048  if( !pIdx->zColAff ){
129049  if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
129050  }
129051  return pIdx->zColAff[iCol];
129052 }
129053 #endif
129054 
129055 
129056 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129057 /*
129058 ** This function is called to estimate the number of rows visited by a
129059 ** range-scan on a skip-scan index. For example:
129060 **
129061 ** CREATE INDEX i1 ON t1(a, b, c);
129062 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
129063 **
129064 ** Value pLoop->nOut is currently set to the estimated number of rows
129065 ** visited for scanning (a=? AND b=?). This function reduces that estimate
129066 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
129067 ** on the stat4 data for the index. this scan will be peformed multiple
129068 ** times (once for each (a,b) combination that matches a=?) is dealt with
129069 ** by the caller.
129070 **
129071 ** It does this by scanning through all stat4 samples, comparing values
129072 ** extracted from pLower and pUpper with the corresponding column in each
129073 ** sample. If L and U are the number of samples found to be less than or
129074 ** equal to the values extracted from pLower and pUpper respectively, and
129075 ** N is the total number of samples, the pLoop->nOut value is adjusted
129076 ** as follows:
129077 **
129078 ** nOut = nOut * ( min(U - L, 1) / N )
129079 **
129080 ** If pLower is NULL, or a value cannot be extracted from the term, L is
129081 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
129082 ** U is set to N.
129083 **
129084 ** Normally, this function sets *pbDone to 1 before returning. However,
129085 ** if no value can be extracted from either pLower or pUpper (and so the
129086 ** estimate of the number of rows delivered remains unchanged), *pbDone
129087 ** is left as is.
129088 **
129089 ** If an error occurs, an SQLite error code is returned. Otherwise,
129090 ** SQLITE_OK.
129091 */
129092 static int whereRangeSkipScanEst(
129093  Parse *pParse, /* Parsing & code generating context */
129094  WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
129095  WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
129096  WhereLoop *pLoop, /* Update the .nOut value of this loop */
129097  int *pbDone /* Set to true if at least one expr. value extracted */
129098 ){
129099  Index *p = pLoop->u.btree.pIndex;
129100  int nEq = pLoop->u.btree.nEq;
129101  sqlite3 *db = pParse->db;
129102  int nLower = -1;
129103  int nUpper = p->nSample+1;
129104  int rc = SQLITE_OK;
129105  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
129106  CollSeq *pColl;
129107 
129108  sqlite3_value *p1 = 0; /* Value extracted from pLower */
129109  sqlite3_value *p2 = 0; /* Value extracted from pUpper */
129110  sqlite3_value *pVal = 0; /* Value extracted from record */
129111 
129112  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
129113  if( pLower ){
129114  rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
129115  nLower = 0;
129116  }
129117  if( pUpper && rc==SQLITE_OK ){
129118  rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
129119  nUpper = p2 ? 0 : p->nSample;
129120  }
129121 
129122  if( p1 || p2 ){
129123  int i;
129124  int nDiff;
129125  for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
129126  rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
129127  if( rc==SQLITE_OK && p1 ){
129128  int res = sqlite3MemCompare(p1, pVal, pColl);
129129  if( res>=0 ) nLower++;
129130  }
129131  if( rc==SQLITE_OK && p2 ){
129132  int res = sqlite3MemCompare(p2, pVal, pColl);
129133  if( res>=0 ) nUpper++;
129134  }
129135  }
129136  nDiff = (nUpper - nLower);
129137  if( nDiff<=0 ) nDiff = 1;
129138 
129139  /* If there is both an upper and lower bound specified, and the
129140  ** comparisons indicate that they are close together, use the fallback
129141  ** method (assume that the scan visits 1/64 of the rows) for estimating
129142  ** the number of rows visited. Otherwise, estimate the number of rows
129143  ** using the method described in the header comment for this function. */
129144  if( nDiff!=1 || pUpper==0 || pLower==0 ){
129145  int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
129146  pLoop->nOut -= nAdjust;
129147  *pbDone = 1;
129148  WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
129149  nLower, nUpper, nAdjust*-1, pLoop->nOut));
129150  }
129151 
129152  }else{
129153  assert( *pbDone==0 );
129154  }
129155 
129156  sqlite3ValueFree(p1);
129157  sqlite3ValueFree(p2);
129158  sqlite3ValueFree(pVal);
129159 
129160  return rc;
129161 }
129162 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
129163 
129164 /*
129165 ** This function is used to estimate the number of rows that will be visited
129166 ** by scanning an index for a range of values. The range may have an upper
129167 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
129168 ** and lower bounds are represented by pLower and pUpper respectively. For
129169 ** example, assuming that index p is on t1(a):
129170 **
129171 ** ... FROM t1 WHERE a > ? AND a < ? ...
129172 ** |_____| |_____|
129173 ** | |
129174 ** pLower pUpper
129175 **
129176 ** If either of the upper or lower bound is not present, then NULL is passed in
129177 ** place of the corresponding WhereTerm.
129178 **
129179 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
129180 ** column subject to the range constraint. Or, equivalently, the number of
129181 ** equality constraints optimized by the proposed index scan. For example,
129182 ** assuming index p is on t1(a, b), and the SQL query is:
129183 **
129184 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
129185 **
129186 ** then nEq is set to 1 (as the range restricted column, b, is the second
129187 ** left-most column of the index). Or, if the query is:
129188 **
129189 ** ... FROM t1 WHERE a > ? AND a < ? ...
129190 **
129191 ** then nEq is set to 0.
129192 **
129193 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
129194 ** number of rows that the index scan is expected to visit without
129195 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
129196 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
129197 ** to account for the range constraints pLower and pUpper.
129198 **
129199 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
129200 ** used, a single range inequality reduces the search space by a factor of 4.
129201 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
129202 ** rows visited by a factor of 64.
129203 */
129204 static int whereRangeScanEst(
129205  Parse *pParse, /* Parsing & code generating context */
129206  WhereLoopBuilder *pBuilder,
129207  WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
129208  WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
129209  WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
129210 ){
129211  int rc = SQLITE_OK;
129212  int nOut = pLoop->nOut;
129213  LogEst nNew;
129214 
129215 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129216  Index *p = pLoop->u.btree.pIndex;
129217  int nEq = pLoop->u.btree.nEq;
129218 
129219  if( p->nSample>0 && nEq<p->nSampleCol ){
129220  if( nEq==pBuilder->nRecValid ){
129221  UnpackedRecord *pRec = pBuilder->pRec;
129222  tRowcnt a[2];
129223  int nBtm = pLoop->u.btree.nBtm;
129224  int nTop = pLoop->u.btree.nTop;
129225 
129226  /* Variable iLower will be set to the estimate of the number of rows in
129227  ** the index that are less than the lower bound of the range query. The
129228  ** lower bound being the concatenation of $P and $L, where $P is the
129229  ** key-prefix formed by the nEq values matched against the nEq left-most
129230  ** columns of the index, and $L is the value in pLower.
129231  **
129232  ** Or, if pLower is NULL or $L cannot be extracted from it (because it
129233  ** is not a simple variable or literal value), the lower bound of the
129234  ** range is $P. Due to a quirk in the way whereKeyStats() works, even
129235  ** if $L is available, whereKeyStats() is called for both ($P) and
129236  ** ($P:$L) and the larger of the two returned values is used.
129237  **
129238  ** Similarly, iUpper is to be set to the estimate of the number of rows
129239  ** less than the upper bound of the range query. Where the upper bound
129240  ** is either ($P) or ($P:$U). Again, even if $U is available, both values
129241  ** of iUpper are requested of whereKeyStats() and the smaller used.
129242  **
129243  ** The number of rows between the two bounds is then just iUpper-iLower.
129244  */
129245  tRowcnt iLower; /* Rows less than the lower bound */
129246  tRowcnt iUpper; /* Rows less than the upper bound */
129247  int iLwrIdx = -2; /* aSample[] for the lower bound */
129248  int iUprIdx = -1; /* aSample[] for the upper bound */
129249 
129250  if( pRec ){
129251  testcase( pRec->nField!=pBuilder->nRecValid );
129252  pRec->nField = pBuilder->nRecValid;
129253  }
129254  /* Determine iLower and iUpper using ($P) only. */
129255  if( nEq==0 ){
129256  iLower = 0;
129257  iUpper = p->nRowEst0;
129258  }else{
129259  /* Note: this call could be optimized away - since the same values must
129260  ** have been requested when testing key $P in whereEqualScanEst(). */
129261  whereKeyStats(pParse, p, pRec, 0, a);
129262  iLower = a[0];
129263  iUpper = a[0] + a[1];
129264  }
129265 
129266  assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
129267  assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
129268  assert( p->aSortOrder!=0 );
129269  if( p->aSortOrder[nEq] ){
129270  /* The roles of pLower and pUpper are swapped for a DESC index */
129271  SWAP(WhereTerm*, pLower, pUpper);
129272  SWAP(int, nBtm, nTop);
129273  }
129274 
129275  /* If possible, improve on the iLower estimate using ($P:$L). */
129276  if( pLower ){
129277  int n; /* Values extracted from pExpr */
129278  Expr *pExpr = pLower->pExpr->pRight;
129279  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
129280  if( rc==SQLITE_OK && n ){
129281  tRowcnt iNew;
129282  u16 mask = WO_GT|WO_LE;
129283  if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
129284  iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
129285  iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
129286  if( iNew>iLower ) iLower = iNew;
129287  nOut--;
129288  pLower = 0;
129289  }
129290  }
129291 
129292  /* If possible, improve on the iUpper estimate using ($P:$U). */
129293  if( pUpper ){
129294  int n; /* Values extracted from pExpr */
129295  Expr *pExpr = pUpper->pExpr->pRight;
129296  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
129297  if( rc==SQLITE_OK && n ){
129298  tRowcnt iNew;
129299  u16 mask = WO_GT|WO_LE;
129300  if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
129301  iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
129302  iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
129303  if( iNew<iUpper ) iUpper = iNew;
129304  nOut--;
129305  pUpper = 0;
129306  }
129307  }
129308 
129309  pBuilder->pRec = pRec;
129310  if( rc==SQLITE_OK ){
129311  if( iUpper>iLower ){
129312  nNew = sqlite3LogEst(iUpper - iLower);
129313  /* TUNING: If both iUpper and iLower are derived from the same
129314  ** sample, then assume they are 4x more selective. This brings
129315  ** the estimated selectivity more in line with what it would be
129316  ** if estimated without the use of STAT3/4 tables. */
129317  if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
129318  }else{
129319  nNew = 10; assert( 10==sqlite3LogEst(2) );
129320  }
129321  if( nNew<nOut ){
129322  nOut = nNew;
129323  }
129324  WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
129325  (u32)iLower, (u32)iUpper, nOut));
129326  }
129327  }else{
129328  int bDone = 0;
129329  rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
129330  if( bDone ) return rc;
129331  }
129332  }
129333 #else
129334  UNUSED_PARAMETER(pParse);
129335  UNUSED_PARAMETER(pBuilder);
129336  assert( pLower || pUpper );
129337 #endif
129338  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
129339  nNew = whereRangeAdjust(pLower, nOut);
129340  nNew = whereRangeAdjust(pUpper, nNew);
129341 
129342  /* TUNING: If there is both an upper and lower limit and neither limit
129343  ** has an application-defined likelihood(), assume the range is
129344  ** reduced by an additional 75%. This means that, by default, an open-ended
129345  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
129346  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
129347  ** match 1/64 of the index. */
129348  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
129349  nNew -= 20;
129350  }
129351 
129352  nOut -= (pLower!=0) + (pUpper!=0);
129353  if( nNew<10 ) nNew = 10;
129354  if( nNew<nOut ) nOut = nNew;
129355 #if defined(WHERETRACE_ENABLED)
129356  if( pLoop->nOut>nOut ){
129357  WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
129358  pLoop->nOut, nOut));
129359  }
129360 #endif
129361  pLoop->nOut = (LogEst)nOut;
129362  return rc;
129363 }
129364 
129365 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129366 /*
129367 ** Estimate the number of rows that will be returned based on
129368 ** an equality constraint x=VALUE and where that VALUE occurs in
129369 ** the histogram data. This only works when x is the left-most
129370 ** column of an index and sqlite_stat3 histogram data is available
129371 ** for that index. When pExpr==NULL that means the constraint is
129372 ** "x IS NULL" instead of "x=VALUE".
129373 **
129374 ** Write the estimated row count into *pnRow and return SQLITE_OK.
129375 ** If unable to make an estimate, leave *pnRow unchanged and return
129376 ** non-zero.
129377 **
129378 ** This routine can fail if it is unable to load a collating sequence
129379 ** required for string comparison, or if unable to allocate memory
129380 ** for a UTF conversion required for comparison. The error is stored
129381 ** in the pParse structure.
129382 */
129383 static int whereEqualScanEst(
129384  Parse *pParse, /* Parsing & code generating context */
129385  WhereLoopBuilder *pBuilder,
129386  Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
129387  tRowcnt *pnRow /* Write the revised row estimate here */
129388 ){
129389  Index *p = pBuilder->pNew->u.btree.pIndex;
129390  int nEq = pBuilder->pNew->u.btree.nEq;
129391  UnpackedRecord *pRec = pBuilder->pRec;
129392  int rc; /* Subfunction return code */
129393  tRowcnt a[2]; /* Statistics */
129394  int bOk;
129395 
129396  assert( nEq>=1 );
129397  assert( nEq<=p->nColumn );
129398  assert( p->aSample!=0 );
129399  assert( p->nSample>0 );
129400  assert( pBuilder->nRecValid<nEq );
129401 
129402  /* If values are not available for all fields of the index to the left
129403  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
129404  if( pBuilder->nRecValid<(nEq-1) ){
129405  return SQLITE_NOTFOUND;
129406  }
129407 
129408  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
129409  ** below would return the same value. */
129410  if( nEq>=p->nColumn ){
129411  *pnRow = 1;
129412  return SQLITE_OK;
129413  }
129414 
129415  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
129416  pBuilder->pRec = pRec;
129417  if( rc!=SQLITE_OK ) return rc;
129418  if( bOk==0 ) return SQLITE_NOTFOUND;
129419  pBuilder->nRecValid = nEq;
129420 
129421  whereKeyStats(pParse, p, pRec, 0, a);
129422  WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
129423  p->zName, nEq-1, (int)a[1]));
129424  *pnRow = a[1];
129425 
129426  return rc;
129427 }
129428 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
129429 
129430 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129431 /*
129432 ** Estimate the number of rows that will be returned based on
129433 ** an IN constraint where the right-hand side of the IN operator
129434 ** is a list of values. Example:
129435 **
129436 ** WHERE x IN (1,2,3,4)
129437 **
129438 ** Write the estimated row count into *pnRow and return SQLITE_OK.
129439 ** If unable to make an estimate, leave *pnRow unchanged and return
129440 ** non-zero.
129441 **
129442 ** This routine can fail if it is unable to load a collating sequence
129443 ** required for string comparison, or if unable to allocate memory
129444 ** for a UTF conversion required for comparison. The error is stored
129445 ** in the pParse structure.
129446 */
129447 static int whereInScanEst(
129448  Parse *pParse, /* Parsing & code generating context */
129449  WhereLoopBuilder *pBuilder,
129450  ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
129451  tRowcnt *pnRow /* Write the revised row estimate here */
129452 ){
129453  Index *p = pBuilder->pNew->u.btree.pIndex;
129454  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
129455  int nRecValid = pBuilder->nRecValid;
129456  int rc = SQLITE_OK; /* Subfunction return code */
129457  tRowcnt nEst; /* Number of rows for a single term */
129458  tRowcnt nRowEst = 0; /* New estimate of the number of rows */
129459  int i; /* Loop counter */
129460 
129461  assert( p->aSample!=0 );
129462  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
129463  nEst = nRow0;
129464  rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
129465  nRowEst += nEst;
129466  pBuilder->nRecValid = nRecValid;
129467  }
129468 
129469  if( rc==SQLITE_OK ){
129470  if( nRowEst > nRow0 ) nRowEst = nRow0;
129471  *pnRow = nRowEst;
129472  WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
129473  }
129474  assert( pBuilder->nRecValid==nRecValid );
129475  return rc;
129476 }
129477 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
129478 
129479 
129480 #ifdef WHERETRACE_ENABLED
129481 /*
129482 ** Print the content of a WhereTerm object
129483 */
129484 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
129485  if( pTerm==0 ){
129486  sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
129487  }else{
129488  char zType[4];
129489  char zLeft[50];
129490  memcpy(zType, "...", 4);
129491  if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
129492  if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
129493  if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
129494  if( pTerm->eOperator & WO_SINGLE ){
129495  sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
129496  pTerm->leftCursor, pTerm->u.leftColumn);
129497  }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
129498  sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
129499  pTerm->u.pOrInfo->indexable);
129500  }else{
129501  sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
129502  }
129503  sqlite3DebugPrintf(
129504  "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
129505  iTerm, pTerm, zType, zLeft, pTerm->truthProb,
129506  pTerm->eOperator, pTerm->wtFlags);
129507  if( pTerm->iField ){
129508  sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
129509  }else{
129510  sqlite3DebugPrintf("\n");
129511  }
129512  sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
129513  }
129514 }
129515 #endif
129516 
129517 #ifdef WHERETRACE_ENABLED
129518 /*
129519 ** Show the complete content of a WhereClause
129520 */
129521 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
129522  int i;
129523  for(i=0; i<pWC->nTerm; i++){
129524  whereTermPrint(&pWC->a[i], i);
129525  }
129526 }
129527 #endif
129528 
129529 #ifdef WHERETRACE_ENABLED
129530 /*
129531 ** Print a WhereLoop object for debugging purposes
129532 */
129533 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
129534  WhereInfo *pWInfo = pWC->pWInfo;
129535  int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
129536  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
129537  Table *pTab = pItem->pTab;
129538  Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
129539  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
129540  p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
129541  sqlite3DebugPrintf(" %12s",
129542  pItem->zAlias ? pItem->zAlias : pTab->zName);
129543  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
129544  const char *zName;
129545  if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
129546  if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
129547  int i = sqlite3Strlen30(zName) - 1;
129548  while( zName[i]!='_' ) i--;
129549  zName += i;
129550  }
129551  sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
129552  }else{
129553  sqlite3DebugPrintf("%20s","");
129554  }
129555  }else{
129556  char *z;
129557  if( p->u.vtab.idxStr ){
129558  z = sqlite3_mprintf("(%d,\"%s\",%x)",
129559  p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
129560  }else{
129561  z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
129562  }
129563  sqlite3DebugPrintf(" %-19s", z);
129564  sqlite3_free(z);
129565  }
129566  if( p->wsFlags & WHERE_SKIPSCAN ){
129567  sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
129568  }else{
129569  sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
129570  }
129571  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
129572  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
129573  int i;
129574  for(i=0; i<p->nLTerm; i++){
129575  whereTermPrint(p->aLTerm[i], i);
129576  }
129577  }
129578 }
129579 #endif
129580 
129581 /*
129582 ** Convert bulk memory into a valid WhereLoop that can be passed
129583 ** to whereLoopClear harmlessly.
129584 */
129585 static void whereLoopInit(WhereLoop *p){
129586  p->aLTerm = p->aLTermSpace;
129587  p->nLTerm = 0;
129588  p->nLSlot = ArraySize(p->aLTermSpace);
129589  p->wsFlags = 0;
129590 }
129591 
129592 /*
129593 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
129594 */
129595 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
129596  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
129597  if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
129598  sqlite3_free(p->u.vtab.idxStr);
129599  p->u.vtab.needFree = 0;
129600  p->u.vtab.idxStr = 0;
129601  }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
129602  sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
129603  sqlite3DbFree(db, p->u.btree.pIndex);
129604  p->u.btree.pIndex = 0;
129605  }
129606  }
129607 }
129608 
129609 /*
129610 ** Deallocate internal memory used by a WhereLoop object
129611 */
129612 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
129613  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
129614  whereLoopClearUnion(db, p);
129615  whereLoopInit(p);
129616 }
129617 
129618 /*
129619 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
129620 */
129621 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
129622  WhereTerm **paNew;
129623  if( p->nLSlot>=n ) return SQLITE_OK;
129624  n = (n+7)&~7;
129625  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
129626  if( paNew==0 ) return SQLITE_NOMEM_BKPT;
129627  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
129628  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
129629  p->aLTerm = paNew;
129630  p->nLSlot = n;
129631  return SQLITE_OK;
129632 }
129633 
129634 /*
129635 ** Transfer content from the second pLoop into the first.
129636 */
129637 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
129638  whereLoopClearUnion(db, pTo);
129639  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
129640  memset(&pTo->u, 0, sizeof(pTo->u));
129641  return SQLITE_NOMEM_BKPT;
129642  }
129643  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
129644  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
129645  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
129646  pFrom->u.vtab.needFree = 0;
129647  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
129648  pFrom->u.btree.pIndex = 0;
129649  }
129650  return SQLITE_OK;
129651 }
129652 
129653 /*
129654 ** Delete a WhereLoop object
129655 */
129656 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
129657  whereLoopClear(db, p);
129658  sqlite3DbFree(db, p);
129659 }
129660 
129661 /*
129662 ** Free a WhereInfo structure
129663 */
129664 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
129665  if( ALWAYS(pWInfo) ){
129666  int i;
129667  for(i=0; i<pWInfo->nLevel; i++){
129668  WhereLevel *pLevel = &pWInfo->a[i];
129669  if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
129670  sqlite3DbFree(db, pLevel->u.in.aInLoop);
129671  }
129672  }
129673  sqlite3WhereClauseClear(&pWInfo->sWC);
129674  while( pWInfo->pLoops ){
129675  WhereLoop *p = pWInfo->pLoops;
129676  pWInfo->pLoops = p->pNextLoop;
129677  whereLoopDelete(db, p);
129678  }
129679  sqlite3DbFree(db, pWInfo);
129680  }
129681 }
129682 
129683 /*
129684 ** Return TRUE if all of the following are true:
129685 **
129686 ** (1) X has the same or lower cost that Y
129687 ** (2) X is a proper subset of Y
129688 ** (3) X skips at least as many columns as Y
129689 **
129690 ** By "proper subset" we mean that X uses fewer WHERE clause terms
129691 ** than Y and that every WHERE clause term used by X is also used
129692 ** by Y.
129693 **
129694 ** If X is a proper subset of Y then Y is a better choice and ought
129695 ** to have a lower cost. This routine returns TRUE when that cost
129696 ** relationship is inverted and needs to be adjusted. The third rule
129697 ** was added because if X uses skip-scan less than Y it still might
129698 ** deserve a lower cost even if it is a proper subset of Y.
129699 */
129700 static int whereLoopCheaperProperSubset(
129701  const WhereLoop *pX, /* First WhereLoop to compare */
129702  const WhereLoop *pY /* Compare against this WhereLoop */
129703 ){
129704  int i, j;
129705  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
129706  return 0; /* X is not a subset of Y */
129707  }
129708  if( pY->nSkip > pX->nSkip ) return 0;
129709  if( pX->rRun >= pY->rRun ){
129710  if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
129711  if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
129712  }
129713  for(i=pX->nLTerm-1; i>=0; i--){
129714  if( pX->aLTerm[i]==0 ) continue;
129715  for(j=pY->nLTerm-1; j>=0; j--){
129716  if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
129717  }
129718  if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
129719  }
129720  return 1; /* All conditions meet */
129721 }
129722 
129723 /*
129724 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
129725 ** that:
129726 **
129727 ** (1) pTemplate costs less than any other WhereLoops that are a proper
129728 ** subset of pTemplate
129729 **
129730 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
129731 ** is a proper subset.
129732 **
129733 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
129734 ** WHERE clause terms than Y and that every WHERE clause term used by X is
129735 ** also used by Y.
129736 */
129737 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
129738  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
129739  for(; p; p=p->pNextLoop){
129740  if( p->iTab!=pTemplate->iTab ) continue;
129741  if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
129742  if( whereLoopCheaperProperSubset(p, pTemplate) ){
129743  /* Adjust pTemplate cost downward so that it is cheaper than its
129744  ** subset p. */
129745  WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
129746  pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
129747  pTemplate->rRun = p->rRun;
129748  pTemplate->nOut = p->nOut - 1;
129749  }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
129750  /* Adjust pTemplate cost upward so that it is costlier than p since
129751  ** pTemplate is a proper subset of p */
129752  WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
129753  pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
129754  pTemplate->rRun = p->rRun;
129755  pTemplate->nOut = p->nOut + 1;
129756  }
129757  }
129758 }
129759 
129760 /*
129761 ** Search the list of WhereLoops in *ppPrev looking for one that can be
129762 ** supplanted by pTemplate.
129763 **
129764 ** Return NULL if the WhereLoop list contains an entry that can supplant
129765 ** pTemplate, in other words if pTemplate does not belong on the list.
129766 **
129767 ** If pX is a WhereLoop that pTemplate can supplant, then return the
129768 ** link that points to pX.
129769 **
129770 ** If pTemplate cannot supplant any existing element of the list but needs
129771 ** to be added to the list, then return a pointer to the tail of the list.
129772 */
129773 static WhereLoop **whereLoopFindLesser(
129774  WhereLoop **ppPrev,
129775  const WhereLoop *pTemplate
129776 ){
129777  WhereLoop *p;
129778  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
129779  if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
129780  /* If either the iTab or iSortIdx values for two WhereLoop are different
129781  ** then those WhereLoops need to be considered separately. Neither is
129782  ** a candidate to replace the other. */
129783  continue;
129784  }
129785  /* In the current implementation, the rSetup value is either zero
129786  ** or the cost of building an automatic index (NlogN) and the NlogN
129787  ** is the same for compatible WhereLoops. */
129788  assert( p->rSetup==0 || pTemplate->rSetup==0
129789  || p->rSetup==pTemplate->rSetup );
129790 
129791  /* whereLoopAddBtree() always generates and inserts the automatic index
129792  ** case first. Hence compatible candidate WhereLoops never have a larger
129793  ** rSetup. Call this SETUP-INVARIANT */
129794  assert( p->rSetup>=pTemplate->rSetup );
129795 
129796  /* Any loop using an appliation-defined index (or PRIMARY KEY or
129797  ** UNIQUE constraint) with one or more == constraints is better
129798  ** than an automatic index. Unless it is a skip-scan. */
129799  if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
129800  && (pTemplate->nSkip)==0
129801  && (pTemplate->wsFlags & WHERE_INDEXED)!=0
129802  && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
129803  && (p->prereq & pTemplate->prereq)==pTemplate->prereq
129804  ){
129805  break;
129806  }
129807 
129808  /* If existing WhereLoop p is better than pTemplate, pTemplate can be
129809  ** discarded. WhereLoop p is better if:
129810  ** (1) p has no more dependencies than pTemplate, and
129811  ** (2) p has an equal or lower cost than pTemplate
129812  */
129813  if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
129814  && p->rSetup<=pTemplate->rSetup /* (2a) */
129815  && p->rRun<=pTemplate->rRun /* (2b) */
129816  && p->nOut<=pTemplate->nOut /* (2c) */
129817  ){
129818  return 0; /* Discard pTemplate */
129819  }
129820 
129821  /* If pTemplate is always better than p, then cause p to be overwritten
129822  ** with pTemplate. pTemplate is better than p if:
129823  ** (1) pTemplate has no more dependences than p, and
129824  ** (2) pTemplate has an equal or lower cost than p.
129825  */
129826  if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
129827  && p->rRun>=pTemplate->rRun /* (2a) */
129828  && p->nOut>=pTemplate->nOut /* (2b) */
129829  ){
129830  assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
129831  break; /* Cause p to be overwritten by pTemplate */
129832  }
129833  }
129834  return ppPrev;
129835 }
129836 
129837 /*
129838 ** Insert or replace a WhereLoop entry using the template supplied.
129839 **
129840 ** An existing WhereLoop entry might be overwritten if the new template
129841 ** is better and has fewer dependencies. Or the template will be ignored
129842 ** and no insert will occur if an existing WhereLoop is faster and has
129843 ** fewer dependencies than the template. Otherwise a new WhereLoop is
129844 ** added based on the template.
129845 **
129846 ** If pBuilder->pOrSet is not NULL then we care about only the
129847 ** prerequisites and rRun and nOut costs of the N best loops. That
129848 ** information is gathered in the pBuilder->pOrSet object. This special
129849 ** processing mode is used only for OR clause processing.
129850 **
129851 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
129852 ** still might overwrite similar loops with the new template if the
129853 ** new template is better. Loops may be overwritten if the following
129854 ** conditions are met:
129855 **
129856 ** (1) They have the same iTab.
129857 ** (2) They have the same iSortIdx.
129858 ** (3) The template has same or fewer dependencies than the current loop
129859 ** (4) The template has the same or lower cost than the current loop
129860 */
129861 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
129862  WhereLoop **ppPrev, *p;
129863  WhereInfo *pWInfo = pBuilder->pWInfo;
129864  sqlite3 *db = pWInfo->pParse->db;
129865  int rc;
129866 
129867  /* If pBuilder->pOrSet is defined, then only keep track of the costs
129868  ** and prereqs.
129869  */
129870  if( pBuilder->pOrSet!=0 ){
129871  if( pTemplate->nLTerm ){
129872 #if WHERETRACE_ENABLED
129873  u16 n = pBuilder->pOrSet->n;
129874  int x =
129875 #endif
129876  whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
129877  pTemplate->nOut);
129878 #if WHERETRACE_ENABLED /* 0x8 */
129879  if( sqlite3WhereTrace & 0x8 ){
129880  sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
129881  whereLoopPrint(pTemplate, pBuilder->pWC);
129882  }
129883 #endif
129884  }
129885  return SQLITE_OK;
129886  }
129887 
129888  /* Look for an existing WhereLoop to replace with pTemplate
129889  */
129890  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
129891  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
129892 
129893  if( ppPrev==0 ){
129894  /* There already exists a WhereLoop on the list that is better
129895  ** than pTemplate, so just ignore pTemplate */
129896 #if WHERETRACE_ENABLED /* 0x8 */
129897  if( sqlite3WhereTrace & 0x8 ){
129898  sqlite3DebugPrintf(" skip: ");
129899  whereLoopPrint(pTemplate, pBuilder->pWC);
129900  }
129901 #endif
129902  return SQLITE_OK;
129903  }else{
129904  p = *ppPrev;
129905  }
129906 
129907  /* If we reach this point it means that either p[] should be overwritten
129908  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
129909  ** WhereLoop and insert it.
129910  */
129911 #if WHERETRACE_ENABLED /* 0x8 */
129912  if( sqlite3WhereTrace & 0x8 ){
129913  if( p!=0 ){
129914  sqlite3DebugPrintf("replace: ");
129915  whereLoopPrint(p, pBuilder->pWC);
129916  }
129917  sqlite3DebugPrintf(" add: ");
129918  whereLoopPrint(pTemplate, pBuilder->pWC);
129919  }
129920 #endif
129921  if( p==0 ){
129922  /* Allocate a new WhereLoop to add to the end of the list */
129923  *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
129924  if( p==0 ) return SQLITE_NOMEM_BKPT;
129925  whereLoopInit(p);
129926  p->pNextLoop = 0;
129927  }else{
129928  /* We will be overwriting WhereLoop p[]. But before we do, first
129929  ** go through the rest of the list and delete any other entries besides
129930  ** p[] that are also supplated by pTemplate */
129931  WhereLoop **ppTail = &p->pNextLoop;
129932  WhereLoop *pToDel;
129933  while( *ppTail ){
129934  ppTail = whereLoopFindLesser(ppTail, pTemplate);
129935  if( ppTail==0 ) break;
129936  pToDel = *ppTail;
129937  if( pToDel==0 ) break;
129938  *ppTail = pToDel->pNextLoop;
129939 #if WHERETRACE_ENABLED /* 0x8 */
129940  if( sqlite3WhereTrace & 0x8 ){
129941  sqlite3DebugPrintf(" delete: ");
129942  whereLoopPrint(pToDel, pBuilder->pWC);
129943  }
129944 #endif
129945  whereLoopDelete(db, pToDel);
129946  }
129947  }
129948  rc = whereLoopXfer(db, p, pTemplate);
129949  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
129950  Index *pIndex = p->u.btree.pIndex;
129951  if( pIndex && pIndex->tnum==0 ){
129952  p->u.btree.pIndex = 0;
129953  }
129954  }
129955  return rc;
129956 }
129957 
129958 /*
129959 ** Adjust the WhereLoop.nOut value downward to account for terms of the
129960 ** WHERE clause that reference the loop but which are not used by an
129961 ** index.
129962 *
129963 ** For every WHERE clause term that is not used by the index
129964 ** and which has a truth probability assigned by one of the likelihood(),
129965 ** likely(), or unlikely() SQL functions, reduce the estimated number
129966 ** of output rows by the probability specified.
129967 **
129968 ** TUNING: For every WHERE clause term that is not used by the index
129969 ** and which does not have an assigned truth probability, heuristics
129970 ** described below are used to try to estimate the truth probability.
129971 ** TODO --> Perhaps this is something that could be improved by better
129972 ** table statistics.
129973 **
129974 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
129975 ** value corresponds to -1 in LogEst notation, so this means decrement
129976 ** the WhereLoop.nOut field for every such WHERE clause term.
129977 **
129978 ** Heuristic 2: If there exists one or more WHERE clause terms of the
129979 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
129980 ** final output row estimate is no greater than 1/4 of the total number
129981 ** of rows in the table. In other words, assume that x==EXPR will filter
129982 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
129983 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
129984 ** on the "x" column and so in that case only cap the output row estimate
129985 ** at 1/2 instead of 1/4.
129986 */
129987 static void whereLoopOutputAdjust(
129988  WhereClause *pWC, /* The WHERE clause */
129989  WhereLoop *pLoop, /* The loop to adjust downward */
129990  LogEst nRow /* Number of rows in the entire table */
129991 ){
129992  WhereTerm *pTerm, *pX;
129993  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
129994  int i, j, k;
129995  LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
129996 
129997  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
129998  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
129999  if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
130000  if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
130001  if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
130002  for(j=pLoop->nLTerm-1; j>=0; j--){
130003  pX = pLoop->aLTerm[j];
130004  if( pX==0 ) continue;
130005  if( pX==pTerm ) break;
130006  if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
130007  }
130008  if( j<0 ){
130009  if( pTerm->truthProb<=0 ){
130010  /* If a truth probability is specified using the likelihood() hints,
130011  ** then use the probability provided by the application. */
130012  pLoop->nOut += pTerm->truthProb;
130013  }else{
130014  /* In the absence of explicit truth probabilities, use heuristics to
130015  ** guess a reasonable truth probability. */
130016  pLoop->nOut--;
130017  if( pTerm->eOperator&(WO_EQ|WO_IS) ){
130018  Expr *pRight = pTerm->pExpr->pRight;
130019  testcase( pTerm->pExpr->op==TK_IS );
130020  if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
130021  k = 10;
130022  }else{
130023  k = 20;
130024  }
130025  if( iReduce<k ) iReduce = k;
130026  }
130027  }
130028  }
130029  }
130030  if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
130031 }
130032 
130033 /*
130034 ** Term pTerm is a vector range comparison operation. The first comparison
130035 ** in the vector can be optimized using column nEq of the index. This
130036 ** function returns the total number of vector elements that can be used
130037 ** as part of the range comparison.
130038 **
130039 ** For example, if the query is:
130040 **
130041 ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
130042 **
130043 ** and the index:
130044 **
130045 ** CREATE INDEX ... ON (a, b, c, d, e)
130046 **
130047 ** then this function would be invoked with nEq=1. The value returned in
130048 ** this case is 3.
130049 */
130050 static int whereRangeVectorLen(
130051  Parse *pParse, /* Parsing context */
130052  int iCur, /* Cursor open on pIdx */
130053  Index *pIdx, /* The index to be used for a inequality constraint */
130054  int nEq, /* Number of prior equality constraints on same index */
130055  WhereTerm *pTerm /* The vector inequality constraint */
130056 ){
130057  int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
130058  int i;
130059 
130060  nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
130061  for(i=1; i<nCmp; i++){
130062  /* Test if comparison i of pTerm is compatible with column (i+nEq)
130063  ** of the index. If not, exit the loop. */
130064  char aff; /* Comparison affinity */
130065  char idxaff = 0; /* Indexed columns affinity */
130066  CollSeq *pColl; /* Comparison collation sequence */
130067  Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
130068  Expr *pRhs = pTerm->pExpr->pRight;
130069  if( pRhs->flags & EP_xIsSelect ){
130070  pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
130071  }else{
130072  pRhs = pRhs->x.pList->a[i].pExpr;
130073  }
130074 
130075  /* Check that the LHS of the comparison is a column reference to
130076  ** the right column of the right source table. And that the sort
130077  ** order of the index column is the same as the sort order of the
130078  ** leftmost index column. */
130079  if( pLhs->op!=TK_COLUMN
130080  || pLhs->iTable!=iCur
130081  || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
130082  || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
130083  ){
130084  break;
130085  }
130086 
130087  testcase( pLhs->iColumn==XN_ROWID );
130088  aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
130089  idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
130090  if( aff!=idxaff ) break;
130091 
130092  pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
130093  if( pColl==0 ) break;
130094  if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
130095  }
130096  return i;
130097 }
130098 
130099 /*
130100 ** Adjust the cost C by the costMult facter T. This only occurs if
130101 ** compiled with -DSQLITE_ENABLE_COSTMULT
130102 */
130103 #ifdef SQLITE_ENABLE_COSTMULT
130104 # define ApplyCostMultiplier(C,T) C += T
130105 #else
130106 # define ApplyCostMultiplier(C,T)
130107 #endif
130108 
130109 /*
130110 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
130111 ** index pIndex. Try to match one more.
130112 **
130113 ** When this function is called, pBuilder->pNew->nOut contains the
130114 ** number of rows expected to be visited by filtering using the nEq
130115 ** terms only. If it is modified, this value is restored before this
130116 ** function returns.
130117 **
130118 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
130119 ** INTEGER PRIMARY KEY.
130120 */
130121 static int whereLoopAddBtreeIndex(
130122  WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
130123  struct SrcList_item *pSrc, /* FROM clause term being analyzed */
130124  Index *pProbe, /* An index on pSrc */
130125  LogEst nInMul /* log(Number of iterations due to IN) */
130126 ){
130127  WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
130128  Parse *pParse = pWInfo->pParse; /* Parsing context */
130129  sqlite3 *db = pParse->db; /* Database connection malloc context */
130130  WhereLoop *pNew; /* Template WhereLoop under construction */
130131  WhereTerm *pTerm; /* A WhereTerm under consideration */
130132  int opMask; /* Valid operators for constraints */
130133  WhereScan scan; /* Iterator for WHERE terms */
130134  Bitmask saved_prereq; /* Original value of pNew->prereq */
130135  u16 saved_nLTerm; /* Original value of pNew->nLTerm */
130136  u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
130137  u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
130138  u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
130139  u16 saved_nSkip; /* Original value of pNew->nSkip */
130140  u32 saved_wsFlags; /* Original value of pNew->wsFlags */
130141  LogEst saved_nOut; /* Original value of pNew->nOut */
130142  int rc = SQLITE_OK; /* Return code */
130143  LogEst rSize; /* Number of rows in the table */
130144  LogEst rLogSize; /* Logarithm of table size */
130145  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
130146 
130147  pNew = pBuilder->pNew;
130148  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
130149  WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
130150  pProbe->zName, pNew->u.btree.nEq));
130151 
130152  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
130153  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
130154  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
130155  opMask = WO_LT|WO_LE;
130156  }else{
130157  assert( pNew->u.btree.nBtm==0 );
130158  opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
130159  }
130160  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
130161 
130162  assert( pNew->u.btree.nEq<pProbe->nColumn );
130163 
130164  saved_nEq = pNew->u.btree.nEq;
130165  saved_nBtm = pNew->u.btree.nBtm;
130166  saved_nTop = pNew->u.btree.nTop;
130167  saved_nSkip = pNew->nSkip;
130168  saved_nLTerm = pNew->nLTerm;
130169  saved_wsFlags = pNew->wsFlags;
130170  saved_prereq = pNew->prereq;
130171  saved_nOut = pNew->nOut;
130172  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
130173  opMask, pProbe);
130174  pNew->rSetup = 0;
130175  rSize = pProbe->aiRowLogEst[0];
130176  rLogSize = estLog(rSize);
130177  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
130178  u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
130179  LogEst rCostIdx;
130180  LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
130181  int nIn = 0;
130182 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
130183  int nRecValid = pBuilder->nRecValid;
130184 #endif
130185  if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
130186  && indexColumnNotNull(pProbe, saved_nEq)
130187  ){
130188  continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
130189  }
130190  if( pTerm->prereqRight & pNew->maskSelf ) continue;
130191 
130192  /* Do not allow the upper bound of a LIKE optimization range constraint
130193  ** to mix with a lower range bound from some other source */
130194  if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
130195 
130196  /* Do not allow IS constraints from the WHERE clause to be used by the
130197  ** right table of a LEFT JOIN. Only constraints in the ON clause are
130198  ** allowed */
130199  if( (pSrc->fg.jointype & JT_LEFT)!=0
130200  && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
130201  && (eOp & (WO_IS|WO_ISNULL))!=0
130202  ){
130203  testcase( eOp & WO_IS );
130204  testcase( eOp & WO_ISNULL );
130205  continue;
130206  }
130207 
130208  pNew->wsFlags = saved_wsFlags;
130209  pNew->u.btree.nEq = saved_nEq;
130210  pNew->u.btree.nBtm = saved_nBtm;
130211  pNew->u.btree.nTop = saved_nTop;
130212  pNew->nLTerm = saved_nLTerm;
130213  if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
130214  pNew->aLTerm[pNew->nLTerm++] = pTerm;
130215  pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
130216 
130217  assert( nInMul==0
130218  || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
130219  || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
130220  || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
130221  );
130222 
130223  if( eOp & WO_IN ){
130224  Expr *pExpr = pTerm->pExpr;
130225  pNew->wsFlags |= WHERE_COLUMN_IN;
130226  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
130227  /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
130228  int i;
130229  nIn = 46; assert( 46==sqlite3LogEst(25) );
130230 
130231  /* The expression may actually be of the form (x, y) IN (SELECT...).
130232  ** In this case there is a separate term for each of (x) and (y).
130233  ** However, the nIn multiplier should only be applied once, not once
130234  ** for each such term. The following loop checks that pTerm is the
130235  ** first such term in use, and sets nIn back to 0 if it is not. */
130236  for(i=0; i<pNew->nLTerm-1; i++){
130237  if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
130238  }
130239  }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
130240  /* "x IN (value, value, ...)" */
130241  nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
130242  assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
130243  ** changes "x IN (?)" into "x=?". */
130244  }
130245  }else if( eOp & (WO_EQ|WO_IS) ){
130246  int iCol = pProbe->aiColumn[saved_nEq];
130247  pNew->wsFlags |= WHERE_COLUMN_EQ;
130248  assert( saved_nEq==pNew->u.btree.nEq );
130249  if( iCol==XN_ROWID
130250  || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
130251  ){
130252  if( iCol>=0 && pProbe->uniqNotNull==0 ){
130253  pNew->wsFlags |= WHERE_UNQ_WANTED;
130254  }else{
130255  pNew->wsFlags |= WHERE_ONEROW;
130256  }
130257  }
130258  }else if( eOp & WO_ISNULL ){
130259  pNew->wsFlags |= WHERE_COLUMN_NULL;
130260  }else if( eOp & (WO_GT|WO_GE) ){
130261  testcase( eOp & WO_GT );
130262  testcase( eOp & WO_GE );
130263  pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
130264  pNew->u.btree.nBtm = whereRangeVectorLen(
130265  pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
130266  );
130267  pBtm = pTerm;
130268  pTop = 0;
130269  if( pTerm->wtFlags & TERM_LIKEOPT ){
130270  /* Range contraints that come from the LIKE optimization are
130271  ** always used in pairs. */
130272  pTop = &pTerm[1];
130273  assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
130274  assert( pTop->wtFlags & TERM_LIKEOPT );
130275  assert( pTop->eOperator==WO_LT );
130276  if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
130277  pNew->aLTerm[pNew->nLTerm++] = pTop;
130278  pNew->wsFlags |= WHERE_TOP_LIMIT;
130279  pNew->u.btree.nTop = 1;
130280  }
130281  }else{
130282  assert( eOp & (WO_LT|WO_LE) );
130283  testcase( eOp & WO_LT );
130284  testcase( eOp & WO_LE );
130285  pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
130286  pNew->u.btree.nTop = whereRangeVectorLen(
130287  pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
130288  );
130289  pTop = pTerm;
130290  pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
130291  pNew->aLTerm[pNew->nLTerm-2] : 0;
130292  }
130293 
130294  /* At this point pNew->nOut is set to the number of rows expected to
130295  ** be visited by the index scan before considering term pTerm, or the
130296  ** values of nIn and nInMul. In other words, assuming that all
130297  ** "x IN(...)" terms are replaced with "x = ?". This block updates
130298  ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
130299  assert( pNew->nOut==saved_nOut );
130300  if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
130301  /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
130302  ** data, using some other estimate. */
130303  whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
130304  }else{
130305  int nEq = ++pNew->u.btree.nEq;
130306  assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
130307 
130308  assert( pNew->nOut==saved_nOut );
130309  if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
130310  assert( (eOp & WO_IN) || nIn==0 );
130311  testcase( eOp & WO_IN );
130312  pNew->nOut += pTerm->truthProb;
130313  pNew->nOut -= nIn;
130314  }else{
130315 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
130316  tRowcnt nOut = 0;
130317  if( nInMul==0
130318  && pProbe->nSample
130319  && pNew->u.btree.nEq<=pProbe->nSampleCol
130320  && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
130321  ){
130322  Expr *pExpr = pTerm->pExpr;
130323  if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
130324  testcase( eOp & WO_EQ );
130325  testcase( eOp & WO_IS );
130326  testcase( eOp & WO_ISNULL );
130327  rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
130328  }else{
130329  rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
130330  }
130331  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
130332  if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
130333  if( nOut ){
130334  pNew->nOut = sqlite3LogEst(nOut);
130335  if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
130336  pNew->nOut -= nIn;
130337  }
130338  }
130339  if( nOut==0 )
130340 #endif
130341  {
130342  pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
130343  if( eOp & WO_ISNULL ){
130344  /* TUNING: If there is no likelihood() value, assume that a
130345  ** "col IS NULL" expression matches twice as many rows
130346  ** as (col=?). */
130347  pNew->nOut += 10;
130348  }
130349  }
130350  }
130351  }
130352 
130353  /* Set rCostIdx to the cost of visiting selected rows in index. Add
130354  ** it to pNew->rRun, which is currently set to the cost of the index
130355  ** seek only. Then, if this is a non-covering index, add the cost of
130356  ** visiting the rows in the main table. */
130357  rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
130358  pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
130359  if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
130360  pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
130361  }
130362  ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
130363 
130364  nOutUnadjusted = pNew->nOut;
130365  pNew->rRun += nInMul + nIn;
130366  pNew->nOut += nInMul + nIn;
130367  whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
130368  rc = whereLoopInsert(pBuilder, pNew);
130369 
130370  if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
130371  pNew->nOut = saved_nOut;
130372  }else{
130373  pNew->nOut = nOutUnadjusted;
130374  }
130375 
130376  if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
130377  && pNew->u.btree.nEq<pProbe->nColumn
130378  ){
130379  whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
130380  }
130381  pNew->nOut = saved_nOut;
130382 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
130383  pBuilder->nRecValid = nRecValid;
130384 #endif
130385  }
130386  pNew->prereq = saved_prereq;
130387  pNew->u.btree.nEq = saved_nEq;
130388  pNew->u.btree.nBtm = saved_nBtm;
130389  pNew->u.btree.nTop = saved_nTop;
130390  pNew->nSkip = saved_nSkip;
130391  pNew->wsFlags = saved_wsFlags;
130392  pNew->nOut = saved_nOut;
130393  pNew->nLTerm = saved_nLTerm;
130394 
130395  /* Consider using a skip-scan if there are no WHERE clause constraints
130396  ** available for the left-most terms of the index, and if the average
130397  ** number of repeats in the left-most terms is at least 18.
130398  **
130399  ** The magic number 18 is selected on the basis that scanning 17 rows
130400  ** is almost always quicker than an index seek (even though if the index
130401  ** contains fewer than 2^17 rows we assume otherwise in other parts of
130402  ** the code). And, even if it is not, it should not be too much slower.
130403  ** On the other hand, the extra seeks could end up being significantly
130404  ** more expensive. */
130405  assert( 42==sqlite3LogEst(18) );
130406  if( saved_nEq==saved_nSkip
130407  && saved_nEq+1<pProbe->nKeyCol
130408  && pProbe->noSkipScan==0
130409  && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
130410  && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
130411  ){
130412  LogEst nIter;
130413  pNew->u.btree.nEq++;
130414  pNew->nSkip++;
130415  pNew->aLTerm[pNew->nLTerm++] = 0;
130416  pNew->wsFlags |= WHERE_SKIPSCAN;
130417  nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
130418  pNew->nOut -= nIter;
130419  /* TUNING: Because uncertainties in the estimates for skip-scan queries,
130420  ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
130421  nIter += 5;
130422  whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
130423  pNew->nOut = saved_nOut;
130424  pNew->u.btree.nEq = saved_nEq;
130425  pNew->nSkip = saved_nSkip;
130426  pNew->wsFlags = saved_wsFlags;
130427  }
130428 
130429  WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
130430  pProbe->zName, saved_nEq, rc));
130431  return rc;
130432 }
130433 
130434 /*
130435 ** Return True if it is possible that pIndex might be useful in
130436 ** implementing the ORDER BY clause in pBuilder.
130437 **
130438 ** Return False if pBuilder does not contain an ORDER BY clause or
130439 ** if there is no way for pIndex to be useful in implementing that
130440 ** ORDER BY clause.
130441 */
130442 static int indexMightHelpWithOrderBy(
130443  WhereLoopBuilder *pBuilder,
130444  Index *pIndex,
130445  int iCursor
130446 ){
130447  ExprList *pOB;
130448  ExprList *aColExpr;
130449  int ii, jj;
130450 
130451  if( pIndex->bUnordered ) return 0;
130452  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
130453  for(ii=0; ii<pOB->nExpr; ii++){
130454  Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
130455  if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
130456  if( pExpr->iColumn<0 ) return 1;
130457  for(jj=0; jj<pIndex->nKeyCol; jj++){
130458  if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
130459  }
130460  }else if( (aColExpr = pIndex->aColExpr)!=0 ){
130461  for(jj=0; jj<pIndex->nKeyCol; jj++){
130462  if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
130463  if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
130464  return 1;
130465  }
130466  }
130467  }
130468  }
130469  return 0;
130470 }
130471 
130472 /*
130473 ** Return a bitmask where 1s indicate that the corresponding column of
130474 ** the table is used by an index. Only the first 63 columns are considered.
130475 */
130476 static Bitmask columnsInIndex(Index *pIdx){
130477  Bitmask m = 0;
130478  int j;
130479  for(j=pIdx->nColumn-1; j>=0; j--){
130480  int x = pIdx->aiColumn[j];
130481  if( x>=0 ){
130482  testcase( x==BMS-1 );
130483  testcase( x==BMS-2 );
130484  if( x<BMS-1 ) m |= MASKBIT(x);
130485  }
130486  }
130487  return m;
130488 }
130489 
130490 /* Check to see if a partial index with pPartIndexWhere can be used
130491 ** in the current query. Return true if it can be and false if not.
130492 */
130493 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
130494  int i;
130495  WhereTerm *pTerm;
130496  while( pWhere->op==TK_AND ){
130497  if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
130498  pWhere = pWhere->pRight;
130499  }
130500  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
130501  Expr *pExpr = pTerm->pExpr;
130502  if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
130503  && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
130504  ){
130505  return 1;
130506  }
130507  }
130508  return 0;
130509 }
130510 
130511 /*
130512 ** Add all WhereLoop objects for a single table of the join where the table
130513 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
130514 ** a b-tree table, not a virtual table.
130515 **
130516 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
130517 ** are calculated as follows:
130518 **
130519 ** For a full scan, assuming the table (or index) contains nRow rows:
130520 **
130521 ** cost = nRow * 3.0 // full-table scan
130522 ** cost = nRow * K // scan of covering index
130523 ** cost = nRow * (K+3.0) // scan of non-covering index
130524 **
130525 ** where K is a value between 1.1 and 3.0 set based on the relative
130526 ** estimated average size of the index and table records.
130527 **
130528 ** For an index scan, where nVisit is the number of index rows visited
130529 ** by the scan, and nSeek is the number of seek operations required on
130530 ** the index b-tree:
130531 **
130532 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
130533 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
130534 **
130535 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
130536 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
130537 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
130538 **
130539 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
130540 ** of uncertainty. For this reason, scoring is designed to pick plans that
130541 ** "do the least harm" if the estimates are inaccurate. For example, a
130542 ** log(nRow) factor is omitted from a non-covering index scan in order to
130543 ** bias the scoring in favor of using an index, since the worst-case
130544 ** performance of using an index is far better than the worst-case performance
130545 ** of a full table scan.
130546 */
130547 static int whereLoopAddBtree(
130548  WhereLoopBuilder *pBuilder, /* WHERE clause information */
130549  Bitmask mPrereq /* Extra prerequesites for using this table */
130550 ){
130551  WhereInfo *pWInfo; /* WHERE analysis context */
130552  Index *pProbe; /* An index we are evaluating */
130553  Index sPk; /* A fake index object for the primary key */
130554  LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
130555  i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
130556  SrcList *pTabList; /* The FROM clause */
130557  struct SrcList_item *pSrc; /* The FROM clause btree term to add */
130558  WhereLoop *pNew; /* Template WhereLoop object */
130559  int rc = SQLITE_OK; /* Return code */
130560  int iSortIdx = 1; /* Index number */
130561  int b; /* A boolean value */
130562  LogEst rSize; /* number of rows in the table */
130563  LogEst rLogSize; /* Logarithm of the number of rows in the table */
130564  WhereClause *pWC; /* The parsed WHERE clause */
130565  Table *pTab; /* Table being queried */
130566 
130567  pNew = pBuilder->pNew;
130568  pWInfo = pBuilder->pWInfo;
130569  pTabList = pWInfo->pTabList;
130570  pSrc = pTabList->a + pNew->iTab;
130571  pTab = pSrc->pTab;
130572  pWC = pBuilder->pWC;
130573  assert( !IsVirtual(pSrc->pTab) );
130574 
130575  if( pSrc->pIBIndex ){
130576  /* An INDEXED BY clause specifies a particular index to use */
130577  pProbe = pSrc->pIBIndex;
130578  }else if( !HasRowid(pTab) ){
130579  pProbe = pTab->pIndex;
130580  }else{
130581  /* There is no INDEXED BY clause. Create a fake Index object in local
130582  ** variable sPk to represent the rowid primary key index. Make this
130583  ** fake index the first in a chain of Index objects with all of the real
130584  ** indices to follow */
130585  Index *pFirst; /* First of real indices on the table */
130586  memset(&sPk, 0, sizeof(Index));
130587  sPk.nKeyCol = 1;
130588  sPk.nColumn = 1;
130589  sPk.aiColumn = &aiColumnPk;
130590  sPk.aiRowLogEst = aiRowEstPk;
130591  sPk.onError = OE_Replace;
130592  sPk.pTable = pTab;
130593  sPk.szIdxRow = pTab->szTabRow;
130594  aiRowEstPk[0] = pTab->nRowLogEst;
130595  aiRowEstPk[1] = 0;
130596  pFirst = pSrc->pTab->pIndex;
130597  if( pSrc->fg.notIndexed==0 ){
130598  /* The real indices of the table are only considered if the
130599  ** NOT INDEXED qualifier is omitted from the FROM clause */
130600  sPk.pNext = pFirst;
130601  }
130602  pProbe = &sPk;
130603  }
130604  rSize = pTab->nRowLogEst;
130605  rLogSize = estLog(rSize);
130606 
130607 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
130608  /* Automatic indexes */
130609  if( !pBuilder->pOrSet /* Not part of an OR optimization */
130610  && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
130611  && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
130612  && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
130613  && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
130614  && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
130615  && !pSrc->fg.isCorrelated /* Not a correlated subquery */
130616  && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
130617  ){
130618  /* Generate auto-index WhereLoops */
130619  WhereTerm *pTerm;
130620  WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
130621  for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
130622  if( pTerm->prereqRight & pNew->maskSelf ) continue;
130623  if( termCanDriveIndex(pTerm, pSrc, 0) ){
130624  pNew->u.btree.nEq = 1;
130625  pNew->nSkip = 0;
130626  pNew->u.btree.pIndex = 0;
130627  pNew->nLTerm = 1;
130628  pNew->aLTerm[0] = pTerm;
130629  /* TUNING: One-time cost for computing the automatic index is
130630  ** estimated to be X*N*log2(N) where N is the number of rows in
130631  ** the table being indexed and where X is 7 (LogEst=28) for normal
130632  ** tables or 1.375 (LogEst=4) for views and subqueries. The value
130633  ** of X is smaller for views and subqueries so that the query planner
130634  ** will be more aggressive about generating automatic indexes for
130635  ** those objects, since there is no opportunity to add schema
130636  ** indexes on subqueries and views. */
130637  pNew->rSetup = rLogSize + rSize + 4;
130638  if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
130639  pNew->rSetup += 24;
130640  }
130641  ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
130642  if( pNew->rSetup<0 ) pNew->rSetup = 0;
130643  /* TUNING: Each index lookup yields 20 rows in the table. This
130644  ** is more than the usual guess of 10 rows, since we have no way
130645  ** of knowing how selective the index will ultimately be. It would
130646  ** not be unreasonable to make this value much larger. */
130647  pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
130648  pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
130649  pNew->wsFlags = WHERE_AUTO_INDEX;
130650  pNew->prereq = mPrereq | pTerm->prereqRight;
130651  rc = whereLoopInsert(pBuilder, pNew);
130652  }
130653  }
130654  }
130655 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
130656 
130657  /* Loop over all indices
130658  */
130659  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
130660  if( pProbe->pPartIdxWhere!=0
130661  && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
130662  testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
130663  continue; /* Partial index inappropriate for this query */
130664  }
130665  rSize = pProbe->aiRowLogEst[0];
130666  pNew->u.btree.nEq = 0;
130667  pNew->u.btree.nBtm = 0;
130668  pNew->u.btree.nTop = 0;
130669  pNew->nSkip = 0;
130670  pNew->nLTerm = 0;
130671  pNew->iSortIdx = 0;
130672  pNew->rSetup = 0;
130673  pNew->prereq = mPrereq;
130674  pNew->nOut = rSize;
130675  pNew->u.btree.pIndex = pProbe;
130676  b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
130677  /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
130678  assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
130679  if( pProbe->tnum<=0 ){
130680  /* Integer primary key index */
130681  pNew->wsFlags = WHERE_IPK;
130682 
130683  /* Full table scan */
130684  pNew->iSortIdx = b ? iSortIdx : 0;
130685  /* TUNING: Cost of full table scan is (N*3.0). */
130686  pNew->rRun = rSize + 16;
130687  ApplyCostMultiplier(pNew->rRun, pTab->costMult);
130688  whereLoopOutputAdjust(pWC, pNew, rSize);
130689  rc = whereLoopInsert(pBuilder, pNew);
130690  pNew->nOut = rSize;
130691  if( rc ) break;
130692  }else{
130693  Bitmask m;
130694  if( pProbe->isCovering ){
130695  pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
130696  m = 0;
130697  }else{
130698  m = pSrc->colUsed & ~columnsInIndex(pProbe);
130699  pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
130700  }
130701 
130702  /* Full scan via index */
130703  if( b
130704  || !HasRowid(pTab)
130705  || pProbe->pPartIdxWhere!=0
130706  || ( m==0
130707  && pProbe->bUnordered==0
130708  && (pProbe->szIdxRow<pTab->szTabRow)
130709  && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
130710  && sqlite3GlobalConfig.bUseCis
130711  && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
130712  )
130713  ){
130714  pNew->iSortIdx = b ? iSortIdx : 0;
130715 
130716  /* The cost of visiting the index rows is N*K, where K is
130717  ** between 1.1 and 3.0, depending on the relative sizes of the
130718  ** index and table rows. */
130719  pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
130720  if( m!=0 ){
130721  /* If this is a non-covering index scan, add in the cost of
130722  ** doing table lookups. The cost will be 3x the number of
130723  ** lookups. Take into account WHERE clause terms that can be
130724  ** satisfied using just the index, and that do not require a
130725  ** table lookup. */
130726  LogEst nLookup = rSize + 16; /* Base cost: N*3 */
130727  int ii;
130728  int iCur = pSrc->iCursor;
130729  WhereClause *pWC2 = &pWInfo->sWC;
130730  for(ii=0; ii<pWC2->nTerm; ii++){
130731  WhereTerm *pTerm = &pWC2->a[ii];
130732  if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
130733  break;
130734  }
130735  /* pTerm can be evaluated using just the index. So reduce
130736  ** the expected number of table lookups accordingly */
130737  if( pTerm->truthProb<=0 ){
130738  nLookup += pTerm->truthProb;
130739  }else{
130740  nLookup--;
130741  if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
130742  }
130743  }
130744 
130745  pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
130746  }
130747  ApplyCostMultiplier(pNew->rRun, pTab->costMult);
130748  whereLoopOutputAdjust(pWC, pNew, rSize);
130749  rc = whereLoopInsert(pBuilder, pNew);
130750  pNew->nOut = rSize;
130751  if( rc ) break;
130752  }
130753  }
130754 
130755  rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
130756 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
130757  sqlite3Stat4ProbeFree(pBuilder->pRec);
130758  pBuilder->nRecValid = 0;
130759  pBuilder->pRec = 0;
130760 #endif
130761 
130762  /* If there was an INDEXED BY clause, then only that one index is
130763  ** considered. */
130764  if( pSrc->pIBIndex ) break;
130765  }
130766  return rc;
130767 }
130768 
130769 #ifndef SQLITE_OMIT_VIRTUALTABLE
130770 
130771 /*
130772 ** Argument pIdxInfo is already populated with all constraints that may
130773 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
130774 ** function marks a subset of those constraints usable, invokes the
130775 ** xBestIndex method and adds the returned plan to pBuilder.
130776 **
130777 ** A constraint is marked usable if:
130778 **
130779 ** * Argument mUsable indicates that its prerequisites are available, and
130780 **
130781 ** * It is not one of the operators specified in the mExclude mask passed
130782 ** as the fourth argument (which in practice is either WO_IN or 0).
130783 **
130784 ** Argument mPrereq is a mask of tables that must be scanned before the
130785 ** virtual table in question. These are added to the plans prerequisites
130786 ** before it is added to pBuilder.
130787 **
130788 ** Output parameter *pbIn is set to true if the plan added to pBuilder
130789 ** uses one or more WO_IN terms, or false otherwise.
130790 */
130791 static int whereLoopAddVirtualOne(
130792  WhereLoopBuilder *pBuilder,
130793  Bitmask mPrereq, /* Mask of tables that must be used. */
130794  Bitmask mUsable, /* Mask of usable tables */
130795  u16 mExclude, /* Exclude terms using these operators */
130796  sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
130797  u16 mNoOmit, /* Do not omit these constraints */
130798  int *pbIn /* OUT: True if plan uses an IN(...) op */
130799 ){
130800  WhereClause *pWC = pBuilder->pWC;
130801  struct sqlite3_index_constraint *pIdxCons;
130802  struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
130803  int i;
130804  int mxTerm;
130805  int rc = SQLITE_OK;
130806  WhereLoop *pNew = pBuilder->pNew;
130807  Parse *pParse = pBuilder->pWInfo->pParse;
130808  struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
130809  int nConstraint = pIdxInfo->nConstraint;
130810 
130811  assert( (mUsable & mPrereq)==mPrereq );
130812  *pbIn = 0;
130813  pNew->prereq = mPrereq;
130814 
130815  /* Set the usable flag on the subset of constraints identified by
130816  ** arguments mUsable and mExclude. */
130817  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
130818  for(i=0; i<nConstraint; i++, pIdxCons++){
130819  WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
130820  pIdxCons->usable = 0;
130821  if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
130822  && (pTerm->eOperator & mExclude)==0
130823  ){
130824  pIdxCons->usable = 1;
130825  }
130826  }
130827 
130828  /* Initialize the output fields of the sqlite3_index_info structure */
130829  memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
130830  assert( pIdxInfo->needToFreeIdxStr==0 );
130831  pIdxInfo->idxStr = 0;
130832  pIdxInfo->idxNum = 0;
130833  pIdxInfo->orderByConsumed = 0;
130834  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
130835  pIdxInfo->estimatedRows = 25;
130836  pIdxInfo->idxFlags = 0;
130837  pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
130838 
130839  /* Invoke the virtual table xBestIndex() method */
130840  rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
130841  if( rc ) return rc;
130842 
130843  mxTerm = -1;
130844  assert( pNew->nLSlot>=nConstraint );
130845  for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
130846  pNew->u.vtab.omitMask = 0;
130847  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
130848  for(i=0; i<nConstraint; i++, pIdxCons++){
130849  int iTerm;
130850  if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
130851  WhereTerm *pTerm;
130852  int j = pIdxCons->iTermOffset;
130853  if( iTerm>=nConstraint
130854  || j<0
130855  || j>=pWC->nTerm
130856  || pNew->aLTerm[iTerm]!=0
130857  || pIdxCons->usable==0
130858  ){
130859  rc = SQLITE_ERROR;
130860  sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
130861  return rc;
130862  }
130863  testcase( iTerm==nConstraint-1 );
130864  testcase( j==0 );
130865  testcase( j==pWC->nTerm-1 );
130866  pTerm = &pWC->a[j];
130867  pNew->prereq |= pTerm->prereqRight;
130868  assert( iTerm<pNew->nLSlot );
130869  pNew->aLTerm[iTerm] = pTerm;
130870  if( iTerm>mxTerm ) mxTerm = iTerm;
130871  testcase( iTerm==15 );
130872  testcase( iTerm==16 );
130873  if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
130874  if( (pTerm->eOperator & WO_IN)!=0 ){
130875  /* A virtual table that is constrained by an IN clause may not
130876  ** consume the ORDER BY clause because (1) the order of IN terms
130877  ** is not necessarily related to the order of output terms and
130878  ** (2) Multiple outputs from a single IN value will not merge
130879  ** together. */
130880  pIdxInfo->orderByConsumed = 0;
130881  pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
130882  *pbIn = 1; assert( (mExclude & WO_IN)==0 );
130883  }
130884  }
130885  }
130886  pNew->u.vtab.omitMask &= ~mNoOmit;
130887 
130888  pNew->nLTerm = mxTerm+1;
130889  assert( pNew->nLTerm<=pNew->nLSlot );
130890  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
130891  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
130892  pIdxInfo->needToFreeIdxStr = 0;
130893  pNew->u.vtab.idxStr = pIdxInfo->idxStr;
130894  pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
130895  pIdxInfo->nOrderBy : 0);
130896  pNew->rSetup = 0;
130897  pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
130898  pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
130899 
130900  /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
130901  ** that the scan will visit at most one row. Clear it otherwise. */
130902  if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
130903  pNew->wsFlags |= WHERE_ONEROW;
130904  }else{
130905  pNew->wsFlags &= ~WHERE_ONEROW;
130906  }
130907  rc = whereLoopInsert(pBuilder, pNew);
130908  if( pNew->u.vtab.needFree ){
130909  sqlite3_free(pNew->u.vtab.idxStr);
130910  pNew->u.vtab.needFree = 0;
130911  }
130912  WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
130913  *pbIn, (sqlite3_uint64)mPrereq,
130914  (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
130915 
130916  return rc;
130917 }
130918 
130919 
130920 /*
130921 ** Add all WhereLoop objects for a table of the join identified by
130922 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
130923 **
130924 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
130925 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
130926 ** entries that occur before the virtual table in the FROM clause and are
130927 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
130928 ** mUnusable mask contains all FROM clause entries that occur after the
130929 ** virtual table and are separated from it by at least one LEFT or
130930 ** CROSS JOIN.
130931 **
130932 ** For example, if the query were:
130933 **
130934 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
130935 **
130936 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
130937 **
130938 ** All the tables in mPrereq must be scanned before the current virtual
130939 ** table. So any terms for which all prerequisites are satisfied by
130940 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
130941 ** Conversely, all tables in mUnusable must be scanned after the current
130942 ** virtual table, so any terms for which the prerequisites overlap with
130943 ** mUnusable should always be configured as "not-usable" for xBestIndex.
130944 */
130945 static int whereLoopAddVirtual(
130946  WhereLoopBuilder *pBuilder, /* WHERE clause information */
130947  Bitmask mPrereq, /* Tables that must be scanned before this one */
130948  Bitmask mUnusable /* Tables that must be scanned after this one */
130949 ){
130950  int rc = SQLITE_OK; /* Return code */
130951  WhereInfo *pWInfo; /* WHERE analysis context */
130952  Parse *pParse; /* The parsing context */
130953  WhereClause *pWC; /* The WHERE clause */
130954  struct SrcList_item *pSrc; /* The FROM clause term to search */
130955  sqlite3_index_info *p; /* Object to pass to xBestIndex() */
130956  int nConstraint; /* Number of constraints in p */
130957  int bIn; /* True if plan uses IN(...) operator */
130958  WhereLoop *pNew;
130959  Bitmask mBest; /* Tables used by best possible plan */
130960  u16 mNoOmit;
130961 
130962  assert( (mPrereq & mUnusable)==0 );
130963  pWInfo = pBuilder->pWInfo;
130964  pParse = pWInfo->pParse;
130965  pWC = pBuilder->pWC;
130966  pNew = pBuilder->pNew;
130967  pSrc = &pWInfo->pTabList->a[pNew->iTab];
130968  assert( IsVirtual(pSrc->pTab) );
130969  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
130970  &mNoOmit);
130971  if( p==0 ) return SQLITE_NOMEM_BKPT;
130972  pNew->rSetup = 0;
130973  pNew->wsFlags = WHERE_VIRTUALTABLE;
130974  pNew->nLTerm = 0;
130975  pNew->u.vtab.needFree = 0;
130976  nConstraint = p->nConstraint;
130977  if( whereLoopResize(pParse->db, pNew, nConstraint) ){
130978  sqlite3DbFree(pParse->db, p);
130979  return SQLITE_NOMEM_BKPT;
130980  }
130981 
130982  /* First call xBestIndex() with all constraints usable. */
130983  WHERETRACE(0x40, (" VirtualOne: all usable\n"));
130984  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
130985 
130986  /* If the call to xBestIndex() with all terms enabled produced a plan
130987  ** that does not require any source tables (IOW: a plan with mBest==0),
130988  ** then there is no point in making any further calls to xBestIndex()
130989  ** since they will all return the same result (if the xBestIndex()
130990  ** implementation is sane). */
130991  if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
130992  int seenZero = 0; /* True if a plan with no prereqs seen */
130993  int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
130994  Bitmask mPrev = 0;
130995  Bitmask mBestNoIn = 0;
130996 
130997  /* If the plan produced by the earlier call uses an IN(...) term, call
130998  ** xBestIndex again, this time with IN(...) terms disabled. */
130999  if( bIn ){
131000  WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
131001  rc = whereLoopAddVirtualOne(
131002  pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
131003  assert( bIn==0 );
131004  mBestNoIn = pNew->prereq & ~mPrereq;
131005  if( mBestNoIn==0 ){
131006  seenZero = 1;
131007  seenZeroNoIN = 1;
131008  }
131009  }
131010 
131011  /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
131012  ** in the set of terms that apply to the current virtual table. */
131013  while( rc==SQLITE_OK ){
131014  int i;
131015  Bitmask mNext = ALLBITS;
131016  assert( mNext>0 );
131017  for(i=0; i<nConstraint; i++){
131018  Bitmask mThis = (
131019  pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
131020  );
131021  if( mThis>mPrev && mThis<mNext ) mNext = mThis;
131022  }
131023  mPrev = mNext;
131024  if( mNext==ALLBITS ) break;
131025  if( mNext==mBest || mNext==mBestNoIn ) continue;
131026  WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
131027  (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
131028  rc = whereLoopAddVirtualOne(
131029  pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
131030  if( pNew->prereq==mPrereq ){
131031  seenZero = 1;
131032  if( bIn==0 ) seenZeroNoIN = 1;
131033  }
131034  }
131035 
131036  /* If the calls to xBestIndex() in the above loop did not find a plan
131037  ** that requires no source tables at all (i.e. one guaranteed to be
131038  ** usable), make a call here with all source tables disabled */
131039  if( rc==SQLITE_OK && seenZero==0 ){
131040  WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
131041  rc = whereLoopAddVirtualOne(
131042  pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
131043  if( bIn==0 ) seenZeroNoIN = 1;
131044  }
131045 
131046  /* If the calls to xBestIndex() have so far failed to find a plan
131047  ** that requires no source tables at all and does not use an IN(...)
131048  ** operator, make a final call to obtain one here. */
131049  if( rc==SQLITE_OK && seenZeroNoIN==0 ){
131050  WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
131051  rc = whereLoopAddVirtualOne(
131052  pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
131053  }
131054  }
131055 
131056  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
131057  sqlite3DbFree(pParse->db, p);
131058  return rc;
131059 }
131060 #endif /* SQLITE_OMIT_VIRTUALTABLE */
131061 
131062 /*
131063 ** Add WhereLoop entries to handle OR terms. This works for either
131064 ** btrees or virtual tables.
131065 */
131066 static int whereLoopAddOr(
131067  WhereLoopBuilder *pBuilder,
131068  Bitmask mPrereq,
131069  Bitmask mUnusable
131070 ){
131071  WhereInfo *pWInfo = pBuilder->pWInfo;
131072  WhereClause *pWC;
131073  WhereLoop *pNew;
131074  WhereTerm *pTerm, *pWCEnd;
131075  int rc = SQLITE_OK;
131076  int iCur;
131077  WhereClause tempWC;
131078  WhereLoopBuilder sSubBuild;
131079  WhereOrSet sSum, sCur;
131080  struct SrcList_item *pItem;
131081 
131082  pWC = pBuilder->pWC;
131083  pWCEnd = pWC->a + pWC->nTerm;
131084  pNew = pBuilder->pNew;
131085  memset(&sSum, 0, sizeof(sSum));
131086  pItem = pWInfo->pTabList->a + pNew->iTab;
131087  iCur = pItem->iCursor;
131088 
131089  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
131090  if( (pTerm->eOperator & WO_OR)!=0
131091  && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
131092  ){
131093  WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
131094  WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
131095  WhereTerm *pOrTerm;
131096  int once = 1;
131097  int i, j;
131098 
131099  sSubBuild = *pBuilder;
131100  sSubBuild.pOrderBy = 0;
131101  sSubBuild.pOrSet = &sCur;
131102 
131103  WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
131104  for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
131105  if( (pOrTerm->eOperator & WO_AND)!=0 ){
131106  sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
131107  }else if( pOrTerm->leftCursor==iCur ){
131108  tempWC.pWInfo = pWC->pWInfo;
131109  tempWC.pOuter = pWC;
131110  tempWC.op = TK_AND;
131111  tempWC.nTerm = 1;
131112  tempWC.a = pOrTerm;
131113  sSubBuild.pWC = &tempWC;
131114  }else{
131115  continue;
131116  }
131117  sCur.n = 0;
131118 #ifdef WHERETRACE_ENABLED
131119  WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
131120  (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
131121  if( sqlite3WhereTrace & 0x400 ){
131122  sqlite3WhereClausePrint(sSubBuild.pWC);
131123  }
131124 #endif
131125 #ifndef SQLITE_OMIT_VIRTUALTABLE
131126  if( IsVirtual(pItem->pTab) ){
131127  rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
131128  }else
131129 #endif
131130  {
131131  rc = whereLoopAddBtree(&sSubBuild, mPrereq);
131132  }
131133  if( rc==SQLITE_OK ){
131134  rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
131135  }
131136  assert( rc==SQLITE_OK || sCur.n==0 );
131137  if( sCur.n==0 ){
131138  sSum.n = 0;
131139  break;
131140  }else if( once ){
131141  whereOrMove(&sSum, &sCur);
131142  once = 0;
131143  }else{
131144  WhereOrSet sPrev;
131145  whereOrMove(&sPrev, &sSum);
131146  sSum.n = 0;
131147  for(i=0; i<sPrev.n; i++){
131148  for(j=0; j<sCur.n; j++){
131149  whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
131150  sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
131151  sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
131152  }
131153  }
131154  }
131155  }
131156  pNew->nLTerm = 1;
131157  pNew->aLTerm[0] = pTerm;
131158  pNew->wsFlags = WHERE_MULTI_OR;
131159  pNew->rSetup = 0;
131160  pNew->iSortIdx = 0;
131161  memset(&pNew->u, 0, sizeof(pNew->u));
131162  for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
131163  /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
131164  ** of all sub-scans required by the OR-scan. However, due to rounding
131165  ** errors, it may be that the cost of the OR-scan is equal to its
131166  ** most expensive sub-scan. Add the smallest possible penalty
131167  ** (equivalent to multiplying the cost by 1.07) to ensure that
131168  ** this does not happen. Otherwise, for WHERE clauses such as the
131169  ** following where there is an index on "y":
131170  **
131171  ** WHERE likelihood(x=?, 0.99) OR y=?
131172  **
131173  ** the planner may elect to "OR" together a full-table scan and an
131174  ** index lookup. And other similarly odd results. */
131175  pNew->rRun = sSum.a[i].rRun + 1;
131176  pNew->nOut = sSum.a[i].nOut;
131177  pNew->prereq = sSum.a[i].prereq;
131178  rc = whereLoopInsert(pBuilder, pNew);
131179  }
131180  WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
131181  }
131182  }
131183  return rc;
131184 }
131185 
131186 /*
131187 ** Add all WhereLoop objects for all tables
131188 */
131189 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
131190  WhereInfo *pWInfo = pBuilder->pWInfo;
131191  Bitmask mPrereq = 0;
131192  Bitmask mPrior = 0;
131193  int iTab;
131194  SrcList *pTabList = pWInfo->pTabList;
131195  struct SrcList_item *pItem;
131196  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
131197  sqlite3 *db = pWInfo->pParse->db;
131198  int rc = SQLITE_OK;
131199  WhereLoop *pNew;
131200  u8 priorJointype = 0;
131201 
131202  /* Loop over the tables in the join, from left to right */
131203  pNew = pBuilder->pNew;
131204  whereLoopInit(pNew);
131205  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
131206  Bitmask mUnusable = 0;
131207  pNew->iTab = iTab;
131208  pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
131209  if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
131210  /* This condition is true when pItem is the FROM clause term on the
131211  ** right-hand-side of a LEFT or CROSS JOIN. */
131212  mPrereq = mPrior;
131213  }
131214  priorJointype = pItem->fg.jointype;
131215 #ifndef SQLITE_OMIT_VIRTUALTABLE
131216  if( IsVirtual(pItem->pTab) ){
131217  struct SrcList_item *p;
131218  for(p=&pItem[1]; p<pEnd; p++){
131219  if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
131220  mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
131221  }
131222  }
131223  rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
131224  }else
131225 #endif /* SQLITE_OMIT_VIRTUALTABLE */
131226  {
131227  rc = whereLoopAddBtree(pBuilder, mPrereq);
131228  }
131229  if( rc==SQLITE_OK ){
131230  rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
131231  }
131232  mPrior |= pNew->maskSelf;
131233  if( rc || db->mallocFailed ) break;
131234  }
131235 
131236  whereLoopClear(db, pNew);
131237  return rc;
131238 }
131239 
131240 /*
131241 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
131242 ** parameters) to see if it outputs rows in the requested ORDER BY
131243 ** (or GROUP BY) without requiring a separate sort operation. Return N:
131244 **
131245 ** N>0: N terms of the ORDER BY clause are satisfied
131246 ** N==0: No terms of the ORDER BY clause are satisfied
131247 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
131248 **
131249 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
131250 ** strict. With GROUP BY and DISTINCT the only requirement is that
131251 ** equivalent rows appear immediately adjacent to one another. GROUP BY
131252 ** and DISTINCT do not require rows to appear in any particular order as long
131253 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
131254 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
131255 ** pOrderBy terms must be matched in strict left-to-right order.
131256 */
131257 static i8 wherePathSatisfiesOrderBy(
131258  WhereInfo *pWInfo, /* The WHERE clause */
131259  ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
131260  WherePath *pPath, /* The WherePath to check */
131261  u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
131262  u16 nLoop, /* Number of entries in pPath->aLoop[] */
131263  WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
131264  Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
131265 ){
131266  u8 revSet; /* True if rev is known */
131267  u8 rev; /* Composite sort order */
131268  u8 revIdx; /* Index sort order */
131269  u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
131270  u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
131271  u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
131272  u16 eqOpMask; /* Allowed equality operators */
131273  u16 nKeyCol; /* Number of key columns in pIndex */
131274  u16 nColumn; /* Total number of ordered columns in the index */
131275  u16 nOrderBy; /* Number terms in the ORDER BY clause */
131276  int iLoop; /* Index of WhereLoop in pPath being processed */
131277  int i, j; /* Loop counters */
131278  int iCur; /* Cursor number for current WhereLoop */
131279  int iColumn; /* A column number within table iCur */
131280  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
131281  WhereTerm *pTerm; /* A single term of the WHERE clause */
131282  Expr *pOBExpr; /* An expression from the ORDER BY clause */
131283  CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
131284  Index *pIndex; /* The index associated with pLoop */
131285  sqlite3 *db = pWInfo->pParse->db; /* Database connection */
131286  Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
131287  Bitmask obDone; /* Mask of all ORDER BY terms */
131288  Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
131289  Bitmask ready; /* Mask of inner loops */
131290 
131291  /*
131292  ** We say the WhereLoop is "one-row" if it generates no more than one
131293  ** row of output. A WhereLoop is one-row if all of the following are true:
131294  ** (a) All index columns match with WHERE_COLUMN_EQ.
131295  ** (b) The index is unique
131296  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
131297  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
131298  **
131299  ** We say the WhereLoop is "order-distinct" if the set of columns from
131300  ** that WhereLoop that are in the ORDER BY clause are different for every
131301  ** row of the WhereLoop. Every one-row WhereLoop is automatically
131302  ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
131303  ** is not order-distinct. To be order-distinct is not quite the same as being
131304  ** UNIQUE since a UNIQUE column or index can have multiple rows that
131305  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
131306  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
131307  **
131308  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
131309  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
131310  ** automatically order-distinct.
131311  */
131312 
131313  assert( pOrderBy!=0 );
131314  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
131315 
131316  nOrderBy = pOrderBy->nExpr;
131317  testcase( nOrderBy==BMS-1 );
131318  if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
131319  isOrderDistinct = 1;
131320  obDone = MASKBIT(nOrderBy)-1;
131321  orderDistinctMask = 0;
131322  ready = 0;
131323  eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
131324  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
131325  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
131326  if( iLoop>0 ) ready |= pLoop->maskSelf;
131327  if( iLoop<nLoop ){
131328  pLoop = pPath->aLoop[iLoop];
131329  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
131330  }else{
131331  pLoop = pLast;
131332  }
131333  if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
131334  if( pLoop->u.vtab.isOrdered ) obSat = obDone;
131335  break;
131336  }
131337  iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
131338 
131339  /* Mark off any ORDER BY term X that is a column in the table of
131340  ** the current loop for which there is term in the WHERE
131341  ** clause of the form X IS NULL or X=? that reference only outer
131342  ** loops.
131343  */
131344  for(i=0; i<nOrderBy; i++){
131345  if( MASKBIT(i) & obSat ) continue;
131346  pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
131347  if( pOBExpr->op!=TK_COLUMN ) continue;
131348  if( pOBExpr->iTable!=iCur ) continue;
131349  pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
131350  ~ready, eqOpMask, 0);
131351  if( pTerm==0 ) continue;
131352  if( pTerm->eOperator==WO_IN ){
131353  /* IN terms are only valid for sorting in the ORDER BY LIMIT
131354  ** optimization, and then only if they are actually used
131355  ** by the query plan */
131356  assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
131357  for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
131358  if( j>=pLoop->nLTerm ) continue;
131359  }
131360  if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
131361  const char *z1, *z2;
131362  pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
131363  if( !pColl ) pColl = db->pDfltColl;
131364  z1 = pColl->zName;
131365  pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
131366  if( !pColl ) pColl = db->pDfltColl;
131367  z2 = pColl->zName;
131368  if( sqlite3StrICmp(z1, z2)!=0 ) continue;
131369  testcase( pTerm->pExpr->op==TK_IS );
131370  }
131371  obSat |= MASKBIT(i);
131372  }
131373 
131374  if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
131375  if( pLoop->wsFlags & WHERE_IPK ){
131376  pIndex = 0;
131377  nKeyCol = 0;
131378  nColumn = 1;
131379  }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
131380  return 0;
131381  }else{
131382  nKeyCol = pIndex->nKeyCol;
131383  nColumn = pIndex->nColumn;
131384  assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
131385  assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
131386  || !HasRowid(pIndex->pTable));
131387  isOrderDistinct = IsUniqueIndex(pIndex);
131388  }
131389 
131390  /* Loop through all columns of the index and deal with the ones
131391  ** that are not constrained by == or IN.
131392  */
131393  rev = revSet = 0;
131394  distinctColumns = 0;
131395  for(j=0; j<nColumn; j++){
131396  u8 bOnce = 1; /* True to run the ORDER BY search loop */
131397 
131398  assert( j>=pLoop->u.btree.nEq
131399  || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
131400  );
131401  if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
131402  u16 eOp = pLoop->aLTerm[j]->eOperator;
131403 
131404  /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
131405  ** doing WHERE_ORDERBY_LIMIT processing).
131406  **
131407  ** If the current term is a column of an ((?,?) IN (SELECT...))
131408  ** expression for which the SELECT returns more than one column,
131409  ** check that it is the only column used by this loop. Otherwise,
131410  ** if it is one of two or more, none of the columns can be
131411  ** considered to match an ORDER BY term. */
131412  if( (eOp & eqOpMask)!=0 ){
131413  if( eOp & WO_ISNULL ){
131414  testcase( isOrderDistinct );
131415  isOrderDistinct = 0;
131416  }
131417  continue;
131418  }else if( ALWAYS(eOp & WO_IN) ){
131419  /* ALWAYS() justification: eOp is an equality operator due to the
131420  ** j<pLoop->u.btree.nEq constraint above. Any equality other
131421  ** than WO_IN is captured by the previous "if". So this one
131422  ** always has to be WO_IN. */
131423  Expr *pX = pLoop->aLTerm[j]->pExpr;
131424  for(i=j+1; i<pLoop->u.btree.nEq; i++){
131425  if( pLoop->aLTerm[i]->pExpr==pX ){
131426  assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
131427  bOnce = 0;
131428  break;
131429  }
131430  }
131431  }
131432  }
131433 
131434  /* Get the column number in the table (iColumn) and sort order
131435  ** (revIdx) for the j-th column of the index.
131436  */
131437  if( pIndex ){
131438  iColumn = pIndex->aiColumn[j];
131439  revIdx = pIndex->aSortOrder[j];
131440  if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
131441  }else{
131442  iColumn = XN_ROWID;
131443  revIdx = 0;
131444  }
131445 
131446  /* An unconstrained column that might be NULL means that this
131447  ** WhereLoop is not well-ordered
131448  */
131449  if( isOrderDistinct
131450  && iColumn>=0
131451  && j>=pLoop->u.btree.nEq
131452  && pIndex->pTable->aCol[iColumn].notNull==0
131453  ){
131454  isOrderDistinct = 0;
131455  }
131456 
131457  /* Find the ORDER BY term that corresponds to the j-th column
131458  ** of the index and mark that ORDER BY term off
131459  */
131460  isMatch = 0;
131461  for(i=0; bOnce && i<nOrderBy; i++){
131462  if( MASKBIT(i) & obSat ) continue;
131463  pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
131464  testcase( wctrlFlags & WHERE_GROUPBY );
131465  testcase( wctrlFlags & WHERE_DISTINCTBY );
131466  if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
131467  if( iColumn>=(-1) ){
131468  if( pOBExpr->op!=TK_COLUMN ) continue;
131469  if( pOBExpr->iTable!=iCur ) continue;
131470  if( pOBExpr->iColumn!=iColumn ) continue;
131471  }else{
131472  if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
131473  continue;
131474  }
131475  }
131476  if( iColumn>=0 ){
131477  pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
131478  if( !pColl ) pColl = db->pDfltColl;
131479  if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
131480  }
131481  isMatch = 1;
131482  break;
131483  }
131484  if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
131485  /* Make sure the sort order is compatible in an ORDER BY clause.
131486  ** Sort order is irrelevant for a GROUP BY clause. */
131487  if( revSet ){
131488  if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
131489  }else{
131490  rev = revIdx ^ pOrderBy->a[i].sortOrder;
131491  if( rev ) *pRevMask |= MASKBIT(iLoop);
131492  revSet = 1;
131493  }
131494  }
131495  if( isMatch ){
131496  if( iColumn==XN_ROWID ){
131497  testcase( distinctColumns==0 );
131498  distinctColumns = 1;
131499  }
131500  obSat |= MASKBIT(i);
131501  }else{
131502  /* No match found */
131503  if( j==0 || j<nKeyCol ){
131504  testcase( isOrderDistinct!=0 );
131505  isOrderDistinct = 0;
131506  }
131507  break;
131508  }
131509  } /* end Loop over all index columns */
131510  if( distinctColumns ){
131511  testcase( isOrderDistinct==0 );
131512  isOrderDistinct = 1;
131513  }
131514  } /* end-if not one-row */
131515 
131516  /* Mark off any other ORDER BY terms that reference pLoop */
131517  if( isOrderDistinct ){
131518  orderDistinctMask |= pLoop->maskSelf;
131519  for(i=0; i<nOrderBy; i++){
131520  Expr *p;
131521  Bitmask mTerm;
131522  if( MASKBIT(i) & obSat ) continue;
131523  p = pOrderBy->a[i].pExpr;
131524  mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
131525  if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
131526  if( (mTerm&~orderDistinctMask)==0 ){
131527  obSat |= MASKBIT(i);
131528  }
131529  }
131530  }
131531  } /* End the loop over all WhereLoops from outer-most down to inner-most */
131532  if( obSat==obDone ) return (i8)nOrderBy;
131533  if( !isOrderDistinct ){
131534  for(i=nOrderBy-1; i>0; i--){
131535  Bitmask m = MASKBIT(i) - 1;
131536  if( (obSat&m)==m ) return i;
131537  }
131538  return 0;
131539  }
131540  return -1;
131541 }
131542 
131543 
131544 /*
131545 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
131546 ** the planner assumes that the specified pOrderBy list is actually a GROUP
131547 ** BY clause - and so any order that groups rows as required satisfies the
131548 ** request.
131549 **
131550 ** Normally, in this case it is not possible for the caller to determine
131551 ** whether or not the rows are really being delivered in sorted order, or
131552 ** just in some other order that provides the required grouping. However,
131553 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
131554 ** this function may be called on the returned WhereInfo object. It returns
131555 ** true if the rows really will be sorted in the specified order, or false
131556 ** otherwise.
131557 **
131558 ** For example, assuming:
131559 **
131560 ** CREATE INDEX i1 ON t1(x, Y);
131561 **
131562 ** then
131563 **
131564 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
131565 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
131566 */
131567 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
131568  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
131569  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
131570  return pWInfo->sorted;
131571 }
131572 
131573 #ifdef WHERETRACE_ENABLED
131574 /* For debugging use only: */
131575 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
131576  static char zName[65];
131577  int i;
131578  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
131579  if( pLast ) zName[i++] = pLast->cId;
131580  zName[i] = 0;
131581  return zName;
131582 }
131583 #endif
131584 
131585 /*
131586 ** Return the cost of sorting nRow rows, assuming that the keys have
131587 ** nOrderby columns and that the first nSorted columns are already in
131588 ** order.
131589 */
131590 static LogEst whereSortingCost(
131591  WhereInfo *pWInfo,
131592  LogEst nRow,
131593  int nOrderBy,
131594  int nSorted
131595 ){
131596  /* TUNING: Estimated cost of a full external sort, where N is
131597  ** the number of rows to sort is:
131598  **
131599  ** cost = (3.0 * N * log(N)).
131600  **
131601  ** Or, if the order-by clause has X terms but only the last Y
131602  ** terms are out of order, then block-sorting will reduce the
131603  ** sorting cost to:
131604  **
131605  ** cost = (3.0 * N * log(N)) * (Y/X)
131606  **
131607  ** The (Y/X) term is implemented using stack variable rScale
131608  ** below. */
131609  LogEst rScale, rSortCost;
131610  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
131611  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
131612  rSortCost = nRow + rScale + 16;
131613 
131614  /* Multiple by log(M) where M is the number of output rows.
131615  ** Use the LIMIT for M if it is smaller */
131616  if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
131617  nRow = pWInfo->iLimit;
131618  }
131619  rSortCost += estLog(nRow);
131620  return rSortCost;
131621 }
131622 
131623 /*
131624 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
131625 ** attempts to find the lowest cost path that visits each WhereLoop
131626 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
131627 **
131628 ** Assume that the total number of output rows that will need to be sorted
131629 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
131630 ** costs if nRowEst==0.
131631 **
131632 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
131633 ** error occurs.
131634 */
131635 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
131636  int mxChoice; /* Maximum number of simultaneous paths tracked */
131637  int nLoop; /* Number of terms in the join */
131638  Parse *pParse; /* Parsing context */
131639  sqlite3 *db; /* The database connection */
131640  int iLoop; /* Loop counter over the terms of the join */
131641  int ii, jj; /* Loop counters */
131642  int mxI = 0; /* Index of next entry to replace */
131643  int nOrderBy; /* Number of ORDER BY clause terms */
131644  LogEst mxCost = 0; /* Maximum cost of a set of paths */
131645  LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
131646  int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
131647  WherePath *aFrom; /* All nFrom paths at the previous level */
131648  WherePath *aTo; /* The nTo best paths at the current level */
131649  WherePath *pFrom; /* An element of aFrom[] that we are working on */
131650  WherePath *pTo; /* An element of aTo[] that we are working on */
131651  WhereLoop *pWLoop; /* One of the WhereLoop objects */
131652  WhereLoop **pX; /* Used to divy up the pSpace memory */
131653  LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
131654  char *pSpace; /* Temporary memory used by this routine */
131655  int nSpace; /* Bytes of space allocated at pSpace */
131656 
131657  pParse = pWInfo->pParse;
131658  db = pParse->db;
131659  nLoop = pWInfo->nLevel;
131660  /* TUNING: For simple queries, only the best path is tracked.
131661  ** For 2-way joins, the 5 best paths are followed.
131662  ** For joins of 3 or more tables, track the 10 best paths */
131663  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
131664  assert( nLoop<=pWInfo->pTabList->nSrc );
131665  WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
131666 
131667  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
131668  ** case the purpose of this call is to estimate the number of rows returned
131669  ** by the overall query. Once this estimate has been obtained, the caller
131670  ** will invoke this function a second time, passing the estimate as the
131671  ** nRowEst parameter. */
131672  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
131673  nOrderBy = 0;
131674  }else{
131675  nOrderBy = pWInfo->pOrderBy->nExpr;
131676  }
131677 
131678  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
131679  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
131680  nSpace += sizeof(LogEst) * nOrderBy;
131681  pSpace = sqlite3DbMallocRawNN(db, nSpace);
131682  if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
131683  aTo = (WherePath*)pSpace;
131684  aFrom = aTo+mxChoice;
131685  memset(aFrom, 0, sizeof(aFrom[0]));
131686  pX = (WhereLoop**)(aFrom+mxChoice);
131687  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
131688  pFrom->aLoop = pX;
131689  }
131690  if( nOrderBy ){
131691  /* If there is an ORDER BY clause and it is not being ignored, set up
131692  ** space for the aSortCost[] array. Each element of the aSortCost array
131693  ** is either zero - meaning it has not yet been initialized - or the
131694  ** cost of sorting nRowEst rows of data where the first X terms of
131695  ** the ORDER BY clause are already in order, where X is the array
131696  ** index. */
131697  aSortCost = (LogEst*)pX;
131698  memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
131699  }
131700  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
131701  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
131702 
131703  /* Seed the search with a single WherePath containing zero WhereLoops.
131704  **
131705  ** TUNING: Do not let the number of iterations go above 28. If the cost
131706  ** of computing an automatic index is not paid back within the first 28
131707  ** rows, then do not use the automatic index. */
131708  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
131709  nFrom = 1;
131710  assert( aFrom[0].isOrdered==0 );
131711  if( nOrderBy ){
131712  /* If nLoop is zero, then there are no FROM terms in the query. Since
131713  ** in this case the query may return a maximum of one row, the results
131714  ** are already in the requested order. Set isOrdered to nOrderBy to
131715  ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
131716  ** -1, indicating that the result set may or may not be ordered,
131717  ** depending on the loops added to the current plan. */
131718  aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
131719  }
131720 
131721  /* Compute successively longer WherePaths using the previous generation
131722  ** of WherePaths as the basis for the next. Keep track of the mxChoice
131723  ** best paths at each generation */
131724  for(iLoop=0; iLoop<nLoop; iLoop++){
131725  nTo = 0;
131726  for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
131727  for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
131728  LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
131729  LogEst rCost; /* Cost of path (pFrom+pWLoop) */
131730  LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
131731  i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
131732  Bitmask maskNew; /* Mask of src visited by (..) */
131733  Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
131734 
131735  if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
131736  if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
131737  if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
131738  /* Do not use an automatic index if the this loop is expected
131739  ** to run less than 2 times. */
131740  assert( 10==sqlite3LogEst(2) );
131741  continue;
131742  }
131743  /* At this point, pWLoop is a candidate to be the next loop.
131744  ** Compute its cost */
131745  rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
131746  rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
131747  nOut = pFrom->nRow + pWLoop->nOut;
131748  maskNew = pFrom->maskLoop | pWLoop->maskSelf;
131749  if( isOrdered<0 ){
131750  isOrdered = wherePathSatisfiesOrderBy(pWInfo,
131751  pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
131752  iLoop, pWLoop, &revMask);
131753  }else{
131754  revMask = pFrom->revLoop;
131755  }
131756  if( isOrdered>=0 && isOrdered<nOrderBy ){
131757  if( aSortCost[isOrdered]==0 ){
131758  aSortCost[isOrdered] = whereSortingCost(
131759  pWInfo, nRowEst, nOrderBy, isOrdered
131760  );
131761  }
131762  rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
131763 
131764  WHERETRACE(0x002,
131765  ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
131766  aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
131767  rUnsorted, rCost));
131768  }else{
131769  rCost = rUnsorted;
131770  }
131771 
131772  /* Check to see if pWLoop should be added to the set of
131773  ** mxChoice best-so-far paths.
131774  **
131775  ** First look for an existing path among best-so-far paths
131776  ** that covers the same set of loops and has the same isOrdered
131777  ** setting as the current path candidate.
131778  **
131779  ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
131780  ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
131781  ** of legal values for isOrdered, -1..64.
131782  */
131783  for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
131784  if( pTo->maskLoop==maskNew
131785  && ((pTo->isOrdered^isOrdered)&0x80)==0
131786  ){
131787  testcase( jj==nTo-1 );
131788  break;
131789  }
131790  }
131791  if( jj>=nTo ){
131792  /* None of the existing best-so-far paths match the candidate. */
131793  if( nTo>=mxChoice
131794  && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
131795  ){
131796  /* The current candidate is no better than any of the mxChoice
131797  ** paths currently in the best-so-far buffer. So discard
131798  ** this candidate as not viable. */
131799 #ifdef WHERETRACE_ENABLED /* 0x4 */
131800  if( sqlite3WhereTrace&0x4 ){
131801  sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
131802  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
131803  isOrdered>=0 ? isOrdered+'0' : '?');
131804  }
131805 #endif
131806  continue;
131807  }
131808  /* If we reach this points it means that the new candidate path
131809  ** needs to be added to the set of best-so-far paths. */
131810  if( nTo<mxChoice ){
131811  /* Increase the size of the aTo set by one */
131812  jj = nTo++;
131813  }else{
131814  /* New path replaces the prior worst to keep count below mxChoice */
131815  jj = mxI;
131816  }
131817  pTo = &aTo[jj];
131818 #ifdef WHERETRACE_ENABLED /* 0x4 */
131819  if( sqlite3WhereTrace&0x4 ){
131820  sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
131821  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
131822  isOrdered>=0 ? isOrdered+'0' : '?');
131823  }
131824 #endif
131825  }else{
131826  /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
131827  ** same set of loops and has the sam isOrdered setting as the
131828  ** candidate path. Check to see if the candidate should replace
131829  ** pTo or if the candidate should be skipped */
131830  if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
131831 #ifdef WHERETRACE_ENABLED /* 0x4 */
131832  if( sqlite3WhereTrace&0x4 ){
131833  sqlite3DebugPrintf(
131834  "Skip %s cost=%-3d,%3d order=%c",
131835  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
131836  isOrdered>=0 ? isOrdered+'0' : '?');
131837  sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
131838  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
131839  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
131840  }
131841 #endif
131842  /* Discard the candidate path from further consideration */
131843  testcase( pTo->rCost==rCost );
131844  continue;
131845  }
131846  testcase( pTo->rCost==rCost+1 );
131847  /* Control reaches here if the candidate path is better than the
131848  ** pTo path. Replace pTo with the candidate. */
131849 #ifdef WHERETRACE_ENABLED /* 0x4 */
131850  if( sqlite3WhereTrace&0x4 ){
131851  sqlite3DebugPrintf(
131852  "Update %s cost=%-3d,%3d order=%c",
131853  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
131854  isOrdered>=0 ? isOrdered+'0' : '?');
131855  sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
131856  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
131857  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
131858  }
131859 #endif
131860  }
131861  /* pWLoop is a winner. Add it to the set of best so far */
131862  pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
131863  pTo->revLoop = revMask;
131864  pTo->nRow = nOut;
131865  pTo->rCost = rCost;
131866  pTo->rUnsorted = rUnsorted;
131867  pTo->isOrdered = isOrdered;
131868  memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
131869  pTo->aLoop[iLoop] = pWLoop;
131870  if( nTo>=mxChoice ){
131871  mxI = 0;
131872  mxCost = aTo[0].rCost;
131873  mxUnsorted = aTo[0].nRow;
131874  for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
131875  if( pTo->rCost>mxCost
131876  || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
131877  ){
131878  mxCost = pTo->rCost;
131879  mxUnsorted = pTo->rUnsorted;
131880  mxI = jj;
131881  }
131882  }
131883  }
131884  }
131885  }
131886 
131887 #ifdef WHERETRACE_ENABLED /* >=2 */
131888  if( sqlite3WhereTrace & 0x02 ){
131889  sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
131890  for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
131891  sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
131892  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
131893  pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
131894  if( pTo->isOrdered>0 ){
131895  sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
131896  }else{
131897  sqlite3DebugPrintf("\n");
131898  }
131899  }
131900  }
131901 #endif
131902 
131903  /* Swap the roles of aFrom and aTo for the next generation */
131904  pFrom = aTo;
131905  aTo = aFrom;
131906  aFrom = pFrom;
131907  nFrom = nTo;
131908  }
131909 
131910  if( nFrom==0 ){
131911  sqlite3ErrorMsg(pParse, "no query solution");
131912  sqlite3DbFree(db, pSpace);
131913  return SQLITE_ERROR;
131914  }
131915 
131916  /* Find the lowest cost path. pFrom will be left pointing to that path */
131917  pFrom = aFrom;
131918  for(ii=1; ii<nFrom; ii++){
131919  if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
131920  }
131921  assert( pWInfo->nLevel==nLoop );
131922  /* Load the lowest cost path into pWInfo */
131923  for(iLoop=0; iLoop<nLoop; iLoop++){
131924  WhereLevel *pLevel = pWInfo->a + iLoop;
131925  pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
131926  pLevel->iFrom = pWLoop->iTab;
131927  pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
131928  }
131929  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
131930  && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
131931  && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
131932  && nRowEst
131933  ){
131934  Bitmask notUsed;
131935  int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom,
131936  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
131937  if( rc==pWInfo->pDistinctSet->nExpr ){
131938  pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
131939  }
131940  }
131941  if( pWInfo->pOrderBy ){
131942  if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
131943  if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
131944  pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
131945  }
131946  }else{
131947  pWInfo->nOBSat = pFrom->isOrdered;
131948  pWInfo->revMask = pFrom->revLoop;
131949  if( pWInfo->nOBSat<=0 ){
131950  pWInfo->nOBSat = 0;
131951  if( nLoop>0 ){
131952  u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
131953  if( (wsFlags & WHERE_ONEROW)==0
131954  && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
131955  ){
131956  Bitmask m = 0;
131957  int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
131958  WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
131959  testcase( wsFlags & WHERE_IPK );
131960  testcase( wsFlags & WHERE_COLUMN_IN );
131961  if( rc==pWInfo->pOrderBy->nExpr ){
131962  pWInfo->bOrderedInnerLoop = 1;
131963  pWInfo->revMask = m;
131964  }
131965  }
131966  }
131967  }
131968  }
131969  if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
131970  && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
131971  ){
131972  Bitmask revMask = 0;
131973  int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
131974  pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
131975  );
131976  assert( pWInfo->sorted==0 );
131977  if( nOrder==pWInfo->pOrderBy->nExpr ){
131978  pWInfo->sorted = 1;
131979  pWInfo->revMask = revMask;
131980  }
131981  }
131982  }
131983 
131984 
131985  pWInfo->nRowOut = pFrom->nRow;
131986 
131987  /* Free temporary memory and return success */
131988  sqlite3DbFree(db, pSpace);
131989  return SQLITE_OK;
131990 }
131991 
131992 /*
131993 ** Most queries use only a single table (they are not joins) and have
131994 ** simple == constraints against indexed fields. This routine attempts
131995 ** to plan those simple cases using much less ceremony than the
131996 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
131997 ** times for the common case.
131998 **
131999 ** Return non-zero on success, if this query can be handled by this
132000 ** no-frills query planner. Return zero if this query needs the
132001 ** general-purpose query planner.
132002 */
132003 static int whereShortCut(WhereLoopBuilder *pBuilder){
132004  WhereInfo *pWInfo;
132005  struct SrcList_item *pItem;
132006  WhereClause *pWC;
132007  WhereTerm *pTerm;
132008  WhereLoop *pLoop;
132009  int iCur;
132010  int j;
132011  Table *pTab;
132012  Index *pIdx;
132013 
132014  pWInfo = pBuilder->pWInfo;
132015  if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
132016  assert( pWInfo->pTabList->nSrc>=1 );
132017  pItem = pWInfo->pTabList->a;
132018  pTab = pItem->pTab;
132019  if( IsVirtual(pTab) ) return 0;
132020  if( pItem->fg.isIndexedBy ) return 0;
132021  iCur = pItem->iCursor;
132022  pWC = &pWInfo->sWC;
132023  pLoop = pBuilder->pNew;
132024  pLoop->wsFlags = 0;
132025  pLoop->nSkip = 0;
132026  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
132027  if( pTerm ){
132028  testcase( pTerm->eOperator & WO_IS );
132029  pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
132030  pLoop->aLTerm[0] = pTerm;
132031  pLoop->nLTerm = 1;
132032  pLoop->u.btree.nEq = 1;
132033  /* TUNING: Cost of a rowid lookup is 10 */
132034  pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
132035  }else{
132036  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
132037  int opMask;
132038  assert( pLoop->aLTermSpace==pLoop->aLTerm );
132039  if( !IsUniqueIndex(pIdx)
132040  || pIdx->pPartIdxWhere!=0
132041  || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
132042  ) continue;
132043  opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
132044  for(j=0; j<pIdx->nKeyCol; j++){
132045  pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
132046  if( pTerm==0 ) break;
132047  testcase( pTerm->eOperator & WO_IS );
132048  pLoop->aLTerm[j] = pTerm;
132049  }
132050  if( j!=pIdx->nKeyCol ) continue;
132051  pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
132052  if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
132053  pLoop->wsFlags |= WHERE_IDX_ONLY;
132054  }
132055  pLoop->nLTerm = j;
132056  pLoop->u.btree.nEq = j;
132057  pLoop->u.btree.pIndex = pIdx;
132058  /* TUNING: Cost of a unique index lookup is 15 */
132059  pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
132060  break;
132061  }
132062  }
132063  if( pLoop->wsFlags ){
132064  pLoop->nOut = (LogEst)1;
132065  pWInfo->a[0].pWLoop = pLoop;
132066  pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
132067  pWInfo->a[0].iTabCur = iCur;
132068  pWInfo->nRowOut = 1;
132069  if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
132070  if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
132071  pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
132072  }
132073 #ifdef SQLITE_DEBUG
132074  pLoop->cId = '0';
132075 #endif
132076  return 1;
132077  }
132078  return 0;
132079 }
132080 
132081 /*
132082 ** Generate the beginning of the loop used for WHERE clause processing.
132083 ** The return value is a pointer to an opaque structure that contains
132084 ** information needed to terminate the loop. Later, the calling routine
132085 ** should invoke sqlite3WhereEnd() with the return value of this function
132086 ** in order to complete the WHERE clause processing.
132087 **
132088 ** If an error occurs, this routine returns NULL.
132089 **
132090 ** The basic idea is to do a nested loop, one loop for each table in
132091 ** the FROM clause of a select. (INSERT and UPDATE statements are the
132092 ** same as a SELECT with only a single table in the FROM clause.) For
132093 ** example, if the SQL is this:
132094 **
132095 ** SELECT * FROM t1, t2, t3 WHERE ...;
132096 **
132097 ** Then the code generated is conceptually like the following:
132098 **
132099 ** foreach row1 in t1 do \ Code generated
132100 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
132101 ** foreach row3 in t3 do /
132102 ** ...
132103 ** end \ Code generated
132104 ** end |-- by sqlite3WhereEnd()
132105 ** end /
132106 **
132107 ** Note that the loops might not be nested in the order in which they
132108 ** appear in the FROM clause if a different order is better able to make
132109 ** use of indices. Note also that when the IN operator appears in
132110 ** the WHERE clause, it might result in additional nested loops for
132111 ** scanning through all values on the right-hand side of the IN.
132112 **
132113 ** There are Btree cursors associated with each table. t1 uses cursor
132114 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
132115 ** And so forth. This routine generates code to open those VDBE cursors
132116 ** and sqlite3WhereEnd() generates the code to close them.
132117 **
132118 ** The code that sqlite3WhereBegin() generates leaves the cursors named
132119 ** in pTabList pointing at their appropriate entries. The [...] code
132120 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
132121 ** data from the various tables of the loop.
132122 **
132123 ** If the WHERE clause is empty, the foreach loops must each scan their
132124 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
132125 ** the tables have indices and there are terms in the WHERE clause that
132126 ** refer to those indices, a complete table scan can be avoided and the
132127 ** code will run much faster. Most of the work of this routine is checking
132128 ** to see if there are indices that can be used to speed up the loop.
132129 **
132130 ** Terms of the WHERE clause are also used to limit which rows actually
132131 ** make it to the "..." in the middle of the loop. After each "foreach",
132132 ** terms of the WHERE clause that use only terms in that loop and outer
132133 ** loops are evaluated and if false a jump is made around all subsequent
132134 ** inner loops (or around the "..." if the test occurs within the inner-
132135 ** most loop)
132136 **
132137 ** OUTER JOINS
132138 **
132139 ** An outer join of tables t1 and t2 is conceptally coded as follows:
132140 **
132141 ** foreach row1 in t1 do
132142 ** flag = 0
132143 ** foreach row2 in t2 do
132144 ** start:
132145 ** ...
132146 ** flag = 1
132147 ** end
132148 ** if flag==0 then
132149 ** move the row2 cursor to a null row
132150 ** goto start
132151 ** fi
132152 ** end
132153 **
132154 ** ORDER BY CLAUSE PROCESSING
132155 **
132156 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
132157 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
132158 ** if there is one. If there is no ORDER BY clause or if this routine
132159 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
132160 **
132161 ** The iIdxCur parameter is the cursor number of an index. If
132162 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
132163 ** to use for OR clause processing. The WHERE clause should use this
132164 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
132165 ** the first cursor in an array of cursors for all indices. iIdxCur should
132166 ** be used to compute the appropriate cursor depending on which index is
132167 ** used.
132168 */
132169 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
132170  Parse *pParse, /* The parser context */
132171  SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
132172  Expr *pWhere, /* The WHERE clause */
132173  ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
132174  ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */
132175  u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
132176  int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
132177  ** If WHERE_USE_LIMIT, then the limit amount */
132178 ){
132179  int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
132180  int nTabList; /* Number of elements in pTabList */
132181  WhereInfo *pWInfo; /* Will become the return value of this function */
132182  Vdbe *v = pParse->pVdbe; /* The virtual database engine */
132183  Bitmask notReady; /* Cursors that are not yet positioned */
132184  WhereLoopBuilder sWLB; /* The WhereLoop builder */
132185  WhereMaskSet *pMaskSet; /* The expression mask set */
132186  WhereLevel *pLevel; /* A single level in pWInfo->a[] */
132187  WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
132188  int ii; /* Loop counter */
132189  sqlite3 *db; /* Database connection */
132190  int rc; /* Return code */
132191  u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
132192 
132193  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
132194  (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
132195  && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
132196  ));
132197 
132198  /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
132199  assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
132200  || (wctrlFlags & WHERE_USE_LIMIT)==0 );
132201 
132202  /* Variable initialization */
132203  db = pParse->db;
132204  memset(&sWLB, 0, sizeof(sWLB));
132205 
132206  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
132207  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
132208  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
132209  sWLB.pOrderBy = pOrderBy;
132210 
132211  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
132212  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
132213  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
132214  wctrlFlags &= ~WHERE_WANT_DISTINCT;
132215  }
132216 
132217  /* The number of tables in the FROM clause is limited by the number of
132218  ** bits in a Bitmask
132219  */
132220  testcase( pTabList->nSrc==BMS );
132221  if( pTabList->nSrc>BMS ){
132222  sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
132223  return 0;
132224  }
132225 
132226  /* This function normally generates a nested loop for all tables in
132227  ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
132228  ** only generate code for the first table in pTabList and assume that
132229  ** any cursors associated with subsequent tables are uninitialized.
132230  */
132231  nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
132232 
132233  /* Allocate and initialize the WhereInfo structure that will become the
132234  ** return value. A single allocation is used to store the WhereInfo
132235  ** struct, the contents of WhereInfo.a[], the WhereClause structure
132236  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
132237  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
132238  ** some architectures. Hence the ROUND8() below.
132239  */
132240  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
132241  pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
132242  if( db->mallocFailed ){
132243  sqlite3DbFree(db, pWInfo);
132244  pWInfo = 0;
132245  goto whereBeginError;
132246  }
132247  pWInfo->pParse = pParse;
132248  pWInfo->pTabList = pTabList;
132249  pWInfo->pOrderBy = pOrderBy;
132250  pWInfo->pDistinctSet = pDistinctSet;
132251  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
132252  pWInfo->nLevel = nTabList;
132253  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
132254  pWInfo->wctrlFlags = wctrlFlags;
132255  pWInfo->iLimit = iAuxArg;
132256  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
132257  memset(&pWInfo->nOBSat, 0,
132258  offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
132259  memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
132260  assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
132261  pMaskSet = &pWInfo->sMaskSet;
132262  sWLB.pWInfo = pWInfo;
132263  sWLB.pWC = &pWInfo->sWC;
132264  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
132265  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
132266  whereLoopInit(sWLB.pNew);
132267 #ifdef SQLITE_DEBUG
132268  sWLB.pNew->cId = '*';
132269 #endif
132270 
132271  /* Split the WHERE clause into separate subexpressions where each
132272  ** subexpression is separated by an AND operator.
132273  */
132274  initMaskSet(pMaskSet);
132275  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
132276  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
132277 
132278  /* Special case: a WHERE clause that is constant. Evaluate the
132279  ** expression and either jump over all of the code or fall thru.
132280  */
132281  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
132282  if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
132283  sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
132284  SQLITE_JUMPIFNULL);
132285  sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
132286  }
132287  }
132288 
132289  /* Special case: No FROM clause
132290  */
132291  if( nTabList==0 ){
132292  if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
132293  if( wctrlFlags & WHERE_WANT_DISTINCT ){
132294  pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
132295  }
132296  }
132297 
132298  /* Assign a bit from the bitmask to every term in the FROM clause.
132299  **
132300  ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
132301  **
132302  ** The rule of the previous sentence ensures thta if X is the bitmask for
132303  ** a table T, then X-1 is the bitmask for all other tables to the left of T.
132304  ** Knowing the bitmask for all tables to the left of a left join is
132305  ** important. Ticket #3015.
132306  **
132307  ** Note that bitmasks are created for all pTabList->nSrc tables in
132308  ** pTabList, not just the first nTabList tables. nTabList is normally
132309  ** equal to pTabList->nSrc but might be shortened to 1 if the
132310  ** WHERE_OR_SUBCLAUSE flag is set.
132311  */
132312  for(ii=0; ii<pTabList->nSrc; ii++){
132313  createMask(pMaskSet, pTabList->a[ii].iCursor);
132314  sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
132315  }
132316 #ifdef SQLITE_DEBUG
132317  for(ii=0; ii<pTabList->nSrc; ii++){
132318  Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
132319  assert( m==MASKBIT(ii) );
132320  }
132321 #endif
132322 
132323  /* Analyze all of the subexpressions. */
132324  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
132325  if( db->mallocFailed ) goto whereBeginError;
132326 
132327  if( wctrlFlags & WHERE_WANT_DISTINCT ){
132328  if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){
132329  /* The DISTINCT marking is pointless. Ignore it. */
132330  pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
132331  }else if( pOrderBy==0 ){
132332  /* Try to ORDER BY the result set to make distinct processing easier */
132333  pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
132334  pWInfo->pOrderBy = pDistinctSet;
132335  }
132336  }
132337 
132338  /* Construct the WhereLoop objects */
132339 #if defined(WHERETRACE_ENABLED)
132340  if( sqlite3WhereTrace & 0xffff ){
132341  sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
132342  if( wctrlFlags & WHERE_USE_LIMIT ){
132343  sqlite3DebugPrintf(", limit: %d", iAuxArg);
132344  }
132345  sqlite3DebugPrintf(")\n");
132346  }
132347  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
132348  sqlite3WhereClausePrint(sWLB.pWC);
132349  }
132350 #endif
132351 
132352  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
132353  rc = whereLoopAddAll(&sWLB);
132354  if( rc ) goto whereBeginError;
132355 
132356 #ifdef WHERETRACE_ENABLED
132357  if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
132358  WhereLoop *p;
132359  int i;
132360  static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
132361  "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
132362  for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
132363  p->cId = zLabel[i%sizeof(zLabel)];
132364  whereLoopPrint(p, sWLB.pWC);
132365  }
132366  }
132367 #endif
132368 
132369  wherePathSolver(pWInfo, 0);
132370  if( db->mallocFailed ) goto whereBeginError;
132371  if( pWInfo->pOrderBy ){
132372  wherePathSolver(pWInfo, pWInfo->nRowOut+1);
132373  if( db->mallocFailed ) goto whereBeginError;
132374  }
132375  }
132376  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
132377  pWInfo->revMask = ALLBITS;
132378  }
132379  if( pParse->nErr || NEVER(db->mallocFailed) ){
132380  goto whereBeginError;
132381  }
132382 #ifdef WHERETRACE_ENABLED
132383  if( sqlite3WhereTrace ){
132384  sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
132385  if( pWInfo->nOBSat>0 ){
132386  sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
132387  }
132388  switch( pWInfo->eDistinct ){
132389  case WHERE_DISTINCT_UNIQUE: {
132390  sqlite3DebugPrintf(" DISTINCT=unique");
132391  break;
132392  }
132393  case WHERE_DISTINCT_ORDERED: {
132394  sqlite3DebugPrintf(" DISTINCT=ordered");
132395  break;
132396  }
132397  case WHERE_DISTINCT_UNORDERED: {
132398  sqlite3DebugPrintf(" DISTINCT=unordered");
132399  break;
132400  }
132401  }
132402  sqlite3DebugPrintf("\n");
132403  for(ii=0; ii<pWInfo->nLevel; ii++){
132404  whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
132405  }
132406  }
132407 #endif
132408  /* Attempt to omit tables from the join that do not effect the result */
132409  if( pWInfo->nLevel>=2
132410  && pDistinctSet!=0
132411  && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
132412  ){
132413  Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet);
132414  if( sWLB.pOrderBy ){
132415  tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
132416  }
132417  while( pWInfo->nLevel>=2 ){
132418  WhereTerm *pTerm, *pEnd;
132419  pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
132420  if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
132421  if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
132422  && (pLoop->wsFlags & WHERE_ONEROW)==0
132423  ){
132424  break;
132425  }
132426  if( (tabUsed & pLoop->maskSelf)!=0 ) break;
132427  pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
132428  for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
132429  if( (pTerm->prereqAll & pLoop->maskSelf)!=0
132430  && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
132431  ){
132432  break;
132433  }
132434  }
132435  if( pTerm<pEnd ) break;
132436  WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
132437  pWInfo->nLevel--;
132438  nTabList--;
132439  }
132440  }
132441  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
132442  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
132443 
132444  /* If the caller is an UPDATE or DELETE statement that is requesting
132445  ** to use a one-pass algorithm, determine if this is appropriate.
132446  */
132447  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
132448  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
132449  int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
132450  int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
132451  if( bOnerow
132452  || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
132453  && 0==(wsFlags & WHERE_VIRTUALTABLE))
132454  ){
132455  pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
132456  if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
132457  if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
132458  bFordelete = OPFLAG_FORDELETE;
132459  }
132460  pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
132461  }
132462  }
132463  }
132464 
132465  /* Open all tables in the pTabList and any indices selected for
132466  ** searching those tables.
132467  */
132468  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
132469  Table *pTab; /* Table to open */
132470  int iDb; /* Index of database containing table/index */
132471  struct SrcList_item *pTabItem;
132472 
132473  pTabItem = &pTabList->a[pLevel->iFrom];
132474  pTab = pTabItem->pTab;
132475  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
132476  pLoop = pLevel->pWLoop;
132477  if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
132478  /* Do nothing */
132479  }else
132480 #ifndef SQLITE_OMIT_VIRTUALTABLE
132481  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
132482  const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
132483  int iCur = pTabItem->iCursor;
132484  sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
132485  }else if( IsVirtual(pTab) ){
132486  /* noop */
132487  }else
132488 #endif
132489  if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
132490  && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
132491  int op = OP_OpenRead;
132492  if( pWInfo->eOnePass!=ONEPASS_OFF ){
132493  op = OP_OpenWrite;
132494  pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
132495  };
132496  sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
132497  assert( pTabItem->iCursor==pLevel->iTabCur );
132498  testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
132499  testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
132500  if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
132501  Bitmask b = pTabItem->colUsed;
132502  int n = 0;
132503  for(; b; b=b>>1, n++){}
132504  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
132505  assert( n<=pTab->nCol );
132506  }
132507 #ifdef SQLITE_ENABLE_CURSOR_HINTS
132508  if( pLoop->u.btree.pIndex!=0 ){
132509  sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
132510  }else
132511 #endif
132512  {
132513  sqlite3VdbeChangeP5(v, bFordelete);
132514  }
132515 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
132516  sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
132517  (const u8*)&pTabItem->colUsed, P4_INT64);
132518 #endif
132519  }else{
132520  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
132521  }
132522  if( pLoop->wsFlags & WHERE_INDEXED ){
132523  Index *pIx = pLoop->u.btree.pIndex;
132524  int iIndexCur;
132525  int op = OP_OpenRead;
132526  /* iAuxArg is always set if to a positive value if ONEPASS is possible */
132527  assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
132528  if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
132529  && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
132530  ){
132531  /* This is one term of an OR-optimization using the PRIMARY KEY of a
132532  ** WITHOUT ROWID table. No need for a separate index */
132533  iIndexCur = pLevel->iTabCur;
132534  op = 0;
132535  }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
132536  Index *pJ = pTabItem->pTab->pIndex;
132537  iIndexCur = iAuxArg;
132538  assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
132539  while( ALWAYS(pJ) && pJ!=pIx ){
132540  iIndexCur++;
132541  pJ = pJ->pNext;
132542  }
132543  op = OP_OpenWrite;
132544  pWInfo->aiCurOnePass[1] = iIndexCur;
132545  }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
132546  iIndexCur = iAuxArg;
132547  op = OP_ReopenIdx;
132548  }else{
132549  iIndexCur = pParse->nTab++;
132550  }
132551  pLevel->iIdxCur = iIndexCur;
132552  assert( pIx->pSchema==pTab->pSchema );
132553  assert( iIndexCur>=0 );
132554  if( op ){
132555  sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
132556  sqlite3VdbeSetP4KeyInfo(pParse, pIx);
132557  if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
132558  && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
132559  && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
132560  ){
132561  sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
132562  }
132563  VdbeComment((v, "%s", pIx->zName));
132564 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
132565  {
132566  u64 colUsed = 0;
132567  int ii, jj;
132568  for(ii=0; ii<pIx->nColumn; ii++){
132569  jj = pIx->aiColumn[ii];
132570  if( jj<0 ) continue;
132571  if( jj>63 ) jj = 63;
132572  if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
132573  colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
132574  }
132575  sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
132576  (u8*)&colUsed, P4_INT64);
132577  }
132578 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
132579  }
132580  }
132581  if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
132582  }
132583  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
132584  if( db->mallocFailed ) goto whereBeginError;
132585 
132586  /* Generate the code to do the search. Each iteration of the for
132587  ** loop below generates code for a single nested loop of the VM
132588  ** program.
132589  */
132590  notReady = ~(Bitmask)0;
132591  for(ii=0; ii<nTabList; ii++){
132592  int addrExplain;
132593  int wsFlags;
132594  pLevel = &pWInfo->a[ii];
132595  wsFlags = pLevel->pWLoop->wsFlags;
132596 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
132597  if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
132598  constructAutomaticIndex(pParse, &pWInfo->sWC,
132599  &pTabList->a[pLevel->iFrom], notReady, pLevel);
132600  if( db->mallocFailed ) goto whereBeginError;
132601  }
132602 #endif
132603  addrExplain = sqlite3WhereExplainOneScan(
132604  pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
132605  );
132606  pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
132607  notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
132608  pWInfo->iContinue = pLevel->addrCont;
132609  if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
132610  sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
132611  }
132612  }
132613 
132614  /* Done. */
132615  VdbeModuleComment((v, "Begin WHERE-core"));
132616  return pWInfo;
132617 
132618  /* Jump here if malloc fails */
132619 whereBeginError:
132620  if( pWInfo ){
132621  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
132622  whereInfoFree(db, pWInfo);
132623  }
132624  return 0;
132625 }
132626 
132627 /*
132628 ** Generate the end of the WHERE loop. See comments on
132629 ** sqlite3WhereBegin() for additional information.
132630 */
132631 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
132632  Parse *pParse = pWInfo->pParse;
132633  Vdbe *v = pParse->pVdbe;
132634  int i;
132635  WhereLevel *pLevel;
132636  WhereLoop *pLoop;
132637  SrcList *pTabList = pWInfo->pTabList;
132638  sqlite3 *db = pParse->db;
132639 
132640  /* Generate loop termination code.
132641  */
132642  VdbeModuleComment((v, "End WHERE-core"));
132643  sqlite3ExprCacheClear(pParse);
132644  for(i=pWInfo->nLevel-1; i>=0; i--){
132645  int addr;
132646  pLevel = &pWInfo->a[i];
132647  pLoop = pLevel->pWLoop;
132648  sqlite3VdbeResolveLabel(v, pLevel->addrCont);
132649  if( pLevel->op!=OP_Noop ){
132650  sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
132651  sqlite3VdbeChangeP5(v, pLevel->p5);
132652  VdbeCoverage(v);
132653  VdbeCoverageIf(v, pLevel->op==OP_Next);
132654  VdbeCoverageIf(v, pLevel->op==OP_Prev);
132655  VdbeCoverageIf(v, pLevel->op==OP_VNext);
132656  }
132657  if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
132658  struct InLoop *pIn;
132659  int j;
132660  sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
132661  for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
132662  sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
132663  if( pIn->eEndLoopOp!=OP_Noop ){
132664  sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
132665  VdbeCoverage(v);
132666  VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
132667  VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
132668  }
132669  sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
132670  }
132671  }
132672  sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
132673  if( pLevel->addrSkip ){
132674  sqlite3VdbeGoto(v, pLevel->addrSkip);
132675  VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
132676  sqlite3VdbeJumpHere(v, pLevel->addrSkip);
132677  sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
132678  }
132679 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
132680  if( pLevel->addrLikeRep ){
132681  sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
132682  pLevel->addrLikeRep);
132683  VdbeCoverage(v);
132684  }
132685 #endif
132686  if( pLevel->iLeftJoin ){
132687  int ws = pLoop->wsFlags;
132688  addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
132689  assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
132690  if( (ws & WHERE_IDX_ONLY)==0 ){
132691  sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
132692  }
132693  if( (ws & WHERE_INDEXED)
132694  || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
132695  ){
132696  sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
132697  }
132698  if( pLevel->op==OP_Return ){
132699  sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
132700  }else{
132701  sqlite3VdbeGoto(v, pLevel->addrFirst);
132702  }
132703  sqlite3VdbeJumpHere(v, addr);
132704  }
132705  VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
132706  pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
132707  }
132708 
132709  /* The "break" point is here, just past the end of the outer loop.
132710  ** Set it.
132711  */
132712  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
132713 
132714  assert( pWInfo->nLevel<=pTabList->nSrc );
132715  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
132716  int k, last;
132717  VdbeOp *pOp;
132718  Index *pIdx = 0;
132719  struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
132720  Table *pTab = pTabItem->pTab;
132721  assert( pTab!=0 );
132722  pLoop = pLevel->pWLoop;
132723 
132724  /* For a co-routine, change all OP_Column references to the table of
132725  ** the co-routine into OP_Copy of result contained in a register.
132726  ** OP_Rowid becomes OP_Null.
132727  */
132728  if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
132729  translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
132730  pTabItem->regResult, 0);
132731  continue;
132732  }
132733 
132734  /* Close all of the cursors that were opened by sqlite3WhereBegin.
132735  ** Except, do not close cursors that will be reused by the OR optimization
132736  ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors
132737  ** created for the ONEPASS optimization.
132738  */
132739  if( (pTab->tabFlags & TF_Ephemeral)==0
132740  && pTab->pSelect==0
132741  && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
132742  ){
132743  int ws = pLoop->wsFlags;
132744  if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
132745  sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
132746  }
132747  if( (ws & WHERE_INDEXED)!=0
132748  && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
132749  && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
132750  ){
132751  sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
132752  }
132753  }
132754 
132755  /* If this scan uses an index, make VDBE code substitutions to read data
132756  ** from the index instead of from the table where possible. In some cases
132757  ** this optimization prevents the table from ever being read, which can
132758  ** yield a significant performance boost.
132759  **
132760  ** Calls to the code generator in between sqlite3WhereBegin and
132761  ** sqlite3WhereEnd will have created code that references the table
132762  ** directly. This loop scans all that code looking for opcodes
132763  ** that reference the table and converts them into opcodes that
132764  ** reference the index.
132765  */
132766  if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
132767  pIdx = pLoop->u.btree.pIndex;
132768  }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
132769  pIdx = pLevel->u.pCovidx;
132770  }
132771  if( pIdx
132772  && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
132773  && !db->mallocFailed
132774  ){
132775  last = sqlite3VdbeCurrentAddr(v);
132776  k = pLevel->addrBody;
132777  pOp = sqlite3VdbeGetOp(v, k);
132778  for(; k<last; k++, pOp++){
132779  if( pOp->p1!=pLevel->iTabCur ) continue;
132780  if( pOp->opcode==OP_Column ){
132781  int x = pOp->p2;
132782  assert( pIdx->pTable==pTab );
132783  if( !HasRowid(pTab) ){
132784  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
132785  x = pPk->aiColumn[x];
132786  assert( x>=0 );
132787  }
132788  x = sqlite3ColumnOfIndex(pIdx, x);
132789  if( x>=0 ){
132790  pOp->p2 = x;
132791  pOp->p1 = pLevel->iIdxCur;
132792  }
132793  assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
132794  }else if( pOp->opcode==OP_Rowid ){
132795  pOp->p1 = pLevel->iIdxCur;
132796  pOp->opcode = OP_IdxRowid;
132797  }
132798  }
132799  }
132800  }
132801 
132802  /* Final cleanup
132803  */
132804  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
132805  whereInfoFree(db, pWInfo);
132806  return;
132807 }
132808 
132809 /************** End of where.c ***********************************************/
132810 /************** Begin file parse.c *******************************************/
132811 /*
132812 ** 2000-05-29
132813 **
132814 ** The author disclaims copyright to this source code. In place of
132815 ** a legal notice, here is a blessing:
132816 **
132817 ** May you do good and not evil.
132818 ** May you find forgiveness for yourself and forgive others.
132819 ** May you share freely, never taking more than you give.
132820 **
132821 *************************************************************************
132822 ** Driver template for the LEMON parser generator.
132823 **
132824 ** The "lemon" program processes an LALR(1) input grammar file, then uses
132825 ** this template to construct a parser. The "lemon" program inserts text
132826 ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
132827 ** interstitial "-" characters) contained in this template is changed into
132828 ** the value of the %name directive from the grammar. Otherwise, the content
132829 ** of this template is copied straight through into the generate parser
132830 ** source file.
132831 **
132832 ** The following is the concatenation of all %include directives from the
132833 ** input grammar file:
132834 */
132835 /* #include <stdio.h> */
132836 /************ Begin %include sections from the grammar ************************/
132837 
132838 /* #include "sqliteInt.h" */
132839 
132840 /*
132841 ** Disable all error recovery processing in the parser push-down
132842 ** automaton.
132843 */
132844 #define YYNOERRORRECOVERY 1
132845 
132846 /*
132847 ** Make yytestcase() the same as testcase()
132848 */
132849 #define yytestcase(X) testcase(X)
132850 
132851 /*
132852 ** Indicate that sqlite3ParserFree() will never be called with a null
132853 ** pointer.
132854 */
132855 #define YYPARSEFREENEVERNULL 1
132856 
132857 /*
132858 ** Alternative datatype for the argument to the malloc() routine passed
132859 ** into sqlite3ParserAlloc(). The default is size_t.
132860 */
132861 #define YYMALLOCARGTYPE u64
132862 
132863 /*
132864 ** An instance of this structure holds information about the
132865 ** LIMIT clause of a SELECT statement.
132866 */
132867 struct LimitVal {
132868  Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
132869  Expr *pOffset; /* The OFFSET expression. NULL if there is none */
132870 };
132871 
132872 /*
132873 ** An instance of the following structure describes the event of a
132874 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
132875 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
132876 **
132877 ** UPDATE ON (a,b,c)
132878 **
132879 ** Then the "b" IdList records the list "a,b,c".
132880 */
132881 struct TrigEvent { int a; IdList * b; };
132882 
132883 /*
132884 ** Disable lookaside memory allocation for objects that might be
132885 ** shared across database connections.
132886 */
132887 static void disableLookaside(Parse *pParse){
132888  pParse->disableLookaside++;
132889  pParse->db->lookaside.bDisable++;
132890 }
132891 
132892 
132893  /*
132894  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
132895  ** all elements in the list. And make sure list length does not exceed
132896  ** SQLITE_LIMIT_COMPOUND_SELECT.
132897  */
132898  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
132899  if( p->pPrior ){
132900  Select *pNext = 0, *pLoop;
132901  int mxSelect, cnt = 0;
132902  for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
132903  pLoop->pNext = pNext;
132904  pLoop->selFlags |= SF_Compound;
132905  }
132906  if( (p->selFlags & SF_MultiValue)==0 &&
132907  (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
132908  cnt>mxSelect
132909  ){
132910  sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
132911  }
132912  }
132913  }
132914 
132915  /* This is a utility routine used to set the ExprSpan.zStart and
132916  ** ExprSpan.zEnd values of pOut so that the span covers the complete
132917  ** range of text beginning with pStart and going to the end of pEnd.
132918  */
132919  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
132920  pOut->zStart = pStart->z;
132921  pOut->zEnd = &pEnd->z[pEnd->n];
132922  }
132923 
132924  /* Construct a new Expr object from a single identifier. Use the
132925  ** new Expr to populate pOut. Set the span of pOut to be the identifier
132926  ** that created the expression.
132927  */
132928  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
132929  Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
132930  if( p ){
132931  memset(p, 0, sizeof(Expr));
132932  p->op = (u8)op;
132933  p->flags = EP_Leaf;
132934  p->iAgg = -1;
132935  p->u.zToken = (char*)&p[1];
132936  memcpy(p->u.zToken, t.z, t.n);
132937  p->u.zToken[t.n] = 0;
132938  if( sqlite3Isquote(p->u.zToken[0]) ){
132939  if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
132940  sqlite3Dequote(p->u.zToken);
132941  }
132942 #if SQLITE_MAX_EXPR_DEPTH>0
132943  p->nHeight = 1;
132944 #endif
132945  }
132946  pOut->pExpr = p;
132947  pOut->zStart = t.z;
132948  pOut->zEnd = &t.z[t.n];
132949  }
132950 
132951  /* This routine constructs a binary expression node out of two ExprSpan
132952  ** objects and uses the result to populate a new ExprSpan object.
132953  */
132954  static void spanBinaryExpr(
132955  Parse *pParse, /* The parsing context. Errors accumulate here */
132956  int op, /* The binary operation */
132957  ExprSpan *pLeft, /* The left operand, and output */
132958  ExprSpan *pRight /* The right operand */
132959  ){
132960  pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
132961  pLeft->zEnd = pRight->zEnd;
132962  }
132963 
132964  /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
132965  ** outside of *ppExpr.
132966  */
132967  static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
132968  if( doNot ){
132969  pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0, 0);
132970  }
132971  }
132972 
132973  /* Construct an expression node for a unary postfix operator
132974  */
132975  static void spanUnaryPostfix(
132976  Parse *pParse, /* Parsing context to record errors */
132977  int op, /* The operator */
132978  ExprSpan *pOperand, /* The operand, and output */
132979  Token *pPostOp /* The operand token for setting the span */
132980  ){
132981  pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
132982  pOperand->zEnd = &pPostOp->z[pPostOp->n];
132983  }
132984 
132985  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
132986  ** unary TK_ISNULL or TK_NOTNULL expression. */
132987  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
132988  sqlite3 *db = pParse->db;
132989  if( pA && pY && pY->op==TK_NULL ){
132990  pA->op = (u8)op;
132991  sqlite3ExprDelete(db, pA->pRight);
132992  pA->pRight = 0;
132993  }
132994  }
132995 
132996  /* Construct an expression node for a unary prefix operator
132997  */
132998  static void spanUnaryPrefix(
132999  ExprSpan *pOut, /* Write the new expression node here */
133000  Parse *pParse, /* Parsing context to record errors */
133001  int op, /* The operator */
133002  ExprSpan *pOperand, /* The operand */
133003  Token *pPreOp /* The operand token for setting the span */
133004  ){
133005  pOut->zStart = pPreOp->z;
133006  pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
133007  pOut->zEnd = pOperand->zEnd;
133008  }
133009 
133010  /* Add a single new term to an ExprList that is used to store a
133011  ** list of identifiers. Report an error if the ID list contains
133012  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
133013  ** error while parsing a legacy schema.
133014  */
133015  static ExprList *parserAddExprIdListTerm(
133016  Parse *pParse,
133017  ExprList *pPrior,
133018  Token *pIdToken,
133019  int hasCollate,
133020  int sortOrder
133021  ){
133022  ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
133023  if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
133024  && pParse->db->init.busy==0
133025  ){
133026  sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
133027  pIdToken->n, pIdToken->z);
133028  }
133029  sqlite3ExprListSetName(pParse, p, pIdToken, 1);
133030  return p;
133031  }
133032 /**************** End of %include directives **********************************/
133033 /* These constants specify the various numeric values for terminal symbols
133034 ** in a format understandable to "makeheaders". This section is blank unless
133035 ** "lemon" is run with the "-m" command-line option.
133036 ***************** Begin makeheaders token definitions *************************/
133037 /**************** End makeheaders token definitions ***************************/
133038 
133039 /* The next sections is a series of control #defines.
133040 ** various aspects of the generated parser.
133041 ** YYCODETYPE is the data type used to store the integer codes
133042 ** that represent terminal and non-terminal symbols.
133043 ** "unsigned char" is used if there are fewer than
133044 ** 256 symbols. Larger types otherwise.
133045 ** YYNOCODE is a number of type YYCODETYPE that is not used for
133046 ** any terminal or nonterminal symbol.
133047 ** YYFALLBACK If defined, this indicates that one or more tokens
133048 ** (also known as: "terminal symbols") have fall-back
133049 ** values which should be used if the original symbol
133050 ** would not parse. This permits keywords to sometimes
133051 ** be used as identifiers, for example.
133052 ** YYACTIONTYPE is the data type used for "action codes" - numbers
133053 ** that indicate what to do in response to the next
133054 ** token.
133055 ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
133056 ** symbols. Background: A "minor type" is a semantic
133057 ** value associated with a terminal or non-terminal
133058 ** symbols. For example, for an "ID" terminal symbol,
133059 ** the minor type might be the name of the identifier.
133060 ** Each non-terminal can have a different minor type.
133061 ** Terminal symbols all have the same minor type, though.
133062 ** This macros defines the minor type for terminal
133063 ** symbols.
133064 ** YYMINORTYPE is the data type used for all minor types.
133065 ** This is typically a union of many types, one of
133066 ** which is sqlite3ParserTOKENTYPE. The entry in the union
133067 ** for terminal symbols is called "yy0".
133068 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
133069 ** zero the stack is dynamically sized using realloc()
133070 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
133071 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
133072 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
133073 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
133074 ** YYERRORSYMBOL is the code number of the error symbol. If not
133075 ** defined, then do no error processing.
133076 ** YYNSTATE the combined number of states.
133077 ** YYNRULE the number of rules in the grammar
133078 ** YY_MAX_SHIFT Maximum value for shift actions
133079 ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
133080 ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
133081 ** YY_MIN_REDUCE Maximum value for reduce actions
133082 ** YY_ERROR_ACTION The yy_action[] code for syntax error
133083 ** YY_ACCEPT_ACTION The yy_action[] code for accept
133084 ** YY_NO_ACTION The yy_action[] code for no-op
133085 */
133086 #ifndef INTERFACE
133087 # define INTERFACE 1
133088 #endif
133089 /************* Begin control #defines *****************************************/
133090 #define YYCODETYPE unsigned char
133091 #define YYNOCODE 252
133092 #define YYACTIONTYPE unsigned short int
133093 #define YYWILDCARD 96
133094 #define sqlite3ParserTOKENTYPE Token
133095 typedef union {
133096  int yyinit;
133097  sqlite3ParserTOKENTYPE yy0;
133098  Expr* yy72;
133099  TriggerStep* yy145;
133100  ExprList* yy148;
133101  SrcList* yy185;
133102  ExprSpan yy190;
133103  int yy194;
133104  Select* yy243;
133105  IdList* yy254;
133106  With* yy285;
133107  struct TrigEvent yy332;
133108  struct LimitVal yy354;
133109  struct {int value; int mask;} yy497;
133110 } YYMINORTYPE;
133111 #ifndef YYSTACKDEPTH
133112 #define YYSTACKDEPTH 100
133113 #endif
133114 #define sqlite3ParserARG_SDECL Parse *pParse;
133115 #define sqlite3ParserARG_PDECL ,Parse *pParse
133116 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
133117 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
133118 #define YYFALLBACK 1
133119 #define YYNSTATE 456
133120 #define YYNRULE 332
133121 #define YY_MAX_SHIFT 455
133122 #define YY_MIN_SHIFTREDUCE 668
133123 #define YY_MAX_SHIFTREDUCE 999
133124 #define YY_MIN_REDUCE 1000
133125 #define YY_MAX_REDUCE 1331
133126 #define YY_ERROR_ACTION 1332
133127 #define YY_ACCEPT_ACTION 1333
133128 #define YY_NO_ACTION 1334
133129 /************* End control #defines *******************************************/
133130 
133131 /* Define the yytestcase() macro to be a no-op if is not already defined
133132 ** otherwise.
133133 **
133134 ** Applications can choose to define yytestcase() in the %include section
133135 ** to a macro that can assist in verifying code coverage. For production
133136 ** code the yytestcase() macro should be turned off. But it is useful
133137 ** for testing.
133138 */
133139 #ifndef yytestcase
133140 # define yytestcase(X)
133141 #endif
133142 
133143 
133144 /* Next are the tables used to determine what action to take based on the
133145 ** current state and lookahead token. These tables are used to implement
133146 ** functions that take a state number and lookahead value and return an
133147 ** action integer.
133148 **
133149 ** Suppose the action integer is N. Then the action is determined as
133150 ** follows
133151 **
133152 ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
133153 ** token onto the stack and goto state N.
133154 **
133155 ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
133156 ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
133157 **
133158 ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
133159 ** and YY_MAX_REDUCE
133160 **
133161 ** N == YY_ERROR_ACTION A syntax error has occurred.
133162 **
133163 ** N == YY_ACCEPT_ACTION The parser accepts its input.
133164 **
133165 ** N == YY_NO_ACTION No such action. Denotes unused
133166 ** slots in the yy_action[] table.
133167 **
133168 ** The action table is constructed as a single large table named yy_action[].
133169 ** Given state S and lookahead X, the action is computed as either:
133170 **
133171 ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
133172 ** (B) N = yy_default[S]
133173 **
133174 ** The (A) formula is preferred. The B formula is used instead if:
133175 ** (1) The yy_shift_ofst[S]+X value is out of range, or
133176 ** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
133177 ** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
133178 ** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
133179 ** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
133180 ** Hence only tests (1) and (2) need to be evaluated.)
133181 **
133182 ** The formulas above are for computing the action when the lookahead is
133183 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
133184 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
133185 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
133186 ** YY_SHIFT_USE_DFLT.
133187 **
133188 ** The following are the tables generated in this section:
133189 **
133190 ** yy_action[] A single table containing all actions.
133191 ** yy_lookahead[] A table containing the lookahead for each entry in
133192 ** yy_action. Used to detect hash collisions.
133193 ** yy_shift_ofst[] For each state, the offset into yy_action for
133194 ** shifting terminals.
133195 ** yy_reduce_ofst[] For each state, the offset into yy_action for
133196 ** shifting non-terminals after a reduce.
133197 ** yy_default[] Default action for each state.
133198 **
133199 *********** Begin parsing tables **********************************************/
133200 #define YY_ACTTAB_COUNT (1567)
133201 static const YYACTIONTYPE yy_action[] = {
133202  /* 0 */ 325, 832, 351, 825, 5, 203, 203, 819, 99, 100,
133203  /* 10 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98,
133204  /* 20 */ 98, 98, 98, 301, 96, 96, 96, 96, 95, 95,
133205  /* 30 */ 94, 94, 94, 93, 351, 325, 977, 977, 824, 824,
133206  /* 40 */ 826, 947, 354, 99, 100, 90, 842, 842, 854, 857,
133207  /* 50 */ 846, 846, 97, 97, 98, 98, 98, 98, 338, 96,
133208  /* 60 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351,
133209  /* 70 */ 95, 95, 94, 94, 94, 93, 351, 791, 977, 977,
133210  /* 80 */ 325, 94, 94, 94, 93, 351, 792, 75, 99, 100,
133211  /* 90 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98,
133212  /* 100 */ 98, 98, 98, 450, 96, 96, 96, 96, 95, 95,
133213  /* 110 */ 94, 94, 94, 93, 351, 1333, 155, 155, 2, 325,
133214  /* 120 */ 275, 146, 132, 52, 52, 93, 351, 99, 100, 90,
133215  /* 130 */ 842, 842, 854, 857, 846, 846, 97, 97, 98, 98,
133216  /* 140 */ 98, 98, 101, 96, 96, 96, 96, 95, 95, 94,
133217  /* 150 */ 94, 94, 93, 351, 958, 958, 325, 268, 428, 413,
133218  /* 160 */ 411, 61, 752, 752, 99, 100, 90, 842, 842, 854,
133219  /* 170 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 60,
133220  /* 180 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133221  /* 190 */ 351, 325, 270, 329, 273, 277, 959, 960, 250, 99,
133222  /* 200 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97,
133223  /* 210 */ 98, 98, 98, 98, 301, 96, 96, 96, 96, 95,
133224  /* 220 */ 95, 94, 94, 94, 93, 351, 325, 938, 1326, 698,
133225  /* 230 */ 706, 1326, 242, 412, 99, 100, 90, 842, 842, 854,
133226  /* 240 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 347,
133227  /* 250 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133228  /* 260 */ 351, 325, 938, 1327, 384, 699, 1327, 381, 379, 99,
133229  /* 270 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97,
133230  /* 280 */ 98, 98, 98, 98, 701, 96, 96, 96, 96, 95,
133231  /* 290 */ 95, 94, 94, 94, 93, 351, 325, 92, 89, 178,
133232  /* 300 */ 833, 936, 373, 700, 99, 100, 90, 842, 842, 854,
133233  /* 310 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 375,
133234  /* 320 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133235  /* 330 */ 351, 325, 1276, 947, 354, 818, 936, 739, 739, 99,
133236  /* 340 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97,
133237  /* 350 */ 98, 98, 98, 98, 230, 96, 96, 96, 96, 95,
133238  /* 360 */ 95, 94, 94, 94, 93, 351, 325, 969, 227, 92,
133239  /* 370 */ 89, 178, 373, 300, 99, 100, 90, 842, 842, 854,
133240  /* 380 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 921,
133241  /* 390 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133242  /* 400 */ 351, 325, 449, 447, 447, 447, 147, 737, 737, 99,
133243  /* 410 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97,
133244  /* 420 */ 98, 98, 98, 98, 296, 96, 96, 96, 96, 95,
133245  /* 430 */ 95, 94, 94, 94, 93, 351, 325, 419, 231, 958,
133246  /* 440 */ 958, 158, 25, 422, 99, 100, 90, 842, 842, 854,
133247  /* 450 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 450,
133248  /* 460 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133249  /* 470 */ 351, 443, 224, 224, 420, 958, 958, 962, 325, 52,
133250  /* 480 */ 52, 959, 960, 176, 415, 78, 99, 100, 90, 842,
133251  /* 490 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98,
133252  /* 500 */ 98, 379, 96, 96, 96, 96, 95, 95, 94, 94,
133253  /* 510 */ 94, 93, 351, 325, 428, 418, 298, 959, 960, 962,
133254  /* 520 */ 81, 99, 88, 90, 842, 842, 854, 857, 846, 846,
133255  /* 530 */ 97, 97, 98, 98, 98, 98, 717, 96, 96, 96,
133256  /* 540 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 843,
133257  /* 550 */ 843, 855, 858, 996, 318, 343, 379, 100, 90, 842,
133258  /* 560 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98,
133259  /* 570 */ 98, 450, 96, 96, 96, 96, 95, 95, 94, 94,
133260  /* 580 */ 94, 93, 351, 325, 350, 350, 350, 260, 377, 340,
133261  /* 590 */ 929, 52, 52, 90, 842, 842, 854, 857, 846, 846,
133262  /* 600 */ 97, 97, 98, 98, 98, 98, 361, 96, 96, 96,
133263  /* 610 */ 96, 95, 95, 94, 94, 94, 93, 351, 86, 445,
133264  /* 620 */ 847, 3, 1203, 361, 360, 378, 344, 813, 958, 958,
133265  /* 630 */ 1300, 86, 445, 729, 3, 212, 169, 287, 405, 282,
133266  /* 640 */ 404, 199, 232, 450, 300, 760, 83, 84, 280, 245,
133267  /* 650 */ 262, 365, 251, 85, 352, 352, 92, 89, 178, 83,
133268  /* 660 */ 84, 242, 412, 52, 52, 448, 85, 352, 352, 246,
133269  /* 670 */ 959, 960, 194, 455, 670, 402, 399, 398, 448, 243,
133270  /* 680 */ 221, 114, 434, 776, 361, 450, 397, 268, 747, 224,
133271  /* 690 */ 224, 132, 132, 198, 832, 434, 452, 451, 428, 427,
133272  /* 700 */ 819, 415, 734, 713, 132, 52, 52, 832, 268, 452,
133273  /* 710 */ 451, 734, 194, 819, 363, 402, 399, 398, 450, 1271,
133274  /* 720 */ 1271, 23, 958, 958, 86, 445, 397, 3, 228, 429,
133275  /* 730 */ 895, 824, 824, 826, 827, 19, 203, 720, 52, 52,
133276  /* 740 */ 428, 408, 439, 249, 824, 824, 826, 827, 19, 229,
133277  /* 750 */ 403, 153, 83, 84, 761, 177, 241, 450, 721, 85,
133278  /* 760 */ 352, 352, 120, 157, 959, 960, 58, 977, 409, 355,
133279  /* 770 */ 330, 448, 268, 428, 430, 320, 790, 32, 32, 86,
133280  /* 780 */ 445, 776, 3, 341, 98, 98, 98, 98, 434, 96,
133281  /* 790 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351,
133282  /* 800 */ 832, 120, 452, 451, 813, 887, 819, 83, 84, 977,
133283  /* 810 */ 813, 132, 410, 920, 85, 352, 352, 132, 407, 789,
133284  /* 820 */ 958, 958, 92, 89, 178, 917, 448, 262, 370, 261,
133285  /* 830 */ 82, 914, 80, 262, 370, 261, 776, 824, 824, 826,
133286  /* 840 */ 827, 19, 934, 434, 96, 96, 96, 96, 95, 95,
133287  /* 850 */ 94, 94, 94, 93, 351, 832, 74, 452, 451, 958,
133288  /* 860 */ 958, 819, 959, 960, 120, 92, 89, 178, 945, 2,
133289  /* 870 */ 918, 965, 268, 1, 976, 76, 445, 762, 3, 708,
133290  /* 880 */ 901, 901, 387, 958, 958, 757, 919, 371, 740, 778,
133291  /* 890 */ 756, 257, 824, 824, 826, 827, 19, 417, 741, 450,
133292  /* 900 */ 24, 959, 960, 83, 84, 369, 958, 958, 177, 226,
133293  /* 910 */ 85, 352, 352, 885, 315, 314, 313, 215, 311, 10,
133294  /* 920 */ 10, 683, 448, 349, 348, 959, 960, 909, 777, 157,
133295  /* 930 */ 120, 958, 958, 337, 776, 416, 711, 310, 450, 434,
133296  /* 940 */ 450, 321, 450, 791, 103, 200, 175, 450, 959, 960,
133297  /* 950 */ 908, 832, 792, 452, 451, 9, 9, 819, 10, 10,
133298  /* 960 */ 52, 52, 51, 51, 180, 716, 248, 10, 10, 171,
133299  /* 970 */ 170, 167, 339, 959, 960, 247, 984, 702, 702, 450,
133300  /* 980 */ 715, 233, 686, 982, 889, 983, 182, 914, 824, 824,
133301  /* 990 */ 826, 827, 19, 183, 256, 423, 132, 181, 394, 10,
133302  /* 1000 */ 10, 889, 891, 749, 958, 958, 917, 268, 985, 198,
133303  /* 1010 */ 985, 349, 348, 425, 415, 299, 817, 832, 326, 825,
133304  /* 1020 */ 120, 332, 133, 819, 268, 98, 98, 98, 98, 91,
133305  /* 1030 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133306  /* 1040 */ 351, 157, 810, 371, 382, 359, 959, 960, 358, 268,
133307  /* 1050 */ 450, 918, 368, 324, 824, 824, 826, 450, 709, 450,
133308  /* 1060 */ 264, 380, 889, 450, 877, 746, 253, 919, 255, 433,
133309  /* 1070 */ 36, 36, 234, 450, 234, 120, 269, 37, 37, 12,
133310  /* 1080 */ 12, 334, 272, 27, 27, 450, 330, 118, 450, 162,
133311  /* 1090 */ 742, 280, 450, 38, 38, 450, 985, 356, 985, 450,
133312  /* 1100 */ 709, 1210, 450, 132, 450, 39, 39, 450, 40, 40,
133313  /* 1110 */ 450, 362, 41, 41, 450, 42, 42, 450, 254, 28,
133314  /* 1120 */ 28, 450, 29, 29, 31, 31, 450, 43, 43, 450,
133315  /* 1130 */ 44, 44, 450, 714, 45, 45, 450, 11, 11, 767,
133316  /* 1140 */ 450, 46, 46, 450, 268, 450, 105, 105, 450, 47,
133317  /* 1150 */ 47, 450, 48, 48, 450, 237, 33, 33, 450, 172,
133318  /* 1160 */ 49, 49, 450, 50, 50, 34, 34, 274, 122, 122,
133319  /* 1170 */ 450, 123, 123, 450, 124, 124, 450, 898, 56, 56,
133320  /* 1180 */ 450, 897, 35, 35, 450, 267, 450, 817, 450, 817,
133321  /* 1190 */ 106, 106, 450, 53, 53, 385, 107, 107, 450, 817,
133322  /* 1200 */ 108, 108, 817, 450, 104, 104, 121, 121, 119, 119,
133323  /* 1210 */ 450, 117, 112, 112, 450, 276, 450, 225, 111, 111,
133324  /* 1220 */ 450, 730, 450, 109, 109, 450, 673, 674, 675, 912,
133325  /* 1230 */ 110, 110, 317, 998, 55, 55, 57, 57, 692, 331,
133326  /* 1240 */ 54, 54, 26, 26, 696, 30, 30, 317, 937, 197,
133327  /* 1250 */ 196, 195, 335, 281, 336, 446, 331, 745, 689, 436,
133328  /* 1260 */ 440, 444, 120, 72, 386, 223, 175, 345, 757, 933,
133329  /* 1270 */ 20, 286, 319, 756, 815, 372, 374, 202, 202, 202,
133330  /* 1280 */ 263, 395, 285, 74, 208, 21, 696, 719, 718, 884,
133331  /* 1290 */ 120, 120, 120, 120, 120, 754, 278, 828, 77, 74,
133332  /* 1300 */ 726, 727, 785, 783, 880, 202, 999, 208, 894, 893,
133333  /* 1310 */ 894, 893, 694, 816, 763, 116, 774, 1290, 431, 432,
133334  /* 1320 */ 302, 999, 390, 303, 823, 697, 691, 680, 159, 289,
133335  /* 1330 */ 679, 884, 681, 952, 291, 218, 293, 7, 316, 828,
133336  /* 1340 */ 173, 805, 259, 364, 252, 911, 376, 713, 295, 435,
133337  /* 1350 */ 308, 168, 955, 993, 135, 400, 990, 284, 882, 881,
133338  /* 1360 */ 205, 928, 926, 59, 333, 62, 144, 156, 130, 72,
133339  /* 1370 */ 802, 366, 367, 393, 137, 185, 189, 160, 139, 383,
133340  /* 1380 */ 67, 896, 140, 141, 142, 148, 389, 812, 775, 266,
133341  /* 1390 */ 219, 190, 154, 391, 913, 876, 271, 406, 191, 322,
133342  /* 1400 */ 682, 733, 192, 342, 732, 724, 731, 711, 723, 421,
133343  /* 1410 */ 705, 71, 323, 6, 204, 771, 288, 79, 297, 346,
133344  /* 1420 */ 772, 704, 290, 283, 703, 770, 292, 294, 967, 239,
133345  /* 1430 */ 769, 102, 862, 438, 426, 240, 424, 442, 73, 213,
133346  /* 1440 */ 688, 238, 22, 453, 953, 214, 217, 216, 454, 677,
133347  /* 1450 */ 676, 671, 753, 125, 115, 235, 126, 669, 353, 166,
133348  /* 1460 */ 127, 244, 179, 357, 306, 304, 305, 307, 113, 892,
133349  /* 1470 */ 327, 890, 811, 328, 134, 128, 136, 138, 743, 258,
133350  /* 1480 */ 907, 184, 143, 129, 910, 186, 63, 64, 145, 187,
133351  /* 1490 */ 906, 65, 8, 66, 13, 188, 202, 899, 265, 149,
133352  /* 1500 */ 987, 388, 150, 685, 161, 392, 285, 193, 279, 396,
133353  /* 1510 */ 151, 401, 68, 14, 15, 722, 69, 236, 831, 131,
133354  /* 1520 */ 830, 860, 70, 751, 16, 414, 755, 4, 174, 220,
133355  /* 1530 */ 222, 784, 201, 152, 779, 77, 74, 17, 18, 875,
133356  /* 1540 */ 861, 859, 916, 864, 915, 207, 206, 942, 163, 437,
133357  /* 1550 */ 948, 943, 164, 209, 1002, 441, 863, 165, 210, 829,
133358  /* 1560 */ 695, 87, 312, 211, 1292, 1291, 309,
133359 };
133360 static const YYCODETYPE yy_lookahead[] = {
133361  /* 0 */ 19, 95, 53, 97, 22, 24, 24, 101, 27, 28,
133362  /* 10 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
133363  /* 20 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
133364  /* 30 */ 49, 50, 51, 52, 53, 19, 55, 55, 132, 133,
133365  /* 40 */ 134, 1, 2, 27, 28, 29, 30, 31, 32, 33,
133366  /* 50 */ 34, 35, 36, 37, 38, 39, 40, 41, 187, 43,
133367  /* 60 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
133368  /* 70 */ 47, 48, 49, 50, 51, 52, 53, 61, 97, 97,
133369  /* 80 */ 19, 49, 50, 51, 52, 53, 70, 26, 27, 28,
133370  /* 90 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
133371  /* 100 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
133372  /* 110 */ 49, 50, 51, 52, 53, 144, 145, 146, 147, 19,
133373  /* 120 */ 16, 22, 92, 172, 173, 52, 53, 27, 28, 29,
133374  /* 130 */ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
133375  /* 140 */ 40, 41, 81, 43, 44, 45, 46, 47, 48, 49,
133376  /* 150 */ 50, 51, 52, 53, 55, 56, 19, 152, 207, 208,
133377  /* 160 */ 115, 24, 117, 118, 27, 28, 29, 30, 31, 32,
133378  /* 170 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 79,
133379  /* 180 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133380  /* 190 */ 53, 19, 88, 157, 90, 23, 97, 98, 193, 27,
133381  /* 200 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
133382  /* 210 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
133383  /* 220 */ 48, 49, 50, 51, 52, 53, 19, 22, 23, 172,
133384  /* 230 */ 23, 26, 119, 120, 27, 28, 29, 30, 31, 32,
133385  /* 240 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187,
133386  /* 250 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133387  /* 260 */ 53, 19, 22, 23, 228, 23, 26, 231, 152, 27,
133388  /* 270 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
133389  /* 280 */ 38, 39, 40, 41, 172, 43, 44, 45, 46, 47,
133390  /* 290 */ 48, 49, 50, 51, 52, 53, 19, 221, 222, 223,
133391  /* 300 */ 23, 96, 152, 172, 27, 28, 29, 30, 31, 32,
133392  /* 310 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152,
133393  /* 320 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133394  /* 330 */ 53, 19, 0, 1, 2, 23, 96, 190, 191, 27,
133395  /* 340 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
133396  /* 350 */ 38, 39, 40, 41, 238, 43, 44, 45, 46, 47,
133397  /* 360 */ 48, 49, 50, 51, 52, 53, 19, 185, 218, 221,
133398  /* 370 */ 222, 223, 152, 152, 27, 28, 29, 30, 31, 32,
133399  /* 380 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 241,
133400  /* 390 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133401  /* 400 */ 53, 19, 152, 168, 169, 170, 22, 190, 191, 27,
133402  /* 410 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
133403  /* 420 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
133404  /* 430 */ 48, 49, 50, 51, 52, 53, 19, 19, 218, 55,
133405  /* 440 */ 56, 24, 22, 152, 27, 28, 29, 30, 31, 32,
133406  /* 450 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152,
133407  /* 460 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133408  /* 470 */ 53, 250, 194, 195, 56, 55, 56, 55, 19, 172,
133409  /* 480 */ 173, 97, 98, 152, 206, 138, 27, 28, 29, 30,
133410  /* 490 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
133411  /* 500 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50,
133412  /* 510 */ 51, 52, 53, 19, 207, 208, 152, 97, 98, 97,
133413  /* 520 */ 138, 27, 28, 29, 30, 31, 32, 33, 34, 35,
133414  /* 530 */ 36, 37, 38, 39, 40, 41, 181, 43, 44, 45,
133415  /* 540 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 30,
133416  /* 550 */ 31, 32, 33, 247, 248, 19, 152, 28, 29, 30,
133417  /* 560 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
133418  /* 570 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50,
133419  /* 580 */ 51, 52, 53, 19, 168, 169, 170, 238, 19, 53,
133420  /* 590 */ 152, 172, 173, 29, 30, 31, 32, 33, 34, 35,
133421  /* 600 */ 36, 37, 38, 39, 40, 41, 152, 43, 44, 45,
133422  /* 610 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 20,
133423  /* 620 */ 101, 22, 23, 169, 170, 56, 207, 85, 55, 56,
133424  /* 630 */ 23, 19, 20, 26, 22, 99, 100, 101, 102, 103,
133425  /* 640 */ 104, 105, 238, 152, 152, 210, 47, 48, 112, 152,
133426  /* 650 */ 108, 109, 110, 54, 55, 56, 221, 222, 223, 47,
133427  /* 660 */ 48, 119, 120, 172, 173, 66, 54, 55, 56, 152,
133428  /* 670 */ 97, 98, 99, 148, 149, 102, 103, 104, 66, 154,
133429  /* 680 */ 23, 156, 83, 26, 230, 152, 113, 152, 163, 194,
133430  /* 690 */ 195, 92, 92, 30, 95, 83, 97, 98, 207, 208,
133431  /* 700 */ 101, 206, 179, 180, 92, 172, 173, 95, 152, 97,
133432  /* 710 */ 98, 188, 99, 101, 219, 102, 103, 104, 152, 119,
133433  /* 720 */ 120, 196, 55, 56, 19, 20, 113, 22, 193, 163,
133434  /* 730 */ 11, 132, 133, 134, 135, 136, 24, 65, 172, 173,
133435  /* 740 */ 207, 208, 250, 152, 132, 133, 134, 135, 136, 193,
133436  /* 750 */ 78, 84, 47, 48, 49, 98, 199, 152, 86, 54,
133437  /* 760 */ 55, 56, 196, 152, 97, 98, 209, 55, 163, 244,
133438  /* 770 */ 107, 66, 152, 207, 208, 164, 175, 172, 173, 19,
133439  /* 780 */ 20, 124, 22, 111, 38, 39, 40, 41, 83, 43,
133440  /* 790 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
133441  /* 800 */ 95, 196, 97, 98, 85, 152, 101, 47, 48, 97,
133442  /* 810 */ 85, 92, 207, 193, 54, 55, 56, 92, 49, 175,
133443  /* 820 */ 55, 56, 221, 222, 223, 12, 66, 108, 109, 110,
133444  /* 830 */ 137, 163, 139, 108, 109, 110, 26, 132, 133, 134,
133445  /* 840 */ 135, 136, 152, 83, 43, 44, 45, 46, 47, 48,
133446  /* 850 */ 49, 50, 51, 52, 53, 95, 26, 97, 98, 55,
133447  /* 860 */ 56, 101, 97, 98, 196, 221, 222, 223, 146, 147,
133448  /* 870 */ 57, 171, 152, 22, 26, 19, 20, 49, 22, 179,
133449  /* 880 */ 108, 109, 110, 55, 56, 116, 73, 219, 75, 124,
133450  /* 890 */ 121, 152, 132, 133, 134, 135, 136, 163, 85, 152,
133451  /* 900 */ 232, 97, 98, 47, 48, 237, 55, 56, 98, 5,
133452  /* 910 */ 54, 55, 56, 193, 10, 11, 12, 13, 14, 172,
133453  /* 920 */ 173, 17, 66, 47, 48, 97, 98, 152, 124, 152,
133454  /* 930 */ 196, 55, 56, 186, 124, 152, 106, 160, 152, 83,
133455  /* 940 */ 152, 164, 152, 61, 22, 211, 212, 152, 97, 98,
133456  /* 950 */ 152, 95, 70, 97, 98, 172, 173, 101, 172, 173,
133457  /* 960 */ 172, 173, 172, 173, 60, 181, 62, 172, 173, 47,
133458  /* 970 */ 48, 123, 186, 97, 98, 71, 100, 55, 56, 152,
133459  /* 980 */ 181, 186, 21, 107, 152, 109, 82, 163, 132, 133,
133460  /* 990 */ 134, 135, 136, 89, 16, 207, 92, 93, 19, 172,
133461  /* 1000 */ 173, 169, 170, 195, 55, 56, 12, 152, 132, 30,
133462  /* 1010 */ 134, 47, 48, 186, 206, 225, 152, 95, 114, 97,
133463  /* 1020 */ 196, 245, 246, 101, 152, 38, 39, 40, 41, 42,
133464  /* 1030 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133465  /* 1040 */ 53, 152, 163, 219, 152, 141, 97, 98, 193, 152,
133466  /* 1050 */ 152, 57, 91, 164, 132, 133, 134, 152, 55, 152,
133467  /* 1060 */ 152, 237, 230, 152, 103, 193, 88, 73, 90, 75,
133468  /* 1070 */ 172, 173, 183, 152, 185, 196, 152, 172, 173, 172,
133469  /* 1080 */ 173, 217, 152, 172, 173, 152, 107, 22, 152, 24,
133470  /* 1090 */ 193, 112, 152, 172, 173, 152, 132, 242, 134, 152,
133471  /* 1100 */ 97, 140, 152, 92, 152, 172, 173, 152, 172, 173,
133472  /* 1110 */ 152, 100, 172, 173, 152, 172, 173, 152, 140, 172,
133473  /* 1120 */ 173, 152, 172, 173, 172, 173, 152, 172, 173, 152,
133474  /* 1130 */ 172, 173, 152, 152, 172, 173, 152, 172, 173, 213,
133475  /* 1140 */ 152, 172, 173, 152, 152, 152, 172, 173, 152, 172,
133476  /* 1150 */ 173, 152, 172, 173, 152, 210, 172, 173, 152, 26,
133477  /* 1160 */ 172, 173, 152, 172, 173, 172, 173, 152, 172, 173,
133478  /* 1170 */ 152, 172, 173, 152, 172, 173, 152, 59, 172, 173,
133479  /* 1180 */ 152, 63, 172, 173, 152, 193, 152, 152, 152, 152,
133480  /* 1190 */ 172, 173, 152, 172, 173, 77, 172, 173, 152, 152,
133481  /* 1200 */ 172, 173, 152, 152, 172, 173, 172, 173, 172, 173,
133482  /* 1210 */ 152, 22, 172, 173, 152, 152, 152, 22, 172, 173,
133483  /* 1220 */ 152, 152, 152, 172, 173, 152, 7, 8, 9, 163,
133484  /* 1230 */ 172, 173, 22, 23, 172, 173, 172, 173, 166, 167,
133485  /* 1240 */ 172, 173, 172, 173, 55, 172, 173, 22, 23, 108,
133486  /* 1250 */ 109, 110, 217, 152, 217, 166, 167, 163, 163, 163,
133487  /* 1260 */ 163, 163, 196, 130, 217, 211, 212, 217, 116, 23,
133488  /* 1270 */ 22, 101, 26, 121, 23, 23, 23, 26, 26, 26,
133489  /* 1280 */ 23, 23, 112, 26, 26, 37, 97, 100, 101, 55,
133490  /* 1290 */ 196, 196, 196, 196, 196, 23, 23, 55, 26, 26,
133491  /* 1300 */ 7, 8, 23, 152, 23, 26, 96, 26, 132, 132,
133492  /* 1310 */ 134, 134, 23, 152, 152, 26, 152, 122, 152, 191,
133493  /* 1320 */ 152, 96, 234, 152, 152, 152, 152, 152, 197, 210,
133494  /* 1330 */ 152, 97, 152, 152, 210, 233, 210, 198, 150, 97,
133495  /* 1340 */ 184, 201, 239, 214, 214, 201, 239, 180, 214, 227,
133496  /* 1350 */ 200, 198, 155, 67, 243, 176, 69, 175, 175, 175,
133497  /* 1360 */ 122, 159, 159, 240, 159, 240, 22, 220, 27, 130,
133498  /* 1370 */ 201, 18, 159, 18, 189, 158, 158, 220, 192, 159,
133499  /* 1380 */ 137, 236, 192, 192, 192, 189, 74, 189, 159, 235,
133500  /* 1390 */ 159, 158, 22, 177, 201, 201, 159, 107, 158, 177,
133501  /* 1400 */ 159, 174, 158, 76, 174, 182, 174, 106, 182, 125,
133502  /* 1410 */ 174, 107, 177, 22, 159, 216, 215, 137, 159, 53,
133503  /* 1420 */ 216, 176, 215, 174, 174, 216, 215, 215, 174, 229,
133504  /* 1430 */ 216, 129, 224, 177, 126, 229, 127, 177, 128, 25,
133505  /* 1440 */ 162, 226, 26, 161, 13, 153, 6, 153, 151, 151,
133506  /* 1450 */ 151, 151, 205, 165, 178, 178, 165, 4, 3, 22,
133507  /* 1460 */ 165, 142, 15, 94, 202, 204, 203, 201, 16, 23,
133508  /* 1470 */ 249, 23, 120, 249, 246, 111, 131, 123, 20, 16,
133509  /* 1480 */ 1, 125, 123, 111, 56, 64, 37, 37, 131, 122,
133510  /* 1490 */ 1, 37, 5, 37, 22, 107, 26, 80, 140, 80,
133511  /* 1500 */ 87, 72, 107, 20, 24, 19, 112, 105, 23, 79,
133512  /* 1510 */ 22, 79, 22, 22, 22, 58, 22, 79, 23, 68,
133513  /* 1520 */ 23, 23, 26, 116, 22, 26, 23, 22, 122, 23,
133514  /* 1530 */ 23, 56, 64, 22, 124, 26, 26, 64, 64, 23,
133515  /* 1540 */ 23, 23, 23, 11, 23, 22, 26, 23, 22, 24,
133516  /* 1550 */ 1, 23, 22, 26, 251, 24, 23, 22, 122, 23,
133517  /* 1560 */ 23, 22, 15, 122, 122, 122, 23,
133518 };
133519 #define YY_SHIFT_USE_DFLT (1567)
133520 #define YY_SHIFT_COUNT (455)
133521 #define YY_SHIFT_MIN (-94)
133522 #define YY_SHIFT_MAX (1549)
133523 static const short yy_shift_ofst[] = {
133524  /* 0 */ 40, 599, 904, 612, 760, 760, 760, 760, 725, -19,
133525  /* 10 */ 16, 16, 100, 760, 760, 760, 760, 760, 760, 760,
133526  /* 20 */ 876, 876, 573, 542, 719, 600, 61, 137, 172, 207,
133527  /* 30 */ 242, 277, 312, 347, 382, 417, 459, 459, 459, 459,
133528  /* 40 */ 459, 459, 459, 459, 459, 459, 459, 459, 459, 459,
133529  /* 50 */ 459, 459, 459, 494, 459, 529, 564, 564, 705, 760,
133530  /* 60 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760,
133531  /* 70 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760,
133532  /* 80 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760,
133533  /* 90 */ 856, 760, 760, 760, 760, 760, 760, 760, 760, 760,
133534  /* 100 */ 760, 760, 760, 760, 987, 746, 746, 746, 746, 746,
133535  /* 110 */ 801, 23, 32, 949, 961, 979, 964, 964, 949, 73,
133536  /* 120 */ 113, -51, 1567, 1567, 1567, 536, 536, 536, 99, 99,
133537  /* 130 */ 813, 813, 667, 205, 240, 949, 949, 949, 949, 949,
133538  /* 140 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949,
133539  /* 150 */ 949, 949, 949, 949, 949, 332, 1011, 422, 422, 113,
133540  /* 160 */ 30, 30, 30, 30, 30, 30, 1567, 1567, 1567, 922,
133541  /* 170 */ -94, -94, 384, 613, 828, 420, 765, 804, 851, 949,
133542  /* 180 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949,
133543  /* 190 */ 949, 949, 949, 949, 949, 672, 672, 672, 949, 949,
133544  /* 200 */ 657, 949, 949, 949, -18, 949, 949, 994, 949, 949,
133545  /* 210 */ 949, 949, 949, 949, 949, 949, 949, 949, 772, 1118,
133546  /* 220 */ 712, 712, 712, 810, 45, 769, 1219, 1133, 418, 418,
133547  /* 230 */ 569, 1133, 569, 830, 607, 663, 882, 418, 693, 882,
133548  /* 240 */ 882, 848, 1152, 1065, 1286, 1238, 1238, 1287, 1287, 1238,
133549  /* 250 */ 1344, 1341, 1239, 1353, 1353, 1353, 1353, 1238, 1355, 1239,
133550  /* 260 */ 1344, 1341, 1341, 1239, 1238, 1355, 1243, 1312, 1238, 1238,
133551  /* 270 */ 1355, 1370, 1238, 1355, 1238, 1355, 1370, 1290, 1290, 1290,
133552  /* 280 */ 1327, 1370, 1290, 1301, 1290, 1327, 1290, 1290, 1284, 1304,
133553  /* 290 */ 1284, 1304, 1284, 1304, 1284, 1304, 1238, 1391, 1238, 1280,
133554  /* 300 */ 1370, 1366, 1366, 1370, 1302, 1308, 1310, 1309, 1239, 1414,
133555  /* 310 */ 1416, 1431, 1431, 1440, 1440, 1440, 1440, 1567, 1567, 1567,
133556  /* 320 */ 1567, 1567, 1567, 1567, 1567, 519, 978, 1210, 1225, 104,
133557  /* 330 */ 1141, 1189, 1246, 1248, 1251, 1252, 1253, 1257, 1258, 1273,
133558  /* 340 */ 1003, 1187, 1293, 1170, 1272, 1279, 1234, 1281, 1176, 1177,
133559  /* 350 */ 1289, 1242, 1195, 1453, 1455, 1437, 1319, 1447, 1369, 1452,
133560  /* 360 */ 1446, 1448, 1352, 1345, 1364, 1354, 1458, 1356, 1463, 1479,
133561  /* 370 */ 1359, 1357, 1449, 1450, 1454, 1456, 1372, 1428, 1421, 1367,
133562  /* 380 */ 1489, 1487, 1472, 1388, 1358, 1417, 1470, 1419, 1413, 1429,
133563  /* 390 */ 1395, 1480, 1483, 1486, 1394, 1402, 1488, 1430, 1490, 1491,
133564  /* 400 */ 1485, 1492, 1432, 1457, 1494, 1438, 1451, 1495, 1497, 1498,
133565  /* 410 */ 1496, 1407, 1502, 1503, 1505, 1499, 1406, 1506, 1507, 1475,
133566  /* 420 */ 1468, 1511, 1410, 1509, 1473, 1510, 1474, 1516, 1509, 1517,
133567  /* 430 */ 1518, 1519, 1520, 1521, 1523, 1532, 1524, 1526, 1525, 1527,
133568  /* 440 */ 1528, 1530, 1531, 1527, 1533, 1535, 1536, 1537, 1539, 1436,
133569  /* 450 */ 1441, 1442, 1443, 1543, 1547, 1549,
133570 };
133571 #define YY_REDUCE_USE_DFLT (-130)
133572 #define YY_REDUCE_COUNT (324)
133573 #define YY_REDUCE_MIN (-129)
133574 #define YY_REDUCE_MAX (1300)
133575 static const short yy_reduce_ofst[] = {
133576  /* 0 */ -29, 566, 525, 605, -49, 307, 491, 533, 668, 435,
133577  /* 10 */ 601, 644, 148, 747, 786, 795, 419, 788, 827, 790,
133578  /* 20 */ 454, 832, 889, 495, 824, 734, 76, 76, 76, 76,
133579  /* 30 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
133580  /* 40 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
133581  /* 50 */ 76, 76, 76, 76, 76, 76, 76, 76, 783, 898,
133582  /* 60 */ 905, 907, 911, 921, 933, 936, 940, 943, 947, 950,
133583  /* 70 */ 952, 955, 958, 962, 965, 969, 974, 977, 980, 984,
133584  /* 80 */ 988, 991, 993, 996, 999, 1002, 1006, 1010, 1018, 1021,
133585  /* 90 */ 1024, 1028, 1032, 1034, 1036, 1040, 1046, 1051, 1058, 1062,
133586  /* 100 */ 1064, 1068, 1070, 1073, 76, 76, 76, 76, 76, 76,
133587  /* 110 */ 76, 76, 76, 855, 36, 523, 235, 416, 777, 76,
133588  /* 120 */ 278, 76, 76, 76, 76, 700, 700, 700, 150, 220,
133589  /* 130 */ 147, 217, 221, 306, 306, 611, 5, 535, 556, 620,
133590  /* 140 */ 720, 872, 897, 116, 864, 349, 1035, 1037, 404, 1047,
133591  /* 150 */ 992, -129, 1050, 492, 62, 722, 879, 1072, 1089, 808,
133592  /* 160 */ 1066, 1094, 1095, 1096, 1097, 1098, 776, 1054, 557, 57,
133593  /* 170 */ 112, 131, 167, 182, 250, 272, 291, 331, 364, 438,
133594  /* 180 */ 497, 517, 591, 653, 690, 739, 775, 798, 892, 908,
133595  /* 190 */ 924, 930, 1015, 1063, 1069, 355, 784, 799, 981, 1101,
133596  /* 200 */ 926, 1151, 1161, 1162, 945, 1164, 1166, 1128, 1168, 1171,
133597  /* 210 */ 1172, 250, 1173, 1174, 1175, 1178, 1180, 1181, 1088, 1102,
133598  /* 220 */ 1119, 1124, 1126, 926, 1131, 1139, 1188, 1140, 1129, 1130,
133599  /* 230 */ 1103, 1144, 1107, 1179, 1156, 1167, 1182, 1134, 1122, 1183,
133600  /* 240 */ 1184, 1150, 1153, 1197, 1111, 1202, 1203, 1123, 1125, 1205,
133601  /* 250 */ 1147, 1185, 1169, 1186, 1190, 1191, 1192, 1213, 1217, 1193,
133602  /* 260 */ 1157, 1196, 1198, 1194, 1220, 1218, 1145, 1154, 1229, 1231,
133603  /* 270 */ 1233, 1216, 1237, 1240, 1241, 1244, 1222, 1227, 1230, 1232,
133604  /* 280 */ 1223, 1235, 1236, 1245, 1249, 1226, 1250, 1254, 1199, 1201,
133605  /* 290 */ 1204, 1207, 1209, 1211, 1214, 1212, 1255, 1208, 1259, 1215,
133606  /* 300 */ 1256, 1200, 1206, 1260, 1247, 1261, 1263, 1262, 1266, 1278,
133607  /* 310 */ 1282, 1292, 1294, 1297, 1298, 1299, 1300, 1221, 1224, 1228,
133608  /* 320 */ 1288, 1291, 1276, 1277, 1295,
133609 };
133610 static const YYACTIONTYPE yy_default[] = {
133611  /* 0 */ 1281, 1271, 1271, 1271, 1203, 1203, 1203, 1203, 1271, 1096,
133612  /* 10 */ 1125, 1125, 1255, 1332, 1332, 1332, 1332, 1332, 1332, 1202,
133613  /* 20 */ 1332, 1332, 1332, 1332, 1271, 1100, 1131, 1332, 1332, 1332,
133614  /* 30 */ 1332, 1204, 1205, 1332, 1332, 1332, 1254, 1256, 1141, 1140,
133615  /* 40 */ 1139, 1138, 1237, 1112, 1136, 1129, 1133, 1204, 1198, 1199,
133616  /* 50 */ 1197, 1201, 1205, 1332, 1132, 1167, 1182, 1166, 1332, 1332,
133617  /* 60 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133618  /* 70 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133619  /* 80 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133620  /* 90 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133621  /* 100 */ 1332, 1332, 1332, 1332, 1176, 1181, 1188, 1180, 1177, 1169,
133622  /* 110 */ 1168, 1170, 1171, 1332, 1019, 1067, 1332, 1332, 1332, 1172,
133623  /* 120 */ 1332, 1173, 1185, 1184, 1183, 1262, 1289, 1288, 1332, 1332,
133624  /* 130 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133625  /* 140 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133626  /* 150 */ 1332, 1332, 1332, 1332, 1332, 1281, 1271, 1025, 1025, 1332,
133627  /* 160 */ 1271, 1271, 1271, 1271, 1271, 1271, 1267, 1100, 1091, 1332,
133628  /* 170 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133629  /* 180 */ 1259, 1257, 1332, 1218, 1332, 1332, 1332, 1332, 1332, 1332,
133630  /* 190 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133631  /* 200 */ 1332, 1332, 1332, 1332, 1096, 1332, 1332, 1332, 1332, 1332,
133632  /* 210 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1283, 1332, 1232,
133633  /* 220 */ 1096, 1096, 1096, 1098, 1080, 1090, 1004, 1135, 1114, 1114,
133634  /* 230 */ 1321, 1135, 1321, 1042, 1303, 1039, 1125, 1114, 1200, 1125,
133635  /* 240 */ 1125, 1097, 1090, 1332, 1324, 1105, 1105, 1323, 1323, 1105,
133636  /* 250 */ 1146, 1070, 1135, 1076, 1076, 1076, 1076, 1105, 1016, 1135,
133637  /* 260 */ 1146, 1070, 1070, 1135, 1105, 1016, 1236, 1318, 1105, 1105,
133638  /* 270 */ 1016, 1211, 1105, 1016, 1105, 1016, 1211, 1068, 1068, 1068,
133639  /* 280 */ 1057, 1211, 1068, 1042, 1068, 1057, 1068, 1068, 1118, 1113,
133640  /* 290 */ 1118, 1113, 1118, 1113, 1118, 1113, 1105, 1206, 1105, 1332,
133641  /* 300 */ 1211, 1215, 1215, 1211, 1130, 1119, 1128, 1126, 1135, 1022,
133642  /* 310 */ 1060, 1286, 1286, 1282, 1282, 1282, 1282, 1329, 1329, 1267,
133643  /* 320 */ 1298, 1298, 1044, 1044, 1298, 1332, 1332, 1332, 1332, 1332,
133644  /* 330 */ 1332, 1293, 1332, 1220, 1332, 1332, 1332, 1332, 1332, 1332,
133645  /* 340 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133646  /* 350 */ 1332, 1332, 1152, 1332, 1000, 1264, 1332, 1332, 1263, 1332,
133647  /* 360 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133648  /* 370 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1320,
133649  /* 380 */ 1332, 1332, 1332, 1332, 1332, 1332, 1235, 1234, 1332, 1332,
133650  /* 390 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133651  /* 400 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133652  /* 410 */ 1332, 1082, 1332, 1332, 1332, 1307, 1332, 1332, 1332, 1332,
133653  /* 420 */ 1332, 1332, 1332, 1127, 1332, 1120, 1332, 1332, 1311, 1332,
133654  /* 430 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1273,
133655  /* 440 */ 1332, 1332, 1332, 1272, 1332, 1332, 1332, 1332, 1332, 1154,
133656  /* 450 */ 1332, 1153, 1157, 1332, 1010, 1332,
133657 };
133658 /********** End of lemon-generated parsing tables *****************************/
133659 
133660 /* The next table maps tokens (terminal symbols) into fallback tokens.
133661 ** If a construct like the following:
133662 **
133663 ** %fallback ID X Y Z.
133664 **
133665 ** appears in the grammar, then ID becomes a fallback token for X, Y,
133666 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
133667 ** but it does not parse, the type of the token is changed to ID and
133668 ** the parse is retried before an error is thrown.
133669 **
133670 ** This feature can be used, for example, to cause some keywords in a language
133671 ** to revert to identifiers if they keyword does not apply in the context where
133672 ** it appears.
133673 */
133674 #ifdef YYFALLBACK
133675 static const YYCODETYPE yyFallback[] = {
133676  0, /* $ => nothing */
133677  0, /* SEMI => nothing */
133678  55, /* EXPLAIN => ID */
133679  55, /* QUERY => ID */
133680  55, /* PLAN => ID */
133681  55, /* BEGIN => ID */
133682  0, /* TRANSACTION => nothing */
133683  55, /* DEFERRED => ID */
133684  55, /* IMMEDIATE => ID */
133685  55, /* EXCLUSIVE => ID */
133686  0, /* COMMIT => nothing */
133687  55, /* END => ID */
133688  55, /* ROLLBACK => ID */
133689  55, /* SAVEPOINT => ID */
133690  55, /* RELEASE => ID */
133691  0, /* TO => nothing */
133692  0, /* TABLE => nothing */
133693  0, /* CREATE => nothing */
133694  55, /* IF => ID */
133695  0, /* NOT => nothing */
133696  0, /* EXISTS => nothing */
133697  55, /* TEMP => ID */
133698  0, /* LP => nothing */
133699  0, /* RP => nothing */
133700  0, /* AS => nothing */
133701  55, /* WITHOUT => ID */
133702  0, /* COMMA => nothing */
133703  0, /* OR => nothing */
133704  0, /* AND => nothing */
133705  0, /* IS => nothing */
133706  55, /* MATCH => ID */
133707  55, /* LIKE_KW => ID */
133708  0, /* BETWEEN => nothing */
133709  0, /* IN => nothing */
133710  0, /* ISNULL => nothing */
133711  0, /* NOTNULL => nothing */
133712  0, /* NE => nothing */
133713  0, /* EQ => nothing */
133714  0, /* GT => nothing */
133715  0, /* LE => nothing */
133716  0, /* LT => nothing */
133717  0, /* GE => nothing */
133718  0, /* ESCAPE => nothing */
133719  0, /* BITAND => nothing */
133720  0, /* BITOR => nothing */
133721  0, /* LSHIFT => nothing */
133722  0, /* RSHIFT => nothing */
133723  0, /* PLUS => nothing */
133724  0, /* MINUS => nothing */
133725  0, /* STAR => nothing */
133726  0, /* SLASH => nothing */
133727  0, /* REM => nothing */
133728  0, /* CONCAT => nothing */
133729  0, /* COLLATE => nothing */
133730  0, /* BITNOT => nothing */
133731  0, /* ID => nothing */
133732  0, /* INDEXED => nothing */
133733  55, /* ABORT => ID */
133734  55, /* ACTION => ID */
133735  55, /* AFTER => ID */
133736  55, /* ANALYZE => ID */
133737  55, /* ASC => ID */
133738  55, /* ATTACH => ID */
133739  55, /* BEFORE => ID */
133740  55, /* BY => ID */
133741  55, /* CASCADE => ID */
133742  55, /* CAST => ID */
133743  55, /* COLUMNKW => ID */
133744  55, /* CONFLICT => ID */
133745  55, /* DATABASE => ID */
133746  55, /* DESC => ID */
133747  55, /* DETACH => ID */
133748  55, /* EACH => ID */
133749  55, /* FAIL => ID */
133750  55, /* FOR => ID */
133751  55, /* IGNORE => ID */
133752  55, /* INITIALLY => ID */
133753  55, /* INSTEAD => ID */
133754  55, /* NO => ID */
133755  55, /* KEY => ID */
133756  55, /* OF => ID */
133757  55, /* OFFSET => ID */
133758  55, /* PRAGMA => ID */
133759  55, /* RAISE => ID */
133760  55, /* RECURSIVE => ID */
133761  55, /* REPLACE => ID */
133762  55, /* RESTRICT => ID */
133763  55, /* ROW => ID */
133764  55, /* TRIGGER => ID */
133765  55, /* VACUUM => ID */
133766  55, /* VIEW => ID */
133767  55, /* VIRTUAL => ID */
133768  55, /* WITH => ID */
133769  55, /* REINDEX => ID */
133770  55, /* RENAME => ID */
133771  55, /* CTIME_KW => ID */
133772 };
133773 #endif /* YYFALLBACK */
133774 
133775 /* The following structure represents a single element of the
133776 ** parser's stack. Information stored includes:
133777 **
133778 ** + The state number for the parser at this level of the stack.
133779 **
133780 ** + The value of the token stored at this level of the stack.
133781 ** (In other words, the "major" token.)
133782 **
133783 ** + The semantic value stored at this level of the stack. This is
133784 ** the information used by the action routines in the grammar.
133785 ** It is sometimes called the "minor" token.
133786 **
133787 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
133788 ** actually contains the reduce action for the second half of the
133789 ** SHIFTREDUCE.
133790 */
133792  YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
133793  YYCODETYPE major; /* The major token value. This is the code
133794  ** number for the token at this stack level */
133795  YYMINORTYPE minor; /* The user-supplied minor token value. This
133796  ** is the value of the token */
133797 };
133798 typedef struct yyStackEntry yyStackEntry;
133799 
133800 /* The state of the parser is completely contained in an instance of
133801 ** the following structure */
133802 struct yyParser {
133803  yyStackEntry *yytos; /* Pointer to top element of the stack */
133804 #ifdef YYTRACKMAXSTACKDEPTH
133805  int yyhwm; /* High-water mark of the stack */
133806 #endif
133807 #ifndef YYNOERRORRECOVERY
133808  int yyerrcnt; /* Shifts left before out of the error */
133809 #endif
133810  sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
133811 #if YYSTACKDEPTH<=0
133812  int yystksz; /* Current side of the stack */
133813  yyStackEntry *yystack; /* The parser's stack */
133814  yyStackEntry yystk0; /* First stack entry */
133815 #else
133816  yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
133817 #endif
133818 };
133819 typedef struct yyParser yyParser;
133820 
133821 #ifndef NDEBUG
133822 /* #include <stdio.h> */
133823 static FILE *yyTraceFILE = 0;
133824 static char *yyTracePrompt = 0;
133825 #endif /* NDEBUG */
133826 
133827 #ifndef NDEBUG
133828 /*
133829 ** Turn parser tracing on by giving a stream to which to write the trace
133830 ** and a prompt to preface each trace message. Tracing is turned off
133831 ** by making either argument NULL
133832 **
133833 ** Inputs:
133834 ** <ul>
133835 ** <li> A FILE* to which trace output should be written.
133836 ** If NULL, then tracing is turned off.
133837 ** <li> A prefix string written at the beginning of every
133838 ** line of trace output. If NULL, then tracing is
133839 ** turned off.
133840 ** </ul>
133841 **
133842 ** Outputs:
133843 ** None.
133844 */
133845 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
133846  yyTraceFILE = TraceFILE;
133847  yyTracePrompt = zTracePrompt;
133848  if( yyTraceFILE==0 ) yyTracePrompt = 0;
133849  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
133850 }
133851 #endif /* NDEBUG */
133852 
133853 #ifndef NDEBUG
133854 /* For tracing shifts, the names of all terminals and nonterminals
133855 ** are required. The following table supplies these names */
133856 static const char *const yyTokenName[] = {
133857  "$", "SEMI", "EXPLAIN", "QUERY",
133858  "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
133859  "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
133860  "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
133861  "TABLE", "CREATE", "IF", "NOT",
133862  "EXISTS", "TEMP", "LP", "RP",
133863  "AS", "WITHOUT", "COMMA", "OR",
133864  "AND", "IS", "MATCH", "LIKE_KW",
133865  "BETWEEN", "IN", "ISNULL", "NOTNULL",
133866  "NE", "EQ", "GT", "LE",
133867  "LT", "GE", "ESCAPE", "BITAND",
133868  "BITOR", "LSHIFT", "RSHIFT", "PLUS",
133869  "MINUS", "STAR", "SLASH", "REM",
133870  "CONCAT", "COLLATE", "BITNOT", "ID",
133871  "INDEXED", "ABORT", "ACTION", "AFTER",
133872  "ANALYZE", "ASC", "ATTACH", "BEFORE",
133873  "BY", "CASCADE", "CAST", "COLUMNKW",
133874  "CONFLICT", "DATABASE", "DESC", "DETACH",
133875  "EACH", "FAIL", "FOR", "IGNORE",
133876  "INITIALLY", "INSTEAD", "NO", "KEY",
133877  "OF", "OFFSET", "PRAGMA", "RAISE",
133878  "RECURSIVE", "REPLACE", "RESTRICT", "ROW",
133879  "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
133880  "WITH", "REINDEX", "RENAME", "CTIME_KW",
133881  "ANY", "STRING", "JOIN_KW", "CONSTRAINT",
133882  "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
133883  "CHECK", "REFERENCES", "AUTOINCR", "ON",
133884  "INSERT", "DELETE", "UPDATE", "SET",
133885  "DEFERRABLE", "FOREIGN", "DROP", "UNION",
133886  "ALL", "EXCEPT", "INTERSECT", "SELECT",
133887  "VALUES", "DISTINCT", "DOT", "FROM",
133888  "JOIN", "USING", "ORDER", "GROUP",
133889  "HAVING", "LIMIT", "WHERE", "INTO",
133890  "FLOAT", "BLOB", "INTEGER", "VARIABLE",
133891  "CASE", "WHEN", "THEN", "ELSE",
133892  "INDEX", "ALTER", "ADD", "error",
133893  "input", "cmdlist", "ecmd", "explain",
133894  "cmdx", "cmd", "transtype", "trans_opt",
133895  "nm", "savepoint_opt", "create_table", "create_table_args",
133896  "createkw", "temp", "ifnotexists", "dbnm",
133897  "columnlist", "conslist_opt", "table_options", "select",
133898  "columnname", "carglist", "typetoken", "typename",
133899  "signed", "plus_num", "minus_num", "ccons",
133900  "term", "expr", "onconf", "sortorder",
133901  "autoinc", "eidlist_opt", "refargs", "defer_subclause",
133902  "refarg", "refact", "init_deferred_pred_opt", "conslist",
133903  "tconscomma", "tcons", "sortlist", "eidlist",
133904  "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
133905  "ifexists", "fullname", "selectnowith", "oneselect",
133906  "with", "multiselect_op", "distinct", "selcollist",
133907  "from", "where_opt", "groupby_opt", "having_opt",
133908  "orderby_opt", "limit_opt", "values", "nexprlist",
133909  "exprlist", "sclp", "as", "seltablist",
133910  "stl_prefix", "joinop", "indexed_opt", "on_opt",
133911  "using_opt", "idlist", "setlist", "insert_cmd",
133912  "idlist_opt", "likeop", "between_op", "in_op",
133913  "paren_exprlist", "case_operand", "case_exprlist", "case_else",
133914  "uniqueflag", "collate", "nmnum", "trigger_decl",
133915  "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
133916  "when_clause", "trigger_cmd", "trnm", "tridxby",
133917  "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
133918  "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
133919  "lp", "anylist", "wqlist",
133920 };
133921 #endif /* NDEBUG */
133922 
133923 #ifndef NDEBUG
133924 /* For tracing reduce actions, the names of all rules are required.
133925 */
133926 static const char *const yyRuleName[] = {
133927  /* 0 */ "explain ::= EXPLAIN",
133928  /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
133929  /* 2 */ "cmdx ::= cmd",
133930  /* 3 */ "cmd ::= BEGIN transtype trans_opt",
133931  /* 4 */ "transtype ::=",
133932  /* 5 */ "transtype ::= DEFERRED",
133933  /* 6 */ "transtype ::= IMMEDIATE",
133934  /* 7 */ "transtype ::= EXCLUSIVE",
133935  /* 8 */ "cmd ::= COMMIT trans_opt",
133936  /* 9 */ "cmd ::= END trans_opt",
133937  /* 10 */ "cmd ::= ROLLBACK trans_opt",
133938  /* 11 */ "cmd ::= SAVEPOINT nm",
133939  /* 12 */ "cmd ::= RELEASE savepoint_opt nm",
133940  /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
133941  /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
133942  /* 15 */ "createkw ::= CREATE",
133943  /* 16 */ "ifnotexists ::=",
133944  /* 17 */ "ifnotexists ::= IF NOT EXISTS",
133945  /* 18 */ "temp ::= TEMP",
133946  /* 19 */ "temp ::=",
133947  /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
133948  /* 21 */ "create_table_args ::= AS select",
133949  /* 22 */ "table_options ::=",
133950  /* 23 */ "table_options ::= WITHOUT nm",
133951  /* 24 */ "columnname ::= nm typetoken",
133952  /* 25 */ "typetoken ::=",
133953  /* 26 */ "typetoken ::= typename LP signed RP",
133954  /* 27 */ "typetoken ::= typename LP signed COMMA signed RP",
133955  /* 28 */ "typename ::= typename ID|STRING",
133956  /* 29 */ "ccons ::= CONSTRAINT nm",
133957  /* 30 */ "ccons ::= DEFAULT term",
133958  /* 31 */ "ccons ::= DEFAULT LP expr RP",
133959  /* 32 */ "ccons ::= DEFAULT PLUS term",
133960  /* 33 */ "ccons ::= DEFAULT MINUS term",
133961  /* 34 */ "ccons ::= DEFAULT ID|INDEXED",
133962  /* 35 */ "ccons ::= NOT NULL onconf",
133963  /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
133964  /* 37 */ "ccons ::= UNIQUE onconf",
133965  /* 38 */ "ccons ::= CHECK LP expr RP",
133966  /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
133967  /* 40 */ "ccons ::= defer_subclause",
133968  /* 41 */ "ccons ::= COLLATE ID|STRING",
133969  /* 42 */ "autoinc ::=",
133970  /* 43 */ "autoinc ::= AUTOINCR",
133971  /* 44 */ "refargs ::=",
133972  /* 45 */ "refargs ::= refargs refarg",
133973  /* 46 */ "refarg ::= MATCH nm",
133974  /* 47 */ "refarg ::= ON INSERT refact",
133975  /* 48 */ "refarg ::= ON DELETE refact",
133976  /* 49 */ "refarg ::= ON UPDATE refact",
133977  /* 50 */ "refact ::= SET NULL",
133978  /* 51 */ "refact ::= SET DEFAULT",
133979  /* 52 */ "refact ::= CASCADE",
133980  /* 53 */ "refact ::= RESTRICT",
133981  /* 54 */ "refact ::= NO ACTION",
133982  /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
133983  /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
133984  /* 57 */ "init_deferred_pred_opt ::=",
133985  /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
133986  /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
133987  /* 60 */ "conslist_opt ::=",
133988  /* 61 */ "tconscomma ::= COMMA",
133989  /* 62 */ "tcons ::= CONSTRAINT nm",
133990  /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
133991  /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
133992  /* 65 */ "tcons ::= CHECK LP expr RP onconf",
133993  /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
133994  /* 67 */ "defer_subclause_opt ::=",
133995  /* 68 */ "onconf ::=",
133996  /* 69 */ "onconf ::= ON CONFLICT resolvetype",
133997  /* 70 */ "orconf ::=",
133998  /* 71 */ "orconf ::= OR resolvetype",
133999  /* 72 */ "resolvetype ::= IGNORE",
134000  /* 73 */ "resolvetype ::= REPLACE",
134001  /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
134002  /* 75 */ "ifexists ::= IF EXISTS",
134003  /* 76 */ "ifexists ::=",
134004  /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
134005  /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
134006  /* 79 */ "cmd ::= select",
134007  /* 80 */ "select ::= with selectnowith",
134008  /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
134009  /* 82 */ "multiselect_op ::= UNION",
134010  /* 83 */ "multiselect_op ::= UNION ALL",
134011  /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT",
134012  /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
134013  /* 86 */ "values ::= VALUES LP nexprlist RP",
134014  /* 87 */ "values ::= values COMMA LP exprlist RP",
134015  /* 88 */ "distinct ::= DISTINCT",
134016  /* 89 */ "distinct ::= ALL",
134017  /* 90 */ "distinct ::=",
134018  /* 91 */ "sclp ::=",
134019  /* 92 */ "selcollist ::= sclp expr as",
134020  /* 93 */ "selcollist ::= sclp STAR",
134021  /* 94 */ "selcollist ::= sclp nm DOT STAR",
134022  /* 95 */ "as ::= AS nm",
134023  /* 96 */ "as ::=",
134024  /* 97 */ "from ::=",
134025  /* 98 */ "from ::= FROM seltablist",
134026  /* 99 */ "stl_prefix ::= seltablist joinop",
134027  /* 100 */ "stl_prefix ::=",
134028  /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
134029  /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
134030  /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
134031  /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
134032  /* 105 */ "dbnm ::=",
134033  /* 106 */ "dbnm ::= DOT nm",
134034  /* 107 */ "fullname ::= nm dbnm",
134035  /* 108 */ "joinop ::= COMMA|JOIN",
134036  /* 109 */ "joinop ::= JOIN_KW JOIN",
134037  /* 110 */ "joinop ::= JOIN_KW nm JOIN",
134038  /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
134039  /* 112 */ "on_opt ::= ON expr",
134040  /* 113 */ "on_opt ::=",
134041  /* 114 */ "indexed_opt ::=",
134042  /* 115 */ "indexed_opt ::= INDEXED BY nm",
134043  /* 116 */ "indexed_opt ::= NOT INDEXED",
134044  /* 117 */ "using_opt ::= USING LP idlist RP",
134045  /* 118 */ "using_opt ::=",
134046  /* 119 */ "orderby_opt ::=",
134047  /* 120 */ "orderby_opt ::= ORDER BY sortlist",
134048  /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
134049  /* 122 */ "sortlist ::= expr sortorder",
134050  /* 123 */ "sortorder ::= ASC",
134051  /* 124 */ "sortorder ::= DESC",
134052  /* 125 */ "sortorder ::=",
134053  /* 126 */ "groupby_opt ::=",
134054  /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
134055  /* 128 */ "having_opt ::=",
134056  /* 129 */ "having_opt ::= HAVING expr",
134057  /* 130 */ "limit_opt ::=",
134058  /* 131 */ "limit_opt ::= LIMIT expr",
134059  /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
134060  /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
134061  /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
134062  /* 135 */ "where_opt ::=",
134063  /* 136 */ "where_opt ::= WHERE expr",
134064  /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
134065  /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
134066  /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
134067  /* 140 */ "setlist ::= nm EQ expr",
134068  /* 141 */ "setlist ::= LP idlist RP EQ expr",
134069  /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
134070  /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
134071  /* 144 */ "insert_cmd ::= INSERT orconf",
134072  /* 145 */ "insert_cmd ::= REPLACE",
134073  /* 146 */ "idlist_opt ::=",
134074  /* 147 */ "idlist_opt ::= LP idlist RP",
134075  /* 148 */ "idlist ::= idlist COMMA nm",
134076  /* 149 */ "idlist ::= nm",
134077  /* 150 */ "expr ::= LP expr RP",
134078  /* 151 */ "term ::= NULL",
134079  /* 152 */ "expr ::= ID|INDEXED",
134080  /* 153 */ "expr ::= JOIN_KW",
134081  /* 154 */ "expr ::= nm DOT nm",
134082  /* 155 */ "expr ::= nm DOT nm DOT nm",
134083  /* 156 */ "term ::= FLOAT|BLOB",
134084  /* 157 */ "term ::= STRING",
134085  /* 158 */ "term ::= INTEGER",
134086  /* 159 */ "expr ::= VARIABLE",
134087  /* 160 */ "expr ::= expr COLLATE ID|STRING",
134088  /* 161 */ "expr ::= CAST LP expr AS typetoken RP",
134089  /* 162 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
134090  /* 163 */ "expr ::= ID|INDEXED LP STAR RP",
134091  /* 164 */ "term ::= CTIME_KW",
134092  /* 165 */ "expr ::= LP nexprlist COMMA expr RP",
134093  /* 166 */ "expr ::= expr AND expr",
134094  /* 167 */ "expr ::= expr OR expr",
134095  /* 168 */ "expr ::= expr LT|GT|GE|LE expr",
134096  /* 169 */ "expr ::= expr EQ|NE expr",
134097  /* 170 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
134098  /* 171 */ "expr ::= expr PLUS|MINUS expr",
134099  /* 172 */ "expr ::= expr STAR|SLASH|REM expr",
134100  /* 173 */ "expr ::= expr CONCAT expr",
134101  /* 174 */ "likeop ::= LIKE_KW|MATCH",
134102  /* 175 */ "likeop ::= NOT LIKE_KW|MATCH",
134103  /* 176 */ "expr ::= expr likeop expr",
134104  /* 177 */ "expr ::= expr likeop expr ESCAPE expr",
134105  /* 178 */ "expr ::= expr ISNULL|NOTNULL",
134106  /* 179 */ "expr ::= expr NOT NULL",
134107  /* 180 */ "expr ::= expr IS expr",
134108  /* 181 */ "expr ::= expr IS NOT expr",
134109  /* 182 */ "expr ::= NOT expr",
134110  /* 183 */ "expr ::= BITNOT expr",
134111  /* 184 */ "expr ::= MINUS expr",
134112  /* 185 */ "expr ::= PLUS expr",
134113  /* 186 */ "between_op ::= BETWEEN",
134114  /* 187 */ "between_op ::= NOT BETWEEN",
134115  /* 188 */ "expr ::= expr between_op expr AND expr",
134116  /* 189 */ "in_op ::= IN",
134117  /* 190 */ "in_op ::= NOT IN",
134118  /* 191 */ "expr ::= expr in_op LP exprlist RP",
134119  /* 192 */ "expr ::= LP select RP",
134120  /* 193 */ "expr ::= expr in_op LP select RP",
134121  /* 194 */ "expr ::= expr in_op nm dbnm paren_exprlist",
134122  /* 195 */ "expr ::= EXISTS LP select RP",
134123  /* 196 */ "expr ::= CASE case_operand case_exprlist case_else END",
134124  /* 197 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
134125  /* 198 */ "case_exprlist ::= WHEN expr THEN expr",
134126  /* 199 */ "case_else ::= ELSE expr",
134127  /* 200 */ "case_else ::=",
134128  /* 201 */ "case_operand ::= expr",
134129  /* 202 */ "case_operand ::=",
134130  /* 203 */ "exprlist ::=",
134131  /* 204 */ "nexprlist ::= nexprlist COMMA expr",
134132  /* 205 */ "nexprlist ::= expr",
134133  /* 206 */ "paren_exprlist ::=",
134134  /* 207 */ "paren_exprlist ::= LP exprlist RP",
134135  /* 208 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
134136  /* 209 */ "uniqueflag ::= UNIQUE",
134137  /* 210 */ "uniqueflag ::=",
134138  /* 211 */ "eidlist_opt ::=",
134139  /* 212 */ "eidlist_opt ::= LP eidlist RP",
134140  /* 213 */ "eidlist ::= eidlist COMMA nm collate sortorder",
134141  /* 214 */ "eidlist ::= nm collate sortorder",
134142  /* 215 */ "collate ::=",
134143  /* 216 */ "collate ::= COLLATE ID|STRING",
134144  /* 217 */ "cmd ::= DROP INDEX ifexists fullname",
134145  /* 218 */ "cmd ::= VACUUM",
134146  /* 219 */ "cmd ::= VACUUM nm",
134147  /* 220 */ "cmd ::= PRAGMA nm dbnm",
134148  /* 221 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
134149  /* 222 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
134150  /* 223 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
134151  /* 224 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
134152  /* 225 */ "plus_num ::= PLUS INTEGER|FLOAT",
134153  /* 226 */ "minus_num ::= MINUS INTEGER|FLOAT",
134154  /* 227 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
134155  /* 228 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
134156  /* 229 */ "trigger_time ::= BEFORE",
134157  /* 230 */ "trigger_time ::= AFTER",
134158  /* 231 */ "trigger_time ::= INSTEAD OF",
134159  /* 232 */ "trigger_time ::=",
134160  /* 233 */ "trigger_event ::= DELETE|INSERT",
134161  /* 234 */ "trigger_event ::= UPDATE",
134162  /* 235 */ "trigger_event ::= UPDATE OF idlist",
134163  /* 236 */ "when_clause ::=",
134164  /* 237 */ "when_clause ::= WHEN expr",
134165  /* 238 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
134166  /* 239 */ "trigger_cmd_list ::= trigger_cmd SEMI",
134167  /* 240 */ "trnm ::= nm DOT nm",
134168  /* 241 */ "tridxby ::= INDEXED BY nm",
134169  /* 242 */ "tridxby ::= NOT INDEXED",
134170  /* 243 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
134171  /* 244 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
134172  /* 245 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
134173  /* 246 */ "trigger_cmd ::= select",
134174  /* 247 */ "expr ::= RAISE LP IGNORE RP",
134175  /* 248 */ "expr ::= RAISE LP raisetype COMMA nm RP",
134176  /* 249 */ "raisetype ::= ROLLBACK",
134177  /* 250 */ "raisetype ::= ABORT",
134178  /* 251 */ "raisetype ::= FAIL",
134179  /* 252 */ "cmd ::= DROP TRIGGER ifexists fullname",
134180  /* 253 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
134181  /* 254 */ "cmd ::= DETACH database_kw_opt expr",
134182  /* 255 */ "key_opt ::=",
134183  /* 256 */ "key_opt ::= KEY expr",
134184  /* 257 */ "cmd ::= REINDEX",
134185  /* 258 */ "cmd ::= REINDEX nm dbnm",
134186  /* 259 */ "cmd ::= ANALYZE",
134187  /* 260 */ "cmd ::= ANALYZE nm dbnm",
134188  /* 261 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
134189  /* 262 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
134190  /* 263 */ "add_column_fullname ::= fullname",
134191  /* 264 */ "cmd ::= create_vtab",
134192  /* 265 */ "cmd ::= create_vtab LP vtabarglist RP",
134193  /* 266 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
134194  /* 267 */ "vtabarg ::=",
134195  /* 268 */ "vtabargtoken ::= ANY",
134196  /* 269 */ "vtabargtoken ::= lp anylist RP",
134197  /* 270 */ "lp ::= LP",
134198  /* 271 */ "with ::=",
134199  /* 272 */ "with ::= WITH wqlist",
134200  /* 273 */ "with ::= WITH RECURSIVE wqlist",
134201  /* 274 */ "wqlist ::= nm eidlist_opt AS LP select RP",
134202  /* 275 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
134203  /* 276 */ "input ::= cmdlist",
134204  /* 277 */ "cmdlist ::= cmdlist ecmd",
134205  /* 278 */ "cmdlist ::= ecmd",
134206  /* 279 */ "ecmd ::= SEMI",
134207  /* 280 */ "ecmd ::= explain cmdx SEMI",
134208  /* 281 */ "explain ::=",
134209  /* 282 */ "trans_opt ::=",
134210  /* 283 */ "trans_opt ::= TRANSACTION",
134211  /* 284 */ "trans_opt ::= TRANSACTION nm",
134212  /* 285 */ "savepoint_opt ::= SAVEPOINT",
134213  /* 286 */ "savepoint_opt ::=",
134214  /* 287 */ "cmd ::= create_table create_table_args",
134215  /* 288 */ "columnlist ::= columnlist COMMA columnname carglist",
134216  /* 289 */ "columnlist ::= columnname carglist",
134217  /* 290 */ "nm ::= ID|INDEXED",
134218  /* 291 */ "nm ::= STRING",
134219  /* 292 */ "nm ::= JOIN_KW",
134220  /* 293 */ "typetoken ::= typename",
134221  /* 294 */ "typename ::= ID|STRING",
134222  /* 295 */ "signed ::= plus_num",
134223  /* 296 */ "signed ::= minus_num",
134224  /* 297 */ "carglist ::= carglist ccons",
134225  /* 298 */ "carglist ::=",
134226  /* 299 */ "ccons ::= NULL onconf",
134227  /* 300 */ "conslist_opt ::= COMMA conslist",
134228  /* 301 */ "conslist ::= conslist tconscomma tcons",
134229  /* 302 */ "conslist ::= tcons",
134230  /* 303 */ "tconscomma ::=",
134231  /* 304 */ "defer_subclause_opt ::= defer_subclause",
134232  /* 305 */ "resolvetype ::= raisetype",
134233  /* 306 */ "selectnowith ::= oneselect",
134234  /* 307 */ "oneselect ::= values",
134235  /* 308 */ "sclp ::= selcollist COMMA",
134236  /* 309 */ "as ::= ID|STRING",
134237  /* 310 */ "expr ::= term",
134238  /* 311 */ "exprlist ::= nexprlist",
134239  /* 312 */ "nmnum ::= plus_num",
134240  /* 313 */ "nmnum ::= nm",
134241  /* 314 */ "nmnum ::= ON",
134242  /* 315 */ "nmnum ::= DELETE",
134243  /* 316 */ "nmnum ::= DEFAULT",
134244  /* 317 */ "plus_num ::= INTEGER|FLOAT",
134245  /* 318 */ "foreach_clause ::=",
134246  /* 319 */ "foreach_clause ::= FOR EACH ROW",
134247  /* 320 */ "trnm ::= nm",
134248  /* 321 */ "tridxby ::=",
134249  /* 322 */ "database_kw_opt ::= DATABASE",
134250  /* 323 */ "database_kw_opt ::=",
134251  /* 324 */ "kwcolumn_opt ::=",
134252  /* 325 */ "kwcolumn_opt ::= COLUMNKW",
134253  /* 326 */ "vtabarglist ::= vtabarg",
134254  /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
134255  /* 328 */ "vtabarg ::= vtabarg vtabargtoken",
134256  /* 329 */ "anylist ::=",
134257  /* 330 */ "anylist ::= anylist LP anylist RP",
134258  /* 331 */ "anylist ::= anylist ANY",
134259 };
134260 #endif /* NDEBUG */
134261 
134262 
134263 #if YYSTACKDEPTH<=0
134264 /*
134265 ** Try to increase the size of the parser stack. Return the number
134266 ** of errors. Return 0 on success.
134267 */
134268 static int yyGrowStack(yyParser *p){
134269  int newSize;
134270  int idx;
134271  yyStackEntry *pNew;
134272 
134273  newSize = p->yystksz*2 + 100;
134274  idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
134275  if( p->yystack==&p->yystk0 ){
134276  pNew = malloc(newSize*sizeof(pNew[0]));
134277  if( pNew ) pNew[0] = p->yystk0;
134278  }else{
134279  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
134280  }
134281  if( pNew ){
134282  p->yystack = pNew;
134283  p->yytos = &p->yystack[idx];
134284 #ifndef NDEBUG
134285  if( yyTraceFILE ){
134286  fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
134287  yyTracePrompt, p->yystksz, newSize);
134288  }
134289 #endif
134290  p->yystksz = newSize;
134291  }
134292  return pNew==0;
134293 }
134294 #endif
134295 
134296 /* Datatype of the argument to the memory allocated passed as the
134297 ** second argument to sqlite3ParserAlloc() below. This can be changed by
134298 ** putting an appropriate #define in the %include section of the input
134299 ** grammar.
134300 */
134301 #ifndef YYMALLOCARGTYPE
134302 # define YYMALLOCARGTYPE size_t
134303 #endif
134304 
134305 /*
134306 ** This function allocates a new parser.
134307 ** The only argument is a pointer to a function which works like
134308 ** malloc.
134309 **
134310 ** Inputs:
134311 ** A pointer to the function used to allocate memory.
134312 **
134313 ** Outputs:
134314 ** A pointer to a parser. This pointer is used in subsequent calls
134315 ** to sqlite3Parser and sqlite3ParserFree.
134316 */
134317 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
134318  yyParser *pParser;
134319  pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
134320  if( pParser ){
134321 #ifdef YYTRACKMAXSTACKDEPTH
134322  pParser->yyhwm = 0;
134323 #endif
134324 #if YYSTACKDEPTH<=0
134325  pParser->yytos = NULL;
134326  pParser->yystack = NULL;
134327  pParser->yystksz = 0;
134328  if( yyGrowStack(pParser) ){
134329  pParser->yystack = &pParser->yystk0;
134330  pParser->yystksz = 1;
134331  }
134332 #endif
134333 #ifndef YYNOERRORRECOVERY
134334  pParser->yyerrcnt = -1;
134335 #endif
134336  pParser->yytos = pParser->yystack;
134337  pParser->yystack[0].stateno = 0;
134338  pParser->yystack[0].major = 0;
134339  }
134340  return pParser;
134341 }
134342 
134343 /* The following function deletes the "minor type" or semantic value
134344 ** associated with a symbol. The symbol can be either a terminal
134345 ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
134346 ** a pointer to the value to be deleted. The code used to do the
134347 ** deletions is derived from the %destructor and/or %token_destructor
134348 ** directives of the input grammar.
134349 */
134350 static void yy_destructor(
134351  yyParser *yypParser, /* The parser */
134352  YYCODETYPE yymajor, /* Type code for object to destroy */
134353  YYMINORTYPE *yypminor /* The object to be destroyed */
134354 ){
134355  sqlite3ParserARG_FETCH;
134356  switch( yymajor ){
134357  /* Here is inserted the actions which take place when a
134358  ** terminal or non-terminal is destroyed. This can happen
134359  ** when the symbol is popped from the stack during a
134360  ** reduce or during error processing or when a parser is
134361  ** being destroyed before it is finished parsing.
134362  **
134363  ** Note: during a reduce, the only symbols destroyed are those
134364  ** which appear on the RHS of the rule, but which are *not* used
134365  ** inside the C code.
134366  */
134367 /********* Begin destructor definitions ***************************************/
134368  case 163: /* select */
134369  case 194: /* selectnowith */
134370  case 195: /* oneselect */
134371  case 206: /* values */
134372 {
134373 sqlite3SelectDelete(pParse->db, (yypminor->yy243));
134374 }
134375  break;
134376  case 172: /* term */
134377  case 173: /* expr */
134378 {
134379 sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
134380 }
134381  break;
134382  case 177: /* eidlist_opt */
134383  case 186: /* sortlist */
134384  case 187: /* eidlist */
134385  case 199: /* selcollist */
134386  case 202: /* groupby_opt */
134387  case 204: /* orderby_opt */
134388  case 207: /* nexprlist */
134389  case 208: /* exprlist */
134390  case 209: /* sclp */
134391  case 218: /* setlist */
134392  case 224: /* paren_exprlist */
134393  case 226: /* case_exprlist */
134394 {
134395 sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
134396 }
134397  break;
134398  case 193: /* fullname */
134399  case 200: /* from */
134400  case 211: /* seltablist */
134401  case 212: /* stl_prefix */
134402 {
134403 sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
134404 }
134405  break;
134406  case 196: /* with */
134407  case 250: /* wqlist */
134408 {
134409 sqlite3WithDelete(pParse->db, (yypminor->yy285));
134410 }
134411  break;
134412  case 201: /* where_opt */
134413  case 203: /* having_opt */
134414  case 215: /* on_opt */
134415  case 225: /* case_operand */
134416  case 227: /* case_else */
134417  case 236: /* when_clause */
134418  case 241: /* key_opt */
134419 {
134420 sqlite3ExprDelete(pParse->db, (yypminor->yy72));
134421 }
134422  break;
134423  case 216: /* using_opt */
134424  case 217: /* idlist */
134425  case 220: /* idlist_opt */
134426 {
134427 sqlite3IdListDelete(pParse->db, (yypminor->yy254));
134428 }
134429  break;
134430  case 232: /* trigger_cmd_list */
134431  case 237: /* trigger_cmd */
134432 {
134433 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
134434 }
134435  break;
134436  case 234: /* trigger_event */
134437 {
134438 sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
134439 }
134440  break;
134441 /********* End destructor definitions *****************************************/
134442  default: break; /* If no destructor action specified: do nothing */
134443  }
134444 }
134445 
134446 /*
134447 ** Pop the parser's stack once.
134448 **
134449 ** If there is a destructor routine associated with the token which
134450 ** is popped from the stack, then call it.
134451 */
134452 static void yy_pop_parser_stack(yyParser *pParser){
134453  yyStackEntry *yytos;
134454  assert( pParser->yytos!=0 );
134455  assert( pParser->yytos > pParser->yystack );
134456  yytos = pParser->yytos--;
134457 #ifndef NDEBUG
134458  if( yyTraceFILE ){
134459  fprintf(yyTraceFILE,"%sPopping %s\n",
134460  yyTracePrompt,
134461  yyTokenName[yytos->major]);
134462  }
134463 #endif
134464  yy_destructor(pParser, yytos->major, &yytos->minor);
134465 }
134466 
134467 /*
134468 ** Deallocate and destroy a parser. Destructors are called for
134469 ** all stack elements before shutting the parser down.
134470 **
134471 ** If the YYPARSEFREENEVERNULL macro exists (for example because it
134472 ** is defined in a %include section of the input grammar) then it is
134473 ** assumed that the input pointer is never NULL.
134474 */
134475 SQLITE_PRIVATE void sqlite3ParserFree(
134476  void *p, /* The parser to be deleted */
134477  void (*freeProc)(void*) /* Function used to reclaim memory */
134478 ){
134479  yyParser *pParser = (yyParser*)p;
134480 #ifndef YYPARSEFREENEVERNULL
134481  if( pParser==0 ) return;
134482 #endif
134483  while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
134484 #if YYSTACKDEPTH<=0
134485  if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
134486 #endif
134487  (*freeProc)((void*)pParser);
134488 }
134489 
134490 /*
134491 ** Return the peak depth of the stack for a parser.
134492 */
134493 #ifdef YYTRACKMAXSTACKDEPTH
134494 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
134495  yyParser *pParser = (yyParser*)p;
134496  return pParser->yyhwm;
134497 }
134498 #endif
134499 
134500 /*
134501 ** Find the appropriate action for a parser given the terminal
134502 ** look-ahead token iLookAhead.
134503 */
134504 static unsigned int yy_find_shift_action(
134505  yyParser *pParser, /* The parser */
134506  YYCODETYPE iLookAhead /* The look-ahead token */
134507 ){
134508  int i;
134509  int stateno = pParser->yytos->stateno;
134510 
134511  if( stateno>=YY_MIN_REDUCE ) return stateno;
134512  assert( stateno <= YY_SHIFT_COUNT );
134513  do{
134514  i = yy_shift_ofst[stateno];
134515  assert( iLookAhead!=YYNOCODE );
134516  i += iLookAhead;
134517  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
134518 #ifdef YYFALLBACK
134519  YYCODETYPE iFallback; /* Fallback token */
134520  if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
134521  && (iFallback = yyFallback[iLookAhead])!=0 ){
134522 #ifndef NDEBUG
134523  if( yyTraceFILE ){
134524  fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
134525  yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
134526  }
134527 #endif
134528  assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
134529  iLookAhead = iFallback;
134530  continue;
134531  }
134532 #endif
134533 #ifdef YYWILDCARD
134534  {
134535  int j = i - iLookAhead + YYWILDCARD;
134536  if(
134537 #if YY_SHIFT_MIN+YYWILDCARD<0
134538  j>=0 &&
134539 #endif
134540 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
134541  j<YY_ACTTAB_COUNT &&
134542 #endif
134543  yy_lookahead[j]==YYWILDCARD && iLookAhead>0
134544  ){
134545 #ifndef NDEBUG
134546  if( yyTraceFILE ){
134547  fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
134548  yyTracePrompt, yyTokenName[iLookAhead],
134549  yyTokenName[YYWILDCARD]);
134550  }
134551 #endif /* NDEBUG */
134552  return yy_action[j];
134553  }
134554  }
134555 #endif /* YYWILDCARD */
134556  return yy_default[stateno];
134557  }else{
134558  return yy_action[i];
134559  }
134560  }while(1);
134561 }
134562 
134563 /*
134564 ** Find the appropriate action for a parser given the non-terminal
134565 ** look-ahead token iLookAhead.
134566 */
134567 static int yy_find_reduce_action(
134568  int stateno, /* Current state number */
134569  YYCODETYPE iLookAhead /* The look-ahead token */
134570 ){
134571  int i;
134572 #ifdef YYERRORSYMBOL
134573  if( stateno>YY_REDUCE_COUNT ){
134574  return yy_default[stateno];
134575  }
134576 #else
134577  assert( stateno<=YY_REDUCE_COUNT );
134578 #endif
134579  i = yy_reduce_ofst[stateno];
134580  assert( i!=YY_REDUCE_USE_DFLT );
134581  assert( iLookAhead!=YYNOCODE );
134582  i += iLookAhead;
134583 #ifdef YYERRORSYMBOL
134584  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
134585  return yy_default[stateno];
134586  }
134587 #else
134588  assert( i>=0 && i<YY_ACTTAB_COUNT );
134589  assert( yy_lookahead[i]==iLookAhead );
134590 #endif
134591  return yy_action[i];
134592 }
134593 
134594 /*
134595 ** The following routine is called if the stack overflows.
134596 */
134597 static void yyStackOverflow(yyParser *yypParser){
134598  sqlite3ParserARG_FETCH;
134599  yypParser->yytos--;
134600 #ifndef NDEBUG
134601  if( yyTraceFILE ){
134602  fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
134603  }
134604 #endif
134605  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
134606  /* Here code is inserted which will execute if the parser
134607  ** stack every overflows */
134608 /******** Begin %stack_overflow code ******************************************/
134609 
134610  sqlite3ErrorMsg(pParse, "parser stack overflow");
134611 /******** End %stack_overflow code ********************************************/
134612  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
134613 }
134614 
134615 /*
134616 ** Print tracing information for a SHIFT action
134617 */
134618 #ifndef NDEBUG
134619 static void yyTraceShift(yyParser *yypParser, int yyNewState){
134620  if( yyTraceFILE ){
134621  if( yyNewState<YYNSTATE ){
134622  fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
134623  yyTracePrompt,yyTokenName[yypParser->yytos->major],
134624  yyNewState);
134625  }else{
134626  fprintf(yyTraceFILE,"%sShift '%s'\n",
134627  yyTracePrompt,yyTokenName[yypParser->yytos->major]);
134628  }
134629  }
134630 }
134631 #else
134632 # define yyTraceShift(X,Y)
134633 #endif
134634 
134635 /*
134636 ** Perform a shift action.
134637 */
134638 static void yy_shift(
134639  yyParser *yypParser, /* The parser to be shifted */
134640  int yyNewState, /* The new state to shift in */
134641  int yyMajor, /* The major token to shift in */
134642  sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
134643 ){
134644  yyStackEntry *yytos;
134645  yypParser->yytos++;
134646 #ifdef YYTRACKMAXSTACKDEPTH
134647  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
134648  yypParser->yyhwm++;
134649  assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
134650  }
134651 #endif
134652 #if YYSTACKDEPTH>0
134653  if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){
134654  yyStackOverflow(yypParser);
134655  return;
134656  }
134657 #else
134658  if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
134659  if( yyGrowStack(yypParser) ){
134660  yyStackOverflow(yypParser);
134661  return;
134662  }
134663  }
134664 #endif
134665  if( yyNewState > YY_MAX_SHIFT ){
134666  yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
134667  }
134668  yytos = yypParser->yytos;
134669  yytos->stateno = (YYACTIONTYPE)yyNewState;
134670  yytos->major = (YYCODETYPE)yyMajor;
134671  yytos->minor.yy0 = yyMinor;
134672  yyTraceShift(yypParser, yyNewState);
134673 }
134674 
134675 /* The following table contains information about every rule that
134676 ** is used during the reduce.
134677 */
134678 static const struct {
134679  YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
134680  unsigned char nrhs; /* Number of right-hand side symbols in the rule */
134681 } yyRuleInfo[] = {
134682  { 147, 1 },
134683  { 147, 3 },
134684  { 148, 1 },
134685  { 149, 3 },
134686  { 150, 0 },
134687  { 150, 1 },
134688  { 150, 1 },
134689  { 150, 1 },
134690  { 149, 2 },
134691  { 149, 2 },
134692  { 149, 2 },
134693  { 149, 2 },
134694  { 149, 3 },
134695  { 149, 5 },
134696  { 154, 6 },
134697  { 156, 1 },
134698  { 158, 0 },
134699  { 158, 3 },
134700  { 157, 1 },
134701  { 157, 0 },
134702  { 155, 5 },
134703  { 155, 2 },
134704  { 162, 0 },
134705  { 162, 2 },
134706  { 164, 2 },
134707  { 166, 0 },
134708  { 166, 4 },
134709  { 166, 6 },
134710  { 167, 2 },
134711  { 171, 2 },
134712  { 171, 2 },
134713  { 171, 4 },
134714  { 171, 3 },
134715  { 171, 3 },
134716  { 171, 2 },
134717  { 171, 3 },
134718  { 171, 5 },
134719  { 171, 2 },
134720  { 171, 4 },
134721  { 171, 4 },
134722  { 171, 1 },
134723  { 171, 2 },
134724  { 176, 0 },
134725  { 176, 1 },
134726  { 178, 0 },
134727  { 178, 2 },
134728  { 180, 2 },
134729  { 180, 3 },
134730  { 180, 3 },
134731  { 180, 3 },
134732  { 181, 2 },
134733  { 181, 2 },
134734  { 181, 1 },
134735  { 181, 1 },
134736  { 181, 2 },
134737  { 179, 3 },
134738  { 179, 2 },
134739  { 182, 0 },
134740  { 182, 2 },
134741  { 182, 2 },
134742  { 161, 0 },
134743  { 184, 1 },
134744  { 185, 2 },
134745  { 185, 7 },
134746  { 185, 5 },
134747  { 185, 5 },
134748  { 185, 10 },
134749  { 188, 0 },
134750  { 174, 0 },
134751  { 174, 3 },
134752  { 189, 0 },
134753  { 189, 2 },
134754  { 190, 1 },
134755  { 190, 1 },
134756  { 149, 4 },
134757  { 192, 2 },
134758  { 192, 0 },
134759  { 149, 9 },
134760  { 149, 4 },
134761  { 149, 1 },
134762  { 163, 2 },
134763  { 194, 3 },
134764  { 197, 1 },
134765  { 197, 2 },
134766  { 197, 1 },
134767  { 195, 9 },
134768  { 206, 4 },
134769  { 206, 5 },
134770  { 198, 1 },
134771  { 198, 1 },
134772  { 198, 0 },
134773  { 209, 0 },
134774  { 199, 3 },
134775  { 199, 2 },
134776  { 199, 4 },
134777  { 210, 2 },
134778  { 210, 0 },
134779  { 200, 0 },
134780  { 200, 2 },
134781  { 212, 2 },
134782  { 212, 0 },
134783  { 211, 7 },
134784  { 211, 9 },
134785  { 211, 7 },
134786  { 211, 7 },
134787  { 159, 0 },
134788  { 159, 2 },
134789  { 193, 2 },
134790  { 213, 1 },
134791  { 213, 2 },
134792  { 213, 3 },
134793  { 213, 4 },
134794  { 215, 2 },
134795  { 215, 0 },
134796  { 214, 0 },
134797  { 214, 3 },
134798  { 214, 2 },
134799  { 216, 4 },
134800  { 216, 0 },
134801  { 204, 0 },
134802  { 204, 3 },
134803  { 186, 4 },
134804  { 186, 2 },
134805  { 175, 1 },
134806  { 175, 1 },
134807  { 175, 0 },
134808  { 202, 0 },
134809  { 202, 3 },
134810  { 203, 0 },
134811  { 203, 2 },
134812  { 205, 0 },
134813  { 205, 2 },
134814  { 205, 4 },
134815  { 205, 4 },
134816  { 149, 6 },
134817  { 201, 0 },
134818  { 201, 2 },
134819  { 149, 8 },
134820  { 218, 5 },
134821  { 218, 7 },
134822  { 218, 3 },
134823  { 218, 5 },
134824  { 149, 6 },
134825  { 149, 7 },
134826  { 219, 2 },
134827  { 219, 1 },
134828  { 220, 0 },
134829  { 220, 3 },
134830  { 217, 3 },
134831  { 217, 1 },
134832  { 173, 3 },
134833  { 172, 1 },
134834  { 173, 1 },
134835  { 173, 1 },
134836  { 173, 3 },
134837  { 173, 5 },
134838  { 172, 1 },
134839  { 172, 1 },
134840  { 172, 1 },
134841  { 173, 1 },
134842  { 173, 3 },
134843  { 173, 6 },
134844  { 173, 5 },
134845  { 173, 4 },
134846  { 172, 1 },
134847  { 173, 5 },
134848  { 173, 3 },
134849  { 173, 3 },
134850  { 173, 3 },
134851  { 173, 3 },
134852  { 173, 3 },
134853  { 173, 3 },
134854  { 173, 3 },
134855  { 173, 3 },
134856  { 221, 1 },
134857  { 221, 2 },
134858  { 173, 3 },
134859  { 173, 5 },
134860  { 173, 2 },
134861  { 173, 3 },
134862  { 173, 3 },
134863  { 173, 4 },
134864  { 173, 2 },
134865  { 173, 2 },
134866  { 173, 2 },
134867  { 173, 2 },
134868  { 222, 1 },
134869  { 222, 2 },
134870  { 173, 5 },
134871  { 223, 1 },
134872  { 223, 2 },
134873  { 173, 5 },
134874  { 173, 3 },
134875  { 173, 5 },
134876  { 173, 5 },
134877  { 173, 4 },
134878  { 173, 5 },
134879  { 226, 5 },
134880  { 226, 4 },
134881  { 227, 2 },
134882  { 227, 0 },
134883  { 225, 1 },
134884  { 225, 0 },
134885  { 208, 0 },
134886  { 207, 3 },
134887  { 207, 1 },
134888  { 224, 0 },
134889  { 224, 3 },
134890  { 149, 12 },
134891  { 228, 1 },
134892  { 228, 0 },
134893  { 177, 0 },
134894  { 177, 3 },
134895  { 187, 5 },
134896  { 187, 3 },
134897  { 229, 0 },
134898  { 229, 2 },
134899  { 149, 4 },
134900  { 149, 1 },
134901  { 149, 2 },
134902  { 149, 3 },
134903  { 149, 5 },
134904  { 149, 6 },
134905  { 149, 5 },
134906  { 149, 6 },
134907  { 169, 2 },
134908  { 170, 2 },
134909  { 149, 5 },
134910  { 231, 11 },
134911  { 233, 1 },
134912  { 233, 1 },
134913  { 233, 2 },
134914  { 233, 0 },
134915  { 234, 1 },
134916  { 234, 1 },
134917  { 234, 3 },
134918  { 236, 0 },
134919  { 236, 2 },
134920  { 232, 3 },
134921  { 232, 2 },
134922  { 238, 3 },
134923  { 239, 3 },
134924  { 239, 2 },
134925  { 237, 7 },
134926  { 237, 5 },
134927  { 237, 5 },
134928  { 237, 1 },
134929  { 173, 4 },
134930  { 173, 6 },
134931  { 191, 1 },
134932  { 191, 1 },
134933  { 191, 1 },
134934  { 149, 4 },
134935  { 149, 6 },
134936  { 149, 3 },
134937  { 241, 0 },
134938  { 241, 2 },
134939  { 149, 1 },
134940  { 149, 3 },
134941  { 149, 1 },
134942  { 149, 3 },
134943  { 149, 6 },
134944  { 149, 7 },
134945  { 242, 1 },
134946  { 149, 1 },
134947  { 149, 4 },
134948  { 244, 8 },
134949  { 246, 0 },
134950  { 247, 1 },
134951  { 247, 3 },
134952  { 248, 1 },
134953  { 196, 0 },
134954  { 196, 2 },
134955  { 196, 3 },
134956  { 250, 6 },
134957  { 250, 8 },
134958  { 144, 1 },
134959  { 145, 2 },
134960  { 145, 1 },
134961  { 146, 1 },
134962  { 146, 3 },
134963  { 147, 0 },
134964  { 151, 0 },
134965  { 151, 1 },
134966  { 151, 2 },
134967  { 153, 1 },
134968  { 153, 0 },
134969  { 149, 2 },
134970  { 160, 4 },
134971  { 160, 2 },
134972  { 152, 1 },
134973  { 152, 1 },
134974  { 152, 1 },
134975  { 166, 1 },
134976  { 167, 1 },
134977  { 168, 1 },
134978  { 168, 1 },
134979  { 165, 2 },
134980  { 165, 0 },
134981  { 171, 2 },
134982  { 161, 2 },
134983  { 183, 3 },
134984  { 183, 1 },
134985  { 184, 0 },
134986  { 188, 1 },
134987  { 190, 1 },
134988  { 194, 1 },
134989  { 195, 1 },
134990  { 209, 2 },
134991  { 210, 1 },
134992  { 173, 1 },
134993  { 208, 1 },
134994  { 230, 1 },
134995  { 230, 1 },
134996  { 230, 1 },
134997  { 230, 1 },
134998  { 230, 1 },
134999  { 169, 1 },
135000  { 235, 0 },
135001  { 235, 3 },
135002  { 238, 1 },
135003  { 239, 0 },
135004  { 240, 1 },
135005  { 240, 0 },
135006  { 243, 0 },
135007  { 243, 1 },
135008  { 245, 1 },
135009  { 245, 3 },
135010  { 246, 2 },
135011  { 249, 0 },
135012  { 249, 4 },
135013  { 249, 2 },
135014 };
135015 
135016 static void yy_accept(yyParser*); /* Forward Declaration */
135017 
135018 /*
135019 ** Perform a reduce action and the shift that must immediately
135020 ** follow the reduce.
135021 */
135022 static void yy_reduce(
135023  yyParser *yypParser, /* The parser */
135024  unsigned int yyruleno /* Number of the rule by which to reduce */
135025 ){
135026  int yygoto; /* The next state */
135027  int yyact; /* The next action */
135028  yyStackEntry *yymsp; /* The top of the parser's stack */
135029  int yysize; /* Amount to pop the stack */
135030  sqlite3ParserARG_FETCH;
135031  yymsp = yypParser->yytos;
135032 #ifndef NDEBUG
135033  if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
135034  yysize = yyRuleInfo[yyruleno].nrhs;
135035  fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
135036  yyRuleName[yyruleno], yymsp[-yysize].stateno);
135037  }
135038 #endif /* NDEBUG */
135039 
135040  /* Check that the stack is large enough to grow by a single entry
135041  ** if the RHS of the rule is empty. This ensures that there is room
135042  ** enough on the stack to push the LHS value */
135043  if( yyRuleInfo[yyruleno].nrhs==0 ){
135044 #ifdef YYTRACKMAXSTACKDEPTH
135045  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
135046  yypParser->yyhwm++;
135047  assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
135048  }
135049 #endif
135050 #if YYSTACKDEPTH>0
135051  if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){
135052  yyStackOverflow(yypParser);
135053  return;
135054  }
135055 #else
135056  if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
135057  if( yyGrowStack(yypParser) ){
135058  yyStackOverflow(yypParser);
135059  return;
135060  }
135061  yymsp = yypParser->yytos;
135062  }
135063 #endif
135064  }
135065 
135066  switch( yyruleno ){
135067  /* Beginning here are the reduction cases. A typical example
135068  ** follows:
135069  ** case 0:
135070  ** #line <lineno> <grammarfile>
135071  ** { ... } // User supplied code
135072  ** #line <lineno> <thisfile>
135073  ** break;
135074  */
135075 /********** Begin reduce actions **********************************************/
135076  YYMINORTYPE yylhsminor;
135077  case 0: /* explain ::= EXPLAIN */
135078 { pParse->explain = 1; }
135079  break;
135080  case 1: /* explain ::= EXPLAIN QUERY PLAN */
135081 { pParse->explain = 2; }
135082  break;
135083  case 2: /* cmdx ::= cmd */
135084 { sqlite3FinishCoding(pParse); }
135085  break;
135086  case 3: /* cmd ::= BEGIN transtype trans_opt */
135087 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
135088  break;
135089  case 4: /* transtype ::= */
135090 {yymsp[1].minor.yy194 = TK_DEFERRED;}
135091  break;
135092  case 5: /* transtype ::= DEFERRED */
135093  case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
135094  case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
135095 {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
135096  break;
135097  case 8: /* cmd ::= COMMIT trans_opt */
135098  case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
135099 {sqlite3CommitTransaction(pParse);}
135100  break;
135101  case 10: /* cmd ::= ROLLBACK trans_opt */
135102 {sqlite3RollbackTransaction(pParse);}
135103  break;
135104  case 11: /* cmd ::= SAVEPOINT nm */
135105 {
135106  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
135107 }
135108  break;
135109  case 12: /* cmd ::= RELEASE savepoint_opt nm */
135110 {
135111  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
135112 }
135113  break;
135114  case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
135115 {
135116  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
135117 }
135118  break;
135119  case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
135120 {
135121  sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
135122 }
135123  break;
135124  case 15: /* createkw ::= CREATE */
135125 {disableLookaside(pParse);}
135126  break;
135127  case 16: /* ifnotexists ::= */
135128  case 19: /* temp ::= */ yytestcase(yyruleno==19);
135129  case 22: /* table_options ::= */ yytestcase(yyruleno==22);
135130  case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
135131  case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
135132  case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
135133  case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
135134  case 90: /* distinct ::= */ yytestcase(yyruleno==90);
135135  case 215: /* collate ::= */ yytestcase(yyruleno==215);
135136 {yymsp[1].minor.yy194 = 0;}
135137  break;
135138  case 17: /* ifnotexists ::= IF NOT EXISTS */
135139 {yymsp[-2].minor.yy194 = 1;}
135140  break;
135141  case 18: /* temp ::= TEMP */
135142  case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
135143 {yymsp[0].minor.yy194 = 1;}
135144  break;
135145  case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
135146 {
135147  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
135148 }
135149  break;
135150  case 21: /* create_table_args ::= AS select */
135151 {
135152  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
135153  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
135154 }
135155  break;
135156  case 23: /* table_options ::= WITHOUT nm */
135157 {
135158  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
135159  yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
135160  }else{
135161  yymsp[-1].minor.yy194 = 0;
135162  sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
135163  }
135164 }
135165  break;
135166  case 24: /* columnname ::= nm typetoken */
135167 {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
135168  break;
135169  case 25: /* typetoken ::= */
135170  case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
135171  case 96: /* as ::= */ yytestcase(yyruleno==96);
135172 {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
135173  break;
135174  case 26: /* typetoken ::= typename LP signed RP */
135175 {
135176  yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
135177 }
135178  break;
135179  case 27: /* typetoken ::= typename LP signed COMMA signed RP */
135180 {
135181  yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
135182 }
135183  break;
135184  case 28: /* typename ::= typename ID|STRING */
135185 {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
135186  break;
135187  case 29: /* ccons ::= CONSTRAINT nm */
135188  case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
135189 {pParse->constraintName = yymsp[0].minor.yy0;}
135190  break;
135191  case 30: /* ccons ::= DEFAULT term */
135192  case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
135193 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
135194  break;
135195  case 31: /* ccons ::= DEFAULT LP expr RP */
135196 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
135197  break;
135198  case 33: /* ccons ::= DEFAULT MINUS term */
135199 {
135200  ExprSpan v;
135201  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0, 0);
135202  v.zStart = yymsp[-1].minor.yy0.z;
135203  v.zEnd = yymsp[0].minor.yy190.zEnd;
135204  sqlite3AddDefaultValue(pParse,&v);
135205 }
135206  break;
135207  case 34: /* ccons ::= DEFAULT ID|INDEXED */
135208 {
135209  ExprSpan v;
135210  spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
135211  sqlite3AddDefaultValue(pParse,&v);
135212 }
135213  break;
135214  case 35: /* ccons ::= NOT NULL onconf */
135215 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
135216  break;
135217  case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
135218 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
135219  break;
135220  case 37: /* ccons ::= UNIQUE onconf */
135221 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
135222  SQLITE_IDXTYPE_UNIQUE);}
135223  break;
135224  case 38: /* ccons ::= CHECK LP expr RP */
135225 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
135226  break;
135227  case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
135228 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
135229  break;
135230  case 40: /* ccons ::= defer_subclause */
135231 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
135232  break;
135233  case 41: /* ccons ::= COLLATE ID|STRING */
135234 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
135235  break;
135236  case 44: /* refargs ::= */
135237 { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
135238  break;
135239  case 45: /* refargs ::= refargs refarg */
135240 { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
135241  break;
135242  case 46: /* refarg ::= MATCH nm */
135243 { yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; }
135244  break;
135245  case 47: /* refarg ::= ON INSERT refact */
135246 { yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; }
135247  break;
135248  case 48: /* refarg ::= ON DELETE refact */
135249 { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; }
135250  break;
135251  case 49: /* refarg ::= ON UPDATE refact */
135252 { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; }
135253  break;
135254  case 50: /* refact ::= SET NULL */
135255 { yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */}
135256  break;
135257  case 51: /* refact ::= SET DEFAULT */
135258 { yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */}
135259  break;
135260  case 52: /* refact ::= CASCADE */
135261 { yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */}
135262  break;
135263  case 53: /* refact ::= RESTRICT */
135264 { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
135265  break;
135266  case 54: /* refact ::= NO ACTION */
135267 { yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */}
135268  break;
135269  case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
135270 {yymsp[-2].minor.yy194 = 0;}
135271  break;
135272  case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
135273  case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
135274  case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144);
135275 {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
135276  break;
135277  case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
135278  case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
135279  case 187: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==187);
135280  case 190: /* in_op ::= NOT IN */ yytestcase(yyruleno==190);
135281  case 216: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==216);
135282 {yymsp[-1].minor.yy194 = 1;}
135283  break;
135284  case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
135285 {yymsp[-1].minor.yy194 = 0;}
135286  break;
135287  case 61: /* tconscomma ::= COMMA */
135288 {pParse->constraintName.n = 0;}
135289  break;
135290  case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
135291 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
135292  break;
135293  case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
135294 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
135295  SQLITE_IDXTYPE_UNIQUE);}
135296  break;
135297  case 65: /* tcons ::= CHECK LP expr RP onconf */
135298 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
135299  break;
135300  case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
135301 {
135302  sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
135303  sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
135304 }
135305  break;
135306  case 68: /* onconf ::= */
135307  case 70: /* orconf ::= */ yytestcase(yyruleno==70);
135308 {yymsp[1].minor.yy194 = OE_Default;}
135309  break;
135310  case 69: /* onconf ::= ON CONFLICT resolvetype */
135311 {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
135312  break;
135313  case 72: /* resolvetype ::= IGNORE */
135314 {yymsp[0].minor.yy194 = OE_Ignore;}
135315  break;
135316  case 73: /* resolvetype ::= REPLACE */
135317  case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145);
135318 {yymsp[0].minor.yy194 = OE_Replace;}
135319  break;
135320  case 74: /* cmd ::= DROP TABLE ifexists fullname */
135321 {
135322  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
135323 }
135324  break;
135325  case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
135326 {
135327  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194);
135328 }
135329  break;
135330  case 78: /* cmd ::= DROP VIEW ifexists fullname */
135331 {
135332  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
135333 }
135334  break;
135335  case 79: /* cmd ::= select */
135336 {
135337  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
135338  sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
135339  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
135340 }
135341  break;
135342  case 80: /* select ::= with selectnowith */
135343 {
135344  Select *p = yymsp[0].minor.yy243;
135345  if( p ){
135346  p->pWith = yymsp[-1].minor.yy285;
135347  parserDoubleLinkSelect(pParse, p);
135348  }else{
135349  sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
135350  }
135351  yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
135352 }
135353  break;
135354  case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
135355 {
135356  Select *pRhs = yymsp[0].minor.yy243;
135357  Select *pLhs = yymsp[-2].minor.yy243;
135358  if( pRhs && pRhs->pPrior ){
135359  SrcList *pFrom;
135360  Token x;
135361  x.n = 0;
135362  parserDoubleLinkSelect(pParse, pRhs);
135363  pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
135364  pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
135365  }
135366  if( pRhs ){
135367  pRhs->op = (u8)yymsp[-1].minor.yy194;
135368  pRhs->pPrior = pLhs;
135369  if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
135370  pRhs->selFlags &= ~SF_MultiValue;
135371  if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
135372  }else{
135373  sqlite3SelectDelete(pParse->db, pLhs);
135374  }
135375  yymsp[-2].minor.yy243 = pRhs;
135376 }
135377  break;
135378  case 82: /* multiselect_op ::= UNION */
135379  case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
135380 {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
135381  break;
135382  case 83: /* multiselect_op ::= UNION ALL */
135383 {yymsp[-1].minor.yy194 = TK_ALL;}
135384  break;
135385  case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
135386 {
135387 #if SELECTTRACE_ENABLED
135388  Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
135389 #endif
135390  yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset);
135391 #if SELECTTRACE_ENABLED
135392  /* Populate the Select.zSelName[] string that is used to help with
135393  ** query planner debugging, to differentiate between multiple Select
135394  ** objects in a complex query.
135395  **
135396  ** If the SELECT keyword is immediately followed by a C-style comment
135397  ** then extract the first few alphanumeric characters from within that
135398  ** comment to be the zSelName value. Otherwise, the label is #N where
135399  ** is an integer that is incremented with each SELECT statement seen.
135400  */
135401  if( yymsp[-8].minor.yy243!=0 ){
135402  const char *z = s.z+6;
135403  int i;
135404  sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
135405  ++pParse->nSelect);
135406  while( z[0]==' ' ) z++;
135407  if( z[0]=='/' && z[1]=='*' ){
135408  z += 2;
135409  while( z[0]==' ' ) z++;
135410  for(i=0; sqlite3Isalnum(z[i]); i++){}
135411  sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
135412  }
135413  }
135414 #endif /* SELECTRACE_ENABLED */
135415 }
135416  break;
135417  case 86: /* values ::= VALUES LP nexprlist RP */
135418 {
135419  yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
135420 }
135421  break;
135422  case 87: /* values ::= values COMMA LP exprlist RP */
135423 {
135424  Select *pRight, *pLeft = yymsp[-4].minor.yy243;
135425  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
135426  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
135427  if( pRight ){
135428  pRight->op = TK_ALL;
135429  pRight->pPrior = pLeft;
135430  yymsp[-4].minor.yy243 = pRight;
135431  }else{
135432  yymsp[-4].minor.yy243 = pLeft;
135433  }
135434 }
135435  break;
135436  case 88: /* distinct ::= DISTINCT */
135437 {yymsp[0].minor.yy194 = SF_Distinct;}
135438  break;
135439  case 89: /* distinct ::= ALL */
135440 {yymsp[0].minor.yy194 = SF_All;}
135441  break;
135442  case 91: /* sclp ::= */
135443  case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
135444  case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
135445  case 203: /* exprlist ::= */ yytestcase(yyruleno==203);
135446  case 206: /* paren_exprlist ::= */ yytestcase(yyruleno==206);
135447  case 211: /* eidlist_opt ::= */ yytestcase(yyruleno==211);
135448 {yymsp[1].minor.yy148 = 0;}
135449  break;
135450  case 92: /* selcollist ::= sclp expr as */
135451 {
135452  yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
135453  if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
135454  sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
135455 }
135456  break;
135457  case 93: /* selcollist ::= sclp STAR */
135458 {
135459  Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
135460  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
135461 }
135462  break;
135463  case 94: /* selcollist ::= sclp nm DOT STAR */
135464 {
135465  Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, 0);
135466  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
135467  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
135468  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
135469 }
135470  break;
135471  case 95: /* as ::= AS nm */
135472  case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
135473  case 225: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==225);
135474  case 226: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==226);
135475 {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
135476  break;
135477  case 97: /* from ::= */
135478 {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
135479  break;
135480  case 98: /* from ::= FROM seltablist */
135481 {
135482  yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
135483  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
135484 }
135485  break;
135486  case 99: /* stl_prefix ::= seltablist joinop */
135487 {
135488  if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194;
135489 }
135490  break;
135491  case 100: /* stl_prefix ::= */
135492 {yymsp[1].minor.yy185 = 0;}
135493  break;
135494  case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
135495 {
135496  yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
135497  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
135498 }
135499  break;
135500  case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
135501 {
135502  yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
135503  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
135504 }
135505  break;
135506  case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
135507 {
135508  yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
135509  }
135510  break;
135511  case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
135512 {
135513  if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
135514  yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
135515  }else if( yymsp[-4].minor.yy185->nSrc==1 ){
135516  yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
135517  if( yymsp[-6].minor.yy185 ){
135518  struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
135519  struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
135520  pNew->zName = pOld->zName;
135521  pNew->zDatabase = pOld->zDatabase;
135522  pNew->pSelect = pOld->pSelect;
135523  pOld->zName = pOld->zDatabase = 0;
135524  pOld->pSelect = 0;
135525  }
135526  sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
135527  }else{
135528  Select *pSubquery;
135529  sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
135530  pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
135531  yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
135532  }
135533  }
135534  break;
135535  case 105: /* dbnm ::= */
135536  case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
135537 {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
135538  break;
135539  case 107: /* fullname ::= nm dbnm */
135540 {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
135541  break;
135542  case 108: /* joinop ::= COMMA|JOIN */
135543 { yymsp[0].minor.yy194 = JT_INNER; }
135544  break;
135545  case 109: /* joinop ::= JOIN_KW JOIN */
135546 {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
135547  break;
135548  case 110: /* joinop ::= JOIN_KW nm JOIN */
135549 {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
135550  break;
135551  case 111: /* joinop ::= JOIN_KW nm nm JOIN */
135552 {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
135553  break;
135554  case 112: /* on_opt ::= ON expr */
135555  case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
135556  case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
135557  case 199: /* case_else ::= ELSE expr */ yytestcase(yyruleno==199);
135558 {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
135559  break;
135560  case 113: /* on_opt ::= */
135561  case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
135562  case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
135563  case 200: /* case_else ::= */ yytestcase(yyruleno==200);
135564  case 202: /* case_operand ::= */ yytestcase(yyruleno==202);
135565 {yymsp[1].minor.yy72 = 0;}
135566  break;
135567  case 115: /* indexed_opt ::= INDEXED BY nm */
135568 {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
135569  break;
135570  case 116: /* indexed_opt ::= NOT INDEXED */
135571 {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
135572  break;
135573  case 117: /* using_opt ::= USING LP idlist RP */
135574 {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
135575  break;
135576  case 118: /* using_opt ::= */
135577  case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146);
135578 {yymsp[1].minor.yy254 = 0;}
135579  break;
135580  case 120: /* orderby_opt ::= ORDER BY sortlist */
135581  case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
135582 {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
135583  break;
135584  case 121: /* sortlist ::= sortlist COMMA expr sortorder */
135585 {
135586  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
135587  sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
135588 }
135589  break;
135590  case 122: /* sortlist ::= expr sortorder */
135591 {
135592  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
135593  sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
135594 }
135595  break;
135596  case 123: /* sortorder ::= ASC */
135597 {yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
135598  break;
135599  case 124: /* sortorder ::= DESC */
135600 {yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
135601  break;
135602  case 125: /* sortorder ::= */
135603 {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
135604  break;
135605  case 130: /* limit_opt ::= */
135606 {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
135607  break;
135608  case 131: /* limit_opt ::= LIMIT expr */
135609 {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
135610  break;
135611  case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
135612 {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
135613  break;
135614  case 133: /* limit_opt ::= LIMIT expr COMMA expr */
135615 {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
135616  break;
135617  case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
135618 {
135619  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
135620  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
135621  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
135622 }
135623  break;
135624  case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
135625 {
135626  sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
135627  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
135628  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
135629  sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
135630 }
135631  break;
135632  case 138: /* setlist ::= setlist COMMA nm EQ expr */
135633 {
135634  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
135635  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
135636 }
135637  break;
135638  case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
135639 {
135640  yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
135641 }
135642  break;
135643  case 140: /* setlist ::= nm EQ expr */
135644 {
135645  yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
135646  sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
135647 }
135648  yymsp[-2].minor.yy148 = yylhsminor.yy148;
135649  break;
135650  case 141: /* setlist ::= LP idlist RP EQ expr */
135651 {
135652  yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
135653 }
135654  break;
135655  case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
135656 {
135657  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
135658  sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
135659 }
135660  break;
135661  case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
135662 {
135663  sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
135664  sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
135665 }
135666  break;
135667  case 147: /* idlist_opt ::= LP idlist RP */
135668 {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
135669  break;
135670  case 148: /* idlist ::= idlist COMMA nm */
135671 {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
135672  break;
135673  case 149: /* idlist ::= nm */
135674 {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
135675  break;
135676  case 150: /* expr ::= LP expr RP */
135677 {spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;}
135678  break;
135679  case 151: /* term ::= NULL */
135680  case 156: /* term ::= FLOAT|BLOB */ yytestcase(yyruleno==156);
135681  case 157: /* term ::= STRING */ yytestcase(yyruleno==157);
135682 {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
135683  break;
135684  case 152: /* expr ::= ID|INDEXED */
135685  case 153: /* expr ::= JOIN_KW */ yytestcase(yyruleno==153);
135686 {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
135687  break;
135688  case 154: /* expr ::= nm DOT nm */
135689 {
135690  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
135691  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
135692  spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
135693  yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
135694 }
135695  break;
135696  case 155: /* expr ::= nm DOT nm DOT nm */
135697 {
135698  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
135699  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
135700  Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
135701  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
135702  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
135703  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
135704 }
135705  break;
135706  case 158: /* term ::= INTEGER */
135707 {
135708  yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
135709  yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z;
135710  yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n;
135711  if( yylhsminor.yy190.pExpr ) yylhsminor.yy190.pExpr->flags |= EP_Leaf;
135712 }
135713  yymsp[0].minor.yy190 = yylhsminor.yy190;
135714  break;
135715  case 159: /* expr ::= VARIABLE */
135716 {
135717  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
135718  u32 n = yymsp[0].minor.yy0.n;
135719  spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
135720  sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n);
135721  }else{
135722  /* When doing a nested parse, one can include terms in an expression
135723  ** that look like this: #1 #2 ... These terms refer to registers
135724  ** in the virtual machine. #N is the N-th register. */
135725  Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
135726  assert( t.n>=2 );
135727  spanSet(&yymsp[0].minor.yy190, &t, &t);
135728  if( pParse->nested==0 ){
135729  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
135730  yymsp[0].minor.yy190.pExpr = 0;
135731  }else{
135732  yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, 0);
135733  if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
135734  }
135735  }
135736 }
135737  break;
135738  case 160: /* expr ::= expr COLLATE ID|STRING */
135739 {
135740  yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
135741  yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
135742 }
135743  break;
135744  case 161: /* expr ::= CAST LP expr AS typetoken RP */
135745 {
135746  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
135747  yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy190.pExpr, 0, &yymsp[-1].minor.yy0);
135748 }
135749  break;
135750  case 162: /* expr ::= ID|INDEXED LP distinct exprlist RP */
135751 {
135752  if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
135753  sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
135754  }
135755  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
135756  spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
135757  if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
135758  yylhsminor.yy190.pExpr->flags |= EP_Distinct;
135759  }
135760 }
135761  yymsp[-4].minor.yy190 = yylhsminor.yy190;
135762  break;
135763  case 163: /* expr ::= ID|INDEXED LP STAR RP */
135764 {
135765  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
135766  spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
135767 }
135768  yymsp[-3].minor.yy190 = yylhsminor.yy190;
135769  break;
135770  case 164: /* term ::= CTIME_KW */
135771 {
135772  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
135773  spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
135774 }
135775  yymsp[0].minor.yy190 = yylhsminor.yy190;
135776  break;
135777  case 165: /* expr ::= LP nexprlist COMMA expr RP */
135778 {
135779  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr);
135780  yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0, 0);
135781  if( yylhsminor.yy190.pExpr ){
135782  yylhsminor.yy190.pExpr->x.pList = pList;
135783  spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
135784  }else{
135785  sqlite3ExprListDelete(pParse->db, pList);
135786  }
135787 }
135788  yymsp[-4].minor.yy190 = yylhsminor.yy190;
135789  break;
135790  case 166: /* expr ::= expr AND expr */
135791  case 167: /* expr ::= expr OR expr */ yytestcase(yyruleno==167);
135792  case 168: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==168);
135793  case 169: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==169);
135794  case 170: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==170);
135795  case 171: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==171);
135796  case 172: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==172);
135797  case 173: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==173);
135798 {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
135799  break;
135800  case 174: /* likeop ::= LIKE_KW|MATCH */
135801 {yymsp[0].minor.yy0=yymsp[0].minor.yy0;/*A-overwrites-X*/}
135802  break;
135803  case 175: /* likeop ::= NOT LIKE_KW|MATCH */
135804 {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
135805  break;
135806  case 176: /* expr ::= expr likeop expr */
135807 {
135808  ExprList *pList;
135809  int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
135810  yymsp[-1].minor.yy0.n &= 0x7fffffff;
135811  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
135812  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
135813  yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
135814  exprNot(pParse, bNot, &yymsp[-2].minor.yy190);
135815  yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
135816  if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
135817 }
135818  break;
135819  case 177: /* expr ::= expr likeop expr ESCAPE expr */
135820 {
135821  ExprList *pList;
135822  int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
135823  yymsp[-3].minor.yy0.n &= 0x7fffffff;
135824  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
135825  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
135826  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
135827  yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
135828  exprNot(pParse, bNot, &yymsp[-4].minor.yy190);
135829  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
135830  if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
135831 }
135832  break;
135833  case 178: /* expr ::= expr ISNULL|NOTNULL */
135834 {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
135835  break;
135836  case 179: /* expr ::= expr NOT NULL */
135837 {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
135838  break;
135839  case 180: /* expr ::= expr IS expr */
135840 {
135841  spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
135842  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
135843 }
135844  break;
135845  case 181: /* expr ::= expr IS NOT expr */
135846 {
135847  spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
135848  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
135849 }
135850  break;
135851  case 182: /* expr ::= NOT expr */
135852  case 183: /* expr ::= BITNOT expr */ yytestcase(yyruleno==183);
135853 {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
135854  break;
135855  case 184: /* expr ::= MINUS expr */
135856 {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
135857  break;
135858  case 185: /* expr ::= PLUS expr */
135859 {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
135860  break;
135861  case 186: /* between_op ::= BETWEEN */
135862  case 189: /* in_op ::= IN */ yytestcase(yyruleno==189);
135863 {yymsp[0].minor.yy194 = 0;}
135864  break;
135865  case 188: /* expr ::= expr between_op expr AND expr */
135866 {
135867  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
135868  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
135869  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0, 0);
135870  if( yymsp[-4].minor.yy190.pExpr ){
135871  yymsp[-4].minor.yy190.pExpr->x.pList = pList;
135872  }else{
135873  sqlite3ExprListDelete(pParse->db, pList);
135874  }
135875  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
135876  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
135877 }
135878  break;
135879  case 191: /* expr ::= expr in_op LP exprlist RP */
135880 {
135881  if( yymsp[-1].minor.yy148==0 ){
135882  /* Expressions of the form
135883  **
135884  ** expr1 IN ()
135885  ** expr1 NOT IN ()
135886  **
135887  ** simplify to constants 0 (false) and 1 (true), respectively,
135888  ** regardless of the value of expr1.
135889  */
135890  sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
135891  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy194]);
135892  }else if( yymsp[-1].minor.yy148->nExpr==1 ){
135893  /* Expressions of the form:
135894  **
135895  ** expr1 IN (?1)
135896  ** expr1 NOT IN (?2)
135897  **
135898  ** with exactly one value on the RHS can be simplified to something
135899  ** like this:
135900  **
135901  ** expr1 == ?1
135902  ** expr1 <> ?2
135903  **
135904  ** But, the RHS of the == or <> is marked with the EP_Generic flag
135905  ** so that it may not contribute to the computation of comparison
135906  ** affinity or the collating sequence to use for comparison. Otherwise,
135907  ** the semantics would be subtly different from IN or NOT IN.
135908  */
135909  Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
135910  yymsp[-1].minor.yy148->a[0].pExpr = 0;
135911  sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
135912  /* pRHS cannot be NULL because a malloc error would have been detected
135913  ** before now and control would have never reached this point */
135914  if( ALWAYS(pRHS) ){
135915  pRHS->flags &= ~EP_Collate;
135916  pRHS->flags |= EP_Generic;
135917  }
135918  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS, 0);
135919  }else{
135920  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
135921  if( yymsp[-4].minor.yy190.pExpr ){
135922  yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
135923  sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
135924  }else{
135925  sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
135926  }
135927  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
135928  }
135929  yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
135930  }
135931  break;
135932  case 192: /* expr ::= LP select RP */
135933 {
135934  spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
135935  yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
135936  sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
135937  }
135938  break;
135939  case 193: /* expr ::= expr in_op LP select RP */
135940 {
135941  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
135942  sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
135943  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
135944  yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
135945  }
135946  break;
135947  case 194: /* expr ::= expr in_op nm dbnm paren_exprlist */
135948 {
135949  SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
135950  Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
135951  if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
135952  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
135953  sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
135954  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
135955  yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n];
135956  }
135957  break;
135958  case 195: /* expr ::= EXISTS LP select RP */
135959 {
135960  Expr *p;
135961  spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
135962  p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
135963  sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
135964  }
135965  break;
135966  case 196: /* expr ::= CASE case_operand case_exprlist case_else END */
135967 {
135968  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
135969  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0, 0);
135970  if( yymsp[-4].minor.yy190.pExpr ){
135971  yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148;
135972  sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
135973  }else{
135974  sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
135975  sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
135976  }
135977 }
135978  break;
135979  case 197: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
135980 {
135981  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
135982  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
135983 }
135984  break;
135985  case 198: /* case_exprlist ::= WHEN expr THEN expr */
135986 {
135987  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
135988  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
135989 }
135990  break;
135991  case 201: /* case_operand ::= expr */
135992 {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
135993  break;
135994  case 204: /* nexprlist ::= nexprlist COMMA expr */
135995 {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
135996  break;
135997  case 205: /* nexprlist ::= expr */
135998 {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
135999  break;
136000  case 207: /* paren_exprlist ::= LP exprlist RP */
136001  case 212: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==212);
136002 {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
136003  break;
136004  case 208: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
136005 {
136006  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
136007  sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
136008  &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
136009 }
136010  break;
136011  case 209: /* uniqueflag ::= UNIQUE */
136012  case 250: /* raisetype ::= ABORT */ yytestcase(yyruleno==250);
136013 {yymsp[0].minor.yy194 = OE_Abort;}
136014  break;
136015  case 210: /* uniqueflag ::= */
136016 {yymsp[1].minor.yy194 = OE_None;}
136017  break;
136018  case 213: /* eidlist ::= eidlist COMMA nm collate sortorder */
136019 {
136020  yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
136021 }
136022  break;
136023  case 214: /* eidlist ::= nm collate sortorder */
136024 {
136025  yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
136026 }
136027  break;
136028  case 217: /* cmd ::= DROP INDEX ifexists fullname */
136029 {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
136030  break;
136031  case 218: /* cmd ::= VACUUM */
136032 {sqlite3Vacuum(pParse,0);}
136033  break;
136034  case 219: /* cmd ::= VACUUM nm */
136035 {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
136036  break;
136037  case 220: /* cmd ::= PRAGMA nm dbnm */
136038 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
136039  break;
136040  case 221: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
136041 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
136042  break;
136043  case 222: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
136044 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
136045  break;
136046  case 223: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
136047 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
136048  break;
136049  case 224: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
136050 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
136051  break;
136052  case 227: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
136053 {
136054  Token all;
136055  all.z = yymsp[-3].minor.yy0.z;
136056  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
136057  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
136058 }
136059  break;
136060  case 228: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
136061 {
136062  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194);
136063  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
136064 }
136065  break;
136066  case 229: /* trigger_time ::= BEFORE */
136067 { yymsp[0].minor.yy194 = TK_BEFORE; }
136068  break;
136069  case 230: /* trigger_time ::= AFTER */
136070 { yymsp[0].minor.yy194 = TK_AFTER; }
136071  break;
136072  case 231: /* trigger_time ::= INSTEAD OF */
136073 { yymsp[-1].minor.yy194 = TK_INSTEAD;}
136074  break;
136075  case 232: /* trigger_time ::= */
136076 { yymsp[1].minor.yy194 = TK_BEFORE; }
136077  break;
136078  case 233: /* trigger_event ::= DELETE|INSERT */
136079  case 234: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==234);
136080 {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
136081  break;
136082  case 235: /* trigger_event ::= UPDATE OF idlist */
136083 {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
136084  break;
136085  case 236: /* when_clause ::= */
136086  case 255: /* key_opt ::= */ yytestcase(yyruleno==255);
136087 { yymsp[1].minor.yy72 = 0; }
136088  break;
136089  case 237: /* when_clause ::= WHEN expr */
136090  case 256: /* key_opt ::= KEY expr */ yytestcase(yyruleno==256);
136091 { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
136092  break;
136093  case 238: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
136094 {
136095  assert( yymsp[-2].minor.yy145!=0 );
136096  yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
136097  yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
136098 }
136099  break;
136100  case 239: /* trigger_cmd_list ::= trigger_cmd SEMI */
136101 {
136102  assert( yymsp[-1].minor.yy145!=0 );
136103  yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
136104 }
136105  break;
136106  case 240: /* trnm ::= nm DOT nm */
136107 {
136108  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
136109  sqlite3ErrorMsg(pParse,
136110  "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
136111  "statements within triggers");
136112 }
136113  break;
136114  case 241: /* tridxby ::= INDEXED BY nm */
136115 {
136116  sqlite3ErrorMsg(pParse,
136117  "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
136118  "within triggers");
136119 }
136120  break;
136121  case 242: /* tridxby ::= NOT INDEXED */
136122 {
136123  sqlite3ErrorMsg(pParse,
136124  "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
136125  "within triggers");
136126 }
136127  break;
136128  case 243: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
136129 {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
136130  break;
136131  case 244: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
136132 {yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/}
136133  break;
136134  case 245: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
136135 {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
136136  break;
136137  case 246: /* trigger_cmd ::= select */
136138 {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
136139  break;
136140  case 247: /* expr ::= RAISE LP IGNORE RP */
136141 {
136142  spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
136143  yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
136144  if( yymsp[-3].minor.yy190.pExpr ){
136145  yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
136146  }
136147 }
136148  break;
136149  case 248: /* expr ::= RAISE LP raisetype COMMA nm RP */
136150 {
136151  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
136152  yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
136153  if( yymsp[-5].minor.yy190.pExpr ) {
136154  yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
136155  }
136156 }
136157  break;
136158  case 249: /* raisetype ::= ROLLBACK */
136159 {yymsp[0].minor.yy194 = OE_Rollback;}
136160  break;
136161  case 251: /* raisetype ::= FAIL */
136162 {yymsp[0].minor.yy194 = OE_Fail;}
136163  break;
136164  case 252: /* cmd ::= DROP TRIGGER ifexists fullname */
136165 {
136166  sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
136167 }
136168  break;
136169  case 253: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
136170 {
136171  sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
136172 }
136173  break;
136174  case 254: /* cmd ::= DETACH database_kw_opt expr */
136175 {
136176  sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
136177 }
136178  break;
136179  case 257: /* cmd ::= REINDEX */
136180 {sqlite3Reindex(pParse, 0, 0);}
136181  break;
136182  case 258: /* cmd ::= REINDEX nm dbnm */
136183 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
136184  break;
136185  case 259: /* cmd ::= ANALYZE */
136186 {sqlite3Analyze(pParse, 0, 0);}
136187  break;
136188  case 260: /* cmd ::= ANALYZE nm dbnm */
136189 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
136190  break;
136191  case 261: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
136192 {
136193  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
136194 }
136195  break;
136196  case 262: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
136197 {
136198  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
136199  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
136200 }
136201  break;
136202  case 263: /* add_column_fullname ::= fullname */
136203 {
136204  disableLookaside(pParse);
136205  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
136206 }
136207  break;
136208  case 264: /* cmd ::= create_vtab */
136209 {sqlite3VtabFinishParse(pParse,0);}
136210  break;
136211  case 265: /* cmd ::= create_vtab LP vtabarglist RP */
136212 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
136213  break;
136214  case 266: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
136215 {
136216  sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
136217 }
136218  break;
136219  case 267: /* vtabarg ::= */
136220 {sqlite3VtabArgInit(pParse);}
136221  break;
136222  case 268: /* vtabargtoken ::= ANY */
136223  case 269: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==269);
136224  case 270: /* lp ::= LP */ yytestcase(yyruleno==270);
136225 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
136226  break;
136227  case 271: /* with ::= */
136228 {yymsp[1].minor.yy285 = 0;}
136229  break;
136230  case 272: /* with ::= WITH wqlist */
136231 { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
136232  break;
136233  case 273: /* with ::= WITH RECURSIVE wqlist */
136234 { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
136235  break;
136236  case 274: /* wqlist ::= nm eidlist_opt AS LP select RP */
136237 {
136238  yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
136239 }
136240  break;
136241  case 275: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
136242 {
136243  yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
136244 }
136245  break;
136246  default:
136247  /* (276) input ::= cmdlist */ yytestcase(yyruleno==276);
136248  /* (277) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==277);
136249  /* (278) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=278);
136250  /* (279) ecmd ::= SEMI */ yytestcase(yyruleno==279);
136251  /* (280) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==280);
136252  /* (281) explain ::= */ yytestcase(yyruleno==281);
136253  /* (282) trans_opt ::= */ yytestcase(yyruleno==282);
136254  /* (283) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==283);
136255  /* (284) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==284);
136256  /* (285) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==285);
136257  /* (286) savepoint_opt ::= */ yytestcase(yyruleno==286);
136258  /* (287) cmd ::= create_table create_table_args */ yytestcase(yyruleno==287);
136259  /* (288) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==288);
136260  /* (289) columnlist ::= columnname carglist */ yytestcase(yyruleno==289);
136261  /* (290) nm ::= ID|INDEXED */ yytestcase(yyruleno==290);
136262  /* (291) nm ::= STRING */ yytestcase(yyruleno==291);
136263  /* (292) nm ::= JOIN_KW */ yytestcase(yyruleno==292);
136264  /* (293) typetoken ::= typename */ yytestcase(yyruleno==293);
136265  /* (294) typename ::= ID|STRING */ yytestcase(yyruleno==294);
136266  /* (295) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=295);
136267  /* (296) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=296);
136268  /* (297) carglist ::= carglist ccons */ yytestcase(yyruleno==297);
136269  /* (298) carglist ::= */ yytestcase(yyruleno==298);
136270  /* (299) ccons ::= NULL onconf */ yytestcase(yyruleno==299);
136271  /* (300) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==300);
136272  /* (301) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==301);
136273  /* (302) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=302);
136274  /* (303) tconscomma ::= */ yytestcase(yyruleno==303);
136275  /* (304) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=304);
136276  /* (305) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=305);
136277  /* (306) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=306);
136278  /* (307) oneselect ::= values */ yytestcase(yyruleno==307);
136279  /* (308) sclp ::= selcollist COMMA */ yytestcase(yyruleno==308);
136280  /* (309) as ::= ID|STRING */ yytestcase(yyruleno==309);
136281  /* (310) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=310);
136282  /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311);
136283  /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312);
136284  /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313);
136285  /* (314) nmnum ::= ON */ yytestcase(yyruleno==314);
136286  /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315);
136287  /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316);
136288  /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317);
136289  /* (318) foreach_clause ::= */ yytestcase(yyruleno==318);
136290  /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319);
136291  /* (320) trnm ::= nm */ yytestcase(yyruleno==320);
136292  /* (321) tridxby ::= */ yytestcase(yyruleno==321);
136293  /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322);
136294  /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323);
136295  /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324);
136296  /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325);
136297  /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326);
136298  /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327);
136299  /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328);
136300  /* (329) anylist ::= */ yytestcase(yyruleno==329);
136301  /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330);
136302  /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331);
136303  break;
136304 /********** End reduce actions ************************************************/
136305  };
136306  assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
136307  yygoto = yyRuleInfo[yyruleno].lhs;
136308  yysize = yyRuleInfo[yyruleno].nrhs;
136309  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
136310  if( yyact <= YY_MAX_SHIFTREDUCE ){
136311  if( yyact>YY_MAX_SHIFT ){
136312  yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
136313  }
136314  yymsp -= yysize-1;
136315  yypParser->yytos = yymsp;
136316  yymsp->stateno = (YYACTIONTYPE)yyact;
136317  yymsp->major = (YYCODETYPE)yygoto;
136318  yyTraceShift(yypParser, yyact);
136319  }else{
136320  assert( yyact == YY_ACCEPT_ACTION );
136321  yypParser->yytos -= yysize;
136322  yy_accept(yypParser);
136323  }
136324 }
136325 
136326 /*
136327 ** The following code executes when the parse fails
136328 */
136329 #ifndef YYNOERRORRECOVERY
136330 static void yy_parse_failed(
136331  yyParser *yypParser /* The parser */
136332 ){
136333  sqlite3ParserARG_FETCH;
136334 #ifndef NDEBUG
136335  if( yyTraceFILE ){
136336  fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
136337  }
136338 #endif
136339  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
136340  /* Here code is inserted which will be executed whenever the
136341  ** parser fails */
136342 /************ Begin %parse_failure code ***************************************/
136343 /************ End %parse_failure code *****************************************/
136344  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
136345 }
136346 #endif /* YYNOERRORRECOVERY */
136347 
136348 /*
136349 ** The following code executes when a syntax error first occurs.
136350 */
136351 static void yy_syntax_error(
136352  yyParser *yypParser, /* The parser */
136353  int yymajor, /* The major type of the error token */
136354  sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
136355 ){
136356  sqlite3ParserARG_FETCH;
136357 #define TOKEN yyminor
136358 /************ Begin %syntax_error code ****************************************/
136359 
136360  UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
136361  assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
136362  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
136363 /************ End %syntax_error code ******************************************/
136364  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
136365 }
136366 
136367 /*
136368 ** The following is executed when the parser accepts
136369 */
136370 static void yy_accept(
136371  yyParser *yypParser /* The parser */
136372 ){
136373  sqlite3ParserARG_FETCH;
136374 #ifndef NDEBUG
136375  if( yyTraceFILE ){
136376  fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
136377  }
136378 #endif
136379 #ifndef YYNOERRORRECOVERY
136380  yypParser->yyerrcnt = -1;
136381 #endif
136382  assert( yypParser->yytos==yypParser->yystack );
136383  /* Here code is inserted which will be executed whenever the
136384  ** parser accepts */
136385 /*********** Begin %parse_accept code *****************************************/
136386 /*********** End %parse_accept code *******************************************/
136387  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
136388 }
136389 
136390 /* The main parser program.
136391 ** The first argument is a pointer to a structure obtained from
136392 ** "sqlite3ParserAlloc" which describes the current state of the parser.
136393 ** The second argument is the major token number. The third is
136394 ** the minor token. The fourth optional argument is whatever the
136395 ** user wants (and specified in the grammar) and is available for
136396 ** use by the action routines.
136397 **
136398 ** Inputs:
136399 ** <ul>
136400 ** <li> A pointer to the parser (an opaque structure.)
136401 ** <li> The major token number.
136402 ** <li> The minor token number.
136403 ** <li> An option argument of a grammar-specified type.
136404 ** </ul>
136405 **
136406 ** Outputs:
136407 ** None.
136408 */
136409 SQLITE_PRIVATE void sqlite3Parser(
136410  void *yyp, /* The parser */
136411  int yymajor, /* The major token code number */
136412  sqlite3ParserTOKENTYPE yyminor /* The value for the token */
136413  sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
136414 ){
136415  YYMINORTYPE yyminorunion;
136416  unsigned int yyact; /* The parser action. */
136417 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
136418  int yyendofinput; /* True if we are at the end of input */
136419 #endif
136420 #ifdef YYERRORSYMBOL
136421  int yyerrorhit = 0; /* True if yymajor has invoked an error */
136422 #endif
136423  yyParser *yypParser; /* The parser */
136424 
136425  yypParser = (yyParser*)yyp;
136426  assert( yypParser->yytos!=0 );
136427 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
136428  yyendofinput = (yymajor==0);
136429 #endif
136430  sqlite3ParserARG_STORE;
136431 
136432 #ifndef NDEBUG
136433  if( yyTraceFILE ){
136434  fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
136435  }
136436 #endif
136437 
136438  do{
136439  yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
136440  if( yyact <= YY_MAX_SHIFTREDUCE ){
136441  yy_shift(yypParser,yyact,yymajor,yyminor);
136442 #ifndef YYNOERRORRECOVERY
136443  yypParser->yyerrcnt--;
136444 #endif
136445  yymajor = YYNOCODE;
136446  }else if( yyact <= YY_MAX_REDUCE ){
136447  yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
136448  }else{
136449  assert( yyact == YY_ERROR_ACTION );
136450  yyminorunion.yy0 = yyminor;
136451 #ifdef YYERRORSYMBOL
136452  int yymx;
136453 #endif
136454 #ifndef NDEBUG
136455  if( yyTraceFILE ){
136456  fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
136457  }
136458 #endif
136459 #ifdef YYERRORSYMBOL
136460  /* A syntax error has occurred.
136461  ** The response to an error depends upon whether or not the
136462  ** grammar defines an error token "ERROR".
136463  **
136464  ** This is what we do if the grammar does define ERROR:
136465  **
136466  ** * Call the %syntax_error function.
136467  **
136468  ** * Begin popping the stack until we enter a state where
136469  ** it is legal to shift the error symbol, then shift
136470  ** the error symbol.
136471  **
136472  ** * Set the error count to three.
136473  **
136474  ** * Begin accepting and shifting new tokens. No new error
136475  ** processing will occur until three tokens have been
136476  ** shifted successfully.
136477  **
136478  */
136479  if( yypParser->yyerrcnt<0 ){
136480  yy_syntax_error(yypParser,yymajor,yyminor);
136481  }
136482  yymx = yypParser->yytos->major;
136483  if( yymx==YYERRORSYMBOL || yyerrorhit ){
136484 #ifndef NDEBUG
136485  if( yyTraceFILE ){
136486  fprintf(yyTraceFILE,"%sDiscard input token %s\n",
136487  yyTracePrompt,yyTokenName[yymajor]);
136488  }
136489 #endif
136490  yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
136491  yymajor = YYNOCODE;
136492  }else{
136493  while( yypParser->yytos >= yypParser->yystack
136494  && yymx != YYERRORSYMBOL
136495  && (yyact = yy_find_reduce_action(
136496  yypParser->yytos->stateno,
136497  YYERRORSYMBOL)) >= YY_MIN_REDUCE
136498  ){
136499  yy_pop_parser_stack(yypParser);
136500  }
136501  if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
136502  yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
136503  yy_parse_failed(yypParser);
136504 #ifndef YYNOERRORRECOVERY
136505  yypParser->yyerrcnt = -1;
136506 #endif
136507  yymajor = YYNOCODE;
136508  }else if( yymx!=YYERRORSYMBOL ){
136509  yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
136510  }
136511  }
136512  yypParser->yyerrcnt = 3;
136513  yyerrorhit = 1;
136514 #elif defined(YYNOERRORRECOVERY)
136515  /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
136516  ** do any kind of error recovery. Instead, simply invoke the syntax
136517  ** error routine and continue going as if nothing had happened.
136518  **
136519  ** Applications can set this macro (for example inside %include) if
136520  ** they intend to abandon the parse upon the first syntax error seen.
136521  */
136522  yy_syntax_error(yypParser,yymajor, yyminor);
136523  yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
136524  yymajor = YYNOCODE;
136525 
136526 #else /* YYERRORSYMBOL is not defined */
136527  /* This is what we do if the grammar does not define ERROR:
136528  **
136529  ** * Report an error message, and throw away the input token.
136530  **
136531  ** * If the input token is $, then fail the parse.
136532  **
136533  ** As before, subsequent error messages are suppressed until
136534  ** three input tokens have been successfully shifted.
136535  */
136536  if( yypParser->yyerrcnt<=0 ){
136537  yy_syntax_error(yypParser,yymajor, yyminor);
136538  }
136539  yypParser->yyerrcnt = 3;
136540  yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
136541  if( yyendofinput ){
136542  yy_parse_failed(yypParser);
136543 #ifndef YYNOERRORRECOVERY
136544  yypParser->yyerrcnt = -1;
136545 #endif
136546  }
136547  yymajor = YYNOCODE;
136548 #endif
136549  }
136550  }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
136551 #ifndef NDEBUG
136552  if( yyTraceFILE ){
136553  yyStackEntry *i;
136554  char cDiv = '[';
136555  fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
136556  for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
136557  fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
136558  cDiv = ' ';
136559  }
136560  fprintf(yyTraceFILE,"]\n");
136561  }
136562 #endif
136563  return;
136564 }
136565 
136566 /************** End of parse.c ***********************************************/
136567 /************** Begin file tokenize.c ****************************************/
136568 /*
136569 ** 2001 September 15
136570 **
136571 ** The author disclaims copyright to this source code. In place of
136572 ** a legal notice, here is a blessing:
136573 **
136574 ** May you do good and not evil.
136575 ** May you find forgiveness for yourself and forgive others.
136576 ** May you share freely, never taking more than you give.
136577 **
136578 *************************************************************************
136579 ** An tokenizer for SQL
136580 **
136581 ** This file contains C code that splits an SQL input string up into
136582 ** individual tokens and sends those tokens one-by-one over to the
136583 ** parser for analysis.
136584 */
136585 /* #include "sqliteInt.h" */
136586 /* #include <stdlib.h> */
136587 
136588 /* Character classes for tokenizing
136589 **
136590 ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
136591 ** using a lookup table, whereas a switch() directly on c uses a binary search.
136592 ** The lookup table is much faster. To maximize speed, and to ensure that
136593 ** a lookup table is used, all of the classes need to be small integers and
136594 ** all of them need to be used within the switch.
136595 */
136596 #define CC_X 0 /* The letter 'x', or start of BLOB literal */
136597 #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
136598 #define CC_ID 2 /* unicode characters usable in IDs */
136599 #define CC_DIGIT 3 /* Digits */
136600 #define CC_DOLLAR 4 /* '$' */
136601 #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
136602 #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
136603 #define CC_SPACE 7 /* Space characters */
136604 #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
136605 #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
136606 #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
136607 #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
136608 #define CC_LT 12 /* '<'. Part of < or <= or <> */
136609 #define CC_GT 13 /* '>'. Part of > or >= */
136610 #define CC_EQ 14 /* '='. Part of = or == */
136611 #define CC_BANG 15 /* '!'. Part of != */
136612 #define CC_SLASH 16 /* '/'. / or c-style comment */
136613 #define CC_LP 17 /* '(' */
136614 #define CC_RP 18 /* ')' */
136615 #define CC_SEMI 19 /* ';' */
136616 #define CC_PLUS 20 /* '+' */
136617 #define CC_STAR 21 /* '*' */
136618 #define CC_PERCENT 22 /* '%' */
136619 #define CC_COMMA 23 /* ',' */
136620 #define CC_AND 24 /* '&' */
136621 #define CC_TILDA 25 /* '~' */
136622 #define CC_DOT 26 /* '.' */
136623 #define CC_ILLEGAL 27 /* Illegal character */
136624 
136625 static const unsigned char aiClass[] = {
136626 #ifdef SQLITE_ASCII
136627 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
136628 /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
136629 /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
136630 /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
136631 /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
136632 /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
136633 /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
136634 /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
136635 /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
136636 /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136637 /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136638 /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136639 /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136640 /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136641 /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136642 /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136643 /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
136644 #endif
136645 #ifdef SQLITE_EBCDIC
136646 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
136647 /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
136648 /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
136649 /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
136650 /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
136651 /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 12, 17, 20, 10,
136652 /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
136653 /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 7,
136654 /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
136655 /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
136656 /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
136657 /* 9x */ 25, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
136658 /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
136659 /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
136660 /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
136661 /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
136662 /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
136663 #endif
136664 };
136665 
136666 /*
136667 ** The charMap() macro maps alphabetic characters (only) into their
136668 ** lower-case ASCII equivalent. On ASCII machines, this is just
136669 ** an upper-to-lower case map. On EBCDIC machines we also need
136670 ** to adjust the encoding. The mapping is only valid for alphabetics
136671 ** which are the only characters for which this feature is used.
136672 **
136673 ** Used by keywordhash.h
136674 */
136675 #ifdef SQLITE_ASCII
136676 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
136677 #endif
136678 #ifdef SQLITE_EBCDIC
136679 # define charMap(X) ebcdicToAscii[(unsigned char)X]
136680 const unsigned char ebcdicToAscii[] = {
136681 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
136682  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
136683  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
136684  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
136685  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
136686  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
136687  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
136688  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
136689  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
136690  0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
136691  0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
136692  0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
136693  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
136694  0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
136695  0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
136696  0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
136697  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
136698 };
136699 #endif
136700 
136701 /*
136702 ** The sqlite3KeywordCode function looks up an identifier to determine if
136703 ** it is a keyword. If it is a keyword, the token code of that keyword is
136704 ** returned. If the input is not a keyword, TK_ID is returned.
136705 **
136706 ** The implementation of this routine was generated by a program,
136707 ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
136708 ** The output of the mkkeywordhash.c program is written into a file
136709 ** named keywordhash.h and then included into this source file by
136710 ** the #include below.
136711 */
136712 /************** Include keywordhash.h in the middle of tokenize.c ************/
136713 /************** Begin file keywordhash.h *************************************/
136714 /***** This file contains automatically generated code ******
136715 **
136716 ** The code in this file has been automatically generated by
136717 **
136718 ** sqlite/tool/mkkeywordhash.c
136719 **
136720 ** The code in this file implements a function that determines whether
136721 ** or not a given identifier is really an SQL keyword. The same thing
136722 ** might be implemented more directly using a hand-written hash table.
136723 ** But by using this automatically generated code, the size of the code
136724 ** is substantially reduced. This is important for embedded applications
136725 ** on platforms with limited memory.
136726 */
136727 /* Hash score: 182 */
136728 static int keywordCode(const char *z, int n, int *pType){
136729  /* zText[] encodes 834 bytes of keywords in 554 bytes */
136730  /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
136731  /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
136732  /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
136733  /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
136734  /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
136735  /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
136736  /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
136737  /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
136738  /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
136739  /* VACUUMVIEWINITIALLY */
136740  static const char zText[553] = {
136741  'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
136742  'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
136743  'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
136744  'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
136745  'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
136746  'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
136747  'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
136748  'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
136749  'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
136750  'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
136751  'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
136752  'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
136753  'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
136754  'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
136755  'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
136756  'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
136757  'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
136758  'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
136759  'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
136760  'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
136761  'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
136762  'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
136763  'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
136764  'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
136765  'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
136766  'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
136767  'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
136768  'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
136769  'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
136770  'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
136771  'V','I','E','W','I','N','I','T','I','A','L','L','Y',
136772  };
136773  static const unsigned char aHash[127] = {
136774  76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
136775  42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
136776  121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
136777  0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
136778  0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
136779  96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
136780  100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
136781  39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
136782  62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
136783  29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
136784  };
136785  static const unsigned char aNext[124] = {
136786  0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
136787  0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
136788  0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
136789  0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
136790  0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
136791  0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
136792  0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
136793  10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
136794  0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
136795  73, 83, 0, 35, 68, 0, 0,
136796  };
136797  static const unsigned char aLen[124] = {
136798  7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
136799  7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
136800  11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
136801  4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
136802  6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
136803  7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
136804  7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
136805  13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
136806  2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
136807  3, 5, 5, 6, 4, 9, 3,
136808  };
136809  static const unsigned short int aOffset[124] = {
136810  0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
136811  36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
136812  86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
136813  159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
136814  199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
136815  250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
136816  320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
136817  387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
136818  460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
136819  521, 524, 529, 534, 540, 544, 549,
136820  };
136821  static const unsigned char aCode[124] = {
136822  TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
136823  TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
136824  TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
136825  TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
136826  TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
136827  TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
136828  TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
136829  TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
136830  TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
136831  TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
136832  TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
136833  TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
136834  TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
136835  TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
136836  TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
136837  TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
136838  TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
136839  TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
136840  TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
136841  TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
136842  TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
136843  TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
136844  TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
136845  TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
136846  TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
136847  };
136848  int i, j;
136849  const char *zKW;
136850  if( n>=2 ){
136851  i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
136852  for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
136853  if( aLen[i]!=n ) continue;
136854  j = 0;
136855  zKW = &zText[aOffset[i]];
136856 #ifdef SQLITE_ASCII
136857  while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
136858 #endif
136859 #ifdef SQLITE_EBCDIC
136860  while( j<n && toupper(z[j])==zKW[j] ){ j++; }
136861 #endif
136862  if( j<n ) continue;
136863  testcase( i==0 ); /* REINDEX */
136864  testcase( i==1 ); /* INDEXED */
136865  testcase( i==2 ); /* INDEX */
136866  testcase( i==3 ); /* DESC */
136867  testcase( i==4 ); /* ESCAPE */
136868  testcase( i==5 ); /* EACH */
136869  testcase( i==6 ); /* CHECK */
136870  testcase( i==7 ); /* KEY */
136871  testcase( i==8 ); /* BEFORE */
136872  testcase( i==9 ); /* FOREIGN */
136873  testcase( i==10 ); /* FOR */
136874  testcase( i==11 ); /* IGNORE */
136875  testcase( i==12 ); /* REGEXP */
136876  testcase( i==13 ); /* EXPLAIN */
136877  testcase( i==14 ); /* INSTEAD */
136878  testcase( i==15 ); /* ADD */
136879  testcase( i==16 ); /* DATABASE */
136880  testcase( i==17 ); /* AS */
136881  testcase( i==18 ); /* SELECT */
136882  testcase( i==19 ); /* TABLE */
136883  testcase( i==20 ); /* LEFT */
136884  testcase( i==21 ); /* THEN */
136885  testcase( i==22 ); /* END */
136886  testcase( i==23 ); /* DEFERRABLE */
136887  testcase( i==24 ); /* ELSE */
136888  testcase( i==25 ); /* EXCEPT */
136889  testcase( i==26 ); /* TRANSACTION */
136890  testcase( i==27 ); /* ACTION */
136891  testcase( i==28 ); /* ON */
136892  testcase( i==29 ); /* NATURAL */
136893  testcase( i==30 ); /* ALTER */
136894  testcase( i==31 ); /* RAISE */
136895  testcase( i==32 ); /* EXCLUSIVE */
136896  testcase( i==33 ); /* EXISTS */
136897  testcase( i==34 ); /* SAVEPOINT */
136898  testcase( i==35 ); /* INTERSECT */
136899  testcase( i==36 ); /* TRIGGER */
136900  testcase( i==37 ); /* REFERENCES */
136901  testcase( i==38 ); /* CONSTRAINT */
136902  testcase( i==39 ); /* INTO */
136903  testcase( i==40 ); /* OFFSET */
136904  testcase( i==41 ); /* OF */
136905  testcase( i==42 ); /* SET */
136906  testcase( i==43 ); /* TEMPORARY */
136907  testcase( i==44 ); /* TEMP */
136908  testcase( i==45 ); /* OR */
136909  testcase( i==46 ); /* UNIQUE */
136910  testcase( i==47 ); /* QUERY */
136911  testcase( i==48 ); /* WITHOUT */
136912  testcase( i==49 ); /* WITH */
136913  testcase( i==50 ); /* OUTER */
136914  testcase( i==51 ); /* RELEASE */
136915  testcase( i==52 ); /* ATTACH */
136916  testcase( i==53 ); /* HAVING */
136917  testcase( i==54 ); /* GROUP */
136918  testcase( i==55 ); /* UPDATE */
136919  testcase( i==56 ); /* BEGIN */
136920  testcase( i==57 ); /* INNER */
136921  testcase( i==58 ); /* RECURSIVE */
136922  testcase( i==59 ); /* BETWEEN */
136923  testcase( i==60 ); /* NOTNULL */
136924  testcase( i==61 ); /* NOT */
136925  testcase( i==62 ); /* NO */
136926  testcase( i==63 ); /* NULL */
136927  testcase( i==64 ); /* LIKE */
136928  testcase( i==65 ); /* CASCADE */
136929  testcase( i==66 ); /* ASC */
136930  testcase( i==67 ); /* DELETE */
136931  testcase( i==68 ); /* CASE */
136932  testcase( i==69 ); /* COLLATE */
136933  testcase( i==70 ); /* CREATE */
136934  testcase( i==71 ); /* CURRENT_DATE */
136935  testcase( i==72 ); /* DETACH */
136936  testcase( i==73 ); /* IMMEDIATE */
136937  testcase( i==74 ); /* JOIN */
136938  testcase( i==75 ); /* INSERT */
136939  testcase( i==76 ); /* MATCH */
136940  testcase( i==77 ); /* PLAN */
136941  testcase( i==78 ); /* ANALYZE */
136942  testcase( i==79 ); /* PRAGMA */
136943  testcase( i==80 ); /* ABORT */
136944  testcase( i==81 ); /* VALUES */
136945  testcase( i==82 ); /* VIRTUAL */
136946  testcase( i==83 ); /* LIMIT */
136947  testcase( i==84 ); /* WHEN */
136948  testcase( i==85 ); /* WHERE */
136949  testcase( i==86 ); /* RENAME */
136950  testcase( i==87 ); /* AFTER */
136951  testcase( i==88 ); /* REPLACE */
136952  testcase( i==89 ); /* AND */
136953  testcase( i==90 ); /* DEFAULT */
136954  testcase( i==91 ); /* AUTOINCREMENT */
136955  testcase( i==92 ); /* TO */
136956  testcase( i==93 ); /* IN */
136957  testcase( i==94 ); /* CAST */
136958  testcase( i==95 ); /* COLUMN */
136959  testcase( i==96 ); /* COMMIT */
136960  testcase( i==97 ); /* CONFLICT */
136961  testcase( i==98 ); /* CROSS */
136962  testcase( i==99 ); /* CURRENT_TIMESTAMP */
136963  testcase( i==100 ); /* CURRENT_TIME */
136964  testcase( i==101 ); /* PRIMARY */
136965  testcase( i==102 ); /* DEFERRED */
136966  testcase( i==103 ); /* DISTINCT */
136967  testcase( i==104 ); /* IS */
136968  testcase( i==105 ); /* DROP */
136969  testcase( i==106 ); /* FAIL */
136970  testcase( i==107 ); /* FROM */
136971  testcase( i==108 ); /* FULL */
136972  testcase( i==109 ); /* GLOB */
136973  testcase( i==110 ); /* BY */
136974  testcase( i==111 ); /* IF */
136975  testcase( i==112 ); /* ISNULL */
136976  testcase( i==113 ); /* ORDER */
136977  testcase( i==114 ); /* RESTRICT */
136978  testcase( i==115 ); /* RIGHT */
136979  testcase( i==116 ); /* ROLLBACK */
136980  testcase( i==117 ); /* ROW */
136981  testcase( i==118 ); /* UNION */
136982  testcase( i==119 ); /* USING */
136983  testcase( i==120 ); /* VACUUM */
136984  testcase( i==121 ); /* VIEW */
136985  testcase( i==122 ); /* INITIALLY */
136986  testcase( i==123 ); /* ALL */
136987  *pType = aCode[i];
136988  break;
136989  }
136990  }
136991  return n;
136992 }
136993 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
136994  int id = TK_ID;
136995  keywordCode((char*)z, n, &id);
136996  return id;
136997 }
136998 #define SQLITE_N_KEYWORD 124
136999 
137000 /************** End of keywordhash.h *****************************************/
137001 /************** Continuing where we left off in tokenize.c *******************/
137002 
137003 
137004 /*
137005 ** If X is a character that can be used in an identifier then
137006 ** IdChar(X) will be true. Otherwise it is false.
137007 **
137008 ** For ASCII, any character with the high-order bit set is
137009 ** allowed in an identifier. For 7-bit characters,
137010 ** sqlite3IsIdChar[X] must be 1.
137011 **
137012 ** For EBCDIC, the rules are more complex but have the same
137013 ** end result.
137014 **
137015 ** Ticket #1066. the SQL standard does not allow '$' in the
137016 ** middle of identifiers. But many SQL implementations do.
137017 ** SQLite will allow '$' in identifiers for compatibility.
137018 ** But the feature is undocumented.
137019 */
137020 #ifdef SQLITE_ASCII
137021 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
137022 #endif
137023 #ifdef SQLITE_EBCDIC
137024 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
137025 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
137026  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
137027  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
137028  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
137029  0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
137030  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
137031  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
137032  1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
137033  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
137034  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
137035  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
137036  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
137037  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
137038 };
137039 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
137040 #endif
137041 
137042 /* Make the IdChar function accessible from ctime.c */
137043 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
137044 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
137045 #endif
137046 
137047 
137048 /*
137049 ** Return the length (in bytes) of the token that begins at z[0].
137050 ** Store the token type in *tokenType before returning.
137051 */
137052 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
137053  int i, c;
137054  switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
137055  ** of the token. See the comment on the CC_ defines
137056  ** above. */
137057  case CC_SPACE: {
137058  testcase( z[0]==' ' );
137059  testcase( z[0]=='\t' );
137060  testcase( z[0]=='\n' );
137061  testcase( z[0]=='\f' );
137062  testcase( z[0]=='\r' );
137063  for(i=1; sqlite3Isspace(z[i]); i++){}
137064  *tokenType = TK_SPACE;
137065  return i;
137066  }
137067  case CC_MINUS: {
137068  if( z[1]=='-' ){
137069  for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
137070  *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
137071  return i;
137072  }
137073  *tokenType = TK_MINUS;
137074  return 1;
137075  }
137076  case CC_LP: {
137077  *tokenType = TK_LP;
137078  return 1;
137079  }
137080  case CC_RP: {
137081  *tokenType = TK_RP;
137082  return 1;
137083  }
137084  case CC_SEMI: {
137085  *tokenType = TK_SEMI;
137086  return 1;
137087  }
137088  case CC_PLUS: {
137089  *tokenType = TK_PLUS;
137090  return 1;
137091  }
137092  case CC_STAR: {
137093  *tokenType = TK_STAR;
137094  return 1;
137095  }
137096  case CC_SLASH: {
137097  if( z[1]!='*' || z[2]==0 ){
137098  *tokenType = TK_SLASH;
137099  return 1;
137100  }
137101  for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
137102  if( c ) i++;
137103  *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
137104  return i;
137105  }
137106  case CC_PERCENT: {
137107  *tokenType = TK_REM;
137108  return 1;
137109  }
137110  case CC_EQ: {
137111  *tokenType = TK_EQ;
137112  return 1 + (z[1]=='=');
137113  }
137114  case CC_LT: {
137115  if( (c=z[1])=='=' ){
137116  *tokenType = TK_LE;
137117  return 2;
137118  }else if( c=='>' ){
137119  *tokenType = TK_NE;
137120  return 2;
137121  }else if( c=='<' ){
137122  *tokenType = TK_LSHIFT;
137123  return 2;
137124  }else{
137125  *tokenType = TK_LT;
137126  return 1;
137127  }
137128  }
137129  case CC_GT: {
137130  if( (c=z[1])=='=' ){
137131  *tokenType = TK_GE;
137132  return 2;
137133  }else if( c=='>' ){
137134  *tokenType = TK_RSHIFT;
137135  return 2;
137136  }else{
137137  *tokenType = TK_GT;
137138  return 1;
137139  }
137140  }
137141  case CC_BANG: {
137142  if( z[1]!='=' ){
137143  *tokenType = TK_ILLEGAL;
137144  return 1;
137145  }else{
137146  *tokenType = TK_NE;
137147  return 2;
137148  }
137149  }
137150  case CC_PIPE: {
137151  if( z[1]!='|' ){
137152  *tokenType = TK_BITOR;
137153  return 1;
137154  }else{
137155  *tokenType = TK_CONCAT;
137156  return 2;
137157  }
137158  }
137159  case CC_COMMA: {
137160  *tokenType = TK_COMMA;
137161  return 1;
137162  }
137163  case CC_AND: {
137164  *tokenType = TK_BITAND;
137165  return 1;
137166  }
137167  case CC_TILDA: {
137168  *tokenType = TK_BITNOT;
137169  return 1;
137170  }
137171  case CC_QUOTE: {
137172  int delim = z[0];
137173  testcase( delim=='`' );
137174  testcase( delim=='\'' );
137175  testcase( delim=='"' );
137176  for(i=1; (c=z[i])!=0; i++){
137177  if( c==delim ){
137178  if( z[i+1]==delim ){
137179  i++;
137180  }else{
137181  break;
137182  }
137183  }
137184  }
137185  if( c=='\'' ){
137186  *tokenType = TK_STRING;
137187  return i+1;
137188  }else if( c!=0 ){
137189  *tokenType = TK_ID;
137190  return i+1;
137191  }else{
137192  *tokenType = TK_ILLEGAL;
137193  return i;
137194  }
137195  }
137196  case CC_DOT: {
137197 #ifndef SQLITE_OMIT_FLOATING_POINT
137198  if( !sqlite3Isdigit(z[1]) )
137199 #endif
137200  {
137201  *tokenType = TK_DOT;
137202  return 1;
137203  }
137204  /* If the next character is a digit, this is a floating point
137205  ** number that begins with ".". Fall thru into the next case */
137206  }
137207  case CC_DIGIT: {
137208  testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
137209  testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
137210  testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
137211  testcase( z[0]=='9' );
137212  *tokenType = TK_INTEGER;
137213 #ifndef SQLITE_OMIT_HEX_INTEGER
137214  if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
137215  for(i=3; sqlite3Isxdigit(z[i]); i++){}
137216  return i;
137217  }
137218 #endif
137219  for(i=0; sqlite3Isdigit(z[i]); i++){}
137220 #ifndef SQLITE_OMIT_FLOATING_POINT
137221  if( z[i]=='.' ){
137222  i++;
137223  while( sqlite3Isdigit(z[i]) ){ i++; }
137224  *tokenType = TK_FLOAT;
137225  }
137226  if( (z[i]=='e' || z[i]=='E') &&
137227  ( sqlite3Isdigit(z[i+1])
137228  || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
137229  )
137230  ){
137231  i += 2;
137232  while( sqlite3Isdigit(z[i]) ){ i++; }
137233  *tokenType = TK_FLOAT;
137234  }
137235 #endif
137236  while( IdChar(z[i]) ){
137237  *tokenType = TK_ILLEGAL;
137238  i++;
137239  }
137240  return i;
137241  }
137242  case CC_QUOTE2: {
137243  for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
137244  *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
137245  return i;
137246  }
137247  case CC_VARNUM: {
137248  *tokenType = TK_VARIABLE;
137249  for(i=1; sqlite3Isdigit(z[i]); i++){}
137250  return i;
137251  }
137252  case CC_DOLLAR:
137253  case CC_VARALPHA: {
137254  int n = 0;
137255  testcase( z[0]=='$' ); testcase( z[0]=='@' );
137256  testcase( z[0]==':' ); testcase( z[0]=='#' );
137257  *tokenType = TK_VARIABLE;
137258  for(i=1; (c=z[i])!=0; i++){
137259  if( IdChar(c) ){
137260  n++;
137261 #ifndef SQLITE_OMIT_TCL_VARIABLE
137262  }else if( c=='(' && n>0 ){
137263  do{
137264  i++;
137265  }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
137266  if( c==')' ){
137267  i++;
137268  }else{
137269  *tokenType = TK_ILLEGAL;
137270  }
137271  break;
137272  }else if( c==':' && z[i+1]==':' ){
137273  i++;
137274 #endif
137275  }else{
137276  break;
137277  }
137278  }
137279  if( n==0 ) *tokenType = TK_ILLEGAL;
137280  return i;
137281  }
137282  case CC_KYWD: {
137283  for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
137284  if( IdChar(z[i]) ){
137285  /* This token started out using characters that can appear in keywords,
137286  ** but z[i] is a character not allowed within keywords, so this must
137287  ** be an identifier instead */
137288  i++;
137289  break;
137290  }
137291  *tokenType = TK_ID;
137292  return keywordCode((char*)z, i, tokenType);
137293  }
137294  case CC_X: {
137295 #ifndef SQLITE_OMIT_BLOB_LITERAL
137296  testcase( z[0]=='x' ); testcase( z[0]=='X' );
137297  if( z[1]=='\'' ){
137298  *tokenType = TK_BLOB;
137299  for(i=2; sqlite3Isxdigit(z[i]); i++){}
137300  if( z[i]!='\'' || i%2 ){
137301  *tokenType = TK_ILLEGAL;
137302  while( z[i] && z[i]!='\'' ){ i++; }
137303  }
137304  if( z[i] ) i++;
137305  return i;
137306  }
137307 #endif
137308  /* If it is not a BLOB literal, then it must be an ID, since no
137309  ** SQL keywords start with the letter 'x'. Fall through */
137310  }
137311  case CC_ID: {
137312  i = 1;
137313  break;
137314  }
137315  default: {
137316  *tokenType = TK_ILLEGAL;
137317  return 1;
137318  }
137319  }
137320  while( IdChar(z[i]) ){ i++; }
137321  *tokenType = TK_ID;
137322  return i;
137323 }
137324 
137325 /*
137326 ** Run the parser on the given SQL string. The parser structure is
137327 ** passed in. An SQLITE_ status code is returned. If an error occurs
137328 ** then an and attempt is made to write an error message into
137329 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
137330 ** error message.
137331 */
137332 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
137333  int nErr = 0; /* Number of errors encountered */
137334  int i; /* Loop counter */
137335  void *pEngine; /* The LEMON-generated LALR(1) parser */
137336  int tokenType; /* type of the next token */
137337  int lastTokenParsed = -1; /* type of the previous token */
137338  sqlite3 *db = pParse->db; /* The database connection */
137339  int mxSqlLen; /* Max length of an SQL string */
137340 
137341  assert( zSql!=0 );
137342  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
137343  if( db->nVdbeActive==0 ){
137344  db->u1.isInterrupted = 0;
137345  }
137346  pParse->rc = SQLITE_OK;
137347  pParse->zTail = zSql;
137348  i = 0;
137349  assert( pzErrMsg!=0 );
137350  /* sqlite3ParserTrace(stdout, "parser: "); */
137351  pEngine = sqlite3ParserAlloc(sqlite3Malloc);
137352  if( pEngine==0 ){
137353  sqlite3OomFault(db);
137354  return SQLITE_NOMEM_BKPT;
137355  }
137356  assert( pParse->pNewTable==0 );
137357  assert( pParse->pNewTrigger==0 );
137358  assert( pParse->nVar==0 );
137359  assert( pParse->nzVar==0 );
137360  assert( pParse->azVar==0 );
137361  while( 1 ){
137362  assert( i>=0 );
137363  if( zSql[i]!=0 ){
137364  pParse->sLastToken.z = &zSql[i];
137365  pParse->sLastToken.n = sqlite3GetToken((u8*)&zSql[i],&tokenType);
137366  i += pParse->sLastToken.n;
137367  if( i>mxSqlLen ){
137368  pParse->rc = SQLITE_TOOBIG;
137369  break;
137370  }
137371  }else{
137372  /* Upon reaching the end of input, call the parser two more times
137373  ** with tokens TK_SEMI and 0, in that order. */
137374  if( lastTokenParsed==TK_SEMI ){
137375  tokenType = 0;
137376  }else if( lastTokenParsed==0 ){
137377  break;
137378  }else{
137379  tokenType = TK_SEMI;
137380  }
137381  }
137382  if( tokenType>=TK_SPACE ){
137383  assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
137384  if( db->u1.isInterrupted ){
137385  pParse->rc = SQLITE_INTERRUPT;
137386  break;
137387  }
137388  if( tokenType==TK_ILLEGAL ){
137389  sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
137390  &pParse->sLastToken);
137391  break;
137392  }
137393  }else{
137394  sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
137395  lastTokenParsed = tokenType;
137396  if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
137397  }
137398  }
137399  assert( nErr==0 );
137400  pParse->zTail = &zSql[i];
137401 #ifdef YYTRACKMAXSTACKDEPTH
137402  sqlite3_mutex_enter(sqlite3MallocMutex());
137403  sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
137404  sqlite3ParserStackPeak(pEngine)
137405  );
137406  sqlite3_mutex_leave(sqlite3MallocMutex());
137407 #endif /* YYDEBUG */
137408  sqlite3ParserFree(pEngine, sqlite3_free);
137409  if( db->mallocFailed ){
137410  pParse->rc = SQLITE_NOMEM_BKPT;
137411  }
137412  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
137413  pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
137414  }
137415  assert( pzErrMsg!=0 );
137416  if( pParse->zErrMsg ){
137417  *pzErrMsg = pParse->zErrMsg;
137418  sqlite3_log(pParse->rc, "%s", *pzErrMsg);
137419  pParse->zErrMsg = 0;
137420  nErr++;
137421  }
137422  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
137423  sqlite3VdbeDelete(pParse->pVdbe);
137424  pParse->pVdbe = 0;
137425  }
137426 #ifndef SQLITE_OMIT_SHARED_CACHE
137427  if( pParse->nested==0 ){
137428  sqlite3DbFree(db, pParse->aTableLock);
137429  pParse->aTableLock = 0;
137430  pParse->nTableLock = 0;
137431  }
137432 #endif
137433 #ifndef SQLITE_OMIT_VIRTUALTABLE
137434  sqlite3_free(pParse->apVtabLock);
137435 #endif
137436 
137437  if( !IN_DECLARE_VTAB ){
137438  /* If the pParse->declareVtab flag is set, do not delete any table
137439  ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
137440  ** will take responsibility for freeing the Table structure.
137441  */
137442  sqlite3DeleteTable(db, pParse->pNewTable);
137443  }
137444 
137445  if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
137446  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
137447  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
137448  sqlite3DbFree(db, pParse->azVar);
137449  while( pParse->pAinc ){
137450  AutoincInfo *p = pParse->pAinc;
137451  pParse->pAinc = p->pNext;
137452  sqlite3DbFree(db, p);
137453  }
137454  while( pParse->pZombieTab ){
137455  Table *p = pParse->pZombieTab;
137456  pParse->pZombieTab = p->pNextZombie;
137457  sqlite3DeleteTable(db, p);
137458  }
137459  assert( nErr==0 || pParse->rc!=SQLITE_OK );
137460  return nErr;
137461 }
137462 
137463 /************** End of tokenize.c ********************************************/
137464 /************** Begin file complete.c ****************************************/
137465 /*
137466 ** 2001 September 15
137467 **
137468 ** The author disclaims copyright to this source code. In place of
137469 ** a legal notice, here is a blessing:
137470 **
137471 ** May you do good and not evil.
137472 ** May you find forgiveness for yourself and forgive others.
137473 ** May you share freely, never taking more than you give.
137474 **
137475 *************************************************************************
137476 ** An tokenizer for SQL
137477 **
137478 ** This file contains C code that implements the sqlite3_complete() API.
137479 ** This code used to be part of the tokenizer.c source file. But by
137480 ** separating it out, the code will be automatically omitted from
137481 ** static links that do not use it.
137482 */
137483 /* #include "sqliteInt.h" */
137484 #ifndef SQLITE_OMIT_COMPLETE
137485 
137486 /*
137487 ** This is defined in tokenize.c. We just have to import the definition.
137488 */
137489 #ifndef SQLITE_AMALGAMATION
137490 #ifdef SQLITE_ASCII
137491 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
137492 #endif
137493 #ifdef SQLITE_EBCDIC
137494 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
137495 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
137496 #endif
137497 #endif /* SQLITE_AMALGAMATION */
137498 
137499 
137500 /*
137501 ** Token types used by the sqlite3_complete() routine. See the header
137502 ** comments on that procedure for additional information.
137503 */
137504 #define tkSEMI 0
137505 #define tkWS 1
137506 #define tkOTHER 2
137507 #ifndef SQLITE_OMIT_TRIGGER
137508 #define tkEXPLAIN 3
137509 #define tkCREATE 4
137510 #define tkTEMP 5
137511 #define tkTRIGGER 6
137512 #define tkEND 7
137513 #endif
137514 
137515 /*
137516 ** Return TRUE if the given SQL string ends in a semicolon.
137517 **
137518 ** Special handling is require for CREATE TRIGGER statements.
137519 ** Whenever the CREATE TRIGGER keywords are seen, the statement
137520 ** must end with ";END;".
137521 **
137522 ** This implementation uses a state machine with 8 states:
137523 **
137524 ** (0) INVALID We have not yet seen a non-whitespace character.
137525 **
137526 ** (1) START At the beginning or end of an SQL statement. This routine
137527 ** returns 1 if it ends in the START state and 0 if it ends
137528 ** in any other state.
137529 **
137530 ** (2) NORMAL We are in the middle of statement which ends with a single
137531 ** semicolon.
137532 **
137533 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
137534 ** a statement.
137535 **
137536 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
137537 ** statement, possibly preceded by EXPLAIN and/or followed by
137538 ** TEMP or TEMPORARY
137539 **
137540 ** (5) TRIGGER We are in the middle of a trigger definition that must be
137541 ** ended by a semicolon, the keyword END, and another semicolon.
137542 **
137543 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
137544 ** the end of a trigger definition.
137545 **
137546 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
137547 ** of a trigger definition.
137548 **
137549 ** Transitions between states above are determined by tokens extracted
137550 ** from the input. The following tokens are significant:
137551 **
137552 ** (0) tkSEMI A semicolon.
137553 ** (1) tkWS Whitespace.
137554 ** (2) tkOTHER Any other SQL token.
137555 ** (3) tkEXPLAIN The "explain" keyword.
137556 ** (4) tkCREATE The "create" keyword.
137557 ** (5) tkTEMP The "temp" or "temporary" keyword.
137558 ** (6) tkTRIGGER The "trigger" keyword.
137559 ** (7) tkEND The "end" keyword.
137560 **
137561 ** Whitespace never causes a state transition and is always ignored.
137562 ** This means that a SQL string of all whitespace is invalid.
137563 **
137564 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
137565 ** to recognize the end of a trigger can be omitted. All we have to do
137566 ** is look for a semicolon that is not part of an string or comment.
137567 */
137568 SQLITE_API int sqlite3_complete(const char *zSql){
137569  u8 state = 0; /* Current state, using numbers defined in header comment */
137570  u8 token; /* Value of the next token */
137571 
137572 #ifndef SQLITE_OMIT_TRIGGER
137573  /* A complex statement machine used to detect the end of a CREATE TRIGGER
137574  ** statement. This is the normal case.
137575  */
137576  static const u8 trans[8][8] = {
137577  /* Token: */
137578  /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
137579  /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
137580  /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
137581  /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
137582  /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
137583  /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
137584  /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
137585  /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
137586  /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
137587  };
137588 #else
137589  /* If triggers are not supported by this compile then the statement machine
137590  ** used to detect the end of a statement is much simpler
137591  */
137592  static const u8 trans[3][3] = {
137593  /* Token: */
137594  /* State: ** SEMI WS OTHER */
137595  /* 0 INVALID: */ { 1, 0, 2, },
137596  /* 1 START: */ { 1, 1, 2, },
137597  /* 2 NORMAL: */ { 1, 2, 2, },
137598  };
137599 #endif /* SQLITE_OMIT_TRIGGER */
137600 
137601 #ifdef SQLITE_ENABLE_API_ARMOR
137602  if( zSql==0 ){
137603  (void)SQLITE_MISUSE_BKPT;
137604  return 0;
137605  }
137606 #endif
137607 
137608  while( *zSql ){
137609  switch( *zSql ){
137610  case ';': { /* A semicolon */
137611  token = tkSEMI;
137612  break;
137613  }
137614  case ' ':
137615  case '\r':
137616  case '\t':
137617  case '\n':
137618  case '\f': { /* White space is ignored */
137619  token = tkWS;
137620  break;
137621  }
137622  case '/': { /* C-style comments */
137623  if( zSql[1]!='*' ){
137624  token = tkOTHER;
137625  break;
137626  }
137627  zSql += 2;
137628  while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
137629  if( zSql[0]==0 ) return 0;
137630  zSql++;
137631  token = tkWS;
137632  break;
137633  }
137634  case '-': { /* SQL-style comments from "--" to end of line */
137635  if( zSql[1]!='-' ){
137636  token = tkOTHER;
137637  break;
137638  }
137639  while( *zSql && *zSql!='\n' ){ zSql++; }
137640  if( *zSql==0 ) return state==1;
137641  token = tkWS;
137642  break;
137643  }
137644  case '[': { /* Microsoft-style identifiers in [...] */
137645  zSql++;
137646  while( *zSql && *zSql!=']' ){ zSql++; }
137647  if( *zSql==0 ) return 0;
137648  token = tkOTHER;
137649  break;
137650  }
137651  case '`': /* Grave-accent quoted symbols used by MySQL */
137652  case '"': /* single- and double-quoted strings */
137653  case '\'': {
137654  int c = *zSql;
137655  zSql++;
137656  while( *zSql && *zSql!=c ){ zSql++; }
137657  if( *zSql==0 ) return 0;
137658  token = tkOTHER;
137659  break;
137660  }
137661  default: {
137662 #ifdef SQLITE_EBCDIC
137663  unsigned char c;
137664 #endif
137665  if( IdChar((u8)*zSql) ){
137666  /* Keywords and unquoted identifiers */
137667  int nId;
137668  for(nId=1; IdChar(zSql[nId]); nId++){}
137669 #ifdef SQLITE_OMIT_TRIGGER
137670  token = tkOTHER;
137671 #else
137672  switch( *zSql ){
137673  case 'c': case 'C': {
137674  if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
137675  token = tkCREATE;
137676  }else{
137677  token = tkOTHER;
137678  }
137679  break;
137680  }
137681  case 't': case 'T': {
137682  if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
137683  token = tkTRIGGER;
137684  }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
137685  token = tkTEMP;
137686  }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
137687  token = tkTEMP;
137688  }else{
137689  token = tkOTHER;
137690  }
137691  break;
137692  }
137693  case 'e': case 'E': {
137694  if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
137695  token = tkEND;
137696  }else
137697 #ifndef SQLITE_OMIT_EXPLAIN
137698  if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
137699  token = tkEXPLAIN;
137700  }else
137701 #endif
137702  {
137703  token = tkOTHER;
137704  }
137705  break;
137706  }
137707  default: {
137708  token = tkOTHER;
137709  break;
137710  }
137711  }
137712 #endif /* SQLITE_OMIT_TRIGGER */
137713  zSql += nId-1;
137714  }else{
137715  /* Operators and special symbols */
137716  token = tkOTHER;
137717  }
137718  break;
137719  }
137720  }
137721  state = trans[state][token];
137722  zSql++;
137723  }
137724  return state==1;
137725 }
137726 
137727 #ifndef SQLITE_OMIT_UTF16
137728 /*
137729 ** This routine is the same as the sqlite3_complete() routine described
137730 ** above, except that the parameter is required to be UTF-16 encoded, not
137731 ** UTF-8.
137732 */
137733 SQLITE_API int sqlite3_complete16(const void *zSql){
137734  sqlite3_value *pVal;
137735  char const *zSql8;
137736  int rc;
137737 
137738 #ifndef SQLITE_OMIT_AUTOINIT
137739  rc = sqlite3_initialize();
137740  if( rc ) return rc;
137741 #endif
137742  pVal = sqlite3ValueNew(0);
137743  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
137744  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
137745  if( zSql8 ){
137746  rc = sqlite3_complete(zSql8);
137747  }else{
137748  rc = SQLITE_NOMEM_BKPT;
137749  }
137750  sqlite3ValueFree(pVal);
137751  return rc & 0xff;
137752 }
137753 #endif /* SQLITE_OMIT_UTF16 */
137754 #endif /* SQLITE_OMIT_COMPLETE */
137755 
137756 /************** End of complete.c ********************************************/
137757 /************** Begin file main.c ********************************************/
137758 /*
137759 ** 2001 September 15
137760 **
137761 ** The author disclaims copyright to this source code. In place of
137762 ** a legal notice, here is a blessing:
137763 **
137764 ** May you do good and not evil.
137765 ** May you find forgiveness for yourself and forgive others.
137766 ** May you share freely, never taking more than you give.
137767 **
137768 *************************************************************************
137769 ** Main file for the SQLite library. The routines in this file
137770 ** implement the programmer interface to the library. Routines in
137771 ** other files are for internal use by SQLite and should not be
137772 ** accessed by users of the library.
137773 */
137774 /* #include "sqliteInt.h" */
137775 
137776 #ifdef SQLITE_ENABLE_FTS3
137777 /************** Include fts3.h in the middle of main.c ***********************/
137778 /************** Begin file fts3.h ********************************************/
137779 /*
137780 ** 2006 Oct 10
137781 **
137782 ** The author disclaims copyright to this source code. In place of
137783 ** a legal notice, here is a blessing:
137784 **
137785 ** May you do good and not evil.
137786 ** May you find forgiveness for yourself and forgive others.
137787 ** May you share freely, never taking more than you give.
137788 **
137789 ******************************************************************************
137790 **
137791 ** This header file is used by programs that want to link against the
137792 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
137793 */
137794 /* #include "sqlite3.h" */
137795 
137796 #if 0
137797 extern "C" {
137798 #endif /* __cplusplus */
137799 
137800 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
137801 
137802 #if 0
137803 } /* extern "C" */
137804 #endif /* __cplusplus */
137805 
137806 /************** End of fts3.h ************************************************/
137807 /************** Continuing where we left off in main.c ***********************/
137808 #endif
137809 #ifdef SQLITE_ENABLE_RTREE
137810 /************** Include rtree.h in the middle of main.c **********************/
137811 /************** Begin file rtree.h *******************************************/
137812 /*
137813 ** 2008 May 26
137814 **
137815 ** The author disclaims copyright to this source code. In place of
137816 ** a legal notice, here is a blessing:
137817 **
137818 ** May you do good and not evil.
137819 ** May you find forgiveness for yourself and forgive others.
137820 ** May you share freely, never taking more than you give.
137821 **
137822 ******************************************************************************
137823 **
137824 ** This header file is used by programs that want to link against the
137825 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
137826 */
137827 /* #include "sqlite3.h" */
137828 
137829 #if 0
137830 extern "C" {
137831 #endif /* __cplusplus */
137832 
137833 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
137834 
137835 #if 0
137836 } /* extern "C" */
137837 #endif /* __cplusplus */
137838 
137839 /************** End of rtree.h ***********************************************/
137840 /************** Continuing where we left off in main.c ***********************/
137841 #endif
137842 #ifdef SQLITE_ENABLE_ICU
137843 /************** Include sqliteicu.h in the middle of main.c ******************/
137844 /************** Begin file sqliteicu.h ***************************************/
137845 /*
137846 ** 2008 May 26
137847 **
137848 ** The author disclaims copyright to this source code. In place of
137849 ** a legal notice, here is a blessing:
137850 **
137851 ** May you do good and not evil.
137852 ** May you find forgiveness for yourself and forgive others.
137853 ** May you share freely, never taking more than you give.
137854 **
137855 ******************************************************************************
137856 **
137857 ** This header file is used by programs that want to link against the
137858 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
137859 */
137860 /* #include "sqlite3.h" */
137861 
137862 #if 0
137863 extern "C" {
137864 #endif /* __cplusplus */
137865 
137866 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
137867 
137868 #if 0
137869 } /* extern "C" */
137870 #endif /* __cplusplus */
137871 
137872 
137873 /************** End of sqliteicu.h *******************************************/
137874 /************** Continuing where we left off in main.c ***********************/
137875 #endif
137876 #ifdef SQLITE_ENABLE_JSON1
137877 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
137878 #endif
137879 #ifdef SQLITE_ENABLE_FTS5
137880 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
137881 #endif
137882 
137883 #ifndef SQLITE_AMALGAMATION
137884 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
137885 ** contains the text of SQLITE_VERSION macro.
137886 */
137887 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
137888 #endif
137889 
137890 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
137891 ** a pointer to the to the sqlite3_version[] string constant.
137892 */
137893 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
137894 
137895 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
137896 ** pointer to a string constant whose value is the same as the
137897 ** SQLITE_SOURCE_ID C preprocessor macro.
137898 */
137899 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
137900 
137901 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
137902 ** returns an integer equal to SQLITE_VERSION_NUMBER.
137903 */
137904 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
137905 
137906 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
137907 ** zero if and only if SQLite was compiled with mutexing code omitted due to
137908 ** the SQLITE_THREADSAFE compile-time option being set to 0.
137909 */
137910 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
137911 
137912 /*
137913 ** When compiling the test fixture or with debugging enabled (on Win32),
137914 ** this variable being set to non-zero will cause OSTRACE macros to emit
137915 ** extra diagnostic information.
137916 */
137917 #ifdef SQLITE_HAVE_OS_TRACE
137918 # ifndef SQLITE_DEBUG_OS_TRACE
137919 # define SQLITE_DEBUG_OS_TRACE 0
137920 # endif
137921  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
137922 #endif
137923 
137924 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
137925 /*
137926 ** If the following function pointer is not NULL and if
137927 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
137928 ** I/O active are written using this function. These messages
137929 ** are intended for debugging activity only.
137930 */
137931 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
137932 #endif
137933 
137934 /*
137935 ** If the following global variable points to a string which is the
137936 ** name of a directory, then that directory will be used to store
137937 ** temporary files.
137938 **
137939 ** See also the "PRAGMA temp_store_directory" SQL command.
137940 */
137941 SQLITE_API char *sqlite3_temp_directory = 0;
137942 
137943 /*
137944 ** If the following global variable points to a string which is the
137945 ** name of a directory, then that directory will be used to store
137946 ** all database files specified with a relative pathname.
137947 **
137948 ** See also the "PRAGMA data_store_directory" SQL command.
137949 */
137950 SQLITE_API char *sqlite3_data_directory = 0;
137951 
137952 /*
137953 ** Initialize SQLite.
137954 **
137955 ** This routine must be called to initialize the memory allocation,
137956 ** VFS, and mutex subsystems prior to doing any serious work with
137957 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
137958 ** this routine will be called automatically by key routines such as
137959 ** sqlite3_open().
137960 **
137961 ** This routine is a no-op except on its very first call for the process,
137962 ** or for the first call after a call to sqlite3_shutdown.
137963 **
137964 ** The first thread to call this routine runs the initialization to
137965 ** completion. If subsequent threads call this routine before the first
137966 ** thread has finished the initialization process, then the subsequent
137967 ** threads must block until the first thread finishes with the initialization.
137968 **
137969 ** The first thread might call this routine recursively. Recursive
137970 ** calls to this routine should not block, of course. Otherwise the
137971 ** initialization process would never complete.
137972 **
137973 ** Let X be the first thread to enter this routine. Let Y be some other
137974 ** thread. Then while the initial invocation of this routine by X is
137975 ** incomplete, it is required that:
137976 **
137977 ** * Calls to this routine from Y must block until the outer-most
137978 ** call by X completes.
137979 **
137980 ** * Recursive calls to this routine from thread X return immediately
137981 ** without blocking.
137982 */
137983 SQLITE_API int sqlite3_initialize(void){
137984  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
137985  int rc; /* Result code */
137986 #ifdef SQLITE_EXTRA_INIT
137987  int bRunExtraInit = 0; /* Extra initialization needed */
137988 #endif
137989 
137990 #ifdef SQLITE_OMIT_WSD
137991  rc = sqlite3_wsd_init(4096, 24);
137992  if( rc!=SQLITE_OK ){
137993  return rc;
137994  }
137995 #endif
137996 
137997  /* If the following assert() fails on some obscure processor/compiler
137998  ** combination, the work-around is to set the correct pointer
137999  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
138000  assert( SQLITE_PTRSIZE==sizeof(char*) );
138001 
138002  /* If SQLite is already completely initialized, then this call
138003  ** to sqlite3_initialize() should be a no-op. But the initialization
138004  ** must be complete. So isInit must not be set until the very end
138005  ** of this routine.
138006  */
138007  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
138008 
138009  /* Make sure the mutex subsystem is initialized. If unable to
138010  ** initialize the mutex subsystem, return early with the error.
138011  ** If the system is so sick that we are unable to allocate a mutex,
138012  ** there is not much SQLite is going to be able to do.
138013  **
138014  ** The mutex subsystem must take care of serializing its own
138015  ** initialization.
138016  */
138017  rc = sqlite3MutexInit();
138018  if( rc ) return rc;
138019 
138020  /* Initialize the malloc() system and the recursive pInitMutex mutex.
138021  ** This operation is protected by the STATIC_MASTER mutex. Note that
138022  ** MutexAlloc() is called for a static mutex prior to initializing the
138023  ** malloc subsystem - this implies that the allocation of a static
138024  ** mutex must not require support from the malloc subsystem.
138025  */
138026  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
138027  sqlite3_mutex_enter(pMaster);
138028  sqlite3GlobalConfig.isMutexInit = 1;
138029  if( !sqlite3GlobalConfig.isMallocInit ){
138030  rc = sqlite3MallocInit();
138031  }
138032  if( rc==SQLITE_OK ){
138033  sqlite3GlobalConfig.isMallocInit = 1;
138034  if( !sqlite3GlobalConfig.pInitMutex ){
138035  sqlite3GlobalConfig.pInitMutex =
138036  sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
138037  if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
138038  rc = SQLITE_NOMEM_BKPT;
138039  }
138040  }
138041  }
138042  if( rc==SQLITE_OK ){
138043  sqlite3GlobalConfig.nRefInitMutex++;
138044  }
138045  sqlite3_mutex_leave(pMaster);
138046 
138047  /* If rc is not SQLITE_OK at this point, then either the malloc
138048  ** subsystem could not be initialized or the system failed to allocate
138049  ** the pInitMutex mutex. Return an error in either case. */
138050  if( rc!=SQLITE_OK ){
138051  return rc;
138052  }
138053 
138054  /* Do the rest of the initialization under the recursive mutex so
138055  ** that we will be able to handle recursive calls into
138056  ** sqlite3_initialize(). The recursive calls normally come through
138057  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
138058  ** recursive calls might also be possible.
138059  **
138060  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
138061  ** to the xInit method, so the xInit method need not be threadsafe.
138062  **
138063  ** The following mutex is what serializes access to the appdef pcache xInit
138064  ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
138065  ** call to sqlite3PcacheInitialize().
138066  */
138067  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
138068  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
138069  sqlite3GlobalConfig.inProgress = 1;
138070 #ifdef SQLITE_ENABLE_SQLLOG
138071  {
138072  extern void sqlite3_init_sqllog(void);
138073  sqlite3_init_sqllog();
138074  }
138075 #endif
138076  memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
138077  sqlite3RegisterBuiltinFunctions();
138078  if( sqlite3GlobalConfig.isPCacheInit==0 ){
138079  rc = sqlite3PcacheInitialize();
138080  }
138081  if( rc==SQLITE_OK ){
138082  sqlite3GlobalConfig.isPCacheInit = 1;
138083  rc = sqlite3OsInit();
138084  }
138085  if( rc==SQLITE_OK ){
138086  sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
138087  sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
138088  sqlite3GlobalConfig.isInit = 1;
138089 #ifdef SQLITE_EXTRA_INIT
138090  bRunExtraInit = 1;
138091 #endif
138092  }
138093  sqlite3GlobalConfig.inProgress = 0;
138094  }
138095  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
138096 
138097  /* Go back under the static mutex and clean up the recursive
138098  ** mutex to prevent a resource leak.
138099  */
138100  sqlite3_mutex_enter(pMaster);
138101  sqlite3GlobalConfig.nRefInitMutex--;
138102  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
138103  assert( sqlite3GlobalConfig.nRefInitMutex==0 );
138104  sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
138105  sqlite3GlobalConfig.pInitMutex = 0;
138106  }
138107  sqlite3_mutex_leave(pMaster);
138108 
138109  /* The following is just a sanity check to make sure SQLite has
138110  ** been compiled correctly. It is important to run this code, but
138111  ** we don't want to run it too often and soak up CPU cycles for no
138112  ** reason. So we run it once during initialization.
138113  */
138114 #ifndef NDEBUG
138115 #ifndef SQLITE_OMIT_FLOATING_POINT
138116  /* This section of code's only "output" is via assert() statements. */
138117  if ( rc==SQLITE_OK ){
138118  u64 x = (((u64)1)<<63)-1;
138119  double y;
138120  assert(sizeof(x)==8);
138121  assert(sizeof(x)==sizeof(y));
138122  memcpy(&y, &x, 8);
138123  assert( sqlite3IsNaN(y) );
138124  }
138125 #endif
138126 #endif
138127 
138128  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
138129  ** compile-time option.
138130  */
138131 #ifdef SQLITE_EXTRA_INIT
138132  if( bRunExtraInit ){
138133  int SQLITE_EXTRA_INIT(const char*);
138134  rc = SQLITE_EXTRA_INIT(0);
138135  }
138136 #endif
138137 
138138  return rc;
138139 }
138140 
138141 /*
138142 ** Undo the effects of sqlite3_initialize(). Must not be called while
138143 ** there are outstanding database connections or memory allocations or
138144 ** while any part of SQLite is otherwise in use in any thread. This
138145 ** routine is not threadsafe. But it is safe to invoke this routine
138146 ** on when SQLite is already shut down. If SQLite is already shut down
138147 ** when this routine is invoked, then this routine is a harmless no-op.
138148 */
138149 SQLITE_API int sqlite3_shutdown(void){
138150 #ifdef SQLITE_OMIT_WSD
138151  int rc = sqlite3_wsd_init(4096, 24);
138152  if( rc!=SQLITE_OK ){
138153  return rc;
138154  }
138155 #endif
138156 
138157  if( sqlite3GlobalConfig.isInit ){
138158 #ifdef SQLITE_EXTRA_SHUTDOWN
138159  void SQLITE_EXTRA_SHUTDOWN(void);
138160  SQLITE_EXTRA_SHUTDOWN();
138161 #endif
138162  sqlite3_os_end();
138163  sqlite3_reset_auto_extension();
138164  sqlite3GlobalConfig.isInit = 0;
138165  }
138166  if( sqlite3GlobalConfig.isPCacheInit ){
138167  sqlite3PcacheShutdown();
138168  sqlite3GlobalConfig.isPCacheInit = 0;
138169  }
138170  if( sqlite3GlobalConfig.isMallocInit ){
138171  sqlite3MallocEnd();
138172  sqlite3GlobalConfig.isMallocInit = 0;
138173 
138174 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
138175  /* The heap subsystem has now been shutdown and these values are supposed
138176  ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
138177  ** which would rely on that heap subsystem; therefore, make sure these
138178  ** values cannot refer to heap memory that was just invalidated when the
138179  ** heap subsystem was shutdown. This is only done if the current call to
138180  ** this function resulted in the heap subsystem actually being shutdown.
138181  */
138182  sqlite3_data_directory = 0;
138183  sqlite3_temp_directory = 0;
138184 #endif
138185  }
138186  if( sqlite3GlobalConfig.isMutexInit ){
138187  sqlite3MutexEnd();
138188  sqlite3GlobalConfig.isMutexInit = 0;
138189  }
138190 
138191  return SQLITE_OK;
138192 }
138193 
138194 /*
138195 ** This API allows applications to modify the global configuration of
138196 ** the SQLite library at run-time.
138197 **
138198 ** This routine should only be called when there are no outstanding
138199 ** database connections or memory allocations. This routine is not
138200 ** threadsafe. Failure to heed these warnings can lead to unpredictable
138201 ** behavior.
138202 */
138203 SQLITE_API int sqlite3_config(int op, ...){
138204  va_list ap;
138205  int rc = SQLITE_OK;
138206 
138207  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
138208  ** the SQLite library is in use. */
138209  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
138210 
138211  va_start(ap, op);
138212  switch( op ){
138213 
138214  /* Mutex configuration options are only available in a threadsafe
138215  ** compile.
138216  */
138217 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
138218  case SQLITE_CONFIG_SINGLETHREAD: {
138219  /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
138220  ** Single-thread. */
138221  sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
138222  sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
138223  break;
138224  }
138225 #endif
138226 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
138227  case SQLITE_CONFIG_MULTITHREAD: {
138228  /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
138229  ** Multi-thread. */
138230  sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
138231  sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
138232  break;
138233  }
138234 #endif
138235 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
138236  case SQLITE_CONFIG_SERIALIZED: {
138237  /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
138238  ** Serialized. */
138239  sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
138240  sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
138241  break;
138242  }
138243 #endif
138244 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
138245  case SQLITE_CONFIG_MUTEX: {
138246  /* Specify an alternative mutex implementation */
138247  sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
138248  break;
138249  }
138250 #endif
138251 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
138252  case SQLITE_CONFIG_GETMUTEX: {
138253  /* Retrieve the current mutex implementation */
138254  *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
138255  break;
138256  }
138257 #endif
138258 
138259  case SQLITE_CONFIG_MALLOC: {
138260  /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
138261  ** single argument which is a pointer to an instance of the
138262  ** sqlite3_mem_methods structure. The argument specifies alternative
138263  ** low-level memory allocation routines to be used in place of the memory
138264  ** allocation routines built into SQLite. */
138265  sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
138266  break;
138267  }
138268  case SQLITE_CONFIG_GETMALLOC: {
138269  /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
138270  ** single argument which is a pointer to an instance of the
138271  ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
138272  ** filled with the currently defined memory allocation routines. */
138273  if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
138274  *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
138275  break;
138276  }
138277  case SQLITE_CONFIG_MEMSTATUS: {
138278  /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
138279  ** single argument of type int, interpreted as a boolean, which enables
138280  ** or disables the collection of memory allocation statistics. */
138281  sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
138282  break;
138283  }
138284  case SQLITE_CONFIG_SCRATCH: {
138285  /* EVIDENCE-OF: R-08404-60887 There are three arguments to
138286  ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
138287  ** which the scratch allocations will be drawn, the size of each scratch
138288  ** allocation (sz), and the maximum number of scratch allocations (N). */
138289  sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
138290  sqlite3GlobalConfig.szScratch = va_arg(ap, int);
138291  sqlite3GlobalConfig.nScratch = va_arg(ap, int);
138292  break;
138293  }
138294  case SQLITE_CONFIG_PAGECACHE: {
138295  /* EVIDENCE-OF: R-18761-36601 There are three arguments to
138296  ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
138297  ** the size of each page cache line (sz), and the number of cache lines
138298  ** (N). */
138299  sqlite3GlobalConfig.pPage = va_arg(ap, void*);
138300  sqlite3GlobalConfig.szPage = va_arg(ap, int);
138301  sqlite3GlobalConfig.nPage = va_arg(ap, int);
138302  break;
138303  }
138304  case SQLITE_CONFIG_PCACHE_HDRSZ: {
138305  /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
138306  ** a single parameter which is a pointer to an integer and writes into
138307  ** that integer the number of extra bytes per page required for each page
138308  ** in SQLITE_CONFIG_PAGECACHE. */
138309  *va_arg(ap, int*) =
138310  sqlite3HeaderSizeBtree() +
138311  sqlite3HeaderSizePcache() +
138312  sqlite3HeaderSizePcache1();
138313  break;
138314  }
138315 
138316  case SQLITE_CONFIG_PCACHE: {
138317  /* no-op */
138318  break;
138319  }
138320  case SQLITE_CONFIG_GETPCACHE: {
138321  /* now an error */
138322  rc = SQLITE_ERROR;
138323  break;
138324  }
138325 
138326  case SQLITE_CONFIG_PCACHE2: {
138327  /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
138328  ** single argument which is a pointer to an sqlite3_pcache_methods2
138329  ** object. This object specifies the interface to a custom page cache
138330  ** implementation. */
138331  sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
138332  break;
138333  }
138334  case SQLITE_CONFIG_GETPCACHE2: {
138335  /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
138336  ** single argument which is a pointer to an sqlite3_pcache_methods2
138337  ** object. SQLite copies of the current page cache implementation into
138338  ** that object. */
138339  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
138340  sqlite3PCacheSetDefault();
138341  }
138342  *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
138343  break;
138344  }
138345 
138346 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
138347 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
138348 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
138349 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
138350  case SQLITE_CONFIG_HEAP: {
138351  /* EVIDENCE-OF: R-19854-42126 There are three arguments to
138352  ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
138353  ** number of bytes in the memory buffer, and the minimum allocation size.
138354  */
138355  sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
138356  sqlite3GlobalConfig.nHeap = va_arg(ap, int);
138357  sqlite3GlobalConfig.mnReq = va_arg(ap, int);
138358 
138359  if( sqlite3GlobalConfig.mnReq<1 ){
138360  sqlite3GlobalConfig.mnReq = 1;
138361  }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
138362  /* cap min request size at 2^12 */
138363  sqlite3GlobalConfig.mnReq = (1<<12);
138364  }
138365 
138366  if( sqlite3GlobalConfig.pHeap==0 ){
138367  /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
138368  ** is NULL, then SQLite reverts to using its default memory allocator
138369  ** (the system malloc() implementation), undoing any prior invocation of
138370  ** SQLITE_CONFIG_MALLOC.
138371  **
138372  ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
138373  ** revert to its default implementation when sqlite3_initialize() is run
138374  */
138375  memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
138376  }else{
138377  /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
138378  ** alternative memory allocator is engaged to handle all of SQLites
138379  ** memory allocation needs. */
138380 #ifdef SQLITE_ENABLE_MEMSYS3
138381  sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
138382 #endif
138383 #ifdef SQLITE_ENABLE_MEMSYS5
138384  sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
138385 #endif
138386  }
138387  break;
138388  }
138389 #endif
138390 
138391  case SQLITE_CONFIG_LOOKASIDE: {
138392  sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
138393  sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
138394  break;
138395  }
138396 
138397  /* Record a pointer to the logger function and its first argument.
138398  ** The default is NULL. Logging is disabled if the function pointer is
138399  ** NULL.
138400  */
138401  case SQLITE_CONFIG_LOG: {
138402  /* MSVC is picky about pulling func ptrs from va lists.
138403  ** http://support.microsoft.com/kb/47961
138404  ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
138405  */
138406  typedef void(*LOGFUNC_t)(void*,int,const char*);
138407  sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
138408  sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
138409  break;
138410  }
138411 
138412  /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
138413  ** can be changed at start-time using the
138414  ** sqlite3_config(SQLITE_CONFIG_URI,1) or
138415  ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
138416  */
138417  case SQLITE_CONFIG_URI: {
138418  /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
138419  ** argument of type int. If non-zero, then URI handling is globally
138420  ** enabled. If the parameter is zero, then URI handling is globally
138421  ** disabled. */
138422  sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
138423  break;
138424  }
138425 
138426  case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
138427  /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
138428  ** option takes a single integer argument which is interpreted as a
138429  ** boolean in order to enable or disable the use of covering indices for
138430  ** full table scans in the query optimizer. */
138431  sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
138432  break;
138433  }
138434 
138435 #ifdef SQLITE_ENABLE_SQLLOG
138436  case SQLITE_CONFIG_SQLLOG: {
138437  typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
138438  sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
138439  sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
138440  break;
138441  }
138442 #endif
138443 
138444  case SQLITE_CONFIG_MMAP_SIZE: {
138445  /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
138446  ** integer (sqlite3_int64) values that are the default mmap size limit
138447  ** (the default setting for PRAGMA mmap_size) and the maximum allowed
138448  ** mmap size limit. */
138449  sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
138450  sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
138451  /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
138452  ** negative, then that argument is changed to its compile-time default.
138453  **
138454  ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
138455  ** silently truncated if necessary so that it does not exceed the
138456  ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
138457  ** compile-time option.
138458  */
138459  if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
138460  mxMmap = SQLITE_MAX_MMAP_SIZE;
138461  }
138462  if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
138463  if( szMmap>mxMmap) szMmap = mxMmap;
138464  sqlite3GlobalConfig.mxMmap = mxMmap;
138465  sqlite3GlobalConfig.szMmap = szMmap;
138466  break;
138467  }
138468 
138469 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
138470  case SQLITE_CONFIG_WIN32_HEAPSIZE: {
138471  /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
138472  ** unsigned integer value that specifies the maximum size of the created
138473  ** heap. */
138474  sqlite3GlobalConfig.nHeap = va_arg(ap, int);
138475  break;
138476  }
138477 #endif
138478 
138479  case SQLITE_CONFIG_PMASZ: {
138480  sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
138481  break;
138482  }
138483 
138484  case SQLITE_CONFIG_STMTJRNL_SPILL: {
138485  sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
138486  break;
138487  }
138488 
138489  default: {
138490  rc = SQLITE_ERROR;
138491  break;
138492  }
138493  }
138494  va_end(ap);
138495  return rc;
138496 }
138497 
138498 /*
138499 ** Set up the lookaside buffers for a database connection.
138500 ** Return SQLITE_OK on success.
138501 ** If lookaside is already active, return SQLITE_BUSY.
138502 **
138503 ** The sz parameter is the number of bytes in each lookaside slot.
138504 ** The cnt parameter is the number of slots. If pStart is NULL the
138505 ** space for the lookaside memory is obtained from sqlite3_malloc().
138506 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
138507 ** the lookaside memory.
138508 */
138509 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
138510 #ifndef SQLITE_OMIT_LOOKASIDE
138511  void *pStart;
138512  if( db->lookaside.nOut ){
138513  return SQLITE_BUSY;
138514  }
138515  /* Free any existing lookaside buffer for this handle before
138516  ** allocating a new one so we don't have to have space for
138517  ** both at the same time.
138518  */
138519  if( db->lookaside.bMalloced ){
138520  sqlite3_free(db->lookaside.pStart);
138521  }
138522  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
138523  ** than a pointer to be useful.
138524  */
138525  sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
138526  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
138527  if( cnt<0 ) cnt = 0;
138528  if( sz==0 || cnt==0 ){
138529  sz = 0;
138530  pStart = 0;
138531  }else if( pBuf==0 ){
138532  sqlite3BeginBenignMalloc();
138533  pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
138534  sqlite3EndBenignMalloc();
138535  if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
138536  }else{
138537  pStart = pBuf;
138538  }
138539  db->lookaside.pStart = pStart;
138540  db->lookaside.pFree = 0;
138541  db->lookaside.sz = (u16)sz;
138542  if( pStart ){
138543  int i;
138544  LookasideSlot *p;
138545  assert( sz > (int)sizeof(LookasideSlot*) );
138546  p = (LookasideSlot*)pStart;
138547  for(i=cnt-1; i>=0; i--){
138548  p->pNext = db->lookaside.pFree;
138549  db->lookaside.pFree = p;
138550  p = (LookasideSlot*)&((u8*)p)[sz];
138551  }
138552  db->lookaside.pEnd = p;
138553  db->lookaside.bDisable = 0;
138554  db->lookaside.bMalloced = pBuf==0 ?1:0;
138555  }else{
138556  db->lookaside.pStart = db;
138557  db->lookaside.pEnd = db;
138558  db->lookaside.bDisable = 1;
138559  db->lookaside.bMalloced = 0;
138560  }
138561 #endif /* SQLITE_OMIT_LOOKASIDE */
138562  return SQLITE_OK;
138563 }
138564 
138565 /*
138566 ** Return the mutex associated with a database connection.
138567 */
138568 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
138569 #ifdef SQLITE_ENABLE_API_ARMOR
138570  if( !sqlite3SafetyCheckOk(db) ){
138571  (void)SQLITE_MISUSE_BKPT;
138572  return 0;
138573  }
138574 #endif
138575  return db->mutex;
138576 }
138577 
138578 /*
138579 ** Free up as much memory as we can from the given database
138580 ** connection.
138581 */
138582 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
138583  int i;
138584 
138585 #ifdef SQLITE_ENABLE_API_ARMOR
138586  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138587 #endif
138588  sqlite3_mutex_enter(db->mutex);
138589  sqlite3BtreeEnterAll(db);
138590  for(i=0; i<db->nDb; i++){
138591  Btree *pBt = db->aDb[i].pBt;
138592  if( pBt ){
138593  Pager *pPager = sqlite3BtreePager(pBt);
138594  sqlite3PagerShrink(pPager);
138595  }
138596  }
138597  sqlite3BtreeLeaveAll(db);
138598  sqlite3_mutex_leave(db->mutex);
138599  return SQLITE_OK;
138600 }
138601 
138602 /*
138603 ** Flush any dirty pages in the pager-cache for any attached database
138604 ** to disk.
138605 */
138606 SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
138607  int i;
138608  int rc = SQLITE_OK;
138609  int bSeenBusy = 0;
138610 
138611 #ifdef SQLITE_ENABLE_API_ARMOR
138612  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138613 #endif
138614  sqlite3_mutex_enter(db->mutex);
138615  sqlite3BtreeEnterAll(db);
138616  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
138617  Btree *pBt = db->aDb[i].pBt;
138618  if( pBt && sqlite3BtreeIsInTrans(pBt) ){
138619  Pager *pPager = sqlite3BtreePager(pBt);
138620  rc = sqlite3PagerFlush(pPager);
138621  if( rc==SQLITE_BUSY ){
138622  bSeenBusy = 1;
138623  rc = SQLITE_OK;
138624  }
138625  }
138626  }
138627  sqlite3BtreeLeaveAll(db);
138628  sqlite3_mutex_leave(db->mutex);
138629  return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
138630 }
138631 
138632 /*
138633 ** Configuration settings for an individual database connection
138634 */
138635 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
138636  va_list ap;
138637  int rc;
138638  va_start(ap, op);
138639  switch( op ){
138640  case SQLITE_DBCONFIG_MAINDBNAME: {
138641  db->aDb[0].zDbSName = va_arg(ap,char*);
138642  rc = SQLITE_OK;
138643  break;
138644  }
138645  case SQLITE_DBCONFIG_LOOKASIDE: {
138646  void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
138647  int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
138648  int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
138649  rc = setupLookaside(db, pBuf, sz, cnt);
138650  break;
138651  }
138652  default: {
138653  static const struct {
138654  int op; /* The opcode */
138655  u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
138656  } aFlagOp[] = {
138657  { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
138658  { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
138659  { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
138660  { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
138661  };
138662  unsigned int i;
138663  rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
138664  for(i=0; i<ArraySize(aFlagOp); i++){
138665  if( aFlagOp[i].op==op ){
138666  int onoff = va_arg(ap, int);
138667  int *pRes = va_arg(ap, int*);
138668  int oldFlags = db->flags;
138669  if( onoff>0 ){
138670  db->flags |= aFlagOp[i].mask;
138671  }else if( onoff==0 ){
138672  db->flags &= ~aFlagOp[i].mask;
138673  }
138674  if( oldFlags!=db->flags ){
138675  sqlite3ExpirePreparedStatements(db);
138676  }
138677  if( pRes ){
138678  *pRes = (db->flags & aFlagOp[i].mask)!=0;
138679  }
138680  rc = SQLITE_OK;
138681  break;
138682  }
138683  }
138684  break;
138685  }
138686  }
138687  va_end(ap);
138688  return rc;
138689 }
138690 
138691 
138692 /*
138693 ** Return true if the buffer z[0..n-1] contains all spaces.
138694 */
138695 static int allSpaces(const char *z, int n){
138696  while( n>0 && z[n-1]==' ' ){ n--; }
138697  return n==0;
138698 }
138699 
138700 /*
138701 ** This is the default collating function named "BINARY" which is always
138702 ** available.
138703 **
138704 ** If the padFlag argument is not NULL then space padding at the end
138705 ** of strings is ignored. This implements the RTRIM collation.
138706 */
138707 static int binCollFunc(
138708  void *padFlag,
138709  int nKey1, const void *pKey1,
138710  int nKey2, const void *pKey2
138711 ){
138712  int rc, n;
138713  n = nKey1<nKey2 ? nKey1 : nKey2;
138714  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
138715  ** strings byte by byte using the memcmp() function from the standard C
138716  ** library. */
138717  rc = memcmp(pKey1, pKey2, n);
138718  if( rc==0 ){
138719  if( padFlag
138720  && allSpaces(((char*)pKey1)+n, nKey1-n)
138721  && allSpaces(((char*)pKey2)+n, nKey2-n)
138722  ){
138723  /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
138724  ** spaces at the end of either string do not change the result. In other
138725  ** words, strings will compare equal to one another as long as they
138726  ** differ only in the number of spaces at the end.
138727  */
138728  }else{
138729  rc = nKey1 - nKey2;
138730  }
138731  }
138732  return rc;
138733 }
138734 
138735 /*
138736 ** Another built-in collating sequence: NOCASE.
138737 **
138738 ** This collating sequence is intended to be used for "case independent
138739 ** comparison". SQLite's knowledge of upper and lower case equivalents
138740 ** extends only to the 26 characters used in the English language.
138741 **
138742 ** At the moment there is only a UTF-8 implementation.
138743 */
138744 static int nocaseCollatingFunc(
138745  void *NotUsed,
138746  int nKey1, const void *pKey1,
138747  int nKey2, const void *pKey2
138748 ){
138749  int r = sqlite3StrNICmp(
138750  (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
138751  UNUSED_PARAMETER(NotUsed);
138752  if( 0==r ){
138753  r = nKey1-nKey2;
138754  }
138755  return r;
138756 }
138757 
138758 /*
138759 ** Return the ROWID of the most recent insert
138760 */
138761 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
138762 #ifdef SQLITE_ENABLE_API_ARMOR
138763  if( !sqlite3SafetyCheckOk(db) ){
138764  (void)SQLITE_MISUSE_BKPT;
138765  return 0;
138766  }
138767 #endif
138768  return db->lastRowid;
138769 }
138770 
138771 /*
138772 ** Return the number of changes in the most recent call to sqlite3_exec().
138773 */
138774 SQLITE_API int sqlite3_changes(sqlite3 *db){
138775 #ifdef SQLITE_ENABLE_API_ARMOR
138776  if( !sqlite3SafetyCheckOk(db) ){
138777  (void)SQLITE_MISUSE_BKPT;
138778  return 0;
138779  }
138780 #endif
138781  return db->nChange;
138782 }
138783 
138784 /*
138785 ** Return the number of changes since the database handle was opened.
138786 */
138787 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
138788 #ifdef SQLITE_ENABLE_API_ARMOR
138789  if( !sqlite3SafetyCheckOk(db) ){
138790  (void)SQLITE_MISUSE_BKPT;
138791  return 0;
138792  }
138793 #endif
138794  return db->nTotalChange;
138795 }
138796 
138797 /*
138798 ** Close all open savepoints. This function only manipulates fields of the
138799 ** database handle object, it does not close any savepoints that may be open
138800 ** at the b-tree/pager level.
138801 */
138802 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
138803  while( db->pSavepoint ){
138804  Savepoint *pTmp = db->pSavepoint;
138805  db->pSavepoint = pTmp->pNext;
138806  sqlite3DbFree(db, pTmp);
138807  }
138808  db->nSavepoint = 0;
138809  db->nStatement = 0;
138810  db->isTransactionSavepoint = 0;
138811 }
138812 
138813 /*
138814 ** Invoke the destructor function associated with FuncDef p, if any. Except,
138815 ** if this is not the last copy of the function, do not invoke it. Multiple
138816 ** copies of a single function are created when create_function() is called
138817 ** with SQLITE_ANY as the encoding.
138818 */
138819 static void functionDestroy(sqlite3 *db, FuncDef *p){
138820  FuncDestructor *pDestructor = p->u.pDestructor;
138821  if( pDestructor ){
138822  pDestructor->nRef--;
138823  if( pDestructor->nRef==0 ){
138824  pDestructor->xDestroy(pDestructor->pUserData);
138825  sqlite3DbFree(db, pDestructor);
138826  }
138827  }
138828 }
138829 
138830 /*
138831 ** Disconnect all sqlite3_vtab objects that belong to database connection
138832 ** db. This is called when db is being closed.
138833 */
138834 static void disconnectAllVtab(sqlite3 *db){
138835 #ifndef SQLITE_OMIT_VIRTUALTABLE
138836  int i;
138837  HashElem *p;
138838  sqlite3BtreeEnterAll(db);
138839  for(i=0; i<db->nDb; i++){
138840  Schema *pSchema = db->aDb[i].pSchema;
138841  if( db->aDb[i].pSchema ){
138842  for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
138843  Table *pTab = (Table *)sqliteHashData(p);
138844  if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
138845  }
138846  }
138847  }
138848  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
138849  Module *pMod = (Module *)sqliteHashData(p);
138850  if( pMod->pEpoTab ){
138851  sqlite3VtabDisconnect(db, pMod->pEpoTab);
138852  }
138853  }
138854  sqlite3VtabUnlockList(db);
138855  sqlite3BtreeLeaveAll(db);
138856 #else
138857  UNUSED_PARAMETER(db);
138858 #endif
138859 }
138860 
138861 /*
138862 ** Return TRUE if database connection db has unfinalized prepared
138863 ** statements or unfinished sqlite3_backup objects.
138864 */
138865 static int connectionIsBusy(sqlite3 *db){
138866  int j;
138867  assert( sqlite3_mutex_held(db->mutex) );
138868  if( db->pVdbe ) return 1;
138869  for(j=0; j<db->nDb; j++){
138870  Btree *pBt = db->aDb[j].pBt;
138871  if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
138872  }
138873  return 0;
138874 }
138875 
138876 /*
138877 ** Close an existing SQLite database
138878 */
138879 static int sqlite3Close(sqlite3 *db, int forceZombie){
138880  if( !db ){
138881  /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
138882  ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
138883  return SQLITE_OK;
138884  }
138885  if( !sqlite3SafetyCheckSickOrOk(db) ){
138886  return SQLITE_MISUSE_BKPT;
138887  }
138888  sqlite3_mutex_enter(db->mutex);
138889  if( db->mTrace & SQLITE_TRACE_CLOSE ){
138890  db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
138891  }
138892 
138893  /* Force xDisconnect calls on all virtual tables */
138894  disconnectAllVtab(db);
138895 
138896  /* If a transaction is open, the disconnectAllVtab() call above
138897  ** will not have called the xDisconnect() method on any virtual
138898  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
138899  ** call will do so. We need to do this before the check for active
138900  ** SQL statements below, as the v-table implementation may be storing
138901  ** some prepared statements internally.
138902  */
138903  sqlite3VtabRollback(db);
138904 
138905  /* Legacy behavior (sqlite3_close() behavior) is to return
138906  ** SQLITE_BUSY if the connection can not be closed immediately.
138907  */
138908  if( !forceZombie && connectionIsBusy(db) ){
138909  sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
138910  "statements or unfinished backups");
138911  sqlite3_mutex_leave(db->mutex);
138912  return SQLITE_BUSY;
138913  }
138914 
138915 #ifdef SQLITE_ENABLE_SQLLOG
138916  if( sqlite3GlobalConfig.xSqllog ){
138917  /* Closing the handle. Fourth parameter is passed the value 2. */
138918  sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
138919  }
138920 #endif
138921 
138922  /* Convert the connection into a zombie and then close it.
138923  */
138924  db->magic = SQLITE_MAGIC_ZOMBIE;
138925  sqlite3LeaveMutexAndCloseZombie(db);
138926  return SQLITE_OK;
138927 }
138928 
138929 /*
138930 ** Two variations on the public interface for closing a database
138931 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
138932 ** leaves the connection option if there are unfinalized prepared
138933 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
138934 ** version forces the connection to become a zombie if there are
138935 ** unclosed resources, and arranges for deallocation when the last
138936 ** prepare statement or sqlite3_backup closes.
138937 */
138938 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
138939 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
138940 
138941 
138942 /*
138943 ** Close the mutex on database connection db.
138944 **
138945 ** Furthermore, if database connection db is a zombie (meaning that there
138946 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
138947 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
138948 ** finished, then free all resources.
138949 */
138950 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
138951  HashElem *i; /* Hash table iterator */
138952  int j;
138953 
138954  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
138955  ** or if the connection has not yet been closed by sqlite3_close_v2(),
138956  ** then just leave the mutex and return.
138957  */
138958  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
138959  sqlite3_mutex_leave(db->mutex);
138960  return;
138961  }
138962 
138963  /* If we reach this point, it means that the database connection has
138964  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
138965  ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
138966  ** go ahead and free all resources.
138967  */
138968 
138969  /* If a transaction is open, roll it back. This also ensures that if
138970  ** any database schemas have been modified by an uncommitted transaction
138971  ** they are reset. And that the required b-tree mutex is held to make
138972  ** the pager rollback and schema reset an atomic operation. */
138973  sqlite3RollbackAll(db, SQLITE_OK);
138974 
138975  /* Free any outstanding Savepoint structures. */
138976  sqlite3CloseSavepoints(db);
138977 
138978  /* Close all database connections */
138979  for(j=0; j<db->nDb; j++){
138980  struct Db *pDb = &db->aDb[j];
138981  if( pDb->pBt ){
138982  sqlite3BtreeClose(pDb->pBt);
138983  pDb->pBt = 0;
138984  if( j!=1 ){
138985  pDb->pSchema = 0;
138986  }
138987  }
138988  }
138989  /* Clear the TEMP schema separately and last */
138990  if( db->aDb[1].pSchema ){
138991  sqlite3SchemaClear(db->aDb[1].pSchema);
138992  }
138993  sqlite3VtabUnlockList(db);
138994 
138995  /* Free up the array of auxiliary databases */
138996  sqlite3CollapseDatabaseArray(db);
138997  assert( db->nDb<=2 );
138998  assert( db->aDb==db->aDbStatic );
138999 
139000  /* Tell the code in notify.c that the connection no longer holds any
139001  ** locks and does not require any further unlock-notify callbacks.
139002  */
139003  sqlite3ConnectionClosed(db);
139004 
139005  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
139006  FuncDef *pNext, *p;
139007  p = sqliteHashData(i);
139008  do{
139009  functionDestroy(db, p);
139010  pNext = p->pNext;
139011  sqlite3DbFree(db, p);
139012  p = pNext;
139013  }while( p );
139014  }
139015  sqlite3HashClear(&db->aFunc);
139016  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
139017  CollSeq *pColl = (CollSeq *)sqliteHashData(i);
139018  /* Invoke any destructors registered for collation sequence user data. */
139019  for(j=0; j<3; j++){
139020  if( pColl[j].xDel ){
139021  pColl[j].xDel(pColl[j].pUser);
139022  }
139023  }
139024  sqlite3DbFree(db, pColl);
139025  }
139026  sqlite3HashClear(&db->aCollSeq);
139027 #ifndef SQLITE_OMIT_VIRTUALTABLE
139028  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
139029  Module *pMod = (Module *)sqliteHashData(i);
139030  if( pMod->xDestroy ){
139031  pMod->xDestroy(pMod->pAux);
139032  }
139033  sqlite3VtabEponymousTableClear(db, pMod);
139034  sqlite3DbFree(db, pMod);
139035  }
139036  sqlite3HashClear(&db->aModule);
139037 #endif
139038 
139039  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
139040  sqlite3ValueFree(db->pErr);
139041  sqlite3CloseExtensions(db);
139042 #if SQLITE_USER_AUTHENTICATION
139043  sqlite3_free(db->auth.zAuthUser);
139044  sqlite3_free(db->auth.zAuthPW);
139045 #endif
139046 
139047  db->magic = SQLITE_MAGIC_ERROR;
139048 
139049  /* The temp-database schema is allocated differently from the other schema
139050  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
139051  ** So it needs to be freed here. Todo: Why not roll the temp schema into
139052  ** the same sqliteMalloc() as the one that allocates the database
139053  ** structure?
139054  */
139055  sqlite3DbFree(db, db->aDb[1].pSchema);
139056  sqlite3_mutex_leave(db->mutex);
139057  db->magic = SQLITE_MAGIC_CLOSED;
139058  sqlite3_mutex_free(db->mutex);
139059  assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
139060  if( db->lookaside.bMalloced ){
139061  sqlite3_free(db->lookaside.pStart);
139062  }
139063  sqlite3_free(db);
139064 }
139065 
139066 /*
139067 ** Rollback all database files. If tripCode is not SQLITE_OK, then
139068 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
139069 ** breaker") and made to return tripCode if there are any further
139070 ** attempts to use that cursor. Read cursors remain open and valid
139071 ** but are "saved" in case the table pages are moved around.
139072 */
139073 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
139074  int i;
139075  int inTrans = 0;
139076  int schemaChange;
139077  assert( sqlite3_mutex_held(db->mutex) );
139078  sqlite3BeginBenignMalloc();
139079 
139080  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
139081  ** This is important in case the transaction being rolled back has
139082  ** modified the database schema. If the b-tree mutexes are not taken
139083  ** here, then another shared-cache connection might sneak in between
139084  ** the database rollback and schema reset, which can cause false
139085  ** corruption reports in some cases. */
139086  sqlite3BtreeEnterAll(db);
139087  schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
139088 
139089  for(i=0; i<db->nDb; i++){
139090  Btree *p = db->aDb[i].pBt;
139091  if( p ){
139092  if( sqlite3BtreeIsInTrans(p) ){
139093  inTrans = 1;
139094  }
139095  sqlite3BtreeRollback(p, tripCode, !schemaChange);
139096  }
139097  }
139098  sqlite3VtabRollback(db);
139099  sqlite3EndBenignMalloc();
139100 
139101  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
139102  sqlite3ExpirePreparedStatements(db);
139103  sqlite3ResetAllSchemasOfConnection(db);
139104  }
139105  sqlite3BtreeLeaveAll(db);
139106 
139107  /* Any deferred constraint violations have now been resolved. */
139108  db->nDeferredCons = 0;
139109  db->nDeferredImmCons = 0;
139110  db->flags &= ~SQLITE_DeferFKs;
139111 
139112  /* If one has been configured, invoke the rollback-hook callback */
139113  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
139114  db->xRollbackCallback(db->pRollbackArg);
139115  }
139116 }
139117 
139118 /*
139119 ** Return a static string containing the name corresponding to the error code
139120 ** specified in the argument.
139121 */
139122 #if defined(SQLITE_NEED_ERR_NAME)
139123 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
139124  const char *zName = 0;
139125  int i, origRc = rc;
139126  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
139127  switch( rc ){
139128  case SQLITE_OK: zName = "SQLITE_OK"; break;
139129  case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
139130  case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
139131  case SQLITE_PERM: zName = "SQLITE_PERM"; break;
139132  case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
139133  case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
139134  case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
139135  case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
139136  case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
139137  case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
139138  case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
139139  case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
139140  case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
139141  case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
139142  case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
139143  case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
139144  case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
139145  case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
139146  case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
139147  case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
139148  case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
139149  case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
139150  case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
139151  case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
139152  case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
139153  case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
139154  case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
139155  case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
139156  case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
139157  case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
139158  case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
139159  case SQLITE_IOERR_CHECKRESERVEDLOCK:
139160  zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
139161  case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
139162  case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
139163  case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
139164  case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
139165  case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
139166  case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
139167  case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
139168  case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
139169  case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
139170  case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
139171  case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
139172  case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
139173  case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
139174  case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
139175  case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
139176  case SQLITE_FULL: zName = "SQLITE_FULL"; break;
139177  case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
139178  case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
139179  case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
139180  case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
139181  case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
139182  case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
139183  case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
139184  case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
139185  case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
139186  case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
139187  case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
139188  case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
139189  case SQLITE_CONSTRAINT_FOREIGNKEY:
139190  zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
139191  case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
139192  case SQLITE_CONSTRAINT_PRIMARYKEY:
139193  zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
139194  case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
139195  case SQLITE_CONSTRAINT_COMMITHOOK:
139196  zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
139197  case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
139198  case SQLITE_CONSTRAINT_FUNCTION:
139199  zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
139200  case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
139201  case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
139202  case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
139203  case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
139204  case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
139205  case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
139206  case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
139207  case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
139208  case SQLITE_ROW: zName = "SQLITE_ROW"; break;
139209  case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
139210  case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
139211  case SQLITE_NOTICE_RECOVER_ROLLBACK:
139212  zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
139213  case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
139214  case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
139215  case SQLITE_DONE: zName = "SQLITE_DONE"; break;
139216  }
139217  }
139218  if( zName==0 ){
139219  static char zBuf[50];
139220  sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
139221  zName = zBuf;
139222  }
139223  return zName;
139224 }
139225 #endif
139226 
139227 /*
139228 ** Return a static string that describes the kind of error specified in the
139229 ** argument.
139230 */
139231 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
139232  static const char* const aMsg[] = {
139233  /* SQLITE_OK */ "not an error",
139234  /* SQLITE_ERROR */ "SQL logic error or missing database",
139235  /* SQLITE_INTERNAL */ 0,
139236  /* SQLITE_PERM */ "access permission denied",
139237  /* SQLITE_ABORT */ "callback requested query abort",
139238  /* SQLITE_BUSY */ "database is locked",
139239  /* SQLITE_LOCKED */ "database table is locked",
139240  /* SQLITE_NOMEM */ "out of memory",
139241  /* SQLITE_READONLY */ "attempt to write a readonly database",
139242  /* SQLITE_INTERRUPT */ "interrupted",
139243  /* SQLITE_IOERR */ "disk I/O error",
139244  /* SQLITE_CORRUPT */ "database disk image is malformed",
139245  /* SQLITE_NOTFOUND */ "unknown operation",
139246  /* SQLITE_FULL */ "database or disk is full",
139247  /* SQLITE_CANTOPEN */ "unable to open database file",
139248  /* SQLITE_PROTOCOL */ "locking protocol",
139249  /* SQLITE_EMPTY */ "table contains no data",
139250  /* SQLITE_SCHEMA */ "database schema has changed",
139251  /* SQLITE_TOOBIG */ "string or blob too big",
139252  /* SQLITE_CONSTRAINT */ "constraint failed",
139253  /* SQLITE_MISMATCH */ "datatype mismatch",
139254  /* SQLITE_MISUSE */ "library routine called out of sequence",
139255  /* SQLITE_NOLFS */ "large file support is disabled",
139256  /* SQLITE_AUTH */ "authorization denied",
139257  /* SQLITE_FORMAT */ "auxiliary database format error",
139258  /* SQLITE_RANGE */ "bind or column index out of range",
139259  /* SQLITE_NOTADB */ "file is encrypted or is not a database",
139260  };
139261  const char *zErr = "unknown error";
139262  switch( rc ){
139263  case SQLITE_ABORT_ROLLBACK: {
139264  zErr = "abort due to ROLLBACK";
139265  break;
139266  }
139267  default: {
139268  rc &= 0xff;
139269  if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
139270  zErr = aMsg[rc];
139271  }
139272  break;
139273  }
139274  }
139275  return zErr;
139276 }
139277 
139278 /*
139279 ** This routine implements a busy callback that sleeps and tries
139280 ** again until a timeout value is reached. The timeout value is
139281 ** an integer number of milliseconds passed in as the first
139282 ** argument.
139283 */
139284 static int sqliteDefaultBusyCallback(
139285  void *ptr, /* Database connection */
139286  int count /* Number of times table has been busy */
139287 ){
139288 #if SQLITE_OS_WIN || HAVE_USLEEP
139289  static const u8 delays[] =
139290  { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
139291  static const u8 totals[] =
139292  { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
139293 # define NDELAY ArraySize(delays)
139294  sqlite3 *db = (sqlite3 *)ptr;
139295  int timeout = db->busyTimeout;
139296  int delay, prior;
139297 
139298  assert( count>=0 );
139299  if( count < NDELAY ){
139300  delay = delays[count];
139301  prior = totals[count];
139302  }else{
139303  delay = delays[NDELAY-1];
139304  prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
139305  }
139306  if( prior + delay > timeout ){
139307  delay = timeout - prior;
139308  if( delay<=0 ) return 0;
139309  }
139310  sqlite3OsSleep(db->pVfs, delay*1000);
139311  return 1;
139312 #else
139313  sqlite3 *db = (sqlite3 *)ptr;
139314  int timeout = ((sqlite3 *)ptr)->busyTimeout;
139315  if( (count+1)*1000 > timeout ){
139316  return 0;
139317  }
139318  sqlite3OsSleep(db->pVfs, 1000000);
139319  return 1;
139320 #endif
139321 }
139322 
139323 /*
139324 ** Invoke the given busy handler.
139325 **
139326 ** This routine is called when an operation failed with a lock.
139327 ** If this routine returns non-zero, the lock is retried. If it
139328 ** returns 0, the operation aborts with an SQLITE_BUSY error.
139329 */
139330 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
139331  int rc;
139332  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
139333  rc = p->xFunc(p->pArg, p->nBusy);
139334  if( rc==0 ){
139335  p->nBusy = -1;
139336  }else{
139337  p->nBusy++;
139338  }
139339  return rc;
139340 }
139341 
139342 /*
139343 ** This routine sets the busy callback for an Sqlite database to the
139344 ** given callback function with the given argument.
139345 */
139346 SQLITE_API int sqlite3_busy_handler(
139347  sqlite3 *db,
139348  int (*xBusy)(void*,int),
139349  void *pArg
139350 ){
139351 #ifdef SQLITE_ENABLE_API_ARMOR
139352  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139353 #endif
139354  sqlite3_mutex_enter(db->mutex);
139355  db->busyHandler.xFunc = xBusy;
139356  db->busyHandler.pArg = pArg;
139357  db->busyHandler.nBusy = 0;
139358  db->busyTimeout = 0;
139359  sqlite3_mutex_leave(db->mutex);
139360  return SQLITE_OK;
139361 }
139362 
139363 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
139364 /*
139365 ** This routine sets the progress callback for an Sqlite database to the
139366 ** given callback function with the given argument. The progress callback will
139367 ** be invoked every nOps opcodes.
139368 */
139369 SQLITE_API void sqlite3_progress_handler(
139370  sqlite3 *db,
139371  int nOps,
139372  int (*xProgress)(void*),
139373  void *pArg
139374 ){
139375 #ifdef SQLITE_ENABLE_API_ARMOR
139376  if( !sqlite3SafetyCheckOk(db) ){
139377  (void)SQLITE_MISUSE_BKPT;
139378  return;
139379  }
139380 #endif
139381  sqlite3_mutex_enter(db->mutex);
139382  if( nOps>0 ){
139383  db->xProgress = xProgress;
139384  db->nProgressOps = (unsigned)nOps;
139385  db->pProgressArg = pArg;
139386  }else{
139387  db->xProgress = 0;
139388  db->nProgressOps = 0;
139389  db->pProgressArg = 0;
139390  }
139391  sqlite3_mutex_leave(db->mutex);
139392 }
139393 #endif
139394 
139395 
139396 /*
139397 ** This routine installs a default busy handler that waits for the
139398 ** specified number of milliseconds before returning 0.
139399 */
139400 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
139401 #ifdef SQLITE_ENABLE_API_ARMOR
139402  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139403 #endif
139404  if( ms>0 ){
139405  sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
139406  db->busyTimeout = ms;
139407  }else{
139408  sqlite3_busy_handler(db, 0, 0);
139409  }
139410  return SQLITE_OK;
139411 }
139412 
139413 /*
139414 ** Cause any pending operation to stop at its earliest opportunity.
139415 */
139416 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
139417 #ifdef SQLITE_ENABLE_API_ARMOR
139418  if( !sqlite3SafetyCheckOk(db) ){
139419  (void)SQLITE_MISUSE_BKPT;
139420  return;
139421  }
139422 #endif
139423  db->u1.isInterrupted = 1;
139424 }
139425 
139426 
139427 /*
139428 ** This function is exactly the same as sqlite3_create_function(), except
139429 ** that it is designed to be called by internal code. The difference is
139430 ** that if a malloc() fails in sqlite3_create_function(), an error code
139431 ** is returned and the mallocFailed flag cleared.
139432 */
139433 SQLITE_PRIVATE int sqlite3CreateFunc(
139434  sqlite3 *db,
139435  const char *zFunctionName,
139436  int nArg,
139437  int enc,
139438  void *pUserData,
139439  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
139440  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
139441  void (*xFinal)(sqlite3_context*),
139442  FuncDestructor *pDestructor
139443 ){
139444  FuncDef *p;
139445  int nName;
139446  int extraFlags;
139447 
139448  assert( sqlite3_mutex_held(db->mutex) );
139449  if( zFunctionName==0 ||
139450  (xSFunc && (xFinal || xStep)) ||
139451  (!xSFunc && (xFinal && !xStep)) ||
139452  (!xSFunc && (!xFinal && xStep)) ||
139453  (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
139454  (255<(nName = sqlite3Strlen30( zFunctionName))) ){
139455  return SQLITE_MISUSE_BKPT;
139456  }
139457 
139458  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
139459  extraFlags = enc & SQLITE_DETERMINISTIC;
139460  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
139461 
139462 #ifndef SQLITE_OMIT_UTF16
139463  /* If SQLITE_UTF16 is specified as the encoding type, transform this
139464  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
139465  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
139466  **
139467  ** If SQLITE_ANY is specified, add three versions of the function
139468  ** to the hash table.
139469  */
139470  if( enc==SQLITE_UTF16 ){
139471  enc = SQLITE_UTF16NATIVE;
139472  }else if( enc==SQLITE_ANY ){
139473  int rc;
139474  rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
139475  pUserData, xSFunc, xStep, xFinal, pDestructor);
139476  if( rc==SQLITE_OK ){
139477  rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
139478  pUserData, xSFunc, xStep, xFinal, pDestructor);
139479  }
139480  if( rc!=SQLITE_OK ){
139481  return rc;
139482  }
139483  enc = SQLITE_UTF16BE;
139484  }
139485 #else
139486  enc = SQLITE_UTF8;
139487 #endif
139488 
139489  /* Check if an existing function is being overridden or deleted. If so,
139490  ** and there are active VMs, then return SQLITE_BUSY. If a function
139491  ** is being overridden/deleted but there are no active VMs, allow the
139492  ** operation to continue but invalidate all precompiled statements.
139493  */
139494  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
139495  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
139496  if( db->nVdbeActive ){
139497  sqlite3ErrorWithMsg(db, SQLITE_BUSY,
139498  "unable to delete/modify user-function due to active statements");
139499  assert( !db->mallocFailed );
139500  return SQLITE_BUSY;
139501  }else{
139502  sqlite3ExpirePreparedStatements(db);
139503  }
139504  }
139505 
139506  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
139507  assert(p || db->mallocFailed);
139508  if( !p ){
139509  return SQLITE_NOMEM_BKPT;
139510  }
139511 
139512  /* If an older version of the function with a configured destructor is
139513  ** being replaced invoke the destructor function here. */
139514  functionDestroy(db, p);
139515 
139516  if( pDestructor ){
139517  pDestructor->nRef++;
139518  }
139519  p->u.pDestructor = pDestructor;
139520  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
139521  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
139522  p->xSFunc = xSFunc ? xSFunc : xStep;
139523  p->xFinalize = xFinal;
139524  p->pUserData = pUserData;
139525  p->nArg = (u16)nArg;
139526  return SQLITE_OK;
139527 }
139528 
139529 /*
139530 ** Create new user functions.
139531 */
139532 SQLITE_API int sqlite3_create_function(
139533  sqlite3 *db,
139534  const char *zFunc,
139535  int nArg,
139536  int enc,
139537  void *p,
139538  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
139539  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
139540  void (*xFinal)(sqlite3_context*)
139541 ){
139542  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
139543  xFinal, 0);
139544 }
139545 
139546 SQLITE_API int sqlite3_create_function_v2(
139547  sqlite3 *db,
139548  const char *zFunc,
139549  int nArg,
139550  int enc,
139551  void *p,
139552  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
139553  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
139554  void (*xFinal)(sqlite3_context*),
139555  void (*xDestroy)(void *)
139556 ){
139557  int rc = SQLITE_ERROR;
139558  FuncDestructor *pArg = 0;
139559 
139560 #ifdef SQLITE_ENABLE_API_ARMOR
139561  if( !sqlite3SafetyCheckOk(db) ){
139562  return SQLITE_MISUSE_BKPT;
139563  }
139564 #endif
139565  sqlite3_mutex_enter(db->mutex);
139566  if( xDestroy ){
139567  pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
139568  if( !pArg ){
139569  xDestroy(p);
139570  goto out;
139571  }
139572  pArg->xDestroy = xDestroy;
139573  pArg->pUserData = p;
139574  }
139575  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
139576  if( pArg && pArg->nRef==0 ){
139577  assert( rc!=SQLITE_OK );
139578  xDestroy(p);
139579  sqlite3DbFree(db, pArg);
139580  }
139581 
139582  out:
139583  rc = sqlite3ApiExit(db, rc);
139584  sqlite3_mutex_leave(db->mutex);
139585  return rc;
139586 }
139587 
139588 #ifndef SQLITE_OMIT_UTF16
139589 SQLITE_API int sqlite3_create_function16(
139590  sqlite3 *db,
139591  const void *zFunctionName,
139592  int nArg,
139593  int eTextRep,
139594  void *p,
139595  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
139596  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
139597  void (*xFinal)(sqlite3_context*)
139598 ){
139599  int rc;
139600  char *zFunc8;
139601 
139602 #ifdef SQLITE_ENABLE_API_ARMOR
139603  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
139604 #endif
139605  sqlite3_mutex_enter(db->mutex);
139606  assert( !db->mallocFailed );
139607  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
139608  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
139609  sqlite3DbFree(db, zFunc8);
139610  rc = sqlite3ApiExit(db, rc);
139611  sqlite3_mutex_leave(db->mutex);
139612  return rc;
139613 }
139614 #endif
139615 
139616 
139617 /*
139618 ** Declare that a function has been overloaded by a virtual table.
139619 **
139620 ** If the function already exists as a regular global function, then
139621 ** this routine is a no-op. If the function does not exist, then create
139622 ** a new one that always throws a run-time error.
139623 **
139624 ** When virtual tables intend to provide an overloaded function, they
139625 ** should call this routine to make sure the global function exists.
139626 ** A global function must exist in order for name resolution to work
139627 ** properly.
139628 */
139629 SQLITE_API int sqlite3_overload_function(
139630  sqlite3 *db,
139631  const char *zName,
139632  int nArg
139633 ){
139634  int rc = SQLITE_OK;
139635 
139636 #ifdef SQLITE_ENABLE_API_ARMOR
139637  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
139638  return SQLITE_MISUSE_BKPT;
139639  }
139640 #endif
139641  sqlite3_mutex_enter(db->mutex);
139642  if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
139643  rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
139644  0, sqlite3InvalidFunction, 0, 0, 0);
139645  }
139646  rc = sqlite3ApiExit(db, rc);
139647  sqlite3_mutex_leave(db->mutex);
139648  return rc;
139649 }
139650 
139651 #ifndef SQLITE_OMIT_TRACE
139652 /*
139653 ** Register a trace function. The pArg from the previously registered trace
139654 ** is returned.
139655 **
139656 ** A NULL trace function means that no tracing is executes. A non-NULL
139657 ** trace is a pointer to a function that is invoked at the start of each
139658 ** SQL statement.
139659 */
139660 #ifndef SQLITE_OMIT_DEPRECATED
139661 SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
139662  void *pOld;
139663 
139664 #ifdef SQLITE_ENABLE_API_ARMOR
139665  if( !sqlite3SafetyCheckOk(db) ){
139666  (void)SQLITE_MISUSE_BKPT;
139667  return 0;
139668  }
139669 #endif
139670  sqlite3_mutex_enter(db->mutex);
139671  pOld = db->pTraceArg;
139672  db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
139673  db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
139674  db->pTraceArg = pArg;
139675  sqlite3_mutex_leave(db->mutex);
139676  return pOld;
139677 }
139678 #endif /* SQLITE_OMIT_DEPRECATED */
139679 
139680 /* Register a trace callback using the version-2 interface.
139681 */
139682 SQLITE_API int sqlite3_trace_v2(
139683  sqlite3 *db, /* Trace this connection */
139684  unsigned mTrace, /* Mask of events to be traced */
139685  int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
139686  void *pArg /* Context */
139687 ){
139688 #ifdef SQLITE_ENABLE_API_ARMOR
139689  if( !sqlite3SafetyCheckOk(db) ){
139690  return SQLITE_MISUSE_BKPT;
139691  }
139692 #endif
139693  sqlite3_mutex_enter(db->mutex);
139694  if( mTrace==0 ) xTrace = 0;
139695  if( xTrace==0 ) mTrace = 0;
139696  db->mTrace = mTrace;
139697  db->xTrace = xTrace;
139698  db->pTraceArg = pArg;
139699  sqlite3_mutex_leave(db->mutex);
139700  return SQLITE_OK;
139701 }
139702 
139703 #ifndef SQLITE_OMIT_DEPRECATED
139704 /*
139705 ** Register a profile function. The pArg from the previously registered
139706 ** profile function is returned.
139707 **
139708 ** A NULL profile function means that no profiling is executes. A non-NULL
139709 ** profile is a pointer to a function that is invoked at the conclusion of
139710 ** each SQL statement that is run.
139711 */
139712 SQLITE_API void *sqlite3_profile(
139713  sqlite3 *db,
139714  void (*xProfile)(void*,const char*,sqlite_uint64),
139715  void *pArg
139716 ){
139717  void *pOld;
139718 
139719 #ifdef SQLITE_ENABLE_API_ARMOR
139720  if( !sqlite3SafetyCheckOk(db) ){
139721  (void)SQLITE_MISUSE_BKPT;
139722  return 0;
139723  }
139724 #endif
139725  sqlite3_mutex_enter(db->mutex);
139726  pOld = db->pProfileArg;
139727  db->xProfile = xProfile;
139728  db->pProfileArg = pArg;
139729  sqlite3_mutex_leave(db->mutex);
139730  return pOld;
139731 }
139732 #endif /* SQLITE_OMIT_DEPRECATED */
139733 #endif /* SQLITE_OMIT_TRACE */
139734 
139735 /*
139736 ** Register a function to be invoked when a transaction commits.
139737 ** If the invoked function returns non-zero, then the commit becomes a
139738 ** rollback.
139739 */
139740 SQLITE_API void *sqlite3_commit_hook(
139741  sqlite3 *db, /* Attach the hook to this database */
139742  int (*xCallback)(void*), /* Function to invoke on each commit */
139743  void *pArg /* Argument to the function */
139744 ){
139745  void *pOld;
139746 
139747 #ifdef SQLITE_ENABLE_API_ARMOR
139748  if( !sqlite3SafetyCheckOk(db) ){
139749  (void)SQLITE_MISUSE_BKPT;
139750  return 0;
139751  }
139752 #endif
139753  sqlite3_mutex_enter(db->mutex);
139754  pOld = db->pCommitArg;
139755  db->xCommitCallback = xCallback;
139756  db->pCommitArg = pArg;
139757  sqlite3_mutex_leave(db->mutex);
139758  return pOld;
139759 }
139760 
139761 /*
139762 ** Register a callback to be invoked each time a row is updated,
139763 ** inserted or deleted using this database connection.
139764 */
139765 SQLITE_API void *sqlite3_update_hook(
139766  sqlite3 *db, /* Attach the hook to this database */
139767  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
139768  void *pArg /* Argument to the function */
139769 ){
139770  void *pRet;
139771 
139772 #ifdef SQLITE_ENABLE_API_ARMOR
139773  if( !sqlite3SafetyCheckOk(db) ){
139774  (void)SQLITE_MISUSE_BKPT;
139775  return 0;
139776  }
139777 #endif
139778  sqlite3_mutex_enter(db->mutex);
139779  pRet = db->pUpdateArg;
139780  db->xUpdateCallback = xCallback;
139781  db->pUpdateArg = pArg;
139782  sqlite3_mutex_leave(db->mutex);
139783  return pRet;
139784 }
139785 
139786 /*
139787 ** Register a callback to be invoked each time a transaction is rolled
139788 ** back by this database connection.
139789 */
139790 SQLITE_API void *sqlite3_rollback_hook(
139791  sqlite3 *db, /* Attach the hook to this database */
139792  void (*xCallback)(void*), /* Callback function */
139793  void *pArg /* Argument to the function */
139794 ){
139795  void *pRet;
139796 
139797 #ifdef SQLITE_ENABLE_API_ARMOR
139798  if( !sqlite3SafetyCheckOk(db) ){
139799  (void)SQLITE_MISUSE_BKPT;
139800  return 0;
139801  }
139802 #endif
139803  sqlite3_mutex_enter(db->mutex);
139804  pRet = db->pRollbackArg;
139805  db->xRollbackCallback = xCallback;
139806  db->pRollbackArg = pArg;
139807  sqlite3_mutex_leave(db->mutex);
139808  return pRet;
139809 }
139810 
139811 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
139812 /*
139813 ** Register a callback to be invoked each time a row is updated,
139814 ** inserted or deleted using this database connection.
139815 */
139816 SQLITE_API void *sqlite3_preupdate_hook(
139817  sqlite3 *db, /* Attach the hook to this database */
139818  void(*xCallback)( /* Callback function */
139819  void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
139820  void *pArg /* First callback argument */
139821 ){
139822  void *pRet;
139823  sqlite3_mutex_enter(db->mutex);
139824  pRet = db->pPreUpdateArg;
139825  db->xPreUpdateCallback = xCallback;
139826  db->pPreUpdateArg = pArg;
139827  sqlite3_mutex_leave(db->mutex);
139828  return pRet;
139829 }
139830 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
139831 
139832 #ifndef SQLITE_OMIT_WAL
139833 /*
139834 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
139835 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
139836 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
139837 ** wal_autocheckpoint()).
139838 */
139839 SQLITE_PRIVATE int sqlite3WalDefaultHook(
139840  void *pClientData, /* Argument */
139841  sqlite3 *db, /* Connection */
139842  const char *zDb, /* Database */
139843  int nFrame /* Size of WAL */
139844 ){
139845  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
139846  sqlite3BeginBenignMalloc();
139847  sqlite3_wal_checkpoint(db, zDb);
139848  sqlite3EndBenignMalloc();
139849  }
139850  return SQLITE_OK;
139851 }
139852 #endif /* SQLITE_OMIT_WAL */
139853 
139854 /*
139855 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
139856 ** a database after committing a transaction if there are nFrame or
139857 ** more frames in the log file. Passing zero or a negative value as the
139858 ** nFrame parameter disables automatic checkpoints entirely.
139859 **
139860 ** The callback registered by this function replaces any existing callback
139861 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
139862 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
139863 ** configured by this function.
139864 */
139865 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
139866 #ifdef SQLITE_OMIT_WAL
139867  UNUSED_PARAMETER(db);
139868  UNUSED_PARAMETER(nFrame);
139869 #else
139870 #ifdef SQLITE_ENABLE_API_ARMOR
139871  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139872 #endif
139873  if( nFrame>0 ){
139874  sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
139875  }else{
139876  sqlite3_wal_hook(db, 0, 0);
139877  }
139878 #endif
139879  return SQLITE_OK;
139880 }
139881 
139882 /*
139883 ** Register a callback to be invoked each time a transaction is written
139884 ** into the write-ahead-log by this database connection.
139885 */
139886 SQLITE_API void *sqlite3_wal_hook(
139887  sqlite3 *db, /* Attach the hook to this db handle */
139888  int(*xCallback)(void *, sqlite3*, const char*, int),
139889  void *pArg /* First argument passed to xCallback() */
139890 ){
139891 #ifndef SQLITE_OMIT_WAL
139892  void *pRet;
139893 #ifdef SQLITE_ENABLE_API_ARMOR
139894  if( !sqlite3SafetyCheckOk(db) ){
139895  (void)SQLITE_MISUSE_BKPT;
139896  return 0;
139897  }
139898 #endif
139899  sqlite3_mutex_enter(db->mutex);
139900  pRet = db->pWalArg;
139901  db->xWalCallback = xCallback;
139902  db->pWalArg = pArg;
139903  sqlite3_mutex_leave(db->mutex);
139904  return pRet;
139905 #else
139906  return 0;
139907 #endif
139908 }
139909 
139910 /*
139911 ** Checkpoint database zDb.
139912 */
139913 SQLITE_API int sqlite3_wal_checkpoint_v2(
139914  sqlite3 *db, /* Database handle */
139915  const char *zDb, /* Name of attached database (or NULL) */
139916  int eMode, /* SQLITE_CHECKPOINT_* value */
139917  int *pnLog, /* OUT: Size of WAL log in frames */
139918  int *pnCkpt /* OUT: Total number of frames checkpointed */
139919 ){
139920 #ifdef SQLITE_OMIT_WAL
139921  return SQLITE_OK;
139922 #else
139923  int rc; /* Return code */
139924  int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
139925 
139926 #ifdef SQLITE_ENABLE_API_ARMOR
139927  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139928 #endif
139929 
139930  /* Initialize the output variables to -1 in case an error occurs. */
139931  if( pnLog ) *pnLog = -1;
139932  if( pnCkpt ) *pnCkpt = -1;
139933 
139934  assert( SQLITE_CHECKPOINT_PASSIVE==0 );
139935  assert( SQLITE_CHECKPOINT_FULL==1 );
139936  assert( SQLITE_CHECKPOINT_RESTART==2 );
139937  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
139938  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
139939  /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
139940  ** mode: */
139941  return SQLITE_MISUSE;
139942  }
139943 
139944  sqlite3_mutex_enter(db->mutex);
139945  if( zDb && zDb[0] ){
139946  iDb = sqlite3FindDbName(db, zDb);
139947  }
139948  if( iDb<0 ){
139949  rc = SQLITE_ERROR;
139950  sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
139951  }else{
139952  db->busyHandler.nBusy = 0;
139953  rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
139954  sqlite3Error(db, rc);
139955  }
139956  rc = sqlite3ApiExit(db, rc);
139957  sqlite3_mutex_leave(db->mutex);
139958  return rc;
139959 #endif
139960 }
139961 
139962 
139963 /*
139964 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
139965 ** to contains a zero-length string, all attached databases are
139966 ** checkpointed.
139967 */
139968 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
139969  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
139970  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
139971  return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
139972 }
139973 
139974 #ifndef SQLITE_OMIT_WAL
139975 /*
139976 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
139977 ** not currently open in WAL mode.
139978 **
139979 ** If a transaction is open on the database being checkpointed, this
139980 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
139981 ** an error occurs while running the checkpoint, an SQLite error code is
139982 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
139983 **
139984 ** The mutex on database handle db should be held by the caller. The mutex
139985 ** associated with the specific b-tree being checkpointed is taken by
139986 ** this function while the checkpoint is running.
139987 **
139988 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
139989 ** checkpointed. If an error is encountered it is returned immediately -
139990 ** no attempt is made to checkpoint any remaining databases.
139991 **
139992 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
139993 */
139994 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
139995  int rc = SQLITE_OK; /* Return code */
139996  int i; /* Used to iterate through attached dbs */
139997  int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
139998 
139999  assert( sqlite3_mutex_held(db->mutex) );
140000  assert( !pnLog || *pnLog==-1 );
140001  assert( !pnCkpt || *pnCkpt==-1 );
140002 
140003  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
140004  if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
140005  rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
140006  pnLog = 0;
140007  pnCkpt = 0;
140008  if( rc==SQLITE_BUSY ){
140009  bBusy = 1;
140010  rc = SQLITE_OK;
140011  }
140012  }
140013  }
140014 
140015  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
140016 }
140017 #endif /* SQLITE_OMIT_WAL */
140018 
140019 /*
140020 ** This function returns true if main-memory should be used instead of
140021 ** a temporary file for transient pager files and statement journals.
140022 ** The value returned depends on the value of db->temp_store (runtime
140023 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
140024 ** following table describes the relationship between these two values
140025 ** and this functions return value.
140026 **
140027 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
140028 ** ----------------- -------------- ------------------------------
140029 ** 0 any file (return 0)
140030 ** 1 1 file (return 0)
140031 ** 1 2 memory (return 1)
140032 ** 1 0 file (return 0)
140033 ** 2 1 file (return 0)
140034 ** 2 2 memory (return 1)
140035 ** 2 0 memory (return 1)
140036 ** 3 any memory (return 1)
140037 */
140038 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
140039 #if SQLITE_TEMP_STORE==1
140040  return ( db->temp_store==2 );
140041 #endif
140042 #if SQLITE_TEMP_STORE==2
140043  return ( db->temp_store!=1 );
140044 #endif
140045 #if SQLITE_TEMP_STORE==3
140046  UNUSED_PARAMETER(db);
140047  return 1;
140048 #endif
140049 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
140050  UNUSED_PARAMETER(db);
140051  return 0;
140052 #endif
140053 }
140054 
140055 /*
140056 ** Return UTF-8 encoded English language explanation of the most recent
140057 ** error.
140058 */
140059 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
140060  const char *z;
140061  if( !db ){
140062  return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
140063  }
140064  if( !sqlite3SafetyCheckSickOrOk(db) ){
140065  return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
140066  }
140067  sqlite3_mutex_enter(db->mutex);
140068  if( db->mallocFailed ){
140069  z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
140070  }else{
140071  testcase( db->pErr==0 );
140072  z = (char*)sqlite3_value_text(db->pErr);
140073  assert( !db->mallocFailed );
140074  if( z==0 ){
140075  z = sqlite3ErrStr(db->errCode);
140076  }
140077  }
140078  sqlite3_mutex_leave(db->mutex);
140079  return z;
140080 }
140081 
140082 #ifndef SQLITE_OMIT_UTF16
140083 /*
140084 ** Return UTF-16 encoded English language explanation of the most recent
140085 ** error.
140086 */
140087 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
140088  static const u16 outOfMem[] = {
140089  'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
140090  };
140091  static const u16 misuse[] = {
140092  'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
140093  'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
140094  'c', 'a', 'l', 'l', 'e', 'd', ' ',
140095  'o', 'u', 't', ' ',
140096  'o', 'f', ' ',
140097  's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
140098  };
140099 
140100  const void *z;
140101  if( !db ){
140102  return (void *)outOfMem;
140103  }
140104  if( !sqlite3SafetyCheckSickOrOk(db) ){
140105  return (void *)misuse;
140106  }
140107  sqlite3_mutex_enter(db->mutex);
140108  if( db->mallocFailed ){
140109  z = (void *)outOfMem;
140110  }else{
140111  z = sqlite3_value_text16(db->pErr);
140112  if( z==0 ){
140113  sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
140114  z = sqlite3_value_text16(db->pErr);
140115  }
140116  /* A malloc() may have failed within the call to sqlite3_value_text16()
140117  ** above. If this is the case, then the db->mallocFailed flag needs to
140118  ** be cleared before returning. Do this directly, instead of via
140119  ** sqlite3ApiExit(), to avoid setting the database handle error message.
140120  */
140121  sqlite3OomClear(db);
140122  }
140123  sqlite3_mutex_leave(db->mutex);
140124  return z;
140125 }
140126 #endif /* SQLITE_OMIT_UTF16 */
140127 
140128 /*
140129 ** Return the most recent error code generated by an SQLite routine. If NULL is
140130 ** passed to this function, we assume a malloc() failed during sqlite3_open().
140131 */
140132 SQLITE_API int sqlite3_errcode(sqlite3 *db){
140133  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
140134  return SQLITE_MISUSE_BKPT;
140135  }
140136  if( !db || db->mallocFailed ){
140137  return SQLITE_NOMEM_BKPT;
140138  }
140139  return db->errCode & db->errMask;
140140 }
140141 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
140142  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
140143  return SQLITE_MISUSE_BKPT;
140144  }
140145  if( !db || db->mallocFailed ){
140146  return SQLITE_NOMEM_BKPT;
140147  }
140148  return db->errCode;
140149 }
140150 SQLITE_API int sqlite3_system_errno(sqlite3 *db){
140151  return db ? db->iSysErrno : 0;
140152 }
140153 
140154 /*
140155 ** Return a string that describes the kind of error specified in the
140156 ** argument. For now, this simply calls the internal sqlite3ErrStr()
140157 ** function.
140158 */
140159 SQLITE_API const char *sqlite3_errstr(int rc){
140160  return sqlite3ErrStr(rc);
140161 }
140162 
140163 /*
140164 ** Create a new collating function for database "db". The name is zName
140165 ** and the encoding is enc.
140166 */
140167 static int createCollation(
140168  sqlite3* db,
140169  const char *zName,
140170  u8 enc,
140171  void* pCtx,
140172  int(*xCompare)(void*,int,const void*,int,const void*),
140173  void(*xDel)(void*)
140174 ){
140175  CollSeq *pColl;
140176  int enc2;
140177 
140178  assert( sqlite3_mutex_held(db->mutex) );
140179 
140180  /* If SQLITE_UTF16 is specified as the encoding type, transform this
140181  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
140182  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
140183  */
140184  enc2 = enc;
140185  testcase( enc2==SQLITE_UTF16 );
140186  testcase( enc2==SQLITE_UTF16_ALIGNED );
140187  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
140188  enc2 = SQLITE_UTF16NATIVE;
140189  }
140190  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
140191  return SQLITE_MISUSE_BKPT;
140192  }
140193 
140194  /* Check if this call is removing or replacing an existing collation
140195  ** sequence. If so, and there are active VMs, return busy. If there
140196  ** are no active VMs, invalidate any pre-compiled statements.
140197  */
140198  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
140199  if( pColl && pColl->xCmp ){
140200  if( db->nVdbeActive ){
140201  sqlite3ErrorWithMsg(db, SQLITE_BUSY,
140202  "unable to delete/modify collation sequence due to active statements");
140203  return SQLITE_BUSY;
140204  }
140205  sqlite3ExpirePreparedStatements(db);
140206 
140207  /* If collation sequence pColl was created directly by a call to
140208  ** sqlite3_create_collation, and not generated by synthCollSeq(),
140209  ** then any copies made by synthCollSeq() need to be invalidated.
140210  ** Also, collation destructor - CollSeq.xDel() - function may need
140211  ** to be called.
140212  */
140213  if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
140214  CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
140215  int j;
140216  for(j=0; j<3; j++){
140217  CollSeq *p = &aColl[j];
140218  if( p->enc==pColl->enc ){
140219  if( p->xDel ){
140220  p->xDel(p->pUser);
140221  }
140222  p->xCmp = 0;
140223  }
140224  }
140225  }
140226  }
140227 
140228  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
140229  if( pColl==0 ) return SQLITE_NOMEM_BKPT;
140230  pColl->xCmp = xCompare;
140231  pColl->pUser = pCtx;
140232  pColl->xDel = xDel;
140233  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
140234  sqlite3Error(db, SQLITE_OK);
140235  return SQLITE_OK;
140236 }
140237 
140238 
140239 /*
140240 ** This array defines hard upper bounds on limit values. The
140241 ** initializer must be kept in sync with the SQLITE_LIMIT_*
140242 ** #defines in sqlite3.h.
140243 */
140244 static const int aHardLimit[] = {
140245  SQLITE_MAX_LENGTH,
140246  SQLITE_MAX_SQL_LENGTH,
140247  SQLITE_MAX_COLUMN,
140248  SQLITE_MAX_EXPR_DEPTH,
140249  SQLITE_MAX_COMPOUND_SELECT,
140250  SQLITE_MAX_VDBE_OP,
140251  SQLITE_MAX_FUNCTION_ARG,
140252  SQLITE_MAX_ATTACHED,
140253  SQLITE_MAX_LIKE_PATTERN_LENGTH,
140254  SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
140255  SQLITE_MAX_TRIGGER_DEPTH,
140256  SQLITE_MAX_WORKER_THREADS,
140257 };
140258 
140259 /*
140260 ** Make sure the hard limits are set to reasonable values
140261 */
140262 #if SQLITE_MAX_LENGTH<100
140263 # error SQLITE_MAX_LENGTH must be at least 100
140264 #endif
140265 #if SQLITE_MAX_SQL_LENGTH<100
140266 # error SQLITE_MAX_SQL_LENGTH must be at least 100
140267 #endif
140268 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
140269 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
140270 #endif
140271 #if SQLITE_MAX_COMPOUND_SELECT<2
140272 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
140273 #endif
140274 #if SQLITE_MAX_VDBE_OP<40
140275 # error SQLITE_MAX_VDBE_OP must be at least 40
140276 #endif
140277 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
140278 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
140279 #endif
140280 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
140281 # error SQLITE_MAX_ATTACHED must be between 0 and 125
140282 #endif
140283 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
140284 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
140285 #endif
140286 #if SQLITE_MAX_COLUMN>32767
140287 # error SQLITE_MAX_COLUMN must not exceed 32767
140288 #endif
140289 #if SQLITE_MAX_TRIGGER_DEPTH<1
140290 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
140291 #endif
140292 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
140293 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
140294 #endif
140295 
140296 
140297 /*
140298 ** Change the value of a limit. Report the old value.
140299 ** If an invalid limit index is supplied, report -1.
140300 ** Make no changes but still report the old value if the
140301 ** new limit is negative.
140302 **
140303 ** A new lower limit does not shrink existing constructs.
140304 ** It merely prevents new constructs that exceed the limit
140305 ** from forming.
140306 */
140307 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
140308  int oldLimit;
140309 
140310 #ifdef SQLITE_ENABLE_API_ARMOR
140311  if( !sqlite3SafetyCheckOk(db) ){
140312  (void)SQLITE_MISUSE_BKPT;
140313  return -1;
140314  }
140315 #endif
140316 
140317  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
140318  ** there is a hard upper bound set at compile-time by a C preprocessor
140319  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
140320  ** "_MAX_".)
140321  */
140322  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
140323  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
140324  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
140325  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
140326  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
140327  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
140328  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
140329  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
140330  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
140331  SQLITE_MAX_LIKE_PATTERN_LENGTH );
140332  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
140333  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
140334  assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
140335  assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
140336 
140337 
140338  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
140339  return -1;
140340  }
140341  oldLimit = db->aLimit[limitId];
140342  if( newLimit>=0 ){ /* IMP: R-52476-28732 */
140343  if( newLimit>aHardLimit[limitId] ){
140344  newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
140345  }
140346  db->aLimit[limitId] = newLimit;
140347  }
140348  return oldLimit; /* IMP: R-53341-35419 */
140349 }
140350 
140351 /*
140352 ** This function is used to parse both URIs and non-URI filenames passed by the
140353 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
140354 ** URIs specified as part of ATTACH statements.
140355 **
140356 ** The first argument to this function is the name of the VFS to use (or
140357 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
140358 ** query parameter. The second argument contains the URI (or non-URI filename)
140359 ** itself. When this function is called the *pFlags variable should contain
140360 ** the default flags to open the database handle with. The value stored in
140361 ** *pFlags may be updated before returning if the URI filename contains
140362 ** "cache=xxx" or "mode=xxx" query parameters.
140363 **
140364 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
140365 ** the VFS that should be used to open the database file. *pzFile is set to
140366 ** point to a buffer containing the name of the file to open. It is the
140367 ** responsibility of the caller to eventually call sqlite3_free() to release
140368 ** this buffer.
140369 **
140370 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
140371 ** may be set to point to a buffer containing an English language error
140372 ** message. It is the responsibility of the caller to eventually release
140373 ** this buffer by calling sqlite3_free().
140374 */
140375 SQLITE_PRIVATE int sqlite3ParseUri(
140376  const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
140377  const char *zUri, /* Nul-terminated URI to parse */
140378  unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
140379  sqlite3_vfs **ppVfs, /* OUT: VFS to use */
140380  char **pzFile, /* OUT: Filename component of URI */
140381  char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
140382 ){
140383  int rc = SQLITE_OK;
140384  unsigned int flags = *pFlags;
140385  const char *zVfs = zDefaultVfs;
140386  char *zFile;
140387  char c;
140388  int nUri = sqlite3Strlen30(zUri);
140389 
140390  assert( *pzErrMsg==0 );
140391 
140392  if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
140393  || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
140394  && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
140395  ){
140396  char *zOpt;
140397  int eState; /* Parser state when parsing URI */
140398  int iIn; /* Input character index */
140399  int iOut = 0; /* Output character index */
140400  u64 nByte = nUri+2; /* Bytes of space to allocate */
140401 
140402  /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
140403  ** method that there may be extra parameters following the file-name. */
140404  flags |= SQLITE_OPEN_URI;
140405 
140406  for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
140407  zFile = sqlite3_malloc64(nByte);
140408  if( !zFile ) return SQLITE_NOMEM_BKPT;
140409 
140410  iIn = 5;
140411 #ifdef SQLITE_ALLOW_URI_AUTHORITY
140412  if( strncmp(zUri+5, "///", 3)==0 ){
140413  iIn = 7;
140414  /* The following condition causes URIs with five leading / characters
140415  ** like file://///host/path to be converted into UNCs like //host/path.
140416  ** The correct URI for that UNC has only two or four leading / characters
140417  ** file://host/path or file:////host/path. But 5 leading slashes is a
140418  ** common error, we are told, so we handle it as a special case. */
140419  if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
140420  }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
140421  iIn = 16;
140422  }
140423 #else
140424  /* Discard the scheme and authority segments of the URI. */
140425  if( zUri[5]=='/' && zUri[6]=='/' ){
140426  iIn = 7;
140427  while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
140428  if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
140429  *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
140430  iIn-7, &zUri[7]);
140431  rc = SQLITE_ERROR;
140432  goto parse_uri_out;
140433  }
140434  }
140435 #endif
140436 
140437  /* Copy the filename and any query parameters into the zFile buffer.
140438  ** Decode %HH escape codes along the way.
140439  **
140440  ** Within this loop, variable eState may be set to 0, 1 or 2, depending
140441  ** on the parsing context. As follows:
140442  **
140443  ** 0: Parsing file-name.
140444  ** 1: Parsing name section of a name=value query parameter.
140445  ** 2: Parsing value section of a name=value query parameter.
140446  */
140447  eState = 0;
140448  while( (c = zUri[iIn])!=0 && c!='#' ){
140449  iIn++;
140450  if( c=='%'
140451  && sqlite3Isxdigit(zUri[iIn])
140452  && sqlite3Isxdigit(zUri[iIn+1])
140453  ){
140454  int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
140455  octet += sqlite3HexToInt(zUri[iIn++]);
140456 
140457  assert( octet>=0 && octet<256 );
140458  if( octet==0 ){
140459  /* This branch is taken when "%00" appears within the URI. In this
140460  ** case we ignore all text in the remainder of the path, name or
140461  ** value currently being parsed. So ignore the current character
140462  ** and skip to the next "?", "=" or "&", as appropriate. */
140463  while( (c = zUri[iIn])!=0 && c!='#'
140464  && (eState!=0 || c!='?')
140465  && (eState!=1 || (c!='=' && c!='&'))
140466  && (eState!=2 || c!='&')
140467  ){
140468  iIn++;
140469  }
140470  continue;
140471  }
140472  c = octet;
140473  }else if( eState==1 && (c=='&' || c=='=') ){
140474  if( zFile[iOut-1]==0 ){
140475  /* An empty option name. Ignore this option altogether. */
140476  while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
140477  continue;
140478  }
140479  if( c=='&' ){
140480  zFile[iOut++] = '\0';
140481  }else{
140482  eState = 2;
140483  }
140484  c = 0;
140485  }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
140486  c = 0;
140487  eState = 1;
140488  }
140489  zFile[iOut++] = c;
140490  }
140491  if( eState==1 ) zFile[iOut++] = '\0';
140492  zFile[iOut++] = '\0';
140493  zFile[iOut++] = '\0';
140494 
140495  /* Check if there were any options specified that should be interpreted
140496  ** here. Options that are interpreted here include "vfs" and those that
140497  ** correspond to flags that may be passed to the sqlite3_open_v2()
140498  ** method. */
140499  zOpt = &zFile[sqlite3Strlen30(zFile)+1];
140500  while( zOpt[0] ){
140501  int nOpt = sqlite3Strlen30(zOpt);
140502  char *zVal = &zOpt[nOpt+1];
140503  int nVal = sqlite3Strlen30(zVal);
140504 
140505  if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
140506  zVfs = zVal;
140507  }else{
140508  struct OpenMode {
140509  const char *z;
140510  int mode;
140511  } *aMode = 0;
140512  char *zModeType = 0;
140513  int mask = 0;
140514  int limit = 0;
140515 
140516  if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
140517  static struct OpenMode aCacheMode[] = {
140518  { "shared", SQLITE_OPEN_SHAREDCACHE },
140519  { "private", SQLITE_OPEN_PRIVATECACHE },
140520  { 0, 0 }
140521  };
140522 
140523  mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
140524  aMode = aCacheMode;
140525  limit = mask;
140526  zModeType = "cache";
140527  }
140528  if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
140529  static struct OpenMode aOpenMode[] = {
140530  { "ro", SQLITE_OPEN_READONLY },
140531  { "rw", SQLITE_OPEN_READWRITE },
140532  { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
140533  { "memory", SQLITE_OPEN_MEMORY },
140534  { 0, 0 }
140535  };
140536 
140537  mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
140538  | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
140539  aMode = aOpenMode;
140540  limit = mask & flags;
140541  zModeType = "access";
140542  }
140543 
140544  if( aMode ){
140545  int i;
140546  int mode = 0;
140547  for(i=0; aMode[i].z; i++){
140548  const char *z = aMode[i].z;
140549  if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
140550  mode = aMode[i].mode;
140551  break;
140552  }
140553  }
140554  if( mode==0 ){
140555  *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
140556  rc = SQLITE_ERROR;
140557  goto parse_uri_out;
140558  }
140559  if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
140560  *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
140561  zModeType, zVal);
140562  rc = SQLITE_PERM;
140563  goto parse_uri_out;
140564  }
140565  flags = (flags & ~mask) | mode;
140566  }
140567  }
140568 
140569  zOpt = &zVal[nVal+1];
140570  }
140571 
140572  }else{
140573  zFile = sqlite3_malloc64(nUri+2);
140574  if( !zFile ) return SQLITE_NOMEM_BKPT;
140575  memcpy(zFile, zUri, nUri);
140576  zFile[nUri] = '\0';
140577  zFile[nUri+1] = '\0';
140578  flags &= ~SQLITE_OPEN_URI;
140579  }
140580 
140581  *ppVfs = sqlite3_vfs_find(zVfs);
140582  if( *ppVfs==0 ){
140583  *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
140584  rc = SQLITE_ERROR;
140585  }
140586  parse_uri_out:
140587  if( rc!=SQLITE_OK ){
140588  sqlite3_free(zFile);
140589  zFile = 0;
140590  }
140591  *pFlags = flags;
140592  *pzFile = zFile;
140593  return rc;
140594 }
140595 
140596 
140597 /*
140598 ** This routine does the work of opening a database on behalf of
140599 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
140600 ** is UTF-8 encoded.
140601 */
140602 static int openDatabase(
140603  const char *zFilename, /* Database filename UTF-8 encoded */
140604  sqlite3 **ppDb, /* OUT: Returned database handle */
140605  unsigned int flags, /* Operational flags */
140606  const char *zVfs /* Name of the VFS to use */
140607 ){
140608  sqlite3 *db; /* Store allocated handle here */
140609  int rc; /* Return code */
140610  int isThreadsafe; /* True for threadsafe connections */
140611  char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
140612  char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
140613 
140614 #ifdef SQLITE_ENABLE_API_ARMOR
140615  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
140616 #endif
140617  *ppDb = 0;
140618 #ifndef SQLITE_OMIT_AUTOINIT
140619  rc = sqlite3_initialize();
140620  if( rc ) return rc;
140621 #endif
140622 
140623  /* Only allow sensible combinations of bits in the flags argument.
140624  ** Throw an error if any non-sense combination is used. If we
140625  ** do not block illegal combinations here, it could trigger
140626  ** assert() statements in deeper layers. Sensible combinations
140627  ** are:
140628  **
140629  ** 1: SQLITE_OPEN_READONLY
140630  ** 2: SQLITE_OPEN_READWRITE
140631  ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
140632  */
140633  assert( SQLITE_OPEN_READONLY == 0x01 );
140634  assert( SQLITE_OPEN_READWRITE == 0x02 );
140635  assert( SQLITE_OPEN_CREATE == 0x04 );
140636  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
140637  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
140638  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
140639  if( ((1<<(flags&7)) & 0x46)==0 ){
140640  return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
140641  }
140642 
140643  if( sqlite3GlobalConfig.bCoreMutex==0 ){
140644  isThreadsafe = 0;
140645  }else if( flags & SQLITE_OPEN_NOMUTEX ){
140646  isThreadsafe = 0;
140647  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
140648  isThreadsafe = 1;
140649  }else{
140650  isThreadsafe = sqlite3GlobalConfig.bFullMutex;
140651  }
140652  if( flags & SQLITE_OPEN_PRIVATECACHE ){
140653  flags &= ~SQLITE_OPEN_SHAREDCACHE;
140654  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
140655  flags |= SQLITE_OPEN_SHAREDCACHE;
140656  }
140657 
140658  /* Remove harmful bits from the flags parameter
140659  **
140660  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
140661  ** dealt with in the previous code block. Besides these, the only
140662  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
140663  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
140664  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
140665  ** off all other flags.
140666  */
140667  flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
140668  SQLITE_OPEN_EXCLUSIVE |
140669  SQLITE_OPEN_MAIN_DB |
140670  SQLITE_OPEN_TEMP_DB |
140671  SQLITE_OPEN_TRANSIENT_DB |
140672  SQLITE_OPEN_MAIN_JOURNAL |
140673  SQLITE_OPEN_TEMP_JOURNAL |
140674  SQLITE_OPEN_SUBJOURNAL |
140675  SQLITE_OPEN_MASTER_JOURNAL |
140676  SQLITE_OPEN_NOMUTEX |
140677  SQLITE_OPEN_FULLMUTEX |
140678  SQLITE_OPEN_WAL
140679  );
140680 
140681  /* Allocate the sqlite data structure */
140682  db = sqlite3MallocZero( sizeof(sqlite3) );
140683  if( db==0 ) goto opendb_out;
140684  if( isThreadsafe ){
140685  db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
140686  if( db->mutex==0 ){
140687  sqlite3_free(db);
140688  db = 0;
140689  goto opendb_out;
140690  }
140691  }
140692  sqlite3_mutex_enter(db->mutex);
140693  db->errMask = 0xff;
140694  db->nDb = 2;
140695  db->magic = SQLITE_MAGIC_BUSY;
140696  db->aDb = db->aDbStatic;
140697 
140698  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
140699  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
140700  db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
140701  db->autoCommit = 1;
140702  db->nextAutovac = -1;
140703  db->szMmap = sqlite3GlobalConfig.szMmap;
140704  db->nextPagesize = 0;
140705  db->nMaxSorterMmap = 0x7FFFFFFF;
140706  db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
140707 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
140708  | SQLITE_AutoIndex
140709 #endif
140710 #if SQLITE_DEFAULT_CKPTFULLFSYNC
140711  | SQLITE_CkptFullFSync
140712 #endif
140713 #if SQLITE_DEFAULT_FILE_FORMAT<4
140714  | SQLITE_LegacyFileFmt
140715 #endif
140716 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
140717  | SQLITE_LoadExtension
140718 #endif
140719 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
140720  | SQLITE_RecTriggers
140721 #endif
140722 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
140723  | SQLITE_ForeignKeys
140724 #endif
140725 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
140726  | SQLITE_ReverseOrder
140727 #endif
140728 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
140729  | SQLITE_CellSizeCk
140730 #endif
140731 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
140732  | SQLITE_Fts3Tokenizer
140733 #endif
140734  ;
140735  sqlite3HashInit(&db->aCollSeq);
140736 #ifndef SQLITE_OMIT_VIRTUALTABLE
140737  sqlite3HashInit(&db->aModule);
140738 #endif
140739 
140740  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
140741  ** and UTF-16, so add a version for each to avoid any unnecessary
140742  ** conversions. The only error that can occur here is a malloc() failure.
140743  **
140744  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
140745  ** functions:
140746  */
140747  createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
140748  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
140749  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
140750  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
140751  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
140752  if( db->mallocFailed ){
140753  goto opendb_out;
140754  }
140755  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
140756  ** strings is BINARY.
140757  */
140758  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
140759  assert( db->pDfltColl!=0 );
140760 
140761  /* Parse the filename/URI argument. */
140762  db->openFlags = flags;
140763  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
140764  if( rc!=SQLITE_OK ){
140765  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
140766  sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
140767  sqlite3_free(zErrMsg);
140768  goto opendb_out;
140769  }
140770 
140771  /* Open the backend database driver */
140772  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
140773  flags | SQLITE_OPEN_MAIN_DB);
140774  if( rc!=SQLITE_OK ){
140775  if( rc==SQLITE_IOERR_NOMEM ){
140776  rc = SQLITE_NOMEM_BKPT;
140777  }
140778  sqlite3Error(db, rc);
140779  goto opendb_out;
140780  }
140781  sqlite3BtreeEnter(db->aDb[0].pBt);
140782  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
140783  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
140784  sqlite3BtreeLeave(db->aDb[0].pBt);
140785  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
140786 
140787  /* The default safety_level for the main database is FULL; for the temp
140788  ** database it is OFF. This matches the pager layer defaults.
140789  */
140790  db->aDb[0].zDbSName = "main";
140791  db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
140792  db->aDb[1].zDbSName = "temp";
140793  db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
140794 
140795  db->magic = SQLITE_MAGIC_OPEN;
140796  if( db->mallocFailed ){
140797  goto opendb_out;
140798  }
140799 
140800  /* Register all built-in functions, but do not attempt to read the
140801  ** database schema yet. This is delayed until the first time the database
140802  ** is accessed.
140803  */
140804  sqlite3Error(db, SQLITE_OK);
140805  sqlite3RegisterPerConnectionBuiltinFunctions(db);
140806  rc = sqlite3_errcode(db);
140807 
140808 #ifdef SQLITE_ENABLE_FTS5
140809  /* Register any built-in FTS5 module before loading the automatic
140810  ** extensions. This allows automatic extensions to register FTS5
140811  ** tokenizers and auxiliary functions. */
140812  if( !db->mallocFailed && rc==SQLITE_OK ){
140813  rc = sqlite3Fts5Init(db);
140814  }
140815 #endif
140816 
140817  /* Load automatic extensions - extensions that have been registered
140818  ** using the sqlite3_automatic_extension() API.
140819  */
140820  if( rc==SQLITE_OK ){
140821  sqlite3AutoLoadExtensions(db);
140822  rc = sqlite3_errcode(db);
140823  if( rc!=SQLITE_OK ){
140824  goto opendb_out;
140825  }
140826  }
140827 
140828 #ifdef SQLITE_ENABLE_FTS1
140829  if( !db->mallocFailed ){
140830  extern int sqlite3Fts1Init(sqlite3*);
140831  rc = sqlite3Fts1Init(db);
140832  }
140833 #endif
140834 
140835 #ifdef SQLITE_ENABLE_FTS2
140836  if( !db->mallocFailed && rc==SQLITE_OK ){
140837  extern int sqlite3Fts2Init(sqlite3*);
140838  rc = sqlite3Fts2Init(db);
140839  }
140840 #endif
140841 
140842 #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
140843  if( !db->mallocFailed && rc==SQLITE_OK ){
140844  rc = sqlite3Fts3Init(db);
140845  }
140846 #endif
140847 
140848 #ifdef SQLITE_ENABLE_ICU
140849  if( !db->mallocFailed && rc==SQLITE_OK ){
140850  rc = sqlite3IcuInit(db);
140851  }
140852 #endif
140853 
140854 #ifdef SQLITE_ENABLE_RTREE
140855  if( !db->mallocFailed && rc==SQLITE_OK){
140856  rc = sqlite3RtreeInit(db);
140857  }
140858 #endif
140859 
140860 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
140861  if( !db->mallocFailed && rc==SQLITE_OK){
140862  rc = sqlite3DbstatRegister(db);
140863  }
140864 #endif
140865 
140866 #ifdef SQLITE_ENABLE_JSON1
140867  if( !db->mallocFailed && rc==SQLITE_OK){
140868  rc = sqlite3Json1Init(db);
140869  }
140870 #endif
140871 
140872  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
140873  ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
140874  ** mode. Doing nothing at all also makes NORMAL the default.
140875  */
140876 #ifdef SQLITE_DEFAULT_LOCKING_MODE
140877  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
140878  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
140879  SQLITE_DEFAULT_LOCKING_MODE);
140880 #endif
140881 
140882  if( rc ) sqlite3Error(db, rc);
140883 
140884  /* Enable the lookaside-malloc subsystem */
140885  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
140886  sqlite3GlobalConfig.nLookaside);
140887 
140888  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
140889 
140890 opendb_out:
140891  if( db ){
140892  assert( db->mutex!=0 || isThreadsafe==0
140893  || sqlite3GlobalConfig.bFullMutex==0 );
140894  sqlite3_mutex_leave(db->mutex);
140895  }
140896  rc = sqlite3_errcode(db);
140897  assert( db!=0 || rc==SQLITE_NOMEM );
140898  if( rc==SQLITE_NOMEM ){
140899  sqlite3_close(db);
140900  db = 0;
140901  }else if( rc!=SQLITE_OK ){
140902  db->magic = SQLITE_MAGIC_SICK;
140903  }
140904  *ppDb = db;
140905 #ifdef SQLITE_ENABLE_SQLLOG
140906  if( sqlite3GlobalConfig.xSqllog ){
140907  /* Opening a db handle. Fourth parameter is passed 0. */
140908  void *pArg = sqlite3GlobalConfig.pSqllogArg;
140909  sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
140910  }
140911 #endif
140912 #if defined(SQLITE_HAS_CODEC)
140913  if( rc==SQLITE_OK ){
140914  const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
140915  if( zHexKey && zHexKey[0] ){
140916  u8 iByte;
140917  int i;
140918  char zKey[40];
140919  for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
140920  iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
140921  if( (i&1)!=0 ) zKey[i/2] = iByte;
140922  }
140923  sqlite3_key_v2(db, 0, zKey, i/2);
140924  }
140925  }
140926 #endif
140927  sqlite3_free(zOpen);
140928  return rc & 0xff;
140929 }
140930 
140931 /*
140932 ** Open a new database handle.
140933 */
140934 SQLITE_API int sqlite3_open(
140935  const char *zFilename,
140936  sqlite3 **ppDb
140937 ){
140938  return openDatabase(zFilename, ppDb,
140939  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
140940 }
140941 SQLITE_API int sqlite3_open_v2(
140942  const char *filename, /* Database filename (UTF-8) */
140943  sqlite3 **ppDb, /* OUT: SQLite db handle */
140944  int flags, /* Flags */
140945  const char *zVfs /* Name of VFS module to use */
140946 ){
140947  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
140948 }
140949 
140950 #ifndef SQLITE_OMIT_UTF16
140951 /*
140952 ** Open a new database handle.
140953 */
140954 SQLITE_API int sqlite3_open16(
140955  const void *zFilename,
140956  sqlite3 **ppDb
140957 ){
140958  char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
140959  sqlite3_value *pVal;
140960  int rc;
140961 
140962 #ifdef SQLITE_ENABLE_API_ARMOR
140963  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
140964 #endif
140965  *ppDb = 0;
140966 #ifndef SQLITE_OMIT_AUTOINIT
140967  rc = sqlite3_initialize();
140968  if( rc ) return rc;
140969 #endif
140970  if( zFilename==0 ) zFilename = "\000\000";
140971  pVal = sqlite3ValueNew(0);
140972  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
140973  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
140974  if( zFilename8 ){
140975  rc = openDatabase(zFilename8, ppDb,
140976  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
140977  assert( *ppDb || rc==SQLITE_NOMEM );
140978  if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
140979  SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
140980  }
140981  }else{
140982  rc = SQLITE_NOMEM_BKPT;
140983  }
140984  sqlite3ValueFree(pVal);
140985 
140986  return rc & 0xff;
140987 }
140988 #endif /* SQLITE_OMIT_UTF16 */
140989 
140990 /*
140991 ** Register a new collation sequence with the database handle db.
140992 */
140993 SQLITE_API int sqlite3_create_collation(
140994  sqlite3* db,
140995  const char *zName,
140996  int enc,
140997  void* pCtx,
140998  int(*xCompare)(void*,int,const void*,int,const void*)
140999 ){
141000  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
141001 }
141002 
141003 /*
141004 ** Register a new collation sequence with the database handle db.
141005 */
141006 SQLITE_API int sqlite3_create_collation_v2(
141007  sqlite3* db,
141008  const char *zName,
141009  int enc,
141010  void* pCtx,
141011  int(*xCompare)(void*,int,const void*,int,const void*),
141012  void(*xDel)(void*)
141013 ){
141014  int rc;
141015 
141016 #ifdef SQLITE_ENABLE_API_ARMOR
141017  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
141018 #endif
141019  sqlite3_mutex_enter(db->mutex);
141020  assert( !db->mallocFailed );
141021  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
141022  rc = sqlite3ApiExit(db, rc);
141023  sqlite3_mutex_leave(db->mutex);
141024  return rc;
141025 }
141026 
141027 #ifndef SQLITE_OMIT_UTF16
141028 /*
141029 ** Register a new collation sequence with the database handle db.
141030 */
141031 SQLITE_API int sqlite3_create_collation16(
141032  sqlite3* db,
141033  const void *zName,
141034  int enc,
141035  void* pCtx,
141036  int(*xCompare)(void*,int,const void*,int,const void*)
141037 ){
141038  int rc = SQLITE_OK;
141039  char *zName8;
141040 
141041 #ifdef SQLITE_ENABLE_API_ARMOR
141042  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
141043 #endif
141044  sqlite3_mutex_enter(db->mutex);
141045  assert( !db->mallocFailed );
141046  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
141047  if( zName8 ){
141048  rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
141049  sqlite3DbFree(db, zName8);
141050  }
141051  rc = sqlite3ApiExit(db, rc);
141052  sqlite3_mutex_leave(db->mutex);
141053  return rc;
141054 }
141055 #endif /* SQLITE_OMIT_UTF16 */
141056 
141057 /*
141058 ** Register a collation sequence factory callback with the database handle
141059 ** db. Replace any previously installed collation sequence factory.
141060 */
141061 SQLITE_API int sqlite3_collation_needed(
141062  sqlite3 *db,
141063  void *pCollNeededArg,
141064  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
141065 ){
141066 #ifdef SQLITE_ENABLE_API_ARMOR
141067  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141068 #endif
141069  sqlite3_mutex_enter(db->mutex);
141070  db->xCollNeeded = xCollNeeded;
141071  db->xCollNeeded16 = 0;
141072  db->pCollNeededArg = pCollNeededArg;
141073  sqlite3_mutex_leave(db->mutex);
141074  return SQLITE_OK;
141075 }
141076 
141077 #ifndef SQLITE_OMIT_UTF16
141078 /*
141079 ** Register a collation sequence factory callback with the database handle
141080 ** db. Replace any previously installed collation sequence factory.
141081 */
141082 SQLITE_API int sqlite3_collation_needed16(
141083  sqlite3 *db,
141084  void *pCollNeededArg,
141085  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
141086 ){
141087 #ifdef SQLITE_ENABLE_API_ARMOR
141088  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141089 #endif
141090  sqlite3_mutex_enter(db->mutex);
141091  db->xCollNeeded = 0;
141092  db->xCollNeeded16 = xCollNeeded16;
141093  db->pCollNeededArg = pCollNeededArg;
141094  sqlite3_mutex_leave(db->mutex);
141095  return SQLITE_OK;
141096 }
141097 #endif /* SQLITE_OMIT_UTF16 */
141098 
141099 #ifndef SQLITE_OMIT_DEPRECATED
141100 /*
141101 ** This function is now an anachronism. It used to be used to recover from a
141102 ** malloc() failure, but SQLite now does this automatically.
141103 */
141104 SQLITE_API int sqlite3_global_recover(void){
141105  return SQLITE_OK;
141106 }
141107 #endif
141108 
141109 /*
141110 ** Test to see whether or not the database connection is in autocommit
141111 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
141112 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
141113 ** by the next COMMIT or ROLLBACK.
141114 */
141115 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
141116 #ifdef SQLITE_ENABLE_API_ARMOR
141117  if( !sqlite3SafetyCheckOk(db) ){
141118  (void)SQLITE_MISUSE_BKPT;
141119  return 0;
141120  }
141121 #endif
141122  return db->autoCommit;
141123 }
141124 
141125 /*
141126 ** The following routines are substitutes for constants SQLITE_CORRUPT,
141127 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
141128 ** constants. They serve two purposes:
141129 **
141130 ** 1. Serve as a convenient place to set a breakpoint in a debugger
141131 ** to detect when version error conditions occurs.
141132 **
141133 ** 2. Invoke sqlite3_log() to provide the source code location where
141134 ** a low-level error is first detected.
141135 */
141136 static int reportError(int iErr, int lineno, const char *zType){
141137  sqlite3_log(iErr, "%s at line %d of [%.10s]",
141138  zType, lineno, 20+sqlite3_sourceid());
141139  return iErr;
141140 }
141141 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
141142  testcase( sqlite3GlobalConfig.xLog!=0 );
141143  return reportError(SQLITE_CORRUPT, lineno, "database corruption");
141144 }
141145 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
141146  testcase( sqlite3GlobalConfig.xLog!=0 );
141147  return reportError(SQLITE_MISUSE, lineno, "misuse");
141148 }
141149 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
141150  testcase( sqlite3GlobalConfig.xLog!=0 );
141151  return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
141152 }
141153 #ifdef SQLITE_DEBUG
141154 SQLITE_PRIVATE int sqlite3NomemError(int lineno){
141155  testcase( sqlite3GlobalConfig.xLog!=0 );
141156  return reportError(SQLITE_NOMEM, lineno, "OOM");
141157 }
141158 SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
141159  testcase( sqlite3GlobalConfig.xLog!=0 );
141160  return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
141161 }
141162 #endif
141163 
141164 #ifndef SQLITE_OMIT_DEPRECATED
141165 /*
141166 ** This is a convenience routine that makes sure that all thread-specific
141167 ** data for this thread has been deallocated.
141168 **
141169 ** SQLite no longer uses thread-specific data so this routine is now a
141170 ** no-op. It is retained for historical compatibility.
141171 */
141172 SQLITE_API void sqlite3_thread_cleanup(void){
141173 }
141174 #endif
141175 
141176 /*
141177 ** Return meta information about a specific column of a database table.
141178 ** See comment in sqlite3.h (sqlite.h.in) for details.
141179 */
141180 SQLITE_API int sqlite3_table_column_metadata(
141181  sqlite3 *db, /* Connection handle */
141182  const char *zDbName, /* Database name or NULL */
141183  const char *zTableName, /* Table name */
141184  const char *zColumnName, /* Column name */
141185  char const **pzDataType, /* OUTPUT: Declared data type */
141186  char const **pzCollSeq, /* OUTPUT: Collation sequence name */
141187  int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
141188  int *pPrimaryKey, /* OUTPUT: True if column part of PK */
141189  int *pAutoinc /* OUTPUT: True if column is auto-increment */
141190 ){
141191  int rc;
141192  char *zErrMsg = 0;
141193  Table *pTab = 0;
141194  Column *pCol = 0;
141195  int iCol = 0;
141196  char const *zDataType = 0;
141197  char const *zCollSeq = 0;
141198  int notnull = 0;
141199  int primarykey = 0;
141200  int autoinc = 0;
141201 
141202 
141203 #ifdef SQLITE_ENABLE_API_ARMOR
141204  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
141205  return SQLITE_MISUSE_BKPT;
141206  }
141207 #endif
141208 
141209  /* Ensure the database schema has been loaded */
141210  sqlite3_mutex_enter(db->mutex);
141211  sqlite3BtreeEnterAll(db);
141212  rc = sqlite3Init(db, &zErrMsg);
141213  if( SQLITE_OK!=rc ){
141214  goto error_out;
141215  }
141216 
141217  /* Locate the table in question */
141218  pTab = sqlite3FindTable(db, zTableName, zDbName);
141219  if( !pTab || pTab->pSelect ){
141220  pTab = 0;
141221  goto error_out;
141222  }
141223 
141224  /* Find the column for which info is requested */
141225  if( zColumnName==0 ){
141226  /* Query for existance of table only */
141227  }else{
141228  for(iCol=0; iCol<pTab->nCol; iCol++){
141229  pCol = &pTab->aCol[iCol];
141230  if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
141231  break;
141232  }
141233  }
141234  if( iCol==pTab->nCol ){
141235  if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
141236  iCol = pTab->iPKey;
141237  pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
141238  }else{
141239  pTab = 0;
141240  goto error_out;
141241  }
141242  }
141243  }
141244 
141245  /* The following block stores the meta information that will be returned
141246  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
141247  ** and autoinc. At this point there are two possibilities:
141248  **
141249  ** 1. The specified column name was rowid", "oid" or "_rowid_"
141250  ** and there is no explicitly declared IPK column.
141251  **
141252  ** 2. The table is not a view and the column name identified an
141253  ** explicitly declared column. Copy meta information from *pCol.
141254  */
141255  if( pCol ){
141256  zDataType = sqlite3ColumnType(pCol,0);
141257  zCollSeq = pCol->zColl;
141258  notnull = pCol->notNull!=0;
141259  primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
141260  autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
141261  }else{
141262  zDataType = "INTEGER";
141263  primarykey = 1;
141264  }
141265  if( !zCollSeq ){
141266  zCollSeq = sqlite3StrBINARY;
141267  }
141268 
141269 error_out:
141270  sqlite3BtreeLeaveAll(db);
141271 
141272  /* Whether the function call succeeded or failed, set the output parameters
141273  ** to whatever their local counterparts contain. If an error did occur,
141274  ** this has the effect of zeroing all output parameters.
141275  */
141276  if( pzDataType ) *pzDataType = zDataType;
141277  if( pzCollSeq ) *pzCollSeq = zCollSeq;
141278  if( pNotNull ) *pNotNull = notnull;
141279  if( pPrimaryKey ) *pPrimaryKey = primarykey;
141280  if( pAutoinc ) *pAutoinc = autoinc;
141281 
141282  if( SQLITE_OK==rc && !pTab ){
141283  sqlite3DbFree(db, zErrMsg);
141284  zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
141285  zColumnName);
141286  rc = SQLITE_ERROR;
141287  }
141288  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
141289  sqlite3DbFree(db, zErrMsg);
141290  rc = sqlite3ApiExit(db, rc);
141291  sqlite3_mutex_leave(db->mutex);
141292  return rc;
141293 }
141294 
141295 /*
141296 ** Sleep for a little while. Return the amount of time slept.
141297 */
141298 SQLITE_API int sqlite3_sleep(int ms){
141299  sqlite3_vfs *pVfs;
141300  int rc;
141301  pVfs = sqlite3_vfs_find(0);
141302  if( pVfs==0 ) return 0;
141303 
141304  /* This function works in milliseconds, but the underlying OsSleep()
141305  ** API uses microseconds. Hence the 1000's.
141306  */
141307  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
141308  return rc;
141309 }
141310 
141311 /*
141312 ** Enable or disable the extended result codes.
141313 */
141314 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
141315 #ifdef SQLITE_ENABLE_API_ARMOR
141316  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141317 #endif
141318  sqlite3_mutex_enter(db->mutex);
141319  db->errMask = onoff ? 0xffffffff : 0xff;
141320  sqlite3_mutex_leave(db->mutex);
141321  return SQLITE_OK;
141322 }
141323 
141324 /*
141325 ** Invoke the xFileControl method on a particular database.
141326 */
141327 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
141328  int rc = SQLITE_ERROR;
141329  Btree *pBtree;
141330 
141331 #ifdef SQLITE_ENABLE_API_ARMOR
141332  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141333 #endif
141334  sqlite3_mutex_enter(db->mutex);
141335  pBtree = sqlite3DbNameToBtree(db, zDbName);
141336  if( pBtree ){
141337  Pager *pPager;
141338  sqlite3_file *fd;
141339  sqlite3BtreeEnter(pBtree);
141340  pPager = sqlite3BtreePager(pBtree);
141341  assert( pPager!=0 );
141342  fd = sqlite3PagerFile(pPager);
141343  assert( fd!=0 );
141344  if( op==SQLITE_FCNTL_FILE_POINTER ){
141345  *(sqlite3_file**)pArg = fd;
141346  rc = SQLITE_OK;
141347  }else if( op==SQLITE_FCNTL_VFS_POINTER ){
141348  *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
141349  rc = SQLITE_OK;
141350  }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
141351  *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
141352  rc = SQLITE_OK;
141353  }else if( fd->pMethods ){
141354  rc = sqlite3OsFileControl(fd, op, pArg);
141355  }else{
141356  rc = SQLITE_NOTFOUND;
141357  }
141358  sqlite3BtreeLeave(pBtree);
141359  }
141360  sqlite3_mutex_leave(db->mutex);
141361  return rc;
141362 }
141363 
141364 /*
141365 ** Interface to the testing logic.
141366 */
141367 SQLITE_API int sqlite3_test_control(int op, ...){
141368  int rc = 0;
141369 #ifdef SQLITE_OMIT_BUILTIN_TEST
141370  UNUSED_PARAMETER(op);
141371 #else
141372  va_list ap;
141373  va_start(ap, op);
141374  switch( op ){
141375 
141376  /*
141377  ** Save the current state of the PRNG.
141378  */
141379  case SQLITE_TESTCTRL_PRNG_SAVE: {
141380  sqlite3PrngSaveState();
141381  break;
141382  }
141383 
141384  /*
141385  ** Restore the state of the PRNG to the last state saved using
141386  ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
141387  ** this verb acts like PRNG_RESET.
141388  */
141389  case SQLITE_TESTCTRL_PRNG_RESTORE: {
141390  sqlite3PrngRestoreState();
141391  break;
141392  }
141393 
141394  /*
141395  ** Reset the PRNG back to its uninitialized state. The next call
141396  ** to sqlite3_randomness() will reseed the PRNG using a single call
141397  ** to the xRandomness method of the default VFS.
141398  */
141399  case SQLITE_TESTCTRL_PRNG_RESET: {
141400  sqlite3_randomness(0,0);
141401  break;
141402  }
141403 
141404  /*
141405  ** sqlite3_test_control(BITVEC_TEST, size, program)
141406  **
141407  ** Run a test against a Bitvec object of size. The program argument
141408  ** is an array of integers that defines the test. Return -1 on a
141409  ** memory allocation error, 0 on success, or non-zero for an error.
141410  ** See the sqlite3BitvecBuiltinTest() for additional information.
141411  */
141412  case SQLITE_TESTCTRL_BITVEC_TEST: {
141413  int sz = va_arg(ap, int);
141414  int *aProg = va_arg(ap, int*);
141415  rc = sqlite3BitvecBuiltinTest(sz, aProg);
141416  break;
141417  }
141418 
141419  /*
141420  ** sqlite3_test_control(FAULT_INSTALL, xCallback)
141421  **
141422  ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
141423  ** if xCallback is not NULL.
141424  **
141425  ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
141426  ** is called immediately after installing the new callback and the return
141427  ** value from sqlite3FaultSim(0) becomes the return from
141428  ** sqlite3_test_control().
141429  */
141430  case SQLITE_TESTCTRL_FAULT_INSTALL: {
141431  /* MSVC is picky about pulling func ptrs from va lists.
141432  ** http://support.microsoft.com/kb/47961
141433  ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
141434  */
141435  typedef int(*TESTCALLBACKFUNC_t)(int);
141436  sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
141437  rc = sqlite3FaultSim(0);
141438  break;
141439  }
141440 
141441  /*
141442  ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
141443  **
141444  ** Register hooks to call to indicate which malloc() failures
141445  ** are benign.
141446  */
141447  case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
141448  typedef void (*void_function)(void);
141449  void_function xBenignBegin;
141450  void_function xBenignEnd;
141451  xBenignBegin = va_arg(ap, void_function);
141452  xBenignEnd = va_arg(ap, void_function);
141453  sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
141454  break;
141455  }
141456 
141457  /*
141458  ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
141459  **
141460  ** Set the PENDING byte to the value in the argument, if X>0.
141461  ** Make no changes if X==0. Return the value of the pending byte
141462  ** as it existing before this routine was called.
141463  **
141464  ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
141465  ** an incompatible database file format. Changing the PENDING byte
141466  ** while any database connection is open results in undefined and
141467  ** deleterious behavior.
141468  */
141469  case SQLITE_TESTCTRL_PENDING_BYTE: {
141470  rc = PENDING_BYTE;
141471 #ifndef SQLITE_OMIT_WSD
141472  {
141473  unsigned int newVal = va_arg(ap, unsigned int);
141474  if( newVal ) sqlite3PendingByte = newVal;
141475  }
141476 #endif
141477  break;
141478  }
141479 
141480  /*
141481  ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
141482  **
141483  ** This action provides a run-time test to see whether or not
141484  ** assert() was enabled at compile-time. If X is true and assert()
141485  ** is enabled, then the return value is true. If X is true and
141486  ** assert() is disabled, then the return value is zero. If X is
141487  ** false and assert() is enabled, then the assertion fires and the
141488  ** process aborts. If X is false and assert() is disabled, then the
141489  ** return value is zero.
141490  */
141491  case SQLITE_TESTCTRL_ASSERT: {
141492  volatile int x = 0;
141493  assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
141494  rc = x;
141495  break;
141496  }
141497 
141498 
141499  /*
141500  ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
141501  **
141502  ** This action provides a run-time test to see how the ALWAYS and
141503  ** NEVER macros were defined at compile-time.
141504  **
141505  ** The return value is ALWAYS(X).
141506  **
141507  ** The recommended test is X==2. If the return value is 2, that means
141508  ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
141509  ** default setting. If the return value is 1, then ALWAYS() is either
141510  ** hard-coded to true or else it asserts if its argument is false.
141511  ** The first behavior (hard-coded to true) is the case if
141512  ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
141513  ** behavior (assert if the argument to ALWAYS() is false) is the case if
141514  ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
141515  **
141516  ** The run-time test procedure might look something like this:
141517  **
141518  ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
141519  ** // ALWAYS() and NEVER() are no-op pass-through macros
141520  ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
141521  ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
141522  ** }else{
141523  ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
141524  ** }
141525  */
141526  case SQLITE_TESTCTRL_ALWAYS: {
141527  int x = va_arg(ap,int);
141528  rc = ALWAYS(x);
141529  break;
141530  }
141531 
141532  /*
141533  ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
141534  **
141535  ** The integer returned reveals the byte-order of the computer on which
141536  ** SQLite is running:
141537  **
141538  ** 1 big-endian, determined at run-time
141539  ** 10 little-endian, determined at run-time
141540  ** 432101 big-endian, determined at compile-time
141541  ** 123410 little-endian, determined at compile-time
141542  */
141543  case SQLITE_TESTCTRL_BYTEORDER: {
141544  rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
141545  break;
141546  }
141547 
141548  /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
141549  **
141550  ** Set the nReserve size to N for the main database on the database
141551  ** connection db.
141552  */
141553  case SQLITE_TESTCTRL_RESERVE: {
141554  sqlite3 *db = va_arg(ap, sqlite3*);
141555  int x = va_arg(ap,int);
141556  sqlite3_mutex_enter(db->mutex);
141557  sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
141558  sqlite3_mutex_leave(db->mutex);
141559  break;
141560  }
141561 
141562  /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
141563  **
141564  ** Enable or disable various optimizations for testing purposes. The
141565  ** argument N is a bitmask of optimizations to be disabled. For normal
141566  ** operation N should be 0. The idea is that a test program (like the
141567  ** SQL Logic Test or SLT test module) can run the same SQL multiple times
141568  ** with various optimizations disabled to verify that the same answer
141569  ** is obtained in every case.
141570  */
141571  case SQLITE_TESTCTRL_OPTIMIZATIONS: {
141572  sqlite3 *db = va_arg(ap, sqlite3*);
141573  db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
141574  break;
141575  }
141576 
141577 #ifdef SQLITE_N_KEYWORD
141578  /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
141579  **
141580  ** If zWord is a keyword recognized by the parser, then return the
141581  ** number of keywords. Or if zWord is not a keyword, return 0.
141582  **
141583  ** This test feature is only available in the amalgamation since
141584  ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
141585  ** is built using separate source files.
141586  */
141587  case SQLITE_TESTCTRL_ISKEYWORD: {
141588  const char *zWord = va_arg(ap, const char*);
141589  int n = sqlite3Strlen30(zWord);
141590  rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
141591  break;
141592  }
141593 #endif
141594 
141595  /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
141596  **
141597  ** Pass pFree into sqlite3ScratchFree().
141598  ** If sz>0 then allocate a scratch buffer into pNew.
141599  */
141600  case SQLITE_TESTCTRL_SCRATCHMALLOC: {
141601  void *pFree, **ppNew;
141602  int sz;
141603  sz = va_arg(ap, int);
141604  ppNew = va_arg(ap, void**);
141605  pFree = va_arg(ap, void*);
141606  if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
141607  sqlite3ScratchFree(pFree);
141608  break;
141609  }
141610 
141611  /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
141612  **
141613  ** If parameter onoff is non-zero, configure the wrappers so that all
141614  ** subsequent calls to localtime() and variants fail. If onoff is zero,
141615  ** undo this setting.
141616  */
141617  case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
141618  sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
141619  break;
141620  }
141621 
141622  /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
141623  **
141624  ** Set or clear a flag that indicates that the database file is always well-
141625  ** formed and never corrupt. This flag is clear by default, indicating that
141626  ** database files might have arbitrary corruption. Setting the flag during
141627  ** testing causes certain assert() statements in the code to be activated
141628  ** that demonstrat invariants on well-formed database files.
141629  */
141630  case SQLITE_TESTCTRL_NEVER_CORRUPT: {
141631  sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
141632  break;
141633  }
141634 
141635  /* Set the threshold at which OP_Once counters reset back to zero.
141636  ** By default this is 0x7ffffffe (over 2 billion), but that value is
141637  ** too big to test in a reasonable amount of time, so this control is
141638  ** provided to set a small and easily reachable reset value.
141639  */
141640  case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
141641  sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
141642  break;
141643  }
141644 
141645  /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
141646  **
141647  ** Set the VDBE coverage callback function to xCallback with context
141648  ** pointer ptr.
141649  */
141650  case SQLITE_TESTCTRL_VDBE_COVERAGE: {
141651 #ifdef SQLITE_VDBE_COVERAGE
141652  typedef void (*branch_callback)(void*,int,u8,u8);
141653  sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
141654  sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
141655 #endif
141656  break;
141657  }
141658 
141659  /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
141660  case SQLITE_TESTCTRL_SORTER_MMAP: {
141661  sqlite3 *db = va_arg(ap, sqlite3*);
141662  db->nMaxSorterMmap = va_arg(ap, int);
141663  break;
141664  }
141665 
141666  /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
141667  **
141668  ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
141669  ** not.
141670  */
141671  case SQLITE_TESTCTRL_ISINIT: {
141672  if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
141673  break;
141674  }
141675 
141676  /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
141677  **
141678  ** This test control is used to create imposter tables. "db" is a pointer
141679  ** to the database connection. dbName is the database name (ex: "main" or
141680  ** "temp") which will receive the imposter. "onOff" turns imposter mode on
141681  ** or off. "tnum" is the root page of the b-tree to which the imposter
141682  ** table should connect.
141683  **
141684  ** Enable imposter mode only when the schema has already been parsed. Then
141685  ** run a single CREATE TABLE statement to construct the imposter table in
141686  ** the parsed schema. Then turn imposter mode back off again.
141687  **
141688  ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
141689  ** the schema to be reparsed the next time it is needed. This has the
141690  ** effect of erasing all imposter tables.
141691  */
141692  case SQLITE_TESTCTRL_IMPOSTER: {
141693  sqlite3 *db = va_arg(ap, sqlite3*);
141694  sqlite3_mutex_enter(db->mutex);
141695  db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
141696  db->init.busy = db->init.imposterTable = va_arg(ap,int);
141697  db->init.newTnum = va_arg(ap,int);
141698  if( db->init.busy==0 && db->init.newTnum>0 ){
141699  sqlite3ResetAllSchemasOfConnection(db);
141700  }
141701  sqlite3_mutex_leave(db->mutex);
141702  break;
141703  }
141704  }
141705  va_end(ap);
141706 #endif /* SQLITE_OMIT_BUILTIN_TEST */
141707  return rc;
141708 }
141709 
141710 /*
141711 ** This is a utility routine, useful to VFS implementations, that checks
141712 ** to see if a database file was a URI that contained a specific query
141713 ** parameter, and if so obtains the value of the query parameter.
141714 **
141715 ** The zFilename argument is the filename pointer passed into the xOpen()
141716 ** method of a VFS implementation. The zParam argument is the name of the
141717 ** query parameter we seek. This routine returns the value of the zParam
141718 ** parameter if it exists. If the parameter does not exist, this routine
141719 ** returns a NULL pointer.
141720 */
141721 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
141722  if( zFilename==0 || zParam==0 ) return 0;
141723  zFilename += sqlite3Strlen30(zFilename) + 1;
141724  while( zFilename[0] ){
141725  int x = strcmp(zFilename, zParam);
141726  zFilename += sqlite3Strlen30(zFilename) + 1;
141727  if( x==0 ) return zFilename;
141728  zFilename += sqlite3Strlen30(zFilename) + 1;
141729  }
141730  return 0;
141731 }
141732 
141733 /*
141734 ** Return a boolean value for a query parameter.
141735 */
141736 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
141737  const char *z = sqlite3_uri_parameter(zFilename, zParam);
141738  bDflt = bDflt!=0;
141739  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
141740 }
141741 
141742 /*
141743 ** Return a 64-bit integer value for a query parameter.
141744 */
141745 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
141746  const char *zFilename, /* Filename as passed to xOpen */
141747  const char *zParam, /* URI parameter sought */
141748  sqlite3_int64 bDflt /* return if parameter is missing */
141749 ){
141750  const char *z = sqlite3_uri_parameter(zFilename, zParam);
141751  sqlite3_int64 v;
141752  if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
141753  bDflt = v;
141754  }
141755  return bDflt;
141756 }
141757 
141758 /*
141759 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
141760 */
141761 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
141762  int i;
141763  for(i=0; i<db->nDb; i++){
141764  if( db->aDb[i].pBt
141765  && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zDbSName)==0)
141766  ){
141767  return db->aDb[i].pBt;
141768  }
141769  }
141770  return 0;
141771 }
141772 
141773 /*
141774 ** Return the filename of the database associated with a database
141775 ** connection.
141776 */
141777 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
141778  Btree *pBt;
141779 #ifdef SQLITE_ENABLE_API_ARMOR
141780  if( !sqlite3SafetyCheckOk(db) ){
141781  (void)SQLITE_MISUSE_BKPT;
141782  return 0;
141783  }
141784 #endif
141785  pBt = sqlite3DbNameToBtree(db, zDbName);
141786  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
141787 }
141788 
141789 /*
141790 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
141791 ** no such database exists.
141792 */
141793 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
141794  Btree *pBt;
141795 #ifdef SQLITE_ENABLE_API_ARMOR
141796  if( !sqlite3SafetyCheckOk(db) ){
141797  (void)SQLITE_MISUSE_BKPT;
141798  return -1;
141799  }
141800 #endif
141801  pBt = sqlite3DbNameToBtree(db, zDbName);
141802  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
141803 }
141804 
141805 #ifdef SQLITE_ENABLE_SNAPSHOT
141806 /*
141807 ** Obtain a snapshot handle for the snapshot of database zDb currently
141808 ** being read by handle db.
141809 */
141810 SQLITE_API int sqlite3_snapshot_get(
141811  sqlite3 *db,
141812  const char *zDb,
141813  sqlite3_snapshot **ppSnapshot
141814 ){
141815  int rc = SQLITE_ERROR;
141816 #ifndef SQLITE_OMIT_WAL
141817  int iDb;
141818 
141819 #ifdef SQLITE_ENABLE_API_ARMOR
141820  if( !sqlite3SafetyCheckOk(db) ){
141821  return SQLITE_MISUSE_BKPT;
141822  }
141823 #endif
141824  sqlite3_mutex_enter(db->mutex);
141825 
141826  iDb = sqlite3FindDbName(db, zDb);
141827  if( iDb==0 || iDb>1 ){
141828  Btree *pBt = db->aDb[iDb].pBt;
141829  if( 0==sqlite3BtreeIsInTrans(pBt) ){
141830  rc = sqlite3BtreeBeginTrans(pBt, 0);
141831  if( rc==SQLITE_OK ){
141832  rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
141833  }
141834  }
141835  }
141836 
141837  sqlite3_mutex_leave(db->mutex);
141838 #endif /* SQLITE_OMIT_WAL */
141839  return rc;
141840 }
141841 
141842 /*
141843 ** Open a read-transaction on the snapshot idendified by pSnapshot.
141844 */
141845 SQLITE_API int sqlite3_snapshot_open(
141846  sqlite3 *db,
141847  const char *zDb,
141848  sqlite3_snapshot *pSnapshot
141849 ){
141850  int rc = SQLITE_ERROR;
141851 #ifndef SQLITE_OMIT_WAL
141852 
141853 #ifdef SQLITE_ENABLE_API_ARMOR
141854  if( !sqlite3SafetyCheckOk(db) ){
141855  return SQLITE_MISUSE_BKPT;
141856  }
141857 #endif
141858  sqlite3_mutex_enter(db->mutex);
141859  if( db->autoCommit==0 ){
141860  int iDb;
141861  iDb = sqlite3FindDbName(db, zDb);
141862  if( iDb==0 || iDb>1 ){
141863  Btree *pBt = db->aDb[iDb].pBt;
141864  if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
141865  rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
141866  if( rc==SQLITE_OK ){
141867  rc = sqlite3BtreeBeginTrans(pBt, 0);
141868  sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
141869  }
141870  }
141871  }
141872  }
141873 
141874  sqlite3_mutex_leave(db->mutex);
141875 #endif /* SQLITE_OMIT_WAL */
141876  return rc;
141877 }
141878 
141879 /*
141880 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
141881 */
141882 SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
141883  sqlite3_free(pSnapshot);
141884 }
141885 #endif /* SQLITE_ENABLE_SNAPSHOT */
141886 
141887 /************** End of main.c ************************************************/
141888 /************** Begin file notify.c ******************************************/
141889 /*
141890 ** 2009 March 3
141891 **
141892 ** The author disclaims copyright to this source code. In place of
141893 ** a legal notice, here is a blessing:
141894 **
141895 ** May you do good and not evil.
141896 ** May you find forgiveness for yourself and forgive others.
141897 ** May you share freely, never taking more than you give.
141898 **
141899 *************************************************************************
141900 **
141901 ** This file contains the implementation of the sqlite3_unlock_notify()
141902 ** API method and its associated functionality.
141903 */
141904 /* #include "sqliteInt.h" */
141905 /* #include "btreeInt.h" */
141906 
141907 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
141908 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
141909 
141910 /*
141911 ** Public interfaces:
141912 **
141913 ** sqlite3ConnectionBlocked()
141914 ** sqlite3ConnectionUnlocked()
141915 ** sqlite3ConnectionClosed()
141916 ** sqlite3_unlock_notify()
141917 */
141918 
141919 #define assertMutexHeld() \
141920  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
141921 
141922 /*
141923 ** Head of a linked list of all sqlite3 objects created by this process
141924 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
141925 ** is not NULL. This variable may only accessed while the STATIC_MASTER
141926 ** mutex is held.
141927 */
141928 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
141929 
141930 #ifndef NDEBUG
141931 /*
141932 ** This function is a complex assert() that verifies the following
141933 ** properties of the blocked connections list:
141934 **
141935 ** 1) Each entry in the list has a non-NULL value for either
141936 ** pUnlockConnection or pBlockingConnection, or both.
141937 **
141938 ** 2) All entries in the list that share a common value for
141939 ** xUnlockNotify are grouped together.
141940 **
141941 ** 3) If the argument db is not NULL, then none of the entries in the
141942 ** blocked connections list have pUnlockConnection or pBlockingConnection
141943 ** set to db. This is used when closing connection db.
141944 */
141945 static void checkListProperties(sqlite3 *db){
141946  sqlite3 *p;
141947  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
141948  int seen = 0;
141949  sqlite3 *p2;
141950 
141951  /* Verify property (1) */
141952  assert( p->pUnlockConnection || p->pBlockingConnection );
141953 
141954  /* Verify property (2) */
141955  for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
141956  if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
141957  assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
141958  assert( db==0 || p->pUnlockConnection!=db );
141959  assert( db==0 || p->pBlockingConnection!=db );
141960  }
141961  }
141962 }
141963 #else
141964 # define checkListProperties(x)
141965 #endif
141966 
141967 /*
141968 ** Remove connection db from the blocked connections list. If connection
141969 ** db is not currently a part of the list, this function is a no-op.
141970 */
141971 static void removeFromBlockedList(sqlite3 *db){
141972  sqlite3 **pp;
141973  assertMutexHeld();
141974  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
141975  if( *pp==db ){
141976  *pp = (*pp)->pNextBlocked;
141977  break;
141978  }
141979  }
141980 }
141981 
141982 /*
141983 ** Add connection db to the blocked connections list. It is assumed
141984 ** that it is not already a part of the list.
141985 */
141986 static void addToBlockedList(sqlite3 *db){
141987  sqlite3 **pp;
141988  assertMutexHeld();
141989  for(
141990  pp=&sqlite3BlockedList;
141991  *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
141992  pp=&(*pp)->pNextBlocked
141993  );
141994  db->pNextBlocked = *pp;
141995  *pp = db;
141996 }
141997 
141998 /*
141999 ** Obtain the STATIC_MASTER mutex.
142000 */
142001 static void enterMutex(void){
142002  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
142003  checkListProperties(0);
142004 }
142005 
142006 /*
142007 ** Release the STATIC_MASTER mutex.
142008 */
142009 static void leaveMutex(void){
142010  assertMutexHeld();
142011  checkListProperties(0);
142012  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
142013 }
142014 
142015 /*
142016 ** Register an unlock-notify callback.
142017 **
142018 ** This is called after connection "db" has attempted some operation
142019 ** but has received an SQLITE_LOCKED error because another connection
142020 ** (call it pOther) in the same process was busy using the same shared
142021 ** cache. pOther is found by looking at db->pBlockingConnection.
142022 **
142023 ** If there is no blocking connection, the callback is invoked immediately,
142024 ** before this routine returns.
142025 **
142026 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
142027 ** a deadlock.
142028 **
142029 ** Otherwise, make arrangements to invoke xNotify when pOther drops
142030 ** its locks.
142031 **
142032 ** Each call to this routine overrides any prior callbacks registered
142033 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
142034 ** cancelled.
142035 */
142036 SQLITE_API int sqlite3_unlock_notify(
142037  sqlite3 *db,
142038  void (*xNotify)(void **, int),
142039  void *pArg
142040 ){
142041  int rc = SQLITE_OK;
142042 
142043  sqlite3_mutex_enter(db->mutex);
142044  enterMutex();
142045 
142046  if( xNotify==0 ){
142047  removeFromBlockedList(db);
142048  db->pBlockingConnection = 0;
142049  db->pUnlockConnection = 0;
142050  db->xUnlockNotify = 0;
142051  db->pUnlockArg = 0;
142052  }else if( 0==db->pBlockingConnection ){
142053  /* The blocking transaction has been concluded. Or there never was a
142054  ** blocking transaction. In either case, invoke the notify callback
142055  ** immediately.
142056  */
142057  xNotify(&pArg, 1);
142058  }else{
142059  sqlite3 *p;
142060 
142061  for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
142062  if( p ){
142063  rc = SQLITE_LOCKED; /* Deadlock detected. */
142064  }else{
142065  db->pUnlockConnection = db->pBlockingConnection;
142066  db->xUnlockNotify = xNotify;
142067  db->pUnlockArg = pArg;
142068  removeFromBlockedList(db);
142069  addToBlockedList(db);
142070  }
142071  }
142072 
142073  leaveMutex();
142074  assert( !db->mallocFailed );
142075  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
142076  sqlite3_mutex_leave(db->mutex);
142077  return rc;
142078 }
142079 
142080 /*
142081 ** This function is called while stepping or preparing a statement
142082 ** associated with connection db. The operation will return SQLITE_LOCKED
142083 ** to the user because it requires a lock that will not be available
142084 ** until connection pBlocker concludes its current transaction.
142085 */
142086 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
142087  enterMutex();
142088  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
142089  addToBlockedList(db);
142090  }
142091  db->pBlockingConnection = pBlocker;
142092  leaveMutex();
142093 }
142094 
142095 /*
142096 ** This function is called when
142097 ** the transaction opened by database db has just finished. Locks held
142098 ** by database connection db have been released.
142099 **
142100 ** This function loops through each entry in the blocked connections
142101 ** list and does the following:
142102 **
142103 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
142104 ** set to db, then set pBlockingConnection=0.
142105 **
142106 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
142107 ** set to db, then invoke the configured unlock-notify callback and
142108 ** set pUnlockConnection=0.
142109 **
142110 ** 3) If the two steps above mean that pBlockingConnection==0 and
142111 ** pUnlockConnection==0, remove the entry from the blocked connections
142112 ** list.
142113 */
142114 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
142115  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
142116  int nArg = 0; /* Number of entries in aArg[] */
142117  sqlite3 **pp; /* Iterator variable */
142118  void **aArg; /* Arguments to the unlock callback */
142119  void **aDyn = 0; /* Dynamically allocated space for aArg[] */
142120  void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
142121 
142122  aArg = aStatic;
142123  enterMutex(); /* Enter STATIC_MASTER mutex */
142124 
142125  /* This loop runs once for each entry in the blocked-connections list. */
142126  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
142127  sqlite3 *p = *pp;
142128 
142129  /* Step 1. */
142130  if( p->pBlockingConnection==db ){
142131  p->pBlockingConnection = 0;
142132  }
142133 
142134  /* Step 2. */
142135  if( p->pUnlockConnection==db ){
142136  assert( p->xUnlockNotify );
142137  if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
142138  xUnlockNotify(aArg, nArg);
142139  nArg = 0;
142140  }
142141 
142142  sqlite3BeginBenignMalloc();
142143  assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
142144  assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
142145  if( (!aDyn && nArg==(int)ArraySize(aStatic))
142146  || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
142147  ){
142148  /* The aArg[] array needs to grow. */
142149  void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
142150  if( pNew ){
142151  memcpy(pNew, aArg, nArg*sizeof(void *));
142152  sqlite3_free(aDyn);
142153  aDyn = aArg = pNew;
142154  }else{
142155  /* This occurs when the array of context pointers that need to
142156  ** be passed to the unlock-notify callback is larger than the
142157  ** aStatic[] array allocated on the stack and the attempt to
142158  ** allocate a larger array from the heap has failed.
142159  **
142160  ** This is a difficult situation to handle. Returning an error
142161  ** code to the caller is insufficient, as even if an error code
142162  ** is returned the transaction on connection db will still be
142163  ** closed and the unlock-notify callbacks on blocked connections
142164  ** will go unissued. This might cause the application to wait
142165  ** indefinitely for an unlock-notify callback that will never
142166  ** arrive.
142167  **
142168  ** Instead, invoke the unlock-notify callback with the context
142169  ** array already accumulated. We can then clear the array and
142170  ** begin accumulating any further context pointers without
142171  ** requiring any dynamic allocation. This is sub-optimal because
142172  ** it means that instead of one callback with a large array of
142173  ** context pointers the application will receive two or more
142174  ** callbacks with smaller arrays of context pointers, which will
142175  ** reduce the applications ability to prioritize multiple
142176  ** connections. But it is the best that can be done under the
142177  ** circumstances.
142178  */
142179  xUnlockNotify(aArg, nArg);
142180  nArg = 0;
142181  }
142182  }
142183  sqlite3EndBenignMalloc();
142184 
142185  aArg[nArg++] = p->pUnlockArg;
142186  xUnlockNotify = p->xUnlockNotify;
142187  p->pUnlockConnection = 0;
142188  p->xUnlockNotify = 0;
142189  p->pUnlockArg = 0;
142190  }
142191 
142192  /* Step 3. */
142193  if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
142194  /* Remove connection p from the blocked connections list. */
142195  *pp = p->pNextBlocked;
142196  p->pNextBlocked = 0;
142197  }else{
142198  pp = &p->pNextBlocked;
142199  }
142200  }
142201 
142202  if( nArg!=0 ){
142203  xUnlockNotify(aArg, nArg);
142204  }
142205  sqlite3_free(aDyn);
142206  leaveMutex(); /* Leave STATIC_MASTER mutex */
142207 }
142208 
142209 /*
142210 ** This is called when the database connection passed as an argument is
142211 ** being closed. The connection is removed from the blocked list.
142212 */
142213 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
142214  sqlite3ConnectionUnlocked(db);
142215  enterMutex();
142216  removeFromBlockedList(db);
142217  checkListProperties(db);
142218  leaveMutex();
142219 }
142220 #endif
142221 
142222 /************** End of notify.c **********************************************/
142223 /************** Begin file fts3.c ********************************************/
142224 /*
142225 ** 2006 Oct 10
142226 **
142227 ** The author disclaims copyright to this source code. In place of
142228 ** a legal notice, here is a blessing:
142229 **
142230 ** May you do good and not evil.
142231 ** May you find forgiveness for yourself and forgive others.
142232 ** May you share freely, never taking more than you give.
142233 **
142234 ******************************************************************************
142235 **
142236 ** This is an SQLite module implementing full-text search.
142237 */
142238 
142239 /*
142240 ** The code in this file is only compiled if:
142241 **
142242 ** * The FTS3 module is being built as an extension
142243 ** (in which case SQLITE_CORE is not defined), or
142244 **
142245 ** * The FTS3 module is being built into the core of
142246 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
142247 */
142248 
142249 /* The full-text index is stored in a series of b+tree (-like)
142250 ** structures called segments which map terms to doclists. The
142251 ** structures are like b+trees in layout, but are constructed from the
142252 ** bottom up in optimal fashion and are not updatable. Since trees
142253 ** are built from the bottom up, things will be described from the
142254 ** bottom up.
142255 **
142256 **
142257 **** Varints ****
142258 ** The basic unit of encoding is a variable-length integer called a
142259 ** varint. We encode variable-length integers in little-endian order
142260 ** using seven bits * per byte as follows:
142261 **
142262 ** KEY:
142263 ** A = 0xxxxxxx 7 bits of data and one flag bit
142264 ** B = 1xxxxxxx 7 bits of data and one flag bit
142265 **
142266 ** 7 bits - A
142267 ** 14 bits - BA
142268 ** 21 bits - BBA
142269 ** and so on.
142270 **
142271 ** This is similar in concept to how sqlite encodes "varints" but
142272 ** the encoding is not the same. SQLite varints are big-endian
142273 ** are are limited to 9 bytes in length whereas FTS3 varints are
142274 ** little-endian and can be up to 10 bytes in length (in theory).
142275 **
142276 ** Example encodings:
142277 **
142278 ** 1: 0x01
142279 ** 127: 0x7f
142280 ** 128: 0x81 0x00
142281 **
142282 **
142283 **** Document lists ****
142284 ** A doclist (document list) holds a docid-sorted list of hits for a
142285 ** given term. Doclists hold docids and associated token positions.
142286 ** A docid is the unique integer identifier for a single document.
142287 ** A position is the index of a word within the document. The first
142288 ** word of the document has a position of 0.
142289 **
142290 ** FTS3 used to optionally store character offsets using a compile-time
142291 ** option. But that functionality is no longer supported.
142292 **
142293 ** A doclist is stored like this:
142294 **
142295 ** array {
142296 ** varint docid; (delta from previous doclist)
142297 ** array { (position list for column 0)
142298 ** varint position; (2 more than the delta from previous position)
142299 ** }
142300 ** array {
142301 ** varint POS_COLUMN; (marks start of position list for new column)
142302 ** varint column; (index of new column)
142303 ** array {
142304 ** varint position; (2 more than the delta from previous position)
142305 ** }
142306 ** }
142307 ** varint POS_END; (marks end of positions for this document.
142308 ** }
142309 **
142310 ** Here, array { X } means zero or more occurrences of X, adjacent in
142311 ** memory. A "position" is an index of a token in the token stream
142312 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
142313 ** in the same logical place as the position element, and act as sentinals
142314 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
142315 ** The positions numbers are not stored literally but rather as two more
142316 ** than the difference from the prior position, or the just the position plus
142317 ** 2 for the first position. Example:
142318 **
142319 ** label: A B C D E F G H I J K
142320 ** value: 123 5 9 1 1 14 35 0 234 72 0
142321 **
142322 ** The 123 value is the first docid. For column zero in this document
142323 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
142324 ** at D signals the start of a new column; the 1 at E indicates that the
142325 ** new column is column number 1. There are two positions at 12 and 45
142326 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
142327 ** 234 at I is the delta to next docid (357). It has one position 70
142328 ** (72-2) and then terminates with the 0 at K.
142329 **
142330 ** A "position-list" is the list of positions for multiple columns for
142331 ** a single docid. A "column-list" is the set of positions for a single
142332 ** column. Hence, a position-list consists of one or more column-lists,
142333 ** a document record consists of a docid followed by a position-list and
142334 ** a doclist consists of one or more document records.
142335 **
142336 ** A bare doclist omits the position information, becoming an
142337 ** array of varint-encoded docids.
142338 **
142339 **** Segment leaf nodes ****
142340 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
142341 ** nodes are written using LeafWriter, and read using LeafReader (to
142342 ** iterate through a single leaf node's data) and LeavesReader (to
142343 ** iterate through a segment's entire leaf layer). Leaf nodes have
142344 ** the format:
142345 **
142346 ** varint iHeight; (height from leaf level, always 0)
142347 ** varint nTerm; (length of first term)
142348 ** char pTerm[nTerm]; (content of first term)
142349 ** varint nDoclist; (length of term's associated doclist)
142350 ** char pDoclist[nDoclist]; (content of doclist)
142351 ** array {
142352 ** (further terms are delta-encoded)
142353 ** varint nPrefix; (length of prefix shared with previous term)
142354 ** varint nSuffix; (length of unshared suffix)
142355 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
142356 ** varint nDoclist; (length of term's associated doclist)
142357 ** char pDoclist[nDoclist]; (content of doclist)
142358 ** }
142359 **
142360 ** Here, array { X } means zero or more occurrences of X, adjacent in
142361 ** memory.
142362 **
142363 ** Leaf nodes are broken into blocks which are stored contiguously in
142364 ** the %_segments table in sorted order. This means that when the end
142365 ** of a node is reached, the next term is in the node with the next
142366 ** greater node id.
142367 **
142368 ** New data is spilled to a new leaf node when the current node
142369 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
142370 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
142371 ** node (a leaf node with a single term and doclist). The goal of
142372 ** these settings is to pack together groups of small doclists while
142373 ** making it efficient to directly access large doclists. The
142374 ** assumption is that large doclists represent terms which are more
142375 ** likely to be query targets.
142376 **
142377 ** TODO(shess) It may be useful for blocking decisions to be more
142378 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
142379 ** node rather than splitting into 2k and .5k nodes. My intuition is
142380 ** that this might extend through 2x or 4x the pagesize.
142381 **
142382 **
142383 **** Segment interior nodes ****
142384 ** Segment interior nodes store blockids for subtree nodes and terms
142385 ** to describe what data is stored by the each subtree. Interior
142386 ** nodes are written using InteriorWriter, and read using
142387 ** InteriorReader. InteriorWriters are created as needed when
142388 ** SegmentWriter creates new leaf nodes, or when an interior node
142389 ** itself grows too big and must be split. The format of interior
142390 ** nodes:
142391 **
142392 ** varint iHeight; (height from leaf level, always >0)
142393 ** varint iBlockid; (block id of node's leftmost subtree)
142394 ** optional {
142395 ** varint nTerm; (length of first term)
142396 ** char pTerm[nTerm]; (content of first term)
142397 ** array {
142398 ** (further terms are delta-encoded)
142399 ** varint nPrefix; (length of shared prefix with previous term)
142400 ** varint nSuffix; (length of unshared suffix)
142401 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
142402 ** }
142403 ** }
142404 **
142405 ** Here, optional { X } means an optional element, while array { X }
142406 ** means zero or more occurrences of X, adjacent in memory.
142407 **
142408 ** An interior node encodes n terms separating n+1 subtrees. The
142409 ** subtree blocks are contiguous, so only the first subtree's blockid
142410 ** is encoded. The subtree at iBlockid will contain all terms less
142411 ** than the first term encoded (or all terms if no term is encoded).
142412 ** Otherwise, for terms greater than or equal to pTerm[i] but less
142413 ** than pTerm[i+1], the subtree for that term will be rooted at
142414 ** iBlockid+i. Interior nodes only store enough term data to
142415 ** distinguish adjacent children (if the rightmost term of the left
142416 ** child is "something", and the leftmost term of the right child is
142417 ** "wicked", only "w" is stored).
142418 **
142419 ** New data is spilled to a new interior node at the same height when
142420 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
142421 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
142422 ** interior nodes and making the tree too skinny. The interior nodes
142423 ** at a given height are naturally tracked by interior nodes at
142424 ** height+1, and so on.
142425 **
142426 **
142427 **** Segment directory ****
142428 ** The segment directory in table %_segdir stores meta-information for
142429 ** merging and deleting segments, and also the root node of the
142430 ** segment's tree.
142431 **
142432 ** The root node is the top node of the segment's tree after encoding
142433 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
142434 ** This could be either a leaf node or an interior node. If the top
142435 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
142436 ** and a new root interior node is generated (which should always fit
142437 ** within ROOT_MAX because it only needs space for 2 varints, the
142438 ** height and the blockid of the previous root).
142439 **
142440 ** The meta-information in the segment directory is:
142441 ** level - segment level (see below)
142442 ** idx - index within level
142443 ** - (level,idx uniquely identify a segment)
142444 ** start_block - first leaf node
142445 ** leaves_end_block - last leaf node
142446 ** end_block - last block (including interior nodes)
142447 ** root - contents of root node
142448 **
142449 ** If the root node is a leaf node, then start_block,
142450 ** leaves_end_block, and end_block are all 0.
142451 **
142452 **
142453 **** Segment merging ****
142454 ** To amortize update costs, segments are grouped into levels and
142455 ** merged in batches. Each increase in level represents exponentially
142456 ** more documents.
142457 **
142458 ** New documents (actually, document updates) are tokenized and
142459 ** written individually (using LeafWriter) to a level 0 segment, with
142460 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
142461 ** level 0 segments are merged into a single level 1 segment. Level 1
142462 ** is populated like level 0, and eventually MERGE_COUNT level 1
142463 ** segments are merged to a single level 2 segment (representing
142464 ** MERGE_COUNT^2 updates), and so on.
142465 **
142466 ** A segment merge traverses all segments at a given level in
142467 ** parallel, performing a straightforward sorted merge. Since segment
142468 ** leaf nodes are written in to the %_segments table in order, this
142469 ** merge traverses the underlying sqlite disk structures efficiently.
142470 ** After the merge, all segment blocks from the merged level are
142471 ** deleted.
142472 **
142473 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
142474 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
142475 ** very similar performance numbers to 16 on insertion, though they're
142476 ** a tiny bit slower (perhaps due to more overhead in merge-time
142477 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
142478 ** 16, 2 about 66% slower than 16.
142479 **
142480 ** At query time, high MERGE_COUNT increases the number of segments
142481 ** which need to be scanned and merged. For instance, with 100k docs
142482 ** inserted:
142483 **
142484 ** MERGE_COUNT segments
142485 ** 16 25
142486 ** 8 12
142487 ** 4 10
142488 ** 2 6
142489 **
142490 ** This appears to have only a moderate impact on queries for very
142491 ** frequent terms (which are somewhat dominated by segment merge
142492 ** costs), and infrequent and non-existent terms still seem to be fast
142493 ** even with many segments.
142494 **
142495 ** TODO(shess) That said, it would be nice to have a better query-side
142496 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
142497 ** optimizations to things like doclist merging will swing the sweet
142498 ** spot around.
142499 **
142500 **
142501 **
142502 **** Handling of deletions and updates ****
142503 ** Since we're using a segmented structure, with no docid-oriented
142504 ** index into the term index, we clearly cannot simply update the term
142505 ** index when a document is deleted or updated. For deletions, we
142506 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
142507 ** we simply write the new doclist. Segment merges overwrite older
142508 ** data for a particular docid with newer data, so deletes or updates
142509 ** will eventually overtake the earlier data and knock it out. The
142510 ** query logic likewise merges doclists so that newer data knocks out
142511 ** older data.
142512 */
142513 
142514 /************** Include fts3Int.h in the middle of fts3.c ********************/
142515 /************** Begin file fts3Int.h *****************************************/
142516 /*
142517 ** 2009 Nov 12
142518 **
142519 ** The author disclaims copyright to this source code. In place of
142520 ** a legal notice, here is a blessing:
142521 **
142522 ** May you do good and not evil.
142523 ** May you find forgiveness for yourself and forgive others.
142524 ** May you share freely, never taking more than you give.
142525 **
142526 ******************************************************************************
142527 **
142528 */
142529 #ifndef _FTSINT_H
142530 #define _FTSINT_H
142531 
142532 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
142533 # define NDEBUG 1
142534 #endif
142535 
142536 /* FTS3/FTS4 require virtual tables */
142537 #ifdef SQLITE_OMIT_VIRTUALTABLE
142538 # undef SQLITE_ENABLE_FTS3
142539 # undef SQLITE_ENABLE_FTS4
142540 #endif
142541 
142542 /*
142543 ** FTS4 is really an extension for FTS3. It is enabled using the
142544 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
142545 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
142546 */
142547 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
142548 # define SQLITE_ENABLE_FTS3
142549 #endif
142550 
142551 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142552 
142553 /* If not building as part of the core, include sqlite3ext.h. */
142554 #ifndef SQLITE_CORE
142555 /* # include "sqlite3ext.h" */
142556 SQLITE_EXTENSION_INIT3
142557 #endif
142558 
142559 /* #include "sqlite3.h" */
142560 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
142561 /************** Begin file fts3_tokenizer.h **********************************/
142562 /*
142563 ** 2006 July 10
142564 **
142565 ** The author disclaims copyright to this source code.
142566 **
142567 *************************************************************************
142568 ** Defines the interface to tokenizers used by fulltext-search. There
142569 ** are three basic components:
142570 **
142571 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
142572 ** interface functions. This is essentially the class structure for
142573 ** tokenizers.
142574 **
142575 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
142576 ** including customization information defined at creation time.
142577 **
142578 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
142579 ** tokens from a particular input.
142580 */
142581 #ifndef _FTS3_TOKENIZER_H_
142582 #define _FTS3_TOKENIZER_H_
142583 
142584 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
142585 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
142586 ** we will need a way to register the API consistently.
142587 */
142588 /* #include "sqlite3.h" */
142589 
142590 /*
142591 ** Structures used by the tokenizer interface. When a new tokenizer
142592 ** implementation is registered, the caller provides a pointer to
142593 ** an sqlite3_tokenizer_module containing pointers to the callback
142594 ** functions that make up an implementation.
142595 **
142596 ** When an fts3 table is created, it passes any arguments passed to
142597 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
142598 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
142599 ** implementation. The xCreate() function in turn returns an
142600 ** sqlite3_tokenizer structure representing the specific tokenizer to
142601 ** be used for the fts3 table (customized by the tokenizer clause arguments).
142602 **
142603 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
142604 ** method is called. It returns an sqlite3_tokenizer_cursor object
142605 ** that may be used to tokenize a specific input buffer based on
142606 ** the tokenization rules supplied by a specific sqlite3_tokenizer
142607 ** object.
142608 */
142609 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
142610 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
142611 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
142612 
142613 struct sqlite3_tokenizer_module {
142614 
142615  /*
142616  ** Structure version. Should always be set to 0 or 1.
142617  */
142618  int iVersion;
142619 
142620  /*
142621  ** Create a new tokenizer. The values in the argv[] array are the
142622  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
142623  ** TABLE statement that created the fts3 table. For example, if
142624  ** the following SQL is executed:
142625  **
142626  ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
142627  **
142628  ** then argc is set to 2, and the argv[] array contains pointers
142629  ** to the strings "arg1" and "arg2".
142630  **
142631  ** This method should return either SQLITE_OK (0), or an SQLite error
142632  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
142633  ** to point at the newly created tokenizer structure. The generic
142634  ** sqlite3_tokenizer.pModule variable should not be initialized by
142635  ** this callback. The caller will do so.
142636  */
142637  int (*xCreate)(
142638  int argc, /* Size of argv array */
142639  const char *const*argv, /* Tokenizer argument strings */
142640  sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
142641  );
142642 
142643  /*
142644  ** Destroy an existing tokenizer. The fts3 module calls this method
142645  ** exactly once for each successful call to xCreate().
142646  */
142647  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
142648 
142649  /*
142650  ** Create a tokenizer cursor to tokenize an input buffer. The caller
142651  ** is responsible for ensuring that the input buffer remains valid
142652  ** until the cursor is closed (using the xClose() method).
142653  */
142654  int (*xOpen)(
142655  sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
142656  const char *pInput, int nBytes, /* Input buffer */
142657  sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
142658  );
142659 
142660  /*
142661  ** Destroy an existing tokenizer cursor. The fts3 module calls this
142662  ** method exactly once for each successful call to xOpen().
142663  */
142664  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
142665 
142666  /*
142667  ** Retrieve the next token from the tokenizer cursor pCursor. This
142668  ** method should either return SQLITE_OK and set the values of the
142669  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
142670  ** the end of the buffer has been reached, or an SQLite error code.
142671  **
142672  ** *ppToken should be set to point at a buffer containing the
142673  ** normalized version of the token (i.e. after any case-folding and/or
142674  ** stemming has been performed). *pnBytes should be set to the length
142675  ** of this buffer in bytes. The input text that generated the token is
142676  ** identified by the byte offsets returned in *piStartOffset and
142677  ** *piEndOffset. *piStartOffset should be set to the index of the first
142678  ** byte of the token in the input buffer. *piEndOffset should be set
142679  ** to the index of the first byte just past the end of the token in
142680  ** the input buffer.
142681  **
142682  ** The buffer *ppToken is set to point at is managed by the tokenizer
142683  ** implementation. It is only required to be valid until the next call
142684  ** to xNext() or xClose().
142685  */
142686  /* TODO(shess) current implementation requires pInput to be
142687  ** nul-terminated. This should either be fixed, or pInput/nBytes
142688  ** should be converted to zInput.
142689  */
142690  int (*xNext)(
142691  sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
142692  const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
142693  int *piStartOffset, /* OUT: Byte offset of token in input buffer */
142694  int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
142695  int *piPosition /* OUT: Number of tokens returned before this one */
142696  );
142697 
142698  /***********************************************************************
142699  ** Methods below this point are only available if iVersion>=1.
142700  */
142701 
142702  /*
142703  ** Configure the language id of a tokenizer cursor.
142704  */
142705  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
142706 };
142707 
142708 struct sqlite3_tokenizer {
142709  const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
142710  /* Tokenizer implementations will typically add additional fields */
142711 };
142712 
142713 struct sqlite3_tokenizer_cursor {
142714  sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
142715  /* Tokenizer implementations will typically add additional fields */
142716 };
142717 
142718 int fts3_global_term_cnt(int iTerm, int iCol);
142719 int fts3_term_cnt(int iTerm, int iCol);
142720 
142721 
142722 #endif /* _FTS3_TOKENIZER_H_ */
142723 
142724 /************** End of fts3_tokenizer.h **************************************/
142725 /************** Continuing where we left off in fts3Int.h ********************/
142726 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
142727 /************** Begin file fts3_hash.h ***************************************/
142728 /*
142729 ** 2001 September 22
142730 **
142731 ** The author disclaims copyright to this source code. In place of
142732 ** a legal notice, here is a blessing:
142733 **
142734 ** May you do good and not evil.
142735 ** May you find forgiveness for yourself and forgive others.
142736 ** May you share freely, never taking more than you give.
142737 **
142738 *************************************************************************
142739 ** This is the header file for the generic hash-table implementation
142740 ** used in SQLite. We've modified it slightly to serve as a standalone
142741 ** hash table implementation for the full-text indexing module.
142742 **
142743 */
142744 #ifndef _FTS3_HASH_H_
142745 #define _FTS3_HASH_H_
142746 
142747 /* Forward declarations of structures. */
142748 typedef struct Fts3Hash Fts3Hash;
142749 typedef struct Fts3HashElem Fts3HashElem;
142750 
142751 /* A complete hash table is an instance of the following structure.
142752 ** The internals of this structure are intended to be opaque -- client
142753 ** code should not attempt to access or modify the fields of this structure
142754 ** directly. Change this structure only by using the routines below.
142755 ** However, many of the "procedures" and "functions" for modifying and
142756 ** accessing this structure are really macros, so we can't really make
142757 ** this structure opaque.
142758 */
142759 struct Fts3Hash {
142760  char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
142761  char copyKey; /* True if copy of key made on insert */
142762  int count; /* Number of entries in this table */
142763  Fts3HashElem *first; /* The first element of the array */
142764  int htsize; /* Number of buckets in the hash table */
142765  struct _fts3ht { /* the hash table */
142766  int count; /* Number of entries with this hash */
142767  Fts3HashElem *chain; /* Pointer to first entry with this hash */
142768  } *ht;
142769 };
142770 
142771 /* Each element in the hash table is an instance of the following
142772 ** structure. All elements are stored on a single doubly-linked list.
142773 **
142774 ** Again, this structure is intended to be opaque, but it can't really
142775 ** be opaque because it is used by macros.
142776 */
142777 struct Fts3HashElem {
142778  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
142779  void *data; /* Data associated with this element */
142780  void *pKey; int nKey; /* Key associated with this element */
142781 };
142782 
142783 /*
142784 ** There are 2 different modes of operation for a hash table:
142785 **
142786 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
142787 ** (including the null-terminator, if any). Case
142788 ** is respected in comparisons.
142789 **
142790 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
142791 ** memcmp() is used to compare keys.
142792 **
142793 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
142794 */
142795 #define FTS3_HASH_STRING 1
142796 #define FTS3_HASH_BINARY 2
142797 
142798 /*
142799 ** Access routines. To delete, insert a NULL pointer.
142800 */
142801 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
142802 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
142803 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
142804 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
142805 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
142806 
142807 /*
142808 ** Shorthand for the functions above
142809 */
142810 #define fts3HashInit sqlite3Fts3HashInit
142811 #define fts3HashInsert sqlite3Fts3HashInsert
142812 #define fts3HashFind sqlite3Fts3HashFind
142813 #define fts3HashClear sqlite3Fts3HashClear
142814 #define fts3HashFindElem sqlite3Fts3HashFindElem
142815 
142816 /*
142817 ** Macros for looping over all elements of a hash table. The idiom is
142818 ** like this:
142819 **
142820 ** Fts3Hash h;
142821 ** Fts3HashElem *p;
142822 ** ...
142823 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
142824 ** SomeStructure *pData = fts3HashData(p);
142825 ** // do something with pData
142826 ** }
142827 */
142828 #define fts3HashFirst(H) ((H)->first)
142829 #define fts3HashNext(E) ((E)->next)
142830 #define fts3HashData(E) ((E)->data)
142831 #define fts3HashKey(E) ((E)->pKey)
142832 #define fts3HashKeysize(E) ((E)->nKey)
142833 
142834 /*
142835 ** Number of entries in a hash table
142836 */
142837 #define fts3HashCount(H) ((H)->count)
142838 
142839 #endif /* _FTS3_HASH_H_ */
142840 
142841 /************** End of fts3_hash.h *******************************************/
142842 /************** Continuing where we left off in fts3Int.h ********************/
142843 
142844 /*
142845 ** This constant determines the maximum depth of an FTS expression tree
142846 ** that the library will create and use. FTS uses recursion to perform
142847 ** various operations on the query tree, so the disadvantage of a large
142848 ** limit is that it may allow very large queries to use large amounts
142849 ** of stack space (perhaps causing a stack overflow).
142850 */
142851 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
142852 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
142853 #endif
142854 
142855 
142856 /*
142857 ** This constant controls how often segments are merged. Once there are
142858 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
142859 ** segment of level N+1.
142860 */
142861 #define FTS3_MERGE_COUNT 16
142862 
142863 /*
142864 ** This is the maximum amount of data (in bytes) to store in the
142865 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
142866 ** populated as documents are inserted/updated/deleted in a transaction
142867 ** and used to create a new segment when the transaction is committed.
142868 ** However if this limit is reached midway through a transaction, a new
142869 ** segment is created and the hash table cleared immediately.
142870 */
142871 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
142872 
142873 /*
142874 ** Macro to return the number of elements in an array. SQLite has a
142875 ** similar macro called ArraySize(). Use a different name to avoid
142876 ** a collision when building an amalgamation with built-in FTS3.
142877 */
142878 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
142879 
142880 
142881 #ifndef MIN
142882 # define MIN(x,y) ((x)<(y)?(x):(y))
142883 #endif
142884 #ifndef MAX
142885 # define MAX(x,y) ((x)>(y)?(x):(y))
142886 #endif
142887 
142888 /*
142889 ** Maximum length of a varint encoded integer. The varint format is different
142890 ** from that used by SQLite, so the maximum length is 10, not 9.
142891 */
142892 #define FTS3_VARINT_MAX 10
142893 
142894 /*
142895 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
142896 ** in the document set and zero or more prefix indexes. All indexes are stored
142897 ** as one or more b+-trees in the %_segments and %_segdir tables.
142898 **
142899 ** It is possible to determine which index a b+-tree belongs to based on the
142900 ** value stored in the "%_segdir.level" column. Given this value L, the index
142901 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
142902 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
142903 ** between 1024 and 2047 to index 1, and so on.
142904 **
142905 ** It is considered impossible for an index to use more than 1024 levels. In
142906 ** theory though this may happen, but only after at least
142907 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
142908 */
142909 #define FTS3_SEGDIR_MAXLEVEL 1024
142910 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
142911 
142912 /*
142913 ** The testcase() macro is only used by the amalgamation. If undefined,
142914 ** make it a no-op.
142915 */
142916 #ifndef testcase
142917 # define testcase(X)
142918 #endif
142919 
142920 /*
142921 ** Terminator values for position-lists and column-lists.
142922 */
142923 #define POS_COLUMN (1) /* Column-list terminator */
142924 #define POS_END (0) /* Position-list terminator */
142925 
142926 /*
142927 ** This section provides definitions to allow the
142928 ** FTS3 extension to be compiled outside of the
142929 ** amalgamation.
142930 */
142931 #ifndef SQLITE_AMALGAMATION
142932 /*
142933 ** Macros indicating that conditional expressions are always true or
142934 ** false.
142935 */
142936 #ifdef SQLITE_COVERAGE_TEST
142937 # define ALWAYS(x) (1)
142938 # define NEVER(X) (0)
142939 #elif defined(SQLITE_DEBUG)
142940 # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
142941 # define NEVER(x) sqlite3Fts3Never((x)!=0)
142942 SQLITE_PRIVATE int sqlite3Fts3Always(int b);
142943 SQLITE_PRIVATE int sqlite3Fts3Never(int b);
142944 #else
142945 # define ALWAYS(x) (x)
142946 # define NEVER(x) (x)
142947 #endif
142948 
142949 /*
142950 ** Internal types used by SQLite.
142951 */
142952 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
142953 typedef short int i16; /* 2-byte (or larger) signed integer */
142954 typedef unsigned int u32; /* 4-byte unsigned integer */
142955 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
142956 typedef sqlite3_int64 i64; /* 8-byte signed integer */
142957 
142958 /*
142959 ** Macro used to suppress compiler warnings for unused parameters.
142960 */
142961 #define UNUSED_PARAMETER(x) (void)(x)
142962 
142963 /*
142964 ** Activate assert() only if SQLITE_TEST is enabled.
142965 */
142966 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
142967 # define NDEBUG 1
142968 #endif
142969 
142970 /*
142971 ** The TESTONLY macro is used to enclose variable declarations or
142972 ** other bits of code that are needed to support the arguments
142973 ** within testcase() and assert() macros.
142974 */
142975 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
142976 # define TESTONLY(X) X
142977 #else
142978 # define TESTONLY(X)
142979 #endif
142980 
142981 #endif /* SQLITE_AMALGAMATION */
142982 
142983 #ifdef SQLITE_DEBUG
142984 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
142985 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
142986 #else
142987 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
142988 #endif
142989 
142990 typedef struct Fts3Table Fts3Table;
142991 typedef struct Fts3Cursor Fts3Cursor;
142992 typedef struct Fts3Expr Fts3Expr;
142993 typedef struct Fts3Phrase Fts3Phrase;
142994 typedef struct Fts3PhraseToken Fts3PhraseToken;
142995 
142996 typedef struct Fts3Doclist Fts3Doclist;
142997 typedef struct Fts3SegFilter Fts3SegFilter;
142998 typedef struct Fts3DeferredToken Fts3DeferredToken;
142999 typedef struct Fts3SegReader Fts3SegReader;
143000 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
143001 
143002 typedef struct MatchinfoBuffer MatchinfoBuffer;
143003 
143004 /*
143005 ** A connection to a fulltext index is an instance of the following
143006 ** structure. The xCreate and xConnect methods create an instance
143007 ** of this structure and xDestroy and xDisconnect free that instance.
143008 ** All other methods receive a pointer to the structure as one of their
143009 ** arguments.
143010 */
143011 struct Fts3Table {
143012  sqlite3_vtab base; /* Base class used by SQLite core */
143013  sqlite3 *db; /* The database connection */
143014  const char *zDb; /* logical database name */
143015  const char *zName; /* virtual table name */
143016  int nColumn; /* number of named columns in virtual table */
143017  char **azColumn; /* column names. malloced */
143018  u8 *abNotindexed; /* True for 'notindexed' columns */
143019  sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
143020  char *zContentTbl; /* content=xxx option, or NULL */
143021  char *zLanguageid; /* languageid=xxx option, or NULL */
143022  int nAutoincrmerge; /* Value configured by 'automerge' */
143023  u32 nLeafAdd; /* Number of leaf blocks added this trans */
143024 
143025  /* Precompiled statements used by the implementation. Each of these
143026  ** statements is run and reset within a single virtual table API call.
143027  */
143028  sqlite3_stmt *aStmt[40];
143029 
143030  char *zReadExprlist;
143031  char *zWriteExprlist;
143032 
143033  int nNodeSize; /* Soft limit for node size */
143034  u8 bFts4; /* True for FTS4, false for FTS3 */
143035  u8 bHasStat; /* True if %_stat table exists (2==unknown) */
143036  u8 bHasDocsize; /* True if %_docsize table exists */
143037  u8 bDescIdx; /* True if doclists are in reverse order */
143038  u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
143039  int nPgsz; /* Page size for host database */
143040  char *zSegmentsTbl; /* Name of %_segments table */
143041  sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
143042 
143043  /*
143044  ** The following array of hash tables is used to buffer pending index
143045  ** updates during transactions. All pending updates buffered at any one
143046  ** time must share a common language-id (see the FTS4 langid= feature).
143047  ** The current language id is stored in variable iPrevLangid.
143048  **
143049  ** A single FTS4 table may have multiple full-text indexes. For each index
143050  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
143051  ** terms that appear in the document set. Each subsequent index in aIndex[]
143052  ** is an index of prefixes of a specific length.
143053  **
143054  ** Variable nPendingData contains an estimate the memory consumed by the
143055  ** pending data structures, including hash table overhead, but not including
143056  ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
143057  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
143058  ** recently inserted record.
143059  */
143060  int nIndex; /* Size of aIndex[] */
143061  struct Fts3Index {
143062  int nPrefix; /* Prefix length (0 for main terms index) */
143063  Fts3Hash hPending; /* Pending terms table for this index */
143064  } *aIndex;
143065  int nMaxPendingData; /* Max pending data before flush to disk */
143066  int nPendingData; /* Current bytes of pending data */
143067  sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
143068  int iPrevLangid; /* Langid of recently inserted document */
143069  int bPrevDelete; /* True if last operation was a delete */
143070 
143071 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
143072  /* State variables used for validating that the transaction control
143073  ** methods of the virtual table are called at appropriate times. These
143074  ** values do not contribute to FTS functionality; they are used for
143075  ** verifying the operation of the SQLite core.
143076  */
143077  int inTransaction; /* True after xBegin but before xCommit/xRollback */
143078  int mxSavepoint; /* Largest valid xSavepoint integer */
143079 #endif
143080 
143081 #ifdef SQLITE_TEST
143082  /* True to disable the incremental doclist optimization. This is controled
143083  ** by special insert command 'test-no-incr-doclist'. */
143084  int bNoIncrDoclist;
143085 #endif
143086 };
143087 
143088 /*
143089 ** When the core wants to read from the virtual table, it creates a
143090 ** virtual table cursor (an instance of the following structure) using
143091 ** the xOpen method. Cursors are destroyed using the xClose method.
143092 */
143093 struct Fts3Cursor {
143094  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
143095  i16 eSearch; /* Search strategy (see below) */
143096  u8 isEof; /* True if at End Of Results */
143097  u8 isRequireSeek; /* True if must seek pStmt to %_content row */
143098  sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
143099  Fts3Expr *pExpr; /* Parsed MATCH query string */
143100  int iLangid; /* Language being queried for */
143101  int nPhrase; /* Number of matchable phrases in query */
143102  Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
143103  sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
143104  char *pNextId; /* Pointer into the body of aDoclist */
143105  char *aDoclist; /* List of docids for full-text queries */
143106  int nDoclist; /* Size of buffer at aDoclist */
143107  u8 bDesc; /* True to sort in descending order */
143108  int eEvalmode; /* An FTS3_EVAL_XX constant */
143109  int nRowAvg; /* Average size of database rows, in pages */
143110  sqlite3_int64 nDoc; /* Documents in table */
143111  i64 iMinDocid; /* Minimum docid to return */
143112  i64 iMaxDocid; /* Maximum docid to return */
143113  int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
143114  MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
143115 };
143116 
143117 #define FTS3_EVAL_FILTER 0
143118 #define FTS3_EVAL_NEXT 1
143119 #define FTS3_EVAL_MATCHINFO 2
143120 
143121 /*
143122 ** The Fts3Cursor.eSearch member is always set to one of the following.
143123 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
143124 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
143125 ** of the column to be searched. For example, in
143126 **
143127 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
143128 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
143129 **
143130 ** Because the LHS of the MATCH operator is 2nd column "b",
143131 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
143132 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
143133 ** indicating that all columns should be searched,
143134 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
143135 */
143136 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
143137 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
143138 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
143139 
143140 /*
143141 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
143142 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
143143 ** above. The upper 16-bits contain a combination of the following
143144 ** bits, used to describe extra constraints on full-text searches.
143145 */
143146 #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
143147 #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
143148 #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
143149 
143150 struct Fts3Doclist {
143151  char *aAll; /* Array containing doclist (or NULL) */
143152  int nAll; /* Size of a[] in bytes */
143153  char *pNextDocid; /* Pointer to next docid */
143154 
143155  sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
143156  int bFreeList; /* True if pList should be sqlite3_free()d */
143157  char *pList; /* Pointer to position list following iDocid */
143158  int nList; /* Length of position list */
143159 };
143160 
143161 /*
143162 ** A "phrase" is a sequence of one or more tokens that must match in
143163 ** sequence. A single token is the base case and the most common case.
143164 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
143165 ** nToken will be the number of tokens in the string.
143166 */
143167 struct Fts3PhraseToken {
143168  char *z; /* Text of the token */
143169  int n; /* Number of bytes in buffer z */
143170  int isPrefix; /* True if token ends with a "*" character */
143171  int bFirst; /* True if token must appear at position 0 */
143172 
143173  /* Variables above this point are populated when the expression is
143174  ** parsed (by code in fts3_expr.c). Below this point the variables are
143175  ** used when evaluating the expression. */
143176  Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
143177  Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
143178 };
143179 
143180 struct Fts3Phrase {
143181  /* Cache of doclist for this phrase. */
143182  Fts3Doclist doclist;
143183  int bIncr; /* True if doclist is loaded incrementally */
143184  int iDoclistToken;
143185 
143186  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
143187  ** OR condition. */
143188  char *pOrPoslist;
143189  i64 iOrDocid;
143190 
143191  /* Variables below this point are populated by fts3_expr.c when parsing
143192  ** a MATCH expression. Everything above is part of the evaluation phase.
143193  */
143194  int nToken; /* Number of tokens in the phrase */
143195  int iColumn; /* Index of column this phrase must match */
143196  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
143197 };
143198 
143199 /*
143200 ** A tree of these objects forms the RHS of a MATCH operator.
143201 **
143202 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
143203 ** points to a malloced buffer, size nDoclist bytes, containing the results
143204 ** of this phrase query in FTS3 doclist format. As usual, the initial
143205 ** "Length" field found in doclists stored on disk is omitted from this
143206 ** buffer.
143207 **
143208 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
143209 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
143210 ** where nCol is the number of columns in the queried FTS table. The array
143211 ** is populated as follows:
143212 **
143213 ** aMI[iCol*3 + 0] = Undefined
143214 ** aMI[iCol*3 + 1] = Number of occurrences
143215 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
143216 **
143217 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
143218 ** when the expression node is.
143219 */
143220 struct Fts3Expr {
143221  int eType; /* One of the FTSQUERY_XXX values defined below */
143222  int nNear; /* Valid if eType==FTSQUERY_NEAR */
143223  Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
143224  Fts3Expr *pLeft; /* Left operand */
143225  Fts3Expr *pRight; /* Right operand */
143226  Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
143227 
143228  /* The following are used by the fts3_eval.c module. */
143229  sqlite3_int64 iDocid; /* Current docid */
143230  u8 bEof; /* True this expression is at EOF already */
143231  u8 bStart; /* True if iDocid is valid */
143232  u8 bDeferred; /* True if this expression is entirely deferred */
143233 
143234  /* The following are used by the fts3_snippet.c module. */
143235  int iPhrase; /* Index of this phrase in matchinfo() results */
143236  u32 *aMI; /* See above */
143237 };
143238 
143239 /*
143240 ** Candidate values for Fts3Query.eType. Note that the order of the first
143241 ** four values is in order of precedence when parsing expressions. For
143242 ** example, the following:
143243 **
143244 ** "a OR b AND c NOT d NEAR e"
143245 **
143246 ** is equivalent to:
143247 **
143248 ** "a OR (b AND (c NOT (d NEAR e)))"
143249 */
143250 #define FTSQUERY_NEAR 1
143251 #define FTSQUERY_NOT 2
143252 #define FTSQUERY_AND 3
143253 #define FTSQUERY_OR 4
143254 #define FTSQUERY_PHRASE 5
143255 
143256 
143257 /* fts3_write.c */
143258 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
143259 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
143260 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
143261 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
143262 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
143263  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
143264 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
143265  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
143266 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
143267 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
143268 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
143269 
143270 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
143271 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
143272 
143273 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
143274 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
143275 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
143276 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
143277 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
143278 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
143279 #else
143280 # define sqlite3Fts3FreeDeferredTokens(x)
143281 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
143282 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
143283 # define sqlite3Fts3FreeDeferredDoclists(x)
143284 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
143285 #endif
143286 
143287 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
143288 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
143289 
143290 /* Special values interpreted by sqlite3SegReaderCursor() */
143291 #define FTS3_SEGCURSOR_PENDING -1
143292 #define FTS3_SEGCURSOR_ALL -2
143293 
143294 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
143295 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
143296 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
143297 
143298 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
143299  int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
143300 
143301 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
143302 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
143303 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
143304 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
143305 #define FTS3_SEGMENT_PREFIX 0x00000008
143306 #define FTS3_SEGMENT_SCAN 0x00000010
143307 #define FTS3_SEGMENT_FIRST 0x00000020
143308 
143309 /* Type passed as 4th argument to SegmentReaderIterate() */
143310 struct Fts3SegFilter {
143311  const char *zTerm;
143312  int nTerm;
143313  int iCol;
143314  int flags;
143315 };
143316 
143317 struct Fts3MultiSegReader {
143318  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
143319  Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
143320  int nSegment; /* Size of apSegment array */
143321  int nAdvance; /* How many seg-readers to advance */
143322  Fts3SegFilter *pFilter; /* Pointer to filter object */
143323  char *aBuffer; /* Buffer to merge doclists in */
143324  int nBuffer; /* Allocated size of aBuffer[] in bytes */
143325 
143326  int iColFilter; /* If >=0, filter for this column */
143327  int bRestart;
143328 
143329  /* Used by fts3.c only. */
143330  int nCost; /* Cost of running iterator */
143331  int bLookup; /* True if a lookup of a single entry. */
143332 
143333  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
143334  char *zTerm; /* Pointer to term buffer */
143335  int nTerm; /* Size of zTerm in bytes */
143336  char *aDoclist; /* Pointer to doclist buffer */
143337  int nDoclist; /* Size of aDoclist[] in bytes */
143338 };
143339 
143340 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
143341 
143342 #define fts3GetVarint32(p, piVal) ( \
143343  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
143344 )
143345 
143346 /* fts3.c */
143347 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
143348 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
143349 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
143350 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
143351 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
143352 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
143353 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
143354 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
143355 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
143356 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
143357 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
143358 
143359 /* fts3_tokenizer.c */
143360 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
143361 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
143362 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
143363  sqlite3_tokenizer **, char **
143364 );
143365 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
143366 
143367 /* fts3_snippet.c */
143368 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
143369 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
143370  const char *, const char *, int, int
143371 );
143372 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
143373 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
143374 
143375 /* fts3_expr.c */
143376 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
143377  char **, int, int, int, const char *, int, Fts3Expr **, char **
143378 );
143379 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
143380 #ifdef SQLITE_TEST
143381 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
143382 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
143383 #endif
143384 
143385 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
143386  sqlite3_tokenizer_cursor **
143387 );
143388 
143389 /* fts3_aux.c */
143390 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
143391 
143392 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
143393 
143394 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
143395  Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
143396 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
143397  Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
143398 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
143399 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
143400 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
143401 
143402 /* fts3_tokenize_vtab.c */
143403 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
143404 
143405 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
143406 #ifndef SQLITE_DISABLE_FTS3_UNICODE
143407 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
143408 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
143409 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
143410 #endif
143411 
143412 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
143413 #endif /* _FTSINT_H */
143414 
143415 /************** End of fts3Int.h *********************************************/
143416 /************** Continuing where we left off in fts3.c ***********************/
143417 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
143418 
143419 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
143420 # define SQLITE_CORE 1
143421 #endif
143422 
143423 /* #include <assert.h> */
143424 /* #include <stdlib.h> */
143425 /* #include <stddef.h> */
143426 /* #include <stdio.h> */
143427 /* #include <string.h> */
143428 /* #include <stdarg.h> */
143429 
143430 /* #include "fts3.h" */
143431 #ifndef SQLITE_CORE
143432 /* # include "sqlite3ext.h" */
143433  SQLITE_EXTENSION_INIT1
143434 #endif
143435 
143436 static int fts3EvalNext(Fts3Cursor *pCsr);
143437 static int fts3EvalStart(Fts3Cursor *pCsr);
143438 static int fts3TermSegReaderCursor(
143439  Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
143440 
143441 #ifndef SQLITE_AMALGAMATION
143442 # if defined(SQLITE_DEBUG)
143443 SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
143444 SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
143445 # endif
143446 #endif
143447 
143448 /*
143449 ** Write a 64-bit variable-length integer to memory starting at p[0].
143450 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
143451 ** The number of bytes written is returned.
143452 */
143453 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
143454  unsigned char *q = (unsigned char *) p;
143455  sqlite_uint64 vu = v;
143456  do{
143457  *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
143458  vu >>= 7;
143459  }while( vu!=0 );
143460  q[-1] &= 0x7f; /* turn off high bit in final byte */
143461  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
143462  return (int) (q - (unsigned char *)p);
143463 }
143464 
143465 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
143466  v = (v & mask1) | ( (*ptr++) << shift ); \
143467  if( (v & mask2)==0 ){ var = v; return ret; }
143468 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
143469  v = (*ptr++); \
143470  if( (v & mask2)==0 ){ var = v; return ret; }
143471 
143472 /*
143473 ** Read a 64-bit variable-length integer from memory starting at p[0].
143474 ** Return the number of bytes read, or 0 on error.
143475 ** The value is stored in *v.
143476 */
143477 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
143478  const char *pStart = p;
143479  u32 a;
143480  u64 b;
143481  int shift;
143482 
143483  GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
143484  GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
143485  GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
143486  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
143487  b = (a & 0x0FFFFFFF );
143488 
143489  for(shift=28; shift<=63; shift+=7){
143490  u64 c = *p++;
143491  b += (c&0x7F) << shift;
143492  if( (c & 0x80)==0 ) break;
143493  }
143494  *v = b;
143495  return (int)(p - pStart);
143496 }
143497 
143498 /*
143499 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
143500 ** 32-bit integer before it is returned.
143501 */
143502 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
143503  u32 a;
143504 
143505 #ifndef fts3GetVarint32
143506  GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
143507 #else
143508  a = (*p++);
143509  assert( a & 0x80 );
143510 #endif
143511 
143512  GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
143513  GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
143514  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
143515  a = (a & 0x0FFFFFFF );
143516  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
143517  return 5;
143518 }
143519 
143520 /*
143521 ** Return the number of bytes required to encode v as a varint
143522 */
143523 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
143524  int i = 0;
143525  do{
143526  i++;
143527  v >>= 7;
143528  }while( v!=0 );
143529  return i;
143530 }
143531 
143532 /*
143533 ** Convert an SQL-style quoted string into a normal string by removing
143534 ** the quote characters. The conversion is done in-place. If the
143535 ** input does not begin with a quote character, then this routine
143536 ** is a no-op.
143537 **
143538 ** Examples:
143539 **
143540 ** "abc" becomes abc
143541 ** 'xyz' becomes xyz
143542 ** [pqr] becomes pqr
143543 ** `mno` becomes mno
143544 **
143545 */
143546 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
143547  char quote; /* Quote character (if any ) */
143548 
143549  quote = z[0];
143550  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
143551  int iIn = 1; /* Index of next byte to read from input */
143552  int iOut = 0; /* Index of next byte to write to output */
143553 
143554  /* If the first byte was a '[', then the close-quote character is a ']' */
143555  if( quote=='[' ) quote = ']';
143556 
143557  while( z[iIn] ){
143558  if( z[iIn]==quote ){
143559  if( z[iIn+1]!=quote ) break;
143560  z[iOut++] = quote;
143561  iIn += 2;
143562  }else{
143563  z[iOut++] = z[iIn++];
143564  }
143565  }
143566  z[iOut] = '\0';
143567  }
143568 }
143569 
143570 /*
143571 ** Read a single varint from the doclist at *pp and advance *pp to point
143572 ** to the first byte past the end of the varint. Add the value of the varint
143573 ** to *pVal.
143574 */
143575 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
143576  sqlite3_int64 iVal;
143577  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
143578  *pVal += iVal;
143579 }
143580 
143581 /*
143582 ** When this function is called, *pp points to the first byte following a
143583 ** varint that is part of a doclist (or position-list, or any other list
143584 ** of varints). This function moves *pp to point to the start of that varint,
143585 ** and sets *pVal by the varint value.
143586 **
143587 ** Argument pStart points to the first byte of the doclist that the
143588 ** varint is part of.
143589 */
143590 static void fts3GetReverseVarint(
143591  char **pp,
143592  char *pStart,
143593  sqlite3_int64 *pVal
143594 ){
143595  sqlite3_int64 iVal;
143596  char *p;
143597 
143598  /* Pointer p now points at the first byte past the varint we are
143599  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
143600  ** clear on character p[-1]. */
143601  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
143602  p++;
143603  *pp = p;
143604 
143605  sqlite3Fts3GetVarint(p, &iVal);
143606  *pVal = iVal;
143607 }
143608 
143609 /*
143610 ** The xDisconnect() virtual table method.
143611 */
143612 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
143613  Fts3Table *p = (Fts3Table *)pVtab;
143614  int i;
143615 
143616  assert( p->nPendingData==0 );
143617  assert( p->pSegments==0 );
143618 
143619  /* Free any prepared statements held */
143620  for(i=0; i<SizeofArray(p->aStmt); i++){
143621  sqlite3_finalize(p->aStmt[i]);
143622  }
143623  sqlite3_free(p->zSegmentsTbl);
143624  sqlite3_free(p->zReadExprlist);
143625  sqlite3_free(p->zWriteExprlist);
143626  sqlite3_free(p->zContentTbl);
143627  sqlite3_free(p->zLanguageid);
143628 
143629  /* Invoke the tokenizer destructor to free the tokenizer. */
143630  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
143631 
143632  sqlite3_free(p);
143633  return SQLITE_OK;
143634 }
143635 
143636 /*
143637 ** Write an error message into *pzErr
143638 */
143639 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
143640  va_list ap;
143641  sqlite3_free(*pzErr);
143642  va_start(ap, zFormat);
143643  *pzErr = sqlite3_vmprintf(zFormat, ap);
143644  va_end(ap);
143645 }
143646 
143647 /*
143648 ** Construct one or more SQL statements from the format string given
143649 ** and then evaluate those statements. The success code is written
143650 ** into *pRc.
143651 **
143652 ** If *pRc is initially non-zero then this routine is a no-op.
143653 */
143654 static void fts3DbExec(
143655  int *pRc, /* Success code */
143656  sqlite3 *db, /* Database in which to run SQL */
143657  const char *zFormat, /* Format string for SQL */
143658  ... /* Arguments to the format string */
143659 ){
143660  va_list ap;
143661  char *zSql;
143662  if( *pRc ) return;
143663  va_start(ap, zFormat);
143664  zSql = sqlite3_vmprintf(zFormat, ap);
143665  va_end(ap);
143666  if( zSql==0 ){
143667  *pRc = SQLITE_NOMEM;
143668  }else{
143669  *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
143670  sqlite3_free(zSql);
143671  }
143672 }
143673 
143674 /*
143675 ** The xDestroy() virtual table method.
143676 */
143677 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
143678  Fts3Table *p = (Fts3Table *)pVtab;
143679  int rc = SQLITE_OK; /* Return code */
143680  const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
143681  sqlite3 *db = p->db; /* Database handle */
143682 
143683  /* Drop the shadow tables */
143684  if( p->zContentTbl==0 ){
143685  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
143686  }
143687  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
143688  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
143689  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
143690  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
143691 
143692  /* If everything has worked, invoke fts3DisconnectMethod() to free the
143693  ** memory associated with the Fts3Table structure and return SQLITE_OK.
143694  ** Otherwise, return an SQLite error code.
143695  */
143696  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
143697 }
143698 
143699 
143700 /*
143701 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
143702 ** passed as the first argument. This is done as part of the xConnect()
143703 ** and xCreate() methods.
143704 **
143705 ** If *pRc is non-zero when this function is called, it is a no-op.
143706 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
143707 ** before returning.
143708 */
143709 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
143710  if( *pRc==SQLITE_OK ){
143711  int i; /* Iterator variable */
143712  int rc; /* Return code */
143713  char *zSql; /* SQL statement passed to declare_vtab() */
143714  char *zCols; /* List of user defined columns */
143715  const char *zLanguageid;
143716 
143717  zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
143718  sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
143719 
143720  /* Create a list of user columns for the virtual table */
143721  zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
143722  for(i=1; zCols && i<p->nColumn; i++){
143723  zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
143724  }
143725 
143726  /* Create the whole "CREATE TABLE" statement to pass to SQLite */
143727  zSql = sqlite3_mprintf(
143728  "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
143729  zCols, p->zName, zLanguageid
143730  );
143731  if( !zCols || !zSql ){
143732  rc = SQLITE_NOMEM;
143733  }else{
143734  rc = sqlite3_declare_vtab(p->db, zSql);
143735  }
143736 
143737  sqlite3_free(zSql);
143738  sqlite3_free(zCols);
143739  *pRc = rc;
143740  }
143741 }
143742 
143743 /*
143744 ** Create the %_stat table if it does not already exist.
143745 */
143746 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
143747  fts3DbExec(pRc, p->db,
143748  "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
143749  "(id INTEGER PRIMARY KEY, value BLOB);",
143750  p->zDb, p->zName
143751  );
143752  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
143753 }
143754 
143755 /*
143756 ** Create the backing store tables (%_content, %_segments and %_segdir)
143757 ** required by the FTS3 table passed as the only argument. This is done
143758 ** as part of the vtab xCreate() method.
143759 **
143760 ** If the p->bHasDocsize boolean is true (indicating that this is an
143761 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
143762 ** %_stat tables required by FTS4.
143763 */
143764 static int fts3CreateTables(Fts3Table *p){
143765  int rc = SQLITE_OK; /* Return code */
143766  int i; /* Iterator variable */
143767  sqlite3 *db = p->db; /* The database connection */
143768 
143769  if( p->zContentTbl==0 ){
143770  const char *zLanguageid = p->zLanguageid;
143771  char *zContentCols; /* Columns of %_content table */
143772 
143773  /* Create a list of user columns for the content table */
143774  zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
143775  for(i=0; zContentCols && i<p->nColumn; i++){
143776  char *z = p->azColumn[i];
143777  zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
143778  }
143779  if( zLanguageid && zContentCols ){
143780  zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
143781  }
143782  if( zContentCols==0 ) rc = SQLITE_NOMEM;
143783 
143784  /* Create the content table */
143785  fts3DbExec(&rc, db,
143786  "CREATE TABLE %Q.'%q_content'(%s)",
143787  p->zDb, p->zName, zContentCols
143788  );
143789  sqlite3_free(zContentCols);
143790  }
143791 
143792  /* Create other tables */
143793  fts3DbExec(&rc, db,
143794  "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
143795  p->zDb, p->zName
143796  );
143797  fts3DbExec(&rc, db,
143798  "CREATE TABLE %Q.'%q_segdir'("
143799  "level INTEGER,"
143800  "idx INTEGER,"
143801  "start_block INTEGER,"
143802  "leaves_end_block INTEGER,"
143803  "end_block INTEGER,"
143804  "root BLOB,"
143805  "PRIMARY KEY(level, idx)"
143806  ");",
143807  p->zDb, p->zName
143808  );
143809  if( p->bHasDocsize ){
143810  fts3DbExec(&rc, db,
143811  "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
143812  p->zDb, p->zName
143813  );
143814  }
143815  assert( p->bHasStat==p->bFts4 );
143816  if( p->bHasStat ){
143817  sqlite3Fts3CreateStatTable(&rc, p);
143818  }
143819  return rc;
143820 }
143821 
143822 /*
143823 ** Store the current database page-size in bytes in p->nPgsz.
143824 **
143825 ** If *pRc is non-zero when this function is called, it is a no-op.
143826 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
143827 ** before returning.
143828 */
143829 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
143830  if( *pRc==SQLITE_OK ){
143831  int rc; /* Return code */
143832  char *zSql; /* SQL text "PRAGMA %Q.page_size" */
143833  sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
143834 
143835  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
143836  if( !zSql ){
143837  rc = SQLITE_NOMEM;
143838  }else{
143839  rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
143840  if( rc==SQLITE_OK ){
143841  sqlite3_step(pStmt);
143842  p->nPgsz = sqlite3_column_int(pStmt, 0);
143843  rc = sqlite3_finalize(pStmt);
143844  }else if( rc==SQLITE_AUTH ){
143845  p->nPgsz = 1024;
143846  rc = SQLITE_OK;
143847  }
143848  }
143849  assert( p->nPgsz>0 || rc!=SQLITE_OK );
143850  sqlite3_free(zSql);
143851  *pRc = rc;
143852  }
143853 }
143854 
143855 /*
143856 ** "Special" FTS4 arguments are column specifications of the following form:
143857 **
143858 ** <key> = <value>
143859 **
143860 ** There may not be whitespace surrounding the "=" character. The <value>
143861 ** term may be quoted, but the <key> may not.
143862 */
143863 static int fts3IsSpecialColumn(
143864  const char *z,
143865  int *pnKey,
143866  char **pzValue
143867 ){
143868  char *zValue;
143869  const char *zCsr = z;
143870 
143871  while( *zCsr!='=' ){
143872  if( *zCsr=='\0' ) return 0;
143873  zCsr++;
143874  }
143875 
143876  *pnKey = (int)(zCsr-z);
143877  zValue = sqlite3_mprintf("%s", &zCsr[1]);
143878  if( zValue ){
143879  sqlite3Fts3Dequote(zValue);
143880  }
143881  *pzValue = zValue;
143882  return 1;
143883 }
143884 
143885 /*
143886 ** Append the output of a printf() style formatting to an existing string.
143887 */
143888 static void fts3Appendf(
143889  int *pRc, /* IN/OUT: Error code */
143890  char **pz, /* IN/OUT: Pointer to string buffer */
143891  const char *zFormat, /* Printf format string to append */
143892  ... /* Arguments for printf format string */
143893 ){
143894  if( *pRc==SQLITE_OK ){
143895  va_list ap;
143896  char *z;
143897  va_start(ap, zFormat);
143898  z = sqlite3_vmprintf(zFormat, ap);
143899  va_end(ap);
143900  if( z && *pz ){
143901  char *z2 = sqlite3_mprintf("%s%s", *pz, z);
143902  sqlite3_free(z);
143903  z = z2;
143904  }
143905  if( z==0 ) *pRc = SQLITE_NOMEM;
143906  sqlite3_free(*pz);
143907  *pz = z;
143908  }
143909 }
143910 
143911 /*
143912 ** Return a copy of input string zInput enclosed in double-quotes (") and
143913 ** with all double quote characters escaped. For example:
143914 **
143915 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
143916 **
143917 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
143918 ** is the callers responsibility to call sqlite3_free() to release this
143919 ** memory.
143920 */
143921 static char *fts3QuoteId(char const *zInput){
143922  int nRet;
143923  char *zRet;
143924  nRet = 2 + (int)strlen(zInput)*2 + 1;
143925  zRet = sqlite3_malloc(nRet);
143926  if( zRet ){
143927  int i;
143928  char *z = zRet;
143929  *(z++) = '"';
143930  for(i=0; zInput[i]; i++){
143931  if( zInput[i]=='"' ) *(z++) = '"';
143932  *(z++) = zInput[i];
143933  }
143934  *(z++) = '"';
143935  *(z++) = '\0';
143936  }
143937  return zRet;
143938 }
143939 
143940 /*
143941 ** Return a list of comma separated SQL expressions and a FROM clause that
143942 ** could be used in a SELECT statement such as the following:
143943 **
143944 ** SELECT <list of expressions> FROM %_content AS x ...
143945 **
143946 ** to return the docid, followed by each column of text data in order
143947 ** from left to write. If parameter zFunc is not NULL, then instead of
143948 ** being returned directly each column of text data is passed to an SQL
143949 ** function named zFunc first. For example, if zFunc is "unzip" and the
143950 ** table has the three user-defined columns "a", "b", and "c", the following
143951 ** string is returned:
143952 **
143953 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
143954 **
143955 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
143956 ** is the responsibility of the caller to eventually free it.
143957 **
143958 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
143959 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
143960 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
143961 ** no error occurs, *pRc is left unmodified.
143962 */
143963 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
143964  char *zRet = 0;
143965  char *zFree = 0;
143966  char *zFunction;
143967  int i;
143968 
143969  if( p->zContentTbl==0 ){
143970  if( !zFunc ){
143971  zFunction = "";
143972  }else{
143973  zFree = zFunction = fts3QuoteId(zFunc);
143974  }
143975  fts3Appendf(pRc, &zRet, "docid");
143976  for(i=0; i<p->nColumn; i++){
143977  fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
143978  }
143979  if( p->zLanguageid ){
143980  fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
143981  }
143982  sqlite3_free(zFree);
143983  }else{
143984  fts3Appendf(pRc, &zRet, "rowid");
143985  for(i=0; i<p->nColumn; i++){
143986  fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
143987  }
143988  if( p->zLanguageid ){
143989  fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
143990  }
143991  }
143992  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
143993  p->zDb,
143994  (p->zContentTbl ? p->zContentTbl : p->zName),
143995  (p->zContentTbl ? "" : "_content")
143996  );
143997  return zRet;
143998 }
143999 
144000 /*
144001 ** Return a list of N comma separated question marks, where N is the number
144002 ** of columns in the %_content table (one for the docid plus one for each
144003 ** user-defined text column).
144004 **
144005 ** If argument zFunc is not NULL, then all but the first question mark
144006 ** is preceded by zFunc and an open bracket, and followed by a closed
144007 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
144008 ** user-defined text columns, the following string is returned:
144009 **
144010 ** "?, zip(?), zip(?), zip(?)"
144011 **
144012 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
144013 ** is the responsibility of the caller to eventually free it.
144014 **
144015 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
144016 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
144017 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
144018 ** no error occurs, *pRc is left unmodified.
144019 */
144020 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
144021  char *zRet = 0;
144022  char *zFree = 0;
144023  char *zFunction;
144024  int i;
144025 
144026  if( !zFunc ){
144027  zFunction = "";
144028  }else{
144029  zFree = zFunction = fts3QuoteId(zFunc);
144030  }
144031  fts3Appendf(pRc, &zRet, "?");
144032  for(i=0; i<p->nColumn; i++){
144033  fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
144034  }
144035  if( p->zLanguageid ){
144036  fts3Appendf(pRc, &zRet, ", ?");
144037  }
144038  sqlite3_free(zFree);
144039  return zRet;
144040 }
144041 
144042 /*
144043 ** This function interprets the string at (*pp) as a non-negative integer
144044 ** value. It reads the integer and sets *pnOut to the value read, then
144045 ** sets *pp to point to the byte immediately following the last byte of
144046 ** the integer value.
144047 **
144048 ** Only decimal digits ('0'..'9') may be part of an integer value.
144049 **
144050 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
144051 ** the output value undefined. Otherwise SQLITE_OK is returned.
144052 **
144053 ** This function is used when parsing the "prefix=" FTS4 parameter.
144054 */
144055 static int fts3GobbleInt(const char **pp, int *pnOut){
144056  const int MAX_NPREFIX = 10000000;
144057  const char *p; /* Iterator pointer */
144058  int nInt = 0; /* Output value */
144059 
144060  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
144061  nInt = nInt * 10 + (p[0] - '0');
144062  if( nInt>MAX_NPREFIX ){
144063  nInt = 0;
144064  break;
144065  }
144066  }
144067  if( p==*pp ) return SQLITE_ERROR;
144068  *pnOut = nInt;
144069  *pp = p;
144070  return SQLITE_OK;
144071 }
144072 
144073 /*
144074 ** This function is called to allocate an array of Fts3Index structures
144075 ** representing the indexes maintained by the current FTS table. FTS tables
144076 ** always maintain the main "terms" index, but may also maintain one or
144077 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
144078 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
144079 **
144080 ** Argument zParam is passed the value of the "prefix=" option if one was
144081 ** specified, or NULL otherwise.
144082 **
144083 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
144084 ** the allocated array. *pnIndex is set to the number of elements in the
144085 ** array. If an error does occur, an SQLite error code is returned.
144086 **
144087 ** Regardless of whether or not an error is returned, it is the responsibility
144088 ** of the caller to call sqlite3_free() on the output array to free it.
144089 */
144090 static int fts3PrefixParameter(
144091  const char *zParam, /* ABC in prefix=ABC parameter to parse */
144092  int *pnIndex, /* OUT: size of *apIndex[] array */
144093  struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
144094 ){
144095  struct Fts3Index *aIndex; /* Allocated array */
144096  int nIndex = 1; /* Number of entries in array */
144097 
144098  if( zParam && zParam[0] ){
144099  const char *p;
144100  nIndex++;
144101  for(p=zParam; *p; p++){
144102  if( *p==',' ) nIndex++;
144103  }
144104  }
144105 
144106  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
144107  *apIndex = aIndex;
144108  if( !aIndex ){
144109  return SQLITE_NOMEM;
144110  }
144111 
144112  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
144113  if( zParam ){
144114  const char *p = zParam;
144115  int i;
144116  for(i=1; i<nIndex; i++){
144117  int nPrefix = 0;
144118  if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
144119  assert( nPrefix>=0 );
144120  if( nPrefix==0 ){
144121  nIndex--;
144122  i--;
144123  }else{
144124  aIndex[i].nPrefix = nPrefix;
144125  }
144126  p++;
144127  }
144128  }
144129 
144130  *pnIndex = nIndex;
144131  return SQLITE_OK;
144132 }
144133 
144134 /*
144135 ** This function is called when initializing an FTS4 table that uses the
144136 ** content=xxx option. It determines the number of and names of the columns
144137 ** of the new FTS4 table.
144138 **
144139 ** The third argument passed to this function is the value passed to the
144140 ** config=xxx option (i.e. "xxx"). This function queries the database for
144141 ** a table of that name. If found, the output variables are populated
144142 ** as follows:
144143 **
144144 ** *pnCol: Set to the number of columns table xxx has,
144145 **
144146 ** *pnStr: Set to the total amount of space required to store a copy
144147 ** of each columns name, including the nul-terminator.
144148 **
144149 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
144150 ** the name of the corresponding column in table xxx. The array
144151 ** and its contents are allocated using a single allocation. It
144152 ** is the responsibility of the caller to free this allocation
144153 ** by eventually passing the *pazCol value to sqlite3_free().
144154 **
144155 ** If the table cannot be found, an error code is returned and the output
144156 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
144157 ** returned (and the output variables are undefined).
144158 */
144159 static int fts3ContentColumns(
144160  sqlite3 *db, /* Database handle */
144161  const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
144162  const char *zTbl, /* Name of content table */
144163  const char ***pazCol, /* OUT: Malloc'd array of column names */
144164  int *pnCol, /* OUT: Size of array *pazCol */
144165  int *pnStr, /* OUT: Bytes of string content */
144166  char **pzErr /* OUT: error message */
144167 ){
144168  int rc = SQLITE_OK; /* Return code */
144169  char *zSql; /* "SELECT *" statement on zTbl */
144170  sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
144171 
144172  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
144173  if( !zSql ){
144174  rc = SQLITE_NOMEM;
144175  }else{
144176  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
144177  if( rc!=SQLITE_OK ){
144178  sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
144179  }
144180  }
144181  sqlite3_free(zSql);
144182 
144183  if( rc==SQLITE_OK ){
144184  const char **azCol; /* Output array */
144185  int nStr = 0; /* Size of all column names (incl. 0x00) */
144186  int nCol; /* Number of table columns */
144187  int i; /* Used to iterate through columns */
144188 
144189  /* Loop through the returned columns. Set nStr to the number of bytes of
144190  ** space required to store a copy of each column name, including the
144191  ** nul-terminator byte. */
144192  nCol = sqlite3_column_count(pStmt);
144193  for(i=0; i<nCol; i++){
144194  const char *zCol = sqlite3_column_name(pStmt, i);
144195  nStr += (int)strlen(zCol) + 1;
144196  }
144197 
144198  /* Allocate and populate the array to return. */
144199  azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
144200  if( azCol==0 ){
144201  rc = SQLITE_NOMEM;
144202  }else{
144203  char *p = (char *)&azCol[nCol];
144204  for(i=0; i<nCol; i++){
144205  const char *zCol = sqlite3_column_name(pStmt, i);
144206  int n = (int)strlen(zCol)+1;
144207  memcpy(p, zCol, n);
144208  azCol[i] = p;
144209  p += n;
144210  }
144211  }
144212  sqlite3_finalize(pStmt);
144213 
144214  /* Set the output variables. */
144215  *pnCol = nCol;
144216  *pnStr = nStr;
144217  *pazCol = azCol;
144218  }
144219 
144220  return rc;
144221 }
144222 
144223 /*
144224 ** This function is the implementation of both the xConnect and xCreate
144225 ** methods of the FTS3 virtual table.
144226 **
144227 ** The argv[] array contains the following:
144228 **
144229 ** argv[0] -> module name ("fts3" or "fts4")
144230 ** argv[1] -> database name
144231 ** argv[2] -> table name
144232 ** argv[...] -> "column name" and other module argument fields.
144233 */
144234 static int fts3InitVtab(
144235  int isCreate, /* True for xCreate, false for xConnect */
144236  sqlite3 *db, /* The SQLite database connection */
144237  void *pAux, /* Hash table containing tokenizers */
144238  int argc, /* Number of elements in argv array */
144239  const char * const *argv, /* xCreate/xConnect argument array */
144240  sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
144241  char **pzErr /* Write any error message here */
144242 ){
144243  Fts3Hash *pHash = (Fts3Hash *)pAux;
144244  Fts3Table *p = 0; /* Pointer to allocated vtab */
144245  int rc = SQLITE_OK; /* Return code */
144246  int i; /* Iterator variable */
144247  int nByte; /* Size of allocation used for *p */
144248  int iCol; /* Column index */
144249  int nString = 0; /* Bytes required to hold all column names */
144250  int nCol = 0; /* Number of columns in the FTS table */
144251  char *zCsr; /* Space for holding column names */
144252  int nDb; /* Bytes required to hold database name */
144253  int nName; /* Bytes required to hold table name */
144254  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
144255  const char **aCol; /* Array of column names */
144256  sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
144257 
144258  int nIndex = 0; /* Size of aIndex[] array */
144259  struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
144260 
144261  /* The results of parsing supported FTS4 key=value options: */
144262  int bNoDocsize = 0; /* True to omit %_docsize table */
144263  int bDescIdx = 0; /* True to store descending indexes */
144264  char *zPrefix = 0; /* Prefix parameter value (or NULL) */
144265  char *zCompress = 0; /* compress=? parameter (or NULL) */
144266  char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
144267  char *zContent = 0; /* content=? parameter (or NULL) */
144268  char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
144269  char **azNotindexed = 0; /* The set of notindexed= columns */
144270  int nNotindexed = 0; /* Size of azNotindexed[] array */
144271 
144272  assert( strlen(argv[0])==4 );
144273  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
144274  || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
144275  );
144276 
144277  nDb = (int)strlen(argv[1]) + 1;
144278  nName = (int)strlen(argv[2]) + 1;
144279 
144280  nByte = sizeof(const char *) * (argc-2);
144281  aCol = (const char **)sqlite3_malloc(nByte);
144282  if( aCol ){
144283  memset((void*)aCol, 0, nByte);
144284  azNotindexed = (char **)sqlite3_malloc(nByte);
144285  }
144286  if( azNotindexed ){
144287  memset(azNotindexed, 0, nByte);
144288  }
144289  if( !aCol || !azNotindexed ){
144290  rc = SQLITE_NOMEM;
144291  goto fts3_init_out;
144292  }
144293 
144294  /* Loop through all of the arguments passed by the user to the FTS3/4
144295  ** module (i.e. all the column names and special arguments). This loop
144296  ** does the following:
144297  **
144298  ** + Figures out the number of columns the FTSX table will have, and
144299  ** the number of bytes of space that must be allocated to store copies
144300  ** of the column names.
144301  **
144302  ** + If there is a tokenizer specification included in the arguments,
144303  ** initializes the tokenizer pTokenizer.
144304  */
144305  for(i=3; rc==SQLITE_OK && i<argc; i++){
144306  char const *z = argv[i];
144307  int nKey;
144308  char *zVal;
144309 
144310  /* Check if this is a tokenizer specification */
144311  if( !pTokenizer
144312  && strlen(z)>8
144313  && 0==sqlite3_strnicmp(z, "tokenize", 8)
144314  && 0==sqlite3Fts3IsIdChar(z[8])
144315  ){
144316  rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
144317  }
144318 
144319  /* Check if it is an FTS4 special argument. */
144320  else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
144321  struct Fts4Option {
144322  const char *zOpt;
144323  int nOpt;
144324  } aFts4Opt[] = {
144325  { "matchinfo", 9 }, /* 0 -> MATCHINFO */
144326  { "prefix", 6 }, /* 1 -> PREFIX */
144327  { "compress", 8 }, /* 2 -> COMPRESS */
144328  { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
144329  { "order", 5 }, /* 4 -> ORDER */
144330  { "content", 7 }, /* 5 -> CONTENT */
144331  { "languageid", 10 }, /* 6 -> LANGUAGEID */
144332  { "notindexed", 10 } /* 7 -> NOTINDEXED */
144333  };
144334 
144335  int iOpt;
144336  if( !zVal ){
144337  rc = SQLITE_NOMEM;
144338  }else{
144339  for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
144340  struct Fts4Option *pOp = &aFts4Opt[iOpt];
144341  if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
144342  break;
144343  }
144344  }
144345  if( iOpt==SizeofArray(aFts4Opt) ){
144346  sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
144347  rc = SQLITE_ERROR;
144348  }else{
144349  switch( iOpt ){
144350  case 0: /* MATCHINFO */
144351  if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
144352  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
144353  rc = SQLITE_ERROR;
144354  }
144355  bNoDocsize = 1;
144356  break;
144357 
144358  case 1: /* PREFIX */
144359  sqlite3_free(zPrefix);
144360  zPrefix = zVal;
144361  zVal = 0;
144362  break;
144363 
144364  case 2: /* COMPRESS */
144365  sqlite3_free(zCompress);
144366  zCompress = zVal;
144367  zVal = 0;
144368  break;
144369 
144370  case 3: /* UNCOMPRESS */
144371  sqlite3_free(zUncompress);
144372  zUncompress = zVal;
144373  zVal = 0;
144374  break;
144375 
144376  case 4: /* ORDER */
144377  if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
144378  && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
144379  ){
144380  sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
144381  rc = SQLITE_ERROR;
144382  }
144383  bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
144384  break;
144385 
144386  case 5: /* CONTENT */
144387  sqlite3_free(zContent);
144388  zContent = zVal;
144389  zVal = 0;
144390  break;
144391 
144392  case 6: /* LANGUAGEID */
144393  assert( iOpt==6 );
144394  sqlite3_free(zLanguageid);
144395  zLanguageid = zVal;
144396  zVal = 0;
144397  break;
144398 
144399  case 7: /* NOTINDEXED */
144400  azNotindexed[nNotindexed++] = zVal;
144401  zVal = 0;
144402  break;
144403  }
144404  }
144405  sqlite3_free(zVal);
144406  }
144407  }
144408 
144409  /* Otherwise, the argument is a column name. */
144410  else {
144411  nString += (int)(strlen(z) + 1);
144412  aCol[nCol++] = z;
144413  }
144414  }
144415 
144416  /* If a content=xxx option was specified, the following:
144417  **
144418  ** 1. Ignore any compress= and uncompress= options.
144419  **
144420  ** 2. If no column names were specified as part of the CREATE VIRTUAL
144421  ** TABLE statement, use all columns from the content table.
144422  */
144423  if( rc==SQLITE_OK && zContent ){
144424  sqlite3_free(zCompress);
144425  sqlite3_free(zUncompress);
144426  zCompress = 0;
144427  zUncompress = 0;
144428  if( nCol==0 ){
144429  sqlite3_free((void*)aCol);
144430  aCol = 0;
144431  rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
144432 
144433  /* If a languageid= option was specified, remove the language id
144434  ** column from the aCol[] array. */
144435  if( rc==SQLITE_OK && zLanguageid ){
144436  int j;
144437  for(j=0; j<nCol; j++){
144438  if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
144439  int k;
144440  for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
144441  nCol--;
144442  break;
144443  }
144444  }
144445  }
144446  }
144447  }
144448  if( rc!=SQLITE_OK ) goto fts3_init_out;
144449 
144450  if( nCol==0 ){
144451  assert( nString==0 );
144452  aCol[0] = "content";
144453  nString = 8;
144454  nCol = 1;
144455  }
144456 
144457  if( pTokenizer==0 ){
144458  rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
144459  if( rc!=SQLITE_OK ) goto fts3_init_out;
144460  }
144461  assert( pTokenizer );
144462 
144463  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
144464  if( rc==SQLITE_ERROR ){
144465  assert( zPrefix );
144466  sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
144467  }
144468  if( rc!=SQLITE_OK ) goto fts3_init_out;
144469 
144470  /* Allocate and populate the Fts3Table structure. */
144471  nByte = sizeof(Fts3Table) + /* Fts3Table */
144472  nCol * sizeof(char *) + /* azColumn */
144473  nIndex * sizeof(struct Fts3Index) + /* aIndex */
144474  nCol * sizeof(u8) + /* abNotindexed */
144475  nName + /* zName */
144476  nDb + /* zDb */
144477  nString; /* Space for azColumn strings */
144478  p = (Fts3Table*)sqlite3_malloc(nByte);
144479  if( p==0 ){
144480  rc = SQLITE_NOMEM;
144481  goto fts3_init_out;
144482  }
144483  memset(p, 0, nByte);
144484  p->db = db;
144485  p->nColumn = nCol;
144486  p->nPendingData = 0;
144487  p->azColumn = (char **)&p[1];
144488  p->pTokenizer = pTokenizer;
144489  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
144490  p->bHasDocsize = (isFts4 && bNoDocsize==0);
144491  p->bHasStat = isFts4;
144492  p->bFts4 = isFts4;
144493  p->bDescIdx = bDescIdx;
144494  p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
144495  p->zContentTbl = zContent;
144496  p->zLanguageid = zLanguageid;
144497  zContent = 0;
144498  zLanguageid = 0;
144499  TESTONLY( p->inTransaction = -1 );
144500  TESTONLY( p->mxSavepoint = -1 );
144501 
144502  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
144503  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
144504  p->nIndex = nIndex;
144505  for(i=0; i<nIndex; i++){
144506  fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
144507  }
144508  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
144509 
144510  /* Fill in the zName and zDb fields of the vtab structure. */
144511  zCsr = (char *)&p->abNotindexed[nCol];
144512  p->zName = zCsr;
144513  memcpy(zCsr, argv[2], nName);
144514  zCsr += nName;
144515  p->zDb = zCsr;
144516  memcpy(zCsr, argv[1], nDb);
144517  zCsr += nDb;
144518 
144519  /* Fill in the azColumn array */
144520  for(iCol=0; iCol<nCol; iCol++){
144521  char *z;
144522  int n = 0;
144523  z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
144524  memcpy(zCsr, z, n);
144525  zCsr[n] = '\0';
144526  sqlite3Fts3Dequote(zCsr);
144527  p->azColumn[iCol] = zCsr;
144528  zCsr += n+1;
144529  assert( zCsr <= &((char *)p)[nByte] );
144530  }
144531 
144532  /* Fill in the abNotindexed array */
144533  for(iCol=0; iCol<nCol; iCol++){
144534  int n = (int)strlen(p->azColumn[iCol]);
144535  for(i=0; i<nNotindexed; i++){
144536  char *zNot = azNotindexed[i];
144537  if( zNot && n==(int)strlen(zNot)
144538  && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
144539  ){
144540  p->abNotindexed[iCol] = 1;
144541  sqlite3_free(zNot);
144542  azNotindexed[i] = 0;
144543  }
144544  }
144545  }
144546  for(i=0; i<nNotindexed; i++){
144547  if( azNotindexed[i] ){
144548  sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
144549  rc = SQLITE_ERROR;
144550  }
144551  }
144552 
144553  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
144554  char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
144555  rc = SQLITE_ERROR;
144556  sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
144557  }
144558  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
144559  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
144560  if( rc!=SQLITE_OK ) goto fts3_init_out;
144561 
144562  /* If this is an xCreate call, create the underlying tables in the
144563  ** database. TODO: For xConnect(), it could verify that said tables exist.
144564  */
144565  if( isCreate ){
144566  rc = fts3CreateTables(p);
144567  }
144568 
144569  /* Check to see if a legacy fts3 table has been "upgraded" by the
144570  ** addition of a %_stat table so that it can use incremental merge.
144571  */
144572  if( !isFts4 && !isCreate ){
144573  p->bHasStat = 2;
144574  }
144575 
144576  /* Figure out the page-size for the database. This is required in order to
144577  ** estimate the cost of loading large doclists from the database. */
144578  fts3DatabasePageSize(&rc, p);
144579  p->nNodeSize = p->nPgsz-35;
144580 
144581  /* Declare the table schema to SQLite. */
144582  fts3DeclareVtab(&rc, p);
144583 
144584 fts3_init_out:
144585  sqlite3_free(zPrefix);
144586  sqlite3_free(aIndex);
144587  sqlite3_free(zCompress);
144588  sqlite3_free(zUncompress);
144589  sqlite3_free(zContent);
144590  sqlite3_free(zLanguageid);
144591  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
144592  sqlite3_free((void *)aCol);
144593  sqlite3_free((void *)azNotindexed);
144594  if( rc!=SQLITE_OK ){
144595  if( p ){
144596  fts3DisconnectMethod((sqlite3_vtab *)p);
144597  }else if( pTokenizer ){
144598  pTokenizer->pModule->xDestroy(pTokenizer);
144599  }
144600  }else{
144601  assert( p->pSegments==0 );
144602  *ppVTab = &p->base;
144603  }
144604  return rc;
144605 }
144606 
144607 /*
144608 ** The xConnect() and xCreate() methods for the virtual table. All the
144609 ** work is done in function fts3InitVtab().
144610 */
144611 static int fts3ConnectMethod(
144612  sqlite3 *db, /* Database connection */
144613  void *pAux, /* Pointer to tokenizer hash table */
144614  int argc, /* Number of elements in argv array */
144615  const char * const *argv, /* xCreate/xConnect argument array */
144616  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
144617  char **pzErr /* OUT: sqlite3_malloc'd error message */
144618 ){
144619  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
144620 }
144621 static int fts3CreateMethod(
144622  sqlite3 *db, /* Database connection */
144623  void *pAux, /* Pointer to tokenizer hash table */
144624  int argc, /* Number of elements in argv array */
144625  const char * const *argv, /* xCreate/xConnect argument array */
144626  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
144627  char **pzErr /* OUT: sqlite3_malloc'd error message */
144628 ){
144629  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
144630 }
144631 
144632 /*
144633 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
144634 ** extension is currently being used by a version of SQLite too old to
144635 ** support estimatedRows. In that case this function is a no-op.
144636 */
144637 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
144638 #if SQLITE_VERSION_NUMBER>=3008002
144639  if( sqlite3_libversion_number()>=3008002 ){
144640  pIdxInfo->estimatedRows = nRow;
144641  }
144642 #endif
144643 }
144644 
144645 /*
144646 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
144647 ** extension is currently being used by a version of SQLite too old to
144648 ** support index-info flags. In that case this function is a no-op.
144649 */
144650 static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
144651 #if SQLITE_VERSION_NUMBER>=3008012
144652  if( sqlite3_libversion_number()>=3008012 ){
144653  pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
144654  }
144655 #endif
144656 }
144657 
144658 /*
144659 ** Implementation of the xBestIndex method for FTS3 tables. There
144660 ** are three possible strategies, in order of preference:
144661 **
144662 ** 1. Direct lookup by rowid or docid.
144663 ** 2. Full-text search using a MATCH operator on a non-docid column.
144664 ** 3. Linear scan of %_content table.
144665 */
144666 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
144667  Fts3Table *p = (Fts3Table *)pVTab;
144668  int i; /* Iterator variable */
144669  int iCons = -1; /* Index of constraint to use */
144670 
144671  int iLangidCons = -1; /* Index of langid=x constraint, if present */
144672  int iDocidGe = -1; /* Index of docid>=x constraint, if present */
144673  int iDocidLe = -1; /* Index of docid<=x constraint, if present */
144674  int iIdx;
144675 
144676  /* By default use a full table scan. This is an expensive option,
144677  ** so search through the constraints to see if a more efficient
144678  ** strategy is possible.
144679  */
144680  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
144681  pInfo->estimatedCost = 5000000;
144682  for(i=0; i<pInfo->nConstraint; i++){
144683  int bDocid; /* True if this constraint is on docid */
144684  struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
144685  if( pCons->usable==0 ){
144686  if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
144687  /* There exists an unusable MATCH constraint. This means that if
144688  ** the planner does elect to use the results of this call as part
144689  ** of the overall query plan the user will see an "unable to use
144690  ** function MATCH in the requested context" error. To discourage
144691  ** this, return a very high cost here. */
144692  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
144693  pInfo->estimatedCost = 1e50;
144694  fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
144695  return SQLITE_OK;
144696  }
144697  continue;
144698  }
144699 
144700  bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
144701 
144702  /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
144703  if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
144704  pInfo->idxNum = FTS3_DOCID_SEARCH;
144705  pInfo->estimatedCost = 1.0;
144706  iCons = i;
144707  }
144708 
144709  /* A MATCH constraint. Use a full-text search.
144710  **
144711  ** If there is more than one MATCH constraint available, use the first
144712  ** one encountered. If there is both a MATCH constraint and a direct
144713  ** rowid/docid lookup, prefer the MATCH strategy. This is done even
144714  ** though the rowid/docid lookup is faster than a MATCH query, selecting
144715  ** it would lead to an "unable to use function MATCH in the requested
144716  ** context" error.
144717  */
144718  if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
144719  && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
144720  ){
144721  pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
144722  pInfo->estimatedCost = 2.0;
144723  iCons = i;
144724  }
144725 
144726  /* Equality constraint on the langid column */
144727  if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
144728  && pCons->iColumn==p->nColumn + 2
144729  ){
144730  iLangidCons = i;
144731  }
144732 
144733  if( bDocid ){
144734  switch( pCons->op ){
144735  case SQLITE_INDEX_CONSTRAINT_GE:
144736  case SQLITE_INDEX_CONSTRAINT_GT:
144737  iDocidGe = i;
144738  break;
144739 
144740  case SQLITE_INDEX_CONSTRAINT_LE:
144741  case SQLITE_INDEX_CONSTRAINT_LT:
144742  iDocidLe = i;
144743  break;
144744  }
144745  }
144746  }
144747 
144748  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
144749  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
144750 
144751  iIdx = 1;
144752  if( iCons>=0 ){
144753  pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
144754  pInfo->aConstraintUsage[iCons].omit = 1;
144755  }
144756  if( iLangidCons>=0 ){
144757  pInfo->idxNum |= FTS3_HAVE_LANGID;
144758  pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
144759  }
144760  if( iDocidGe>=0 ){
144761  pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
144762  pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
144763  }
144764  if( iDocidLe>=0 ){
144765  pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
144766  pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
144767  }
144768 
144769  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
144770  ** docid) order. Both ascending and descending are possible.
144771  */
144772  if( pInfo->nOrderBy==1 ){
144773  struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
144774  if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
144775  if( pOrder->desc ){
144776  pInfo->idxStr = "DESC";
144777  }else{
144778  pInfo->idxStr = "ASC";
144779  }
144780  pInfo->orderByConsumed = 1;
144781  }
144782  }
144783 
144784  assert( p->pSegments==0 );
144785  return SQLITE_OK;
144786 }
144787 
144788 /*
144789 ** Implementation of xOpen method.
144790 */
144791 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
144792  sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
144793 
144794  UNUSED_PARAMETER(pVTab);
144795 
144796  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
144797  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
144798  ** if the allocation fails, return SQLITE_NOMEM.
144799  */
144800  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
144801  if( !pCsr ){
144802  return SQLITE_NOMEM;
144803  }
144804  memset(pCsr, 0, sizeof(Fts3Cursor));
144805  return SQLITE_OK;
144806 }
144807 
144808 /*
144809 ** Close the cursor. For additional information see the documentation
144810 ** on the xClose method of the virtual table interface.
144811 */
144812 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
144813  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
144814  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
144815  sqlite3_finalize(pCsr->pStmt);
144816  sqlite3Fts3ExprFree(pCsr->pExpr);
144817  sqlite3Fts3FreeDeferredTokens(pCsr);
144818  sqlite3_free(pCsr->aDoclist);
144819  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
144820  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
144821  sqlite3_free(pCsr);
144822  return SQLITE_OK;
144823 }
144824 
144825 /*
144826 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
144827 ** compose and prepare an SQL statement of the form:
144828 **
144829 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
144830 **
144831 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
144832 ** it. If an error occurs, return an SQLite error code.
144833 **
144834 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
144835 */
144836 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
144837  int rc = SQLITE_OK;
144838  if( pCsr->pStmt==0 ){
144839  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
144840  char *zSql;
144841  zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
144842  if( !zSql ) return SQLITE_NOMEM;
144843  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
144844  sqlite3_free(zSql);
144845  }
144846  *ppStmt = pCsr->pStmt;
144847  return rc;
144848 }
144849 
144850 /*
144851 ** Position the pCsr->pStmt statement so that it is on the row
144852 ** of the %_content table that contains the last match. Return
144853 ** SQLITE_OK on success.
144854 */
144855 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
144856  int rc = SQLITE_OK;
144857  if( pCsr->isRequireSeek ){
144858  sqlite3_stmt *pStmt = 0;
144859 
144860  rc = fts3CursorSeekStmt(pCsr, &pStmt);
144861  if( rc==SQLITE_OK ){
144862  sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
144863  pCsr->isRequireSeek = 0;
144864  if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
144865  return SQLITE_OK;
144866  }else{
144867  rc = sqlite3_reset(pCsr->pStmt);
144868  if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
144869  /* If no row was found and no error has occurred, then the %_content
144870  ** table is missing a row that is present in the full-text index.
144871  ** The data structures are corrupt. */
144872  rc = FTS_CORRUPT_VTAB;
144873  pCsr->isEof = 1;
144874  }
144875  }
144876  }
144877  }
144878 
144879  if( rc!=SQLITE_OK && pContext ){
144880  sqlite3_result_error_code(pContext, rc);
144881  }
144882  return rc;
144883 }
144884 
144885 /*
144886 ** This function is used to process a single interior node when searching
144887 ** a b-tree for a term or term prefix. The node data is passed to this
144888 ** function via the zNode/nNode parameters. The term to search for is
144889 ** passed in zTerm/nTerm.
144890 **
144891 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
144892 ** of the child node that heads the sub-tree that may contain the term.
144893 **
144894 ** If piLast is not NULL, then *piLast is set to the right-most child node
144895 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
144896 ** a prefix.
144897 **
144898 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
144899 */
144900 static int fts3ScanInteriorNode(
144901  const char *zTerm, /* Term to select leaves for */
144902  int nTerm, /* Size of term zTerm in bytes */
144903  const char *zNode, /* Buffer containing segment interior node */
144904  int nNode, /* Size of buffer at zNode */
144905  sqlite3_int64 *piFirst, /* OUT: Selected child node */
144906  sqlite3_int64 *piLast /* OUT: Selected child node */
144907 ){
144908  int rc = SQLITE_OK; /* Return code */
144909  const char *zCsr = zNode; /* Cursor to iterate through node */
144910  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
144911  char *zBuffer = 0; /* Buffer to load terms into */
144912  int nAlloc = 0; /* Size of allocated buffer */
144913  int isFirstTerm = 1; /* True when processing first term on page */
144914  sqlite3_int64 iChild; /* Block id of child node to descend to */
144915 
144916  /* Skip over the 'height' varint that occurs at the start of every
144917  ** interior node. Then load the blockid of the left-child of the b-tree
144918  ** node into variable iChild.
144919  **
144920  ** Even if the data structure on disk is corrupted, this (reading two
144921  ** varints from the buffer) does not risk an overread. If zNode is a
144922  ** root node, then the buffer comes from a SELECT statement. SQLite does
144923  ** not make this guarantee explicitly, but in practice there are always
144924  ** either more than 20 bytes of allocated space following the nNode bytes of
144925  ** contents, or two zero bytes. Or, if the node is read from the %_segments
144926  ** table, then there are always 20 bytes of zeroed padding following the
144927  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
144928  */
144929  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
144930  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
144931  if( zCsr>zEnd ){
144932  return FTS_CORRUPT_VTAB;
144933  }
144934 
144935  while( zCsr<zEnd && (piFirst || piLast) ){
144936  int cmp; /* memcmp() result */
144937  int nSuffix; /* Size of term suffix */
144938  int nPrefix = 0; /* Size of term prefix */
144939  int nBuffer; /* Total term size */
144940 
144941  /* Load the next term on the node into zBuffer. Use realloc() to expand
144942  ** the size of zBuffer if required. */
144943  if( !isFirstTerm ){
144944  zCsr += fts3GetVarint32(zCsr, &nPrefix);
144945  }
144946  isFirstTerm = 0;
144947  zCsr += fts3GetVarint32(zCsr, &nSuffix);
144948 
144949  if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
144950  rc = FTS_CORRUPT_VTAB;
144951  goto finish_scan;
144952  }
144953  if( nPrefix+nSuffix>nAlloc ){
144954  char *zNew;
144955  nAlloc = (nPrefix+nSuffix) * 2;
144956  zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
144957  if( !zNew ){
144958  rc = SQLITE_NOMEM;
144959  goto finish_scan;
144960  }
144961  zBuffer = zNew;
144962  }
144963  assert( zBuffer );
144964  memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
144965  nBuffer = nPrefix + nSuffix;
144966  zCsr += nSuffix;
144967 
144968  /* Compare the term we are searching for with the term just loaded from
144969  ** the interior node. If the specified term is greater than or equal
144970  ** to the term from the interior node, then all terms on the sub-tree
144971  ** headed by node iChild are smaller than zTerm. No need to search
144972  ** iChild.
144973  **
144974  ** If the interior node term is larger than the specified term, then
144975  ** the tree headed by iChild may contain the specified term.
144976  */
144977  cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
144978  if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
144979  *piFirst = iChild;
144980  piFirst = 0;
144981  }
144982 
144983  if( piLast && cmp<0 ){
144984  *piLast = iChild;
144985  piLast = 0;
144986  }
144987 
144988  iChild++;
144989  };
144990 
144991  if( piFirst ) *piFirst = iChild;
144992  if( piLast ) *piLast = iChild;
144993 
144994  finish_scan:
144995  sqlite3_free(zBuffer);
144996  return rc;
144997 }
144998 
144999 
145000 /*
145001 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
145002 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
145003 ** contains a term. This function searches the sub-tree headed by the zNode
145004 ** node for the range of leaf nodes that may contain the specified term
145005 ** or terms for which the specified term is a prefix.
145006 **
145007 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
145008 ** left-most leaf node in the tree that may contain the specified term.
145009 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
145010 ** right-most leaf node that may contain a term for which the specified
145011 ** term is a prefix.
145012 **
145013 ** It is possible that the range of returned leaf nodes does not contain
145014 ** the specified term or any terms for which it is a prefix. However, if the
145015 ** segment does contain any such terms, they are stored within the identified
145016 ** range. Because this function only inspects interior segment nodes (and
145017 ** never loads leaf nodes into memory), it is not possible to be sure.
145018 **
145019 ** If an error occurs, an error code other than SQLITE_OK is returned.
145020 */
145021 static int fts3SelectLeaf(
145022  Fts3Table *p, /* Virtual table handle */
145023  const char *zTerm, /* Term to select leaves for */
145024  int nTerm, /* Size of term zTerm in bytes */
145025  const char *zNode, /* Buffer containing segment interior node */
145026  int nNode, /* Size of buffer at zNode */
145027  sqlite3_int64 *piLeaf, /* Selected leaf node */
145028  sqlite3_int64 *piLeaf2 /* Selected leaf node */
145029 ){
145030  int rc = SQLITE_OK; /* Return code */
145031  int iHeight; /* Height of this node in tree */
145032 
145033  assert( piLeaf || piLeaf2 );
145034 
145035  fts3GetVarint32(zNode, &iHeight);
145036  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
145037  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
145038 
145039  if( rc==SQLITE_OK && iHeight>1 ){
145040  char *zBlob = 0; /* Blob read from %_segments table */
145041  int nBlob = 0; /* Size of zBlob in bytes */
145042 
145043  if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
145044  rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
145045  if( rc==SQLITE_OK ){
145046  rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
145047  }
145048  sqlite3_free(zBlob);
145049  piLeaf = 0;
145050  zBlob = 0;
145051  }
145052 
145053  if( rc==SQLITE_OK ){
145054  rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
145055  }
145056  if( rc==SQLITE_OK ){
145057  rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
145058  }
145059  sqlite3_free(zBlob);
145060  }
145061 
145062  return rc;
145063 }
145064 
145065 /*
145066 ** This function is used to create delta-encoded serialized lists of FTS3
145067 ** varints. Each call to this function appends a single varint to a list.
145068 */
145069 static void fts3PutDeltaVarint(
145070  char **pp, /* IN/OUT: Output pointer */
145071  sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
145072  sqlite3_int64 iVal /* Write this value to the list */
145073 ){
145074  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
145075  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
145076  *piPrev = iVal;
145077 }
145078 
145079 /*
145080 ** When this function is called, *ppPoslist is assumed to point to the
145081 ** start of a position-list. After it returns, *ppPoslist points to the
145082 ** first byte after the position-list.
145083 **
145084 ** A position list is list of positions (delta encoded) and columns for
145085 ** a single document record of a doclist. So, in other words, this
145086 ** routine advances *ppPoslist so that it points to the next docid in
145087 ** the doclist, or to the first byte past the end of the doclist.
145088 **
145089 ** If pp is not NULL, then the contents of the position list are copied
145090 ** to *pp. *pp is set to point to the first byte past the last byte copied
145091 ** before this function returns.
145092 */
145093 static void fts3PoslistCopy(char **pp, char **ppPoslist){
145094  char *pEnd = *ppPoslist;
145095  char c = 0;
145096 
145097  /* The end of a position list is marked by a zero encoded as an FTS3
145098  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
145099  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
145100  ** of some other, multi-byte, value.
145101  **
145102  ** The following while-loop moves pEnd to point to the first byte that is not
145103  ** immediately preceded by a byte with the 0x80 bit set. Then increments
145104  ** pEnd once more so that it points to the byte immediately following the
145105  ** last byte in the position-list.
145106  */
145107  while( *pEnd | c ){
145108  c = *pEnd++ & 0x80;
145109  testcase( c!=0 && (*pEnd)==0 );
145110  }
145111  pEnd++; /* Advance past the POS_END terminator byte */
145112 
145113  if( pp ){
145114  int n = (int)(pEnd - *ppPoslist);
145115  char *p = *pp;
145116  memcpy(p, *ppPoslist, n);
145117  p += n;
145118  *pp = p;
145119  }
145120  *ppPoslist = pEnd;
145121 }
145122 
145123 /*
145124 ** When this function is called, *ppPoslist is assumed to point to the
145125 ** start of a column-list. After it returns, *ppPoslist points to the
145126 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
145127 **
145128 ** A column-list is list of delta-encoded positions for a single column
145129 ** within a single document within a doclist.
145130 **
145131 ** The column-list is terminated either by a POS_COLUMN varint (1) or
145132 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
145133 ** the POS_COLUMN or POS_END that terminates the column-list.
145134 **
145135 ** If pp is not NULL, then the contents of the column-list are copied
145136 ** to *pp. *pp is set to point to the first byte past the last byte copied
145137 ** before this function returns. The POS_COLUMN or POS_END terminator
145138 ** is not copied into *pp.
145139 */
145140 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
145141  char *pEnd = *ppPoslist;
145142  char c = 0;
145143 
145144  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
145145  ** not part of a multi-byte varint.
145146  */
145147  while( 0xFE & (*pEnd | c) ){
145148  c = *pEnd++ & 0x80;
145149  testcase( c!=0 && ((*pEnd)&0xfe)==0 );
145150  }
145151  if( pp ){
145152  int n = (int)(pEnd - *ppPoslist);
145153  char *p = *pp;
145154  memcpy(p, *ppPoslist, n);
145155  p += n;
145156  *pp = p;
145157  }
145158  *ppPoslist = pEnd;
145159 }
145160 
145161 /*
145162 ** Value used to signify the end of an position-list. This is safe because
145163 ** it is not possible to have a document with 2^31 terms.
145164 */
145165 #define POSITION_LIST_END 0x7fffffff
145166 
145167 /*
145168 ** This function is used to help parse position-lists. When this function is
145169 ** called, *pp may point to the start of the next varint in the position-list
145170 ** being parsed, or it may point to 1 byte past the end of the position-list
145171 ** (in which case **pp will be a terminator bytes POS_END (0) or
145172 ** (1)).
145173 **
145174 ** If *pp points past the end of the current position-list, set *pi to
145175 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
145176 ** increment the current value of *pi by the value read, and set *pp to
145177 ** point to the next value before returning.
145178 **
145179 ** Before calling this routine *pi must be initialized to the value of
145180 ** the previous position, or zero if we are reading the first position
145181 ** in the position-list. Because positions are delta-encoded, the value
145182 ** of the previous position is needed in order to compute the value of
145183 ** the next position.
145184 */
145185 static void fts3ReadNextPos(
145186  char **pp, /* IN/OUT: Pointer into position-list buffer */
145187  sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
145188 ){
145189  if( (**pp)&0xFE ){
145190  fts3GetDeltaVarint(pp, pi);
145191  *pi -= 2;
145192  }else{
145193  *pi = POSITION_LIST_END;
145194  }
145195 }
145196 
145197 /*
145198 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
145199 ** the value of iCol encoded as a varint to *pp. This will start a new
145200 ** column list.
145201 **
145202 ** Set *pp to point to the byte just after the last byte written before
145203 ** returning (do not modify it if iCol==0). Return the total number of bytes
145204 ** written (0 if iCol==0).
145205 */
145206 static int fts3PutColNumber(char **pp, int iCol){
145207  int n = 0; /* Number of bytes written */
145208  if( iCol ){
145209  char *p = *pp; /* Output pointer */
145210  n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
145211  *p = 0x01;
145212  *pp = &p[n];
145213  }
145214  return n;
145215 }
145216 
145217 /*
145218 ** Compute the union of two position lists. The output written
145219 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
145220 ** order and with any duplicates removed. All pointers are
145221 ** updated appropriately. The caller is responsible for insuring
145222 ** that there is enough space in *pp to hold the complete output.
145223 */
145224 static void fts3PoslistMerge(
145225  char **pp, /* Output buffer */
145226  char **pp1, /* Left input list */
145227  char **pp2 /* Right input list */
145228 ){
145229  char *p = *pp;
145230  char *p1 = *pp1;
145231  char *p2 = *pp2;
145232 
145233  while( *p1 || *p2 ){
145234  int iCol1; /* The current column index in pp1 */
145235  int iCol2; /* The current column index in pp2 */
145236 
145237  if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
145238  else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
145239  else iCol1 = 0;
145240 
145241  if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
145242  else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
145243  else iCol2 = 0;
145244 
145245  if( iCol1==iCol2 ){
145246  sqlite3_int64 i1 = 0; /* Last position from pp1 */
145247  sqlite3_int64 i2 = 0; /* Last position from pp2 */
145248  sqlite3_int64 iPrev = 0;
145249  int n = fts3PutColNumber(&p, iCol1);
145250  p1 += n;
145251  p2 += n;
145252 
145253  /* At this point, both p1 and p2 point to the start of column-lists
145254  ** for the same column (the column with index iCol1 and iCol2).
145255  ** A column-list is a list of non-negative delta-encoded varints, each
145256  ** incremented by 2 before being stored. Each list is terminated by a
145257  ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
145258  ** and writes the results to buffer p. p is left pointing to the byte
145259  ** after the list written. No terminator (POS_END or POS_COLUMN) is
145260  ** written to the output.
145261  */
145262  fts3GetDeltaVarint(&p1, &i1);
145263  fts3GetDeltaVarint(&p2, &i2);
145264  do {
145265  fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
145266  iPrev -= 2;
145267  if( i1==i2 ){
145268  fts3ReadNextPos(&p1, &i1);
145269  fts3ReadNextPos(&p2, &i2);
145270  }else if( i1<i2 ){
145271  fts3ReadNextPos(&p1, &i1);
145272  }else{
145273  fts3ReadNextPos(&p2, &i2);
145274  }
145275  }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
145276  }else if( iCol1<iCol2 ){
145277  p1 += fts3PutColNumber(&p, iCol1);
145278  fts3ColumnlistCopy(&p, &p1);
145279  }else{
145280  p2 += fts3PutColNumber(&p, iCol2);
145281  fts3ColumnlistCopy(&p, &p2);
145282  }
145283  }
145284 
145285  *p++ = POS_END;
145286  *pp = p;
145287  *pp1 = p1 + 1;
145288  *pp2 = p2 + 1;
145289 }
145290 
145291 /*
145292 ** This function is used to merge two position lists into one. When it is
145293 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
145294 ** the part of a doclist that follows each document id. For example, if a row
145295 ** contains:
145296 **
145297 ** 'a b c'|'x y z'|'a b b a'
145298 **
145299 ** Then the position list for this row for token 'b' would consist of:
145300 **
145301 ** 0x02 0x01 0x02 0x03 0x03 0x00
145302 **
145303 ** When this function returns, both *pp1 and *pp2 are left pointing to the
145304 ** byte following the 0x00 terminator of their respective position lists.
145305 **
145306 ** If isSaveLeft is 0, an entry is added to the output position list for
145307 ** each position in *pp2 for which there exists one or more positions in
145308 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
145309 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
145310 ** slots before it.
145311 **
145312 ** e.g. nToken==1 searches for adjacent positions.
145313 */
145314 static int fts3PoslistPhraseMerge(
145315  char **pp, /* IN/OUT: Preallocated output buffer */
145316  int nToken, /* Maximum difference in token positions */
145317  int isSaveLeft, /* Save the left position */
145318  int isExact, /* If *pp1 is exactly nTokens before *pp2 */
145319  char **pp1, /* IN/OUT: Left input list */
145320  char **pp2 /* IN/OUT: Right input list */
145321 ){
145322  char *p = *pp;
145323  char *p1 = *pp1;
145324  char *p2 = *pp2;
145325  int iCol1 = 0;
145326  int iCol2 = 0;
145327 
145328  /* Never set both isSaveLeft and isExact for the same invocation. */
145329  assert( isSaveLeft==0 || isExact==0 );
145330 
145331  assert( p!=0 && *p1!=0 && *p2!=0 );
145332  if( *p1==POS_COLUMN ){
145333  p1++;
145334  p1 += fts3GetVarint32(p1, &iCol1);
145335  }
145336  if( *p2==POS_COLUMN ){
145337  p2++;
145338  p2 += fts3GetVarint32(p2, &iCol2);
145339  }
145340 
145341  while( 1 ){
145342  if( iCol1==iCol2 ){
145343  char *pSave = p;
145344  sqlite3_int64 iPrev = 0;
145345  sqlite3_int64 iPos1 = 0;
145346  sqlite3_int64 iPos2 = 0;
145347 
145348  if( iCol1 ){
145349  *p++ = POS_COLUMN;
145350  p += sqlite3Fts3PutVarint(p, iCol1);
145351  }
145352 
145353  assert( *p1!=POS_END && *p1!=POS_COLUMN );
145354  assert( *p2!=POS_END && *p2!=POS_COLUMN );
145355  fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
145356  fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
145357 
145358  while( 1 ){
145359  if( iPos2==iPos1+nToken
145360  || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
145361  ){
145362  sqlite3_int64 iSave;
145363  iSave = isSaveLeft ? iPos1 : iPos2;
145364  fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
145365  pSave = 0;
145366  assert( p );
145367  }
145368  if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
145369  if( (*p2&0xFE)==0 ) break;
145370  fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
145371  }else{
145372  if( (*p1&0xFE)==0 ) break;
145373  fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
145374  }
145375  }
145376 
145377  if( pSave ){
145378  assert( pp && p );
145379  p = pSave;
145380  }
145381 
145382  fts3ColumnlistCopy(0, &p1);
145383  fts3ColumnlistCopy(0, &p2);
145384  assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
145385  if( 0==*p1 || 0==*p2 ) break;
145386 
145387  p1++;
145388  p1 += fts3GetVarint32(p1, &iCol1);
145389  p2++;
145390  p2 += fts3GetVarint32(p2, &iCol2);
145391  }
145392 
145393  /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
145394  ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
145395  ** end of the position list, or the 0x01 that precedes the next
145396  ** column-number in the position list.
145397  */
145398  else if( iCol1<iCol2 ){
145399  fts3ColumnlistCopy(0, &p1);
145400  if( 0==*p1 ) break;
145401  p1++;
145402  p1 += fts3GetVarint32(p1, &iCol1);
145403  }else{
145404  fts3ColumnlistCopy(0, &p2);
145405  if( 0==*p2 ) break;
145406  p2++;
145407  p2 += fts3GetVarint32(p2, &iCol2);
145408  }
145409  }
145410 
145411  fts3PoslistCopy(0, &p2);
145412  fts3PoslistCopy(0, &p1);
145413  *pp1 = p1;
145414  *pp2 = p2;
145415  if( *pp==p ){
145416  return 0;
145417  }
145418  *p++ = 0x00;
145419  *pp = p;
145420  return 1;
145421 }
145422 
145423 /*
145424 ** Merge two position-lists as required by the NEAR operator. The argument
145425 ** position lists correspond to the left and right phrases of an expression
145426 ** like:
145427 **
145428 ** "phrase 1" NEAR "phrase number 2"
145429 **
145430 ** Position list *pp1 corresponds to the left-hand side of the NEAR
145431 ** expression and *pp2 to the right. As usual, the indexes in the position
145432 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
145433 ** in the example above).
145434 **
145435 ** The output position list - written to *pp - is a copy of *pp2 with those
145436 ** entries that are not sufficiently NEAR entries in *pp1 removed.
145437 */
145438 static int fts3PoslistNearMerge(
145439  char **pp, /* Output buffer */
145440  char *aTmp, /* Temporary buffer space */
145441  int nRight, /* Maximum difference in token positions */
145442  int nLeft, /* Maximum difference in token positions */
145443  char **pp1, /* IN/OUT: Left input list */
145444  char **pp2 /* IN/OUT: Right input list */
145445 ){
145446  char *p1 = *pp1;
145447  char *p2 = *pp2;
145448 
145449  char *pTmp1 = aTmp;
145450  char *pTmp2;
145451  char *aTmp2;
145452  int res = 1;
145453 
145454  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
145455  aTmp2 = pTmp2 = pTmp1;
145456  *pp1 = p1;
145457  *pp2 = p2;
145458  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
145459  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
145460  fts3PoslistMerge(pp, &aTmp, &aTmp2);
145461  }else if( pTmp1!=aTmp ){
145462  fts3PoslistCopy(pp, &aTmp);
145463  }else if( pTmp2!=aTmp2 ){
145464  fts3PoslistCopy(pp, &aTmp2);
145465  }else{
145466  res = 0;
145467  }
145468 
145469  return res;
145470 }
145471 
145472 /*
145473 ** An instance of this function is used to merge together the (potentially
145474 ** large number of) doclists for each term that matches a prefix query.
145475 ** See function fts3TermSelectMerge() for details.
145476 */
145477 typedef struct TermSelect TermSelect;
145478 struct TermSelect {
145479  char *aaOutput[16]; /* Malloc'd output buffers */
145480  int anOutput[16]; /* Size each output buffer in bytes */
145481 };
145482 
145483 /*
145484 ** This function is used to read a single varint from a buffer. Parameter
145485 ** pEnd points 1 byte past the end of the buffer. When this function is
145486 ** called, if *pp points to pEnd or greater, then the end of the buffer
145487 ** has been reached. In this case *pp is set to 0 and the function returns.
145488 **
145489 ** If *pp does not point to or past pEnd, then a single varint is read
145490 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
145491 **
145492 ** If bDescIdx is false, the value read is added to *pVal before returning.
145493 ** If it is true, the value read is subtracted from *pVal before this
145494 ** function returns.
145495 */
145496 static void fts3GetDeltaVarint3(
145497  char **pp, /* IN/OUT: Point to read varint from */
145498  char *pEnd, /* End of buffer */
145499  int bDescIdx, /* True if docids are descending */
145500  sqlite3_int64 *pVal /* IN/OUT: Integer value */
145501 ){
145502  if( *pp>=pEnd ){
145503  *pp = 0;
145504  }else{
145505  sqlite3_int64 iVal;
145506  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
145507  if( bDescIdx ){
145508  *pVal -= iVal;
145509  }else{
145510  *pVal += iVal;
145511  }
145512  }
145513 }
145514 
145515 /*
145516 ** This function is used to write a single varint to a buffer. The varint
145517 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
145518 ** end of the value written.
145519 **
145520 ** If *pbFirst is zero when this function is called, the value written to
145521 ** the buffer is that of parameter iVal.
145522 **
145523 ** If *pbFirst is non-zero when this function is called, then the value
145524 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
145525 ** (if bDescIdx is non-zero).
145526 **
145527 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
145528 ** to the value of parameter iVal.
145529 */
145530 static void fts3PutDeltaVarint3(
145531  char **pp, /* IN/OUT: Output pointer */
145532  int bDescIdx, /* True for descending docids */
145533  sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
145534  int *pbFirst, /* IN/OUT: True after first int written */
145535  sqlite3_int64 iVal /* Write this value to the list */
145536 ){
145537  sqlite3_int64 iWrite;
145538  if( bDescIdx==0 || *pbFirst==0 ){
145539  iWrite = iVal - *piPrev;
145540  }else{
145541  iWrite = *piPrev - iVal;
145542  }
145543  assert( *pbFirst || *piPrev==0 );
145544  assert( *pbFirst==0 || iWrite>0 );
145545  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
145546  *piPrev = iVal;
145547  *pbFirst = 1;
145548 }
145549 
145550 
145551 /*
145552 ** This macro is used by various functions that merge doclists. The two
145553 ** arguments are 64-bit docid values. If the value of the stack variable
145554 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
145555 ** Otherwise, (i2-i1).
145556 **
145557 ** Using this makes it easier to write code that can merge doclists that are
145558 ** sorted in either ascending or descending order.
145559 */
145560 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
145561 
145562 /*
145563 ** This function does an "OR" merge of two doclists (output contains all
145564 ** positions contained in either argument doclist). If the docids in the
145565 ** input doclists are sorted in ascending order, parameter bDescDoclist
145566 ** should be false. If they are sorted in ascending order, it should be
145567 ** passed a non-zero value.
145568 **
145569 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
145570 ** containing the output doclist and SQLITE_OK is returned. In this case
145571 ** *pnOut is set to the number of bytes in the output doclist.
145572 **
145573 ** If an error occurs, an SQLite error code is returned. The output values
145574 ** are undefined in this case.
145575 */
145576 static int fts3DoclistOrMerge(
145577  int bDescDoclist, /* True if arguments are desc */
145578  char *a1, int n1, /* First doclist */
145579  char *a2, int n2, /* Second doclist */
145580  char **paOut, int *pnOut /* OUT: Malloc'd doclist */
145581 ){
145582  sqlite3_int64 i1 = 0;
145583  sqlite3_int64 i2 = 0;
145584  sqlite3_int64 iPrev = 0;
145585  char *pEnd1 = &a1[n1];
145586  char *pEnd2 = &a2[n2];
145587  char *p1 = a1;
145588  char *p2 = a2;
145589  char *p;
145590  char *aOut;
145591  int bFirstOut = 0;
145592 
145593  *paOut = 0;
145594  *pnOut = 0;
145595 
145596  /* Allocate space for the output. Both the input and output doclists
145597  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
145598  ** then the first docid in each list is simply encoded as a varint. For
145599  ** each subsequent docid, the varint stored is the difference between the
145600  ** current and previous docid (a positive number - since the list is in
145601  ** ascending order).
145602  **
145603  ** The first docid written to the output is therefore encoded using the
145604  ** same number of bytes as it is in whichever of the input lists it is
145605  ** read from. And each subsequent docid read from the same input list
145606  ** consumes either the same or less bytes as it did in the input (since
145607  ** the difference between it and the previous value in the output must
145608  ** be a positive value less than or equal to the delta value read from
145609  ** the input list). The same argument applies to all but the first docid
145610  ** read from the 'other' list. And to the contents of all position lists
145611  ** that will be copied and merged from the input to the output.
145612  **
145613  ** However, if the first docid copied to the output is a negative number,
145614  ** then the encoding of the first docid from the 'other' input list may
145615  ** be larger in the output than it was in the input (since the delta value
145616  ** may be a larger positive integer than the actual docid).
145617  **
145618  ** The space required to store the output is therefore the sum of the
145619  ** sizes of the two inputs, plus enough space for exactly one of the input
145620  ** docids to grow.
145621  **
145622  ** A symetric argument may be made if the doclists are in descending
145623  ** order.
145624  */
145625  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
145626  if( !aOut ) return SQLITE_NOMEM;
145627 
145628  p = aOut;
145629  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
145630  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
145631  while( p1 || p2 ){
145632  sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
145633 
145634  if( p2 && p1 && iDiff==0 ){
145635  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
145636  fts3PoslistMerge(&p, &p1, &p2);
145637  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
145638  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
145639  }else if( !p2 || (p1 && iDiff<0) ){
145640  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
145641  fts3PoslistCopy(&p, &p1);
145642  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
145643  }else{
145644  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
145645  fts3PoslistCopy(&p, &p2);
145646  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
145647  }
145648  }
145649 
145650  *paOut = aOut;
145651  *pnOut = (int)(p-aOut);
145652  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
145653  return SQLITE_OK;
145654 }
145655 
145656 /*
145657 ** This function does a "phrase" merge of two doclists. In a phrase merge,
145658 ** the output contains a copy of each position from the right-hand input
145659 ** doclist for which there is a position in the left-hand input doclist
145660 ** exactly nDist tokens before it.
145661 **
145662 ** If the docids in the input doclists are sorted in ascending order,
145663 ** parameter bDescDoclist should be false. If they are sorted in ascending
145664 ** order, it should be passed a non-zero value.
145665 **
145666 ** The right-hand input doclist is overwritten by this function.
145667 */
145668 static int fts3DoclistPhraseMerge(
145669  int bDescDoclist, /* True if arguments are desc */
145670  int nDist, /* Distance from left to right (1=adjacent) */
145671  char *aLeft, int nLeft, /* Left doclist */
145672  char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
145673 ){
145674  sqlite3_int64 i1 = 0;
145675  sqlite3_int64 i2 = 0;
145676  sqlite3_int64 iPrev = 0;
145677  char *aRight = *paRight;
145678  char *pEnd1 = &aLeft[nLeft];
145679  char *pEnd2 = &aRight[*pnRight];
145680  char *p1 = aLeft;
145681  char *p2 = aRight;
145682  char *p;
145683  int bFirstOut = 0;
145684  char *aOut;
145685 
145686  assert( nDist>0 );
145687  if( bDescDoclist ){
145688  aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
145689  if( aOut==0 ) return SQLITE_NOMEM;
145690  }else{
145691  aOut = aRight;
145692  }
145693  p = aOut;
145694 
145695  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
145696  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
145697 
145698  while( p1 && p2 ){
145699  sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
145700  if( iDiff==0 ){
145701  char *pSave = p;
145702  sqlite3_int64 iPrevSave = iPrev;
145703  int bFirstOutSave = bFirstOut;
145704 
145705  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
145706  if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
145707  p = pSave;
145708  iPrev = iPrevSave;
145709  bFirstOut = bFirstOutSave;
145710  }
145711  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
145712  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
145713  }else if( iDiff<0 ){
145714  fts3PoslistCopy(0, &p1);
145715  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
145716  }else{
145717  fts3PoslistCopy(0, &p2);
145718  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
145719  }
145720  }
145721 
145722  *pnRight = (int)(p - aOut);
145723  if( bDescDoclist ){
145724  sqlite3_free(aRight);
145725  *paRight = aOut;
145726  }
145727 
145728  return SQLITE_OK;
145729 }
145730 
145731 /*
145732 ** Argument pList points to a position list nList bytes in size. This
145733 ** function checks to see if the position list contains any entries for
145734 ** a token in position 0 (of any column). If so, it writes argument iDelta
145735 ** to the output buffer pOut, followed by a position list consisting only
145736 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
145737 ** The value returned is the number of bytes written to pOut (if any).
145738 */
145739 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
145740  sqlite3_int64 iDelta, /* Varint that may be written to pOut */
145741  char *pList, /* Position list (no 0x00 term) */
145742  int nList, /* Size of pList in bytes */
145743  char *pOut /* Write output here */
145744 ){
145745  int nOut = 0;
145746  int bWritten = 0; /* True once iDelta has been written */
145747  char *p = pList;
145748  char *pEnd = &pList[nList];
145749 
145750  if( *p!=0x01 ){
145751  if( *p==0x02 ){
145752  nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
145753  pOut[nOut++] = 0x02;
145754  bWritten = 1;
145755  }
145756  fts3ColumnlistCopy(0, &p);
145757  }
145758 
145759  while( p<pEnd && *p==0x01 ){
145760  sqlite3_int64 iCol;
145761  p++;
145762  p += sqlite3Fts3GetVarint(p, &iCol);
145763  if( *p==0x02 ){
145764  if( bWritten==0 ){
145765  nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
145766  bWritten = 1;
145767  }
145768  pOut[nOut++] = 0x01;
145769  nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
145770  pOut[nOut++] = 0x02;
145771  }
145772  fts3ColumnlistCopy(0, &p);
145773  }
145774  if( bWritten ){
145775  pOut[nOut++] = 0x00;
145776  }
145777 
145778  return nOut;
145779 }
145780 
145781 
145782 /*
145783 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
145784 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
145785 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
145786 **
145787 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
145788 ** the responsibility of the caller to free any doclists left in the
145789 ** TermSelect.aaOutput[] array.
145790 */
145791 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
145792  char *aOut = 0;
145793  int nOut = 0;
145794  int i;
145795 
145796  /* Loop through the doclists in the aaOutput[] array. Merge them all
145797  ** into a single doclist.
145798  */
145799  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
145800  if( pTS->aaOutput[i] ){
145801  if( !aOut ){
145802  aOut = pTS->aaOutput[i];
145803  nOut = pTS->anOutput[i];
145804  pTS->aaOutput[i] = 0;
145805  }else{
145806  int nNew;
145807  char *aNew;
145808 
145809  int rc = fts3DoclistOrMerge(p->bDescIdx,
145810  pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
145811  );
145812  if( rc!=SQLITE_OK ){
145813  sqlite3_free(aOut);
145814  return rc;
145815  }
145816 
145817  sqlite3_free(pTS->aaOutput[i]);
145818  sqlite3_free(aOut);
145819  pTS->aaOutput[i] = 0;
145820  aOut = aNew;
145821  nOut = nNew;
145822  }
145823  }
145824  }
145825 
145826  pTS->aaOutput[0] = aOut;
145827  pTS->anOutput[0] = nOut;
145828  return SQLITE_OK;
145829 }
145830 
145831 /*
145832 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
145833 ** as the first argument. The merge is an "OR" merge (see function
145834 ** fts3DoclistOrMerge() for details).
145835 **
145836 ** This function is called with the doclist for each term that matches
145837 ** a queried prefix. It merges all these doclists into one, the doclist
145838 ** for the specified prefix. Since there can be a very large number of
145839 ** doclists to merge, the merging is done pair-wise using the TermSelect
145840 ** object.
145841 **
145842 ** This function returns SQLITE_OK if the merge is successful, or an
145843 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
145844 */
145845 static int fts3TermSelectMerge(
145846  Fts3Table *p, /* FTS table handle */
145847  TermSelect *pTS, /* TermSelect object to merge into */
145848  char *aDoclist, /* Pointer to doclist */
145849  int nDoclist /* Size of aDoclist in bytes */
145850 ){
145851  if( pTS->aaOutput[0]==0 ){
145852  /* If this is the first term selected, copy the doclist to the output
145853  ** buffer using memcpy().
145854  **
145855  ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
145856  ** allocation. This is so as to ensure that the buffer is big enough
145857  ** to hold the current doclist AND'd with any other doclist. If the
145858  ** doclists are stored in order=ASC order, this padding would not be
145859  ** required (since the size of [doclistA AND doclistB] is always less
145860  ** than or equal to the size of [doclistA] in that case). But this is
145861  ** not true for order=DESC. For example, a doclist containing (1, -1)
145862  ** may be smaller than (-1), as in the first example the -1 may be stored
145863  ** as a single-byte delta, whereas in the second it must be stored as a
145864  ** FTS3_VARINT_MAX byte varint.
145865  **
145866  ** Similar padding is added in the fts3DoclistOrMerge() function.
145867  */
145868  pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
145869  pTS->anOutput[0] = nDoclist;
145870  if( pTS->aaOutput[0] ){
145871  memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
145872  }else{
145873  return SQLITE_NOMEM;
145874  }
145875  }else{
145876  char *aMerge = aDoclist;
145877  int nMerge = nDoclist;
145878  int iOut;
145879 
145880  for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
145881  if( pTS->aaOutput[iOut]==0 ){
145882  assert( iOut>0 );
145883  pTS->aaOutput[iOut] = aMerge;
145884  pTS->anOutput[iOut] = nMerge;
145885  break;
145886  }else{
145887  char *aNew;
145888  int nNew;
145889 
145890  int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
145891  pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
145892  );
145893  if( rc!=SQLITE_OK ){
145894  if( aMerge!=aDoclist ) sqlite3_free(aMerge);
145895  return rc;
145896  }
145897 
145898  if( aMerge!=aDoclist ) sqlite3_free(aMerge);
145899  sqlite3_free(pTS->aaOutput[iOut]);
145900  pTS->aaOutput[iOut] = 0;
145901 
145902  aMerge = aNew;
145903  nMerge = nNew;
145904  if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
145905  pTS->aaOutput[iOut] = aMerge;
145906  pTS->anOutput[iOut] = nMerge;
145907  }
145908  }
145909  }
145910  }
145911  return SQLITE_OK;
145912 }
145913 
145914 /*
145915 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
145916 */
145917 static int fts3SegReaderCursorAppend(
145918  Fts3MultiSegReader *pCsr,
145919  Fts3SegReader *pNew
145920 ){
145921  if( (pCsr->nSegment%16)==0 ){
145922  Fts3SegReader **apNew;
145923  int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
145924  apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
145925  if( !apNew ){
145926  sqlite3Fts3SegReaderFree(pNew);
145927  return SQLITE_NOMEM;
145928  }
145929  pCsr->apSegment = apNew;
145930  }
145931  pCsr->apSegment[pCsr->nSegment++] = pNew;
145932  return SQLITE_OK;
145933 }
145934 
145935 /*
145936 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
145937 ** 8th argument.
145938 **
145939 ** This function returns SQLITE_OK if successful, or an SQLite error code
145940 ** otherwise.
145941 */
145942 static int fts3SegReaderCursor(
145943  Fts3Table *p, /* FTS3 table handle */
145944  int iLangid, /* Language id */
145945  int iIndex, /* Index to search (from 0 to p->nIndex-1) */
145946  int iLevel, /* Level of segments to scan */
145947  const char *zTerm, /* Term to query for */
145948  int nTerm, /* Size of zTerm in bytes */
145949  int isPrefix, /* True for a prefix search */
145950  int isScan, /* True to scan from zTerm to EOF */
145951  Fts3MultiSegReader *pCsr /* Cursor object to populate */
145952 ){
145953  int rc = SQLITE_OK; /* Error code */
145954  sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
145955  int rc2; /* Result of sqlite3_reset() */
145956 
145957  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
145958  ** for the pending-terms. If this is a scan, then this call must be being
145959  ** made by an fts4aux module, not an FTS table. In this case calling
145960  ** Fts3SegReaderPending might segfault, as the data structures used by
145961  ** fts4aux are not completely populated. So it's easiest to filter these
145962  ** calls out here. */
145963  if( iLevel<0 && p->aIndex ){
145964  Fts3SegReader *pSeg = 0;
145965  rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
145966  if( rc==SQLITE_OK && pSeg ){
145967  rc = fts3SegReaderCursorAppend(pCsr, pSeg);
145968  }
145969  }
145970 
145971  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
145972  if( rc==SQLITE_OK ){
145973  rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
145974  }
145975 
145976  while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
145977  Fts3SegReader *pSeg = 0;
145978 
145979  /* Read the values returned by the SELECT into local variables. */
145980  sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
145981  sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
145982  sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
145983  int nRoot = sqlite3_column_bytes(pStmt, 4);
145984  char const *zRoot = sqlite3_column_blob(pStmt, 4);
145985 
145986  /* If zTerm is not NULL, and this segment is not stored entirely on its
145987  ** root node, the range of leaves scanned can be reduced. Do this. */
145988  if( iStartBlock && zTerm ){
145989  sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
145990  rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
145991  if( rc!=SQLITE_OK ) goto finished;
145992  if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
145993  }
145994 
145995  rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
145996  (isPrefix==0 && isScan==0),
145997  iStartBlock, iLeavesEndBlock,
145998  iEndBlock, zRoot, nRoot, &pSeg
145999  );
146000  if( rc!=SQLITE_OK ) goto finished;
146001  rc = fts3SegReaderCursorAppend(pCsr, pSeg);
146002  }
146003  }
146004 
146005  finished:
146006  rc2 = sqlite3_reset(pStmt);
146007  if( rc==SQLITE_DONE ) rc = rc2;
146008 
146009  return rc;
146010 }
146011 
146012 /*
146013 ** Set up a cursor object for iterating through a full-text index or a
146014 ** single level therein.
146015 */
146016 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
146017  Fts3Table *p, /* FTS3 table handle */
146018  int iLangid, /* Language-id to search */
146019  int iIndex, /* Index to search (from 0 to p->nIndex-1) */
146020  int iLevel, /* Level of segments to scan */
146021  const char *zTerm, /* Term to query for */
146022  int nTerm, /* Size of zTerm in bytes */
146023  int isPrefix, /* True for a prefix search */
146024  int isScan, /* True to scan from zTerm to EOF */
146025  Fts3MultiSegReader *pCsr /* Cursor object to populate */
146026 ){
146027  assert( iIndex>=0 && iIndex<p->nIndex );
146028  assert( iLevel==FTS3_SEGCURSOR_ALL
146029  || iLevel==FTS3_SEGCURSOR_PENDING
146030  || iLevel>=0
146031  );
146032  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
146033  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
146034  assert( isPrefix==0 || isScan==0 );
146035 
146036  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
146037  return fts3SegReaderCursor(
146038  p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
146039  );
146040 }
146041 
146042 /*
146043 ** In addition to its current configuration, have the Fts3MultiSegReader
146044 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
146045 **
146046 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
146047 */
146048 static int fts3SegReaderCursorAddZero(
146049  Fts3Table *p, /* FTS virtual table handle */
146050  int iLangid,
146051  const char *zTerm, /* Term to scan doclist of */
146052  int nTerm, /* Number of bytes in zTerm */
146053  Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
146054 ){
146055  return fts3SegReaderCursor(p,
146056  iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
146057  );
146058 }
146059 
146060 /*
146061 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
146062 ** if isPrefix is true, to scan the doclist for all terms for which
146063 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
146064 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
146065 ** an SQLite error code.
146066 **
146067 ** It is the responsibility of the caller to free this object by eventually
146068 ** passing it to fts3SegReaderCursorFree()
146069 **
146070 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
146071 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
146072 */
146073 static int fts3TermSegReaderCursor(
146074  Fts3Cursor *pCsr, /* Virtual table cursor handle */
146075  const char *zTerm, /* Term to query for */
146076  int nTerm, /* Size of zTerm in bytes */
146077  int isPrefix, /* True for a prefix search */
146078  Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
146079 ){
146080  Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
146081  int rc = SQLITE_NOMEM; /* Return code */
146082 
146083  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
146084  if( pSegcsr ){
146085  int i;
146086  int bFound = 0; /* True once an index has been found */
146087  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
146088 
146089  if( isPrefix ){
146090  for(i=1; bFound==0 && i<p->nIndex; i++){
146091  if( p->aIndex[i].nPrefix==nTerm ){
146092  bFound = 1;
146093  rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
146094  i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
146095  );
146096  pSegcsr->bLookup = 1;
146097  }
146098  }
146099 
146100  for(i=1; bFound==0 && i<p->nIndex; i++){
146101  if( p->aIndex[i].nPrefix==nTerm+1 ){
146102  bFound = 1;
146103  rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
146104  i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
146105  );
146106  if( rc==SQLITE_OK ){
146107  rc = fts3SegReaderCursorAddZero(
146108  p, pCsr->iLangid, zTerm, nTerm, pSegcsr
146109  );
146110  }
146111  }
146112  }
146113  }
146114 
146115  if( bFound==0 ){
146116  rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
146117  0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
146118  );
146119  pSegcsr->bLookup = !isPrefix;
146120  }
146121  }
146122 
146123  *ppSegcsr = pSegcsr;
146124  return rc;
146125 }
146126 
146127 /*
146128 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
146129 */
146130 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
146131  sqlite3Fts3SegReaderFinish(pSegcsr);
146132  sqlite3_free(pSegcsr);
146133 }
146134 
146135 /*
146136 ** This function retrieves the doclist for the specified term (or term
146137 ** prefix) from the database.
146138 */
146139 static int fts3TermSelect(
146140  Fts3Table *p, /* Virtual table handle */
146141  Fts3PhraseToken *pTok, /* Token to query for */
146142  int iColumn, /* Column to query (or -ve for all columns) */
146143  int *pnOut, /* OUT: Size of buffer at *ppOut */
146144  char **ppOut /* OUT: Malloced result buffer */
146145 ){
146146  int rc; /* Return code */
146147  Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
146148  TermSelect tsc; /* Object for pair-wise doclist merging */
146149  Fts3SegFilter filter; /* Segment term filter configuration */
146150 
146151  pSegcsr = pTok->pSegcsr;
146152  memset(&tsc, 0, sizeof(TermSelect));
146153 
146154  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
146155  | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
146156  | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
146157  | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
146158  filter.iCol = iColumn;
146159  filter.zTerm = pTok->z;
146160  filter.nTerm = pTok->n;
146161 
146162  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
146163  while( SQLITE_OK==rc
146164  && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
146165  ){
146166  rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
146167  }
146168 
146169  if( rc==SQLITE_OK ){
146170  rc = fts3TermSelectFinishMerge(p, &tsc);
146171  }
146172  if( rc==SQLITE_OK ){
146173  *ppOut = tsc.aaOutput[0];
146174  *pnOut = tsc.anOutput[0];
146175  }else{
146176  int i;
146177  for(i=0; i<SizeofArray(tsc.aaOutput); i++){
146178  sqlite3_free(tsc.aaOutput[i]);
146179  }
146180  }
146181 
146182  fts3SegReaderCursorFree(pSegcsr);
146183  pTok->pSegcsr = 0;
146184  return rc;
146185 }
146186 
146187 /*
146188 ** This function counts the total number of docids in the doclist stored
146189 ** in buffer aList[], size nList bytes.
146190 **
146191 ** If the isPoslist argument is true, then it is assumed that the doclist
146192 ** contains a position-list following each docid. Otherwise, it is assumed
146193 ** that the doclist is simply a list of docids stored as delta encoded
146194 ** varints.
146195 */
146196 static int fts3DoclistCountDocids(char *aList, int nList){
146197  int nDoc = 0; /* Return value */
146198  if( aList ){
146199  char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
146200  char *p = aList; /* Cursor */
146201  while( p<aEnd ){
146202  nDoc++;
146203  while( (*p++)&0x80 ); /* Skip docid varint */
146204  fts3PoslistCopy(0, &p); /* Skip over position list */
146205  }
146206  }
146207 
146208  return nDoc;
146209 }
146210 
146211 /*
146212 ** Advance the cursor to the next row in the %_content table that
146213 ** matches the search criteria. For a MATCH search, this will be
146214 ** the next row that matches. For a full-table scan, this will be
146215 ** simply the next row in the %_content table. For a docid lookup,
146216 ** this routine simply sets the EOF flag.
146217 **
146218 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
146219 ** even if we reach end-of-file. The fts3EofMethod() will be called
146220 ** subsequently to determine whether or not an EOF was hit.
146221 */
146222 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
146223  int rc;
146224  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
146225  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
146226  if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
146227  pCsr->isEof = 1;
146228  rc = sqlite3_reset(pCsr->pStmt);
146229  }else{
146230  pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
146231  rc = SQLITE_OK;
146232  }
146233  }else{
146234  rc = fts3EvalNext((Fts3Cursor *)pCursor);
146235  }
146236  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
146237  return rc;
146238 }
146239 
146240 /*
146241 ** The following are copied from sqliteInt.h.
146242 **
146243 ** Constants for the largest and smallest possible 64-bit signed integers.
146244 ** These macros are designed to work correctly on both 32-bit and 64-bit
146245 ** compilers.
146246 */
146247 #ifndef SQLITE_AMALGAMATION
146248 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
146249 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
146250 #endif
146251 
146252 /*
146253 ** If the numeric type of argument pVal is "integer", then return it
146254 ** converted to a 64-bit signed integer. Otherwise, return a copy of
146255 ** the second parameter, iDefault.
146256 */
146257 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
146258  if( pVal ){
146259  int eType = sqlite3_value_numeric_type(pVal);
146260  if( eType==SQLITE_INTEGER ){
146261  return sqlite3_value_int64(pVal);
146262  }
146263  }
146264  return iDefault;
146265 }
146266 
146267 /*
146268 ** This is the xFilter interface for the virtual table. See
146269 ** the virtual table xFilter method documentation for additional
146270 ** information.
146271 **
146272 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
146273 ** the %_content table.
146274 **
146275 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
146276 ** in the %_content table.
146277 **
146278 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
146279 ** column on the left-hand side of the MATCH operator is column
146280 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
146281 ** side of the MATCH operator.
146282 */
146283 static int fts3FilterMethod(
146284  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
146285  int idxNum, /* Strategy index */
146286  const char *idxStr, /* Unused */
146287  int nVal, /* Number of elements in apVal */
146288  sqlite3_value **apVal /* Arguments for the indexing scheme */
146289 ){
146290  int rc = SQLITE_OK;
146291  char *zSql; /* SQL statement used to access %_content */
146292  int eSearch;
146293  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
146294  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
146295 
146296  sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
146297  sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
146298  sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
146299  sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
146300  int iIdx;
146301 
146302  UNUSED_PARAMETER(idxStr);
146303  UNUSED_PARAMETER(nVal);
146304 
146305  eSearch = (idxNum & 0x0000FFFF);
146306  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
146307  assert( p->pSegments==0 );
146308 
146309  /* Collect arguments into local variables */
146310  iIdx = 0;
146311  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
146312  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
146313  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
146314  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
146315  assert( iIdx==nVal );
146316 
146317  /* In case the cursor has been used before, clear it now. */
146318  sqlite3_finalize(pCsr->pStmt);
146319  sqlite3_free(pCsr->aDoclist);
146320  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
146321  sqlite3Fts3ExprFree(pCsr->pExpr);
146322  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
146323 
146324  /* Set the lower and upper bounds on docids to return */
146325  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
146326  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
146327 
146328  if( idxStr ){
146329  pCsr->bDesc = (idxStr[0]=='D');
146330  }else{
146331  pCsr->bDesc = p->bDescIdx;
146332  }
146333  pCsr->eSearch = (i16)eSearch;
146334 
146335  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
146336  int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
146337  const char *zQuery = (const char *)sqlite3_value_text(pCons);
146338 
146339  if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
146340  return SQLITE_NOMEM;
146341  }
146342 
146343  pCsr->iLangid = 0;
146344  if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
146345 
146346  assert( p->base.zErrMsg==0 );
146347  rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
146348  p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
146349  &p->base.zErrMsg
146350  );
146351  if( rc!=SQLITE_OK ){
146352  return rc;
146353  }
146354 
146355  rc = fts3EvalStart(pCsr);
146356  sqlite3Fts3SegmentsClose(p);
146357  if( rc!=SQLITE_OK ) return rc;
146358  pCsr->pNextId = pCsr->aDoclist;
146359  pCsr->iPrevId = 0;
146360  }
146361 
146362  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
146363  ** statement loops through all rows of the %_content table. For a
146364  ** full-text query or docid lookup, the statement retrieves a single
146365  ** row by docid.
146366  */
146367  if( eSearch==FTS3_FULLSCAN_SEARCH ){
146368  if( pDocidGe || pDocidLe ){
146369  zSql = sqlite3_mprintf(
146370  "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
146371  p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
146372  (pCsr->bDesc ? "DESC" : "ASC")
146373  );
146374  }else{
146375  zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
146376  p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
146377  );
146378  }
146379  if( zSql ){
146380  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
146381  sqlite3_free(zSql);
146382  }else{
146383  rc = SQLITE_NOMEM;
146384  }
146385  }else if( eSearch==FTS3_DOCID_SEARCH ){
146386  rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
146387  if( rc==SQLITE_OK ){
146388  rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
146389  }
146390  }
146391  if( rc!=SQLITE_OK ) return rc;
146392 
146393  return fts3NextMethod(pCursor);
146394 }
146395 
146396 /*
146397 ** This is the xEof method of the virtual table. SQLite calls this
146398 ** routine to find out if it has reached the end of a result set.
146399 */
146400 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
146401  return ((Fts3Cursor *)pCursor)->isEof;
146402 }
146403 
146404 /*
146405 ** This is the xRowid method. The SQLite core calls this routine to
146406 ** retrieve the rowid for the current row of the result set. fts3
146407 ** exposes %_content.docid as the rowid for the virtual table. The
146408 ** rowid should be written to *pRowid.
146409 */
146410 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
146411  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
146412  *pRowid = pCsr->iPrevId;
146413  return SQLITE_OK;
146414 }
146415 
146416 /*
146417 ** This is the xColumn method, called by SQLite to request a value from
146418 ** the row that the supplied cursor currently points to.
146419 **
146420 ** If:
146421 **
146422 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
146423 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
146424 ** (iCol == p->nColumn+1) -> Docid column
146425 ** (iCol == p->nColumn+2) -> Langid column
146426 */
146427 static int fts3ColumnMethod(
146428  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
146429  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
146430  int iCol /* Index of column to read value from */
146431 ){
146432  int rc = SQLITE_OK; /* Return Code */
146433  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
146434  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
146435 
146436  /* The column value supplied by SQLite must be in range. */
146437  assert( iCol>=0 && iCol<=p->nColumn+2 );
146438 
146439  if( iCol==p->nColumn+1 ){
146440  /* This call is a request for the "docid" column. Since "docid" is an
146441  ** alias for "rowid", use the xRowid() method to obtain the value.
146442  */
146443  sqlite3_result_int64(pCtx, pCsr->iPrevId);
146444  }else if( iCol==p->nColumn ){
146445  /* The extra column whose name is the same as the table.
146446  ** Return a blob which is a pointer to the cursor. */
146447  sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
146448  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
146449  sqlite3_result_int64(pCtx, pCsr->iLangid);
146450  }else{
146451  /* The requested column is either a user column (one that contains
146452  ** indexed data), or the language-id column. */
146453  rc = fts3CursorSeek(0, pCsr);
146454 
146455  if( rc==SQLITE_OK ){
146456  if( iCol==p->nColumn+2 ){
146457  int iLangid = 0;
146458  if( p->zLanguageid ){
146459  iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
146460  }
146461  sqlite3_result_int(pCtx, iLangid);
146462  }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
146463  sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
146464  }
146465  }
146466  }
146467 
146468  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
146469  return rc;
146470 }
146471 
146472 /*
146473 ** This function is the implementation of the xUpdate callback used by
146474 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
146475 ** inserted, updated or deleted.
146476 */
146477 static int fts3UpdateMethod(
146478  sqlite3_vtab *pVtab, /* Virtual table handle */
146479  int nArg, /* Size of argument array */
146480  sqlite3_value **apVal, /* Array of arguments */
146481  sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
146482 ){
146483  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
146484 }
146485 
146486 /*
146487 ** Implementation of xSync() method. Flush the contents of the pending-terms
146488 ** hash-table to the database.
146489 */
146490 static int fts3SyncMethod(sqlite3_vtab *pVtab){
146491 
146492  /* Following an incremental-merge operation, assuming that the input
146493  ** segments are not completely consumed (the usual case), they are updated
146494  ** in place to remove the entries that have already been merged. This
146495  ** involves updating the leaf block that contains the smallest unmerged
146496  ** entry and each block (if any) between the leaf and the root node. So
146497  ** if the height of the input segment b-trees is N, and input segments
146498  ** are merged eight at a time, updating the input segments at the end
146499  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
146500  ** small - often between 0 and 2. So the overhead of the incremental
146501  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
146502  ** dwarfing the actual productive work accomplished, the incremental merge
146503  ** is only attempted if it will write at least 64 leaf blocks. Hence
146504  ** nMinMerge.
146505  **
146506  ** Of course, updating the input segments also involves deleting a bunch
146507  ** of blocks from the segments table. But this is not considered overhead
146508  ** as it would also be required by a crisis-merge that used the same input
146509  ** segments.
146510  */
146511  const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
146512 
146513  Fts3Table *p = (Fts3Table*)pVtab;
146514  int rc = sqlite3Fts3PendingTermsFlush(p);
146515 
146516  if( rc==SQLITE_OK
146517  && p->nLeafAdd>(nMinMerge/16)
146518  && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
146519  ){
146520  int mxLevel = 0; /* Maximum relative level value in db */
146521  int A; /* Incr-merge parameter A */
146522 
146523  rc = sqlite3Fts3MaxLevel(p, &mxLevel);
146524  assert( rc==SQLITE_OK || mxLevel==0 );
146525  A = p->nLeafAdd * mxLevel;
146526  A += (A/2);
146527  if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
146528  }
146529  sqlite3Fts3SegmentsClose(p);
146530  return rc;
146531 }
146532 
146533 /*
146534 ** If it is currently unknown whether or not the FTS table has an %_stat
146535 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
146536 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
146537 ** if an error occurs.
146538 */
146539 static int fts3SetHasStat(Fts3Table *p){
146540  int rc = SQLITE_OK;
146541  if( p->bHasStat==2 ){
146542  const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
146543  char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
146544  if( zSql ){
146545  sqlite3_stmt *pStmt = 0;
146546  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
146547  if( rc==SQLITE_OK ){
146548  int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
146549  rc = sqlite3_finalize(pStmt);
146550  if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
146551  }
146552  sqlite3_free(zSql);
146553  }else{
146554  rc = SQLITE_NOMEM;
146555  }
146556  }
146557  return rc;
146558 }
146559 
146560 /*
146561 ** Implementation of xBegin() method.
146562 */
146563 static int fts3BeginMethod(sqlite3_vtab *pVtab){
146564  Fts3Table *p = (Fts3Table*)pVtab;
146565  UNUSED_PARAMETER(pVtab);
146566  assert( p->pSegments==0 );
146567  assert( p->nPendingData==0 );
146568  assert( p->inTransaction!=1 );
146569  TESTONLY( p->inTransaction = 1 );
146570  TESTONLY( p->mxSavepoint = -1; );
146571  p->nLeafAdd = 0;
146572  return fts3SetHasStat(p);
146573 }
146574 
146575 /*
146576 ** Implementation of xCommit() method. This is a no-op. The contents of
146577 ** the pending-terms hash-table have already been flushed into the database
146578 ** by fts3SyncMethod().
146579 */
146580 static int fts3CommitMethod(sqlite3_vtab *pVtab){
146581  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
146582  UNUSED_PARAMETER(pVtab);
146583  assert( p->nPendingData==0 );
146584  assert( p->inTransaction!=0 );
146585  assert( p->pSegments==0 );
146586  TESTONLY( p->inTransaction = 0 );
146587  TESTONLY( p->mxSavepoint = -1; );
146588  return SQLITE_OK;
146589 }
146590 
146591 /*
146592 ** Implementation of xRollback(). Discard the contents of the pending-terms
146593 ** hash-table. Any changes made to the database are reverted by SQLite.
146594 */
146595 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
146596  Fts3Table *p = (Fts3Table*)pVtab;
146597  sqlite3Fts3PendingTermsClear(p);
146598  assert( p->inTransaction!=0 );
146599  TESTONLY( p->inTransaction = 0 );
146600  TESTONLY( p->mxSavepoint = -1; );
146601  return SQLITE_OK;
146602 }
146603 
146604 /*
146605 ** When called, *ppPoslist must point to the byte immediately following the
146606 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
146607 ** moves *ppPoslist so that it instead points to the first byte of the
146608 ** same position list.
146609 */
146610 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
146611  char *p = &(*ppPoslist)[-2];
146612  char c = 0;
146613 
146614  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
146615  while( p>pStart && (c=*p--)==0 );
146616 
146617  /* Search backwards for a varint with value zero (the end of the previous
146618  ** poslist). This is an 0x00 byte preceded by some byte that does not
146619  ** have the 0x80 bit set. */
146620  while( p>pStart && (*p & 0x80) | c ){
146621  c = *p--;
146622  }
146623  assert( p==pStart || c==0 );
146624 
146625  /* At this point p points to that preceding byte without the 0x80 bit
146626  ** set. So to find the start of the poslist, skip forward 2 bytes then
146627  ** over a varint.
146628  **
146629  ** Normally. The other case is that p==pStart and the poslist to return
146630  ** is the first in the doclist. In this case do not skip forward 2 bytes.
146631  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
146632  ** is required for cases where the first byte of a doclist and the
146633  ** doclist is empty. For example, if the first docid is 10, a doclist
146634  ** that begins with:
146635  **
146636  ** 0x0A 0x00 <next docid delta varint>
146637  */
146638  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
146639  while( *p++&0x80 );
146640  *ppPoslist = p;
146641 }
146642 
146643 /*
146644 ** Helper function used by the implementation of the overloaded snippet(),
146645 ** offsets() and optimize() SQL functions.
146646 **
146647 ** If the value passed as the third argument is a blob of size
146648 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
146649 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
146650 ** message is written to context pContext and SQLITE_ERROR returned. The
146651 ** string passed via zFunc is used as part of the error message.
146652 */
146653 static int fts3FunctionArg(
146654  sqlite3_context *pContext, /* SQL function call context */
146655  const char *zFunc, /* Function name */
146656  sqlite3_value *pVal, /* argv[0] passed to function */
146657  Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
146658 ){
146659  Fts3Cursor *pRet;
146660  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
146661  || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
146662  ){
146663  char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
146664  sqlite3_result_error(pContext, zErr, -1);
146665  sqlite3_free(zErr);
146666  return SQLITE_ERROR;
146667  }
146668  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
146669  *ppCsr = pRet;
146670  return SQLITE_OK;
146671 }
146672 
146673 /*
146674 ** Implementation of the snippet() function for FTS3
146675 */
146676 static void fts3SnippetFunc(
146677  sqlite3_context *pContext, /* SQLite function call context */
146678  int nVal, /* Size of apVal[] array */
146679  sqlite3_value **apVal /* Array of arguments */
146680 ){
146681  Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
146682  const char *zStart = "<b>";
146683  const char *zEnd = "</b>";
146684  const char *zEllipsis = "<b>...</b>";
146685  int iCol = -1;
146686  int nToken = 15; /* Default number of tokens in snippet */
146687 
146688  /* There must be at least one argument passed to this function (otherwise
146689  ** the non-overloaded version would have been called instead of this one).
146690  */
146691  assert( nVal>=1 );
146692 
146693  if( nVal>6 ){
146694  sqlite3_result_error(pContext,
146695  "wrong number of arguments to function snippet()", -1);
146696  return;
146697  }
146698  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
146699 
146700  switch( nVal ){
146701  case 6: nToken = sqlite3_value_int(apVal[5]);
146702  case 5: iCol = sqlite3_value_int(apVal[4]);
146703  case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
146704  case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
146705  case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
146706  }
146707  if( !zEllipsis || !zEnd || !zStart ){
146708  sqlite3_result_error_nomem(pContext);
146709  }else if( nToken==0 ){
146710  sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
146711  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
146712  sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
146713  }
146714 }
146715 
146716 /*
146717 ** Implementation of the offsets() function for FTS3
146718 */
146719 static void fts3OffsetsFunc(
146720  sqlite3_context *pContext, /* SQLite function call context */
146721  int nVal, /* Size of argument array */
146722  sqlite3_value **apVal /* Array of arguments */
146723 ){
146724  Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
146725 
146726  UNUSED_PARAMETER(nVal);
146727 
146728  assert( nVal==1 );
146729  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
146730  assert( pCsr );
146731  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
146732  sqlite3Fts3Offsets(pContext, pCsr);
146733  }
146734 }
146735 
146736 /*
146737 ** Implementation of the special optimize() function for FTS3. This
146738 ** function merges all segments in the database to a single segment.
146739 ** Example usage is:
146740 **
146741 ** SELECT optimize(t) FROM t LIMIT 1;
146742 **
146743 ** where 't' is the name of an FTS3 table.
146744 */
146745 static void fts3OptimizeFunc(
146746  sqlite3_context *pContext, /* SQLite function call context */
146747  int nVal, /* Size of argument array */
146748  sqlite3_value **apVal /* Array of arguments */
146749 ){
146750  int rc; /* Return code */
146751  Fts3Table *p; /* Virtual table handle */
146752  Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
146753 
146754  UNUSED_PARAMETER(nVal);
146755 
146756  assert( nVal==1 );
146757  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
146758  p = (Fts3Table *)pCursor->base.pVtab;
146759  assert( p );
146760 
146761  rc = sqlite3Fts3Optimize(p);
146762 
146763  switch( rc ){
146764  case SQLITE_OK:
146765  sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
146766  break;
146767  case SQLITE_DONE:
146768  sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
146769  break;
146770  default:
146771  sqlite3_result_error_code(pContext, rc);
146772  break;
146773  }
146774 }
146775 
146776 /*
146777 ** Implementation of the matchinfo() function for FTS3
146778 */
146779 static void fts3MatchinfoFunc(
146780  sqlite3_context *pContext, /* SQLite function call context */
146781  int nVal, /* Size of argument array */
146782  sqlite3_value **apVal /* Array of arguments */
146783 ){
146784  Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
146785  assert( nVal==1 || nVal==2 );
146786  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
146787  const char *zArg = 0;
146788  if( nVal>1 ){
146789  zArg = (const char *)sqlite3_value_text(apVal[1]);
146790  }
146791  sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
146792  }
146793 }
146794 
146795 /*
146796 ** This routine implements the xFindFunction method for the FTS3
146797 ** virtual table.
146798 */
146799 static int fts3FindFunctionMethod(
146800  sqlite3_vtab *pVtab, /* Virtual table handle */
146801  int nArg, /* Number of SQL function arguments */
146802  const char *zName, /* Name of SQL function */
146803  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
146804  void **ppArg /* Unused */
146805 ){
146806  struct Overloaded {
146807  const char *zName;
146808  void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
146809  } aOverload[] = {
146810  { "snippet", fts3SnippetFunc },
146811  { "offsets", fts3OffsetsFunc },
146812  { "optimize", fts3OptimizeFunc },
146813  { "matchinfo", fts3MatchinfoFunc },
146814  };
146815  int i; /* Iterator variable */
146816 
146817  UNUSED_PARAMETER(pVtab);
146818  UNUSED_PARAMETER(nArg);
146819  UNUSED_PARAMETER(ppArg);
146820 
146821  for(i=0; i<SizeofArray(aOverload); i++){
146822  if( strcmp(zName, aOverload[i].zName)==0 ){
146823  *pxFunc = aOverload[i].xFunc;
146824  return 1;
146825  }
146826  }
146827 
146828  /* No function of the specified name was found. Return 0. */
146829  return 0;
146830 }
146831 
146832 /*
146833 ** Implementation of FTS3 xRename method. Rename an fts3 table.
146834 */
146835 static int fts3RenameMethod(
146836  sqlite3_vtab *pVtab, /* Virtual table handle */
146837  const char *zName /* New name of table */
146838 ){
146839  Fts3Table *p = (Fts3Table *)pVtab;
146840  sqlite3 *db = p->db; /* Database connection */
146841  int rc; /* Return Code */
146842 
146843  /* At this point it must be known if the %_stat table exists or not.
146844  ** So bHasStat may not be 2. */
146845  rc = fts3SetHasStat(p);
146846 
146847  /* As it happens, the pending terms table is always empty here. This is
146848  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
146849  ** always opens a savepoint transaction. And the xSavepoint() method
146850  ** flushes the pending terms table. But leave the (no-op) call to
146851  ** PendingTermsFlush() in in case that changes.
146852  */
146853  assert( p->nPendingData==0 );
146854  if( rc==SQLITE_OK ){
146855  rc = sqlite3Fts3PendingTermsFlush(p);
146856  }
146857 
146858  if( p->zContentTbl==0 ){
146859  fts3DbExec(&rc, db,
146860  "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
146861  p->zDb, p->zName, zName
146862  );
146863  }
146864 
146865  if( p->bHasDocsize ){
146866  fts3DbExec(&rc, db,
146867  "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
146868  p->zDb, p->zName, zName
146869  );
146870  }
146871  if( p->bHasStat ){
146872  fts3DbExec(&rc, db,
146873  "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
146874  p->zDb, p->zName, zName
146875  );
146876  }
146877  fts3DbExec(&rc, db,
146878  "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
146879  p->zDb, p->zName, zName
146880  );
146881  fts3DbExec(&rc, db,
146882  "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
146883  p->zDb, p->zName, zName
146884  );
146885  return rc;
146886 }
146887 
146888 /*
146889 ** The xSavepoint() method.
146890 **
146891 ** Flush the contents of the pending-terms table to disk.
146892 */
146893 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
146894  int rc = SQLITE_OK;
146895  UNUSED_PARAMETER(iSavepoint);
146896  assert( ((Fts3Table *)pVtab)->inTransaction );
146897  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
146898  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
146899  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
146900  rc = fts3SyncMethod(pVtab);
146901  }
146902  return rc;
146903 }
146904 
146905 /*
146906 ** The xRelease() method.
146907 **
146908 ** This is a no-op.
146909 */
146910 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
146911  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
146912  UNUSED_PARAMETER(iSavepoint);
146913  UNUSED_PARAMETER(pVtab);
146914  assert( p->inTransaction );
146915  assert( p->mxSavepoint >= iSavepoint );
146916  TESTONLY( p->mxSavepoint = iSavepoint-1 );
146917  return SQLITE_OK;
146918 }
146919 
146920 /*
146921 ** The xRollbackTo() method.
146922 **
146923 ** Discard the contents of the pending terms table.
146924 */
146925 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
146926  Fts3Table *p = (Fts3Table*)pVtab;
146927  UNUSED_PARAMETER(iSavepoint);
146928  assert( p->inTransaction );
146929  assert( p->mxSavepoint >= iSavepoint );
146930  TESTONLY( p->mxSavepoint = iSavepoint );
146931  sqlite3Fts3PendingTermsClear(p);
146932  return SQLITE_OK;
146933 }
146934 
146935 static const sqlite3_module fts3Module = {
146936  /* iVersion */ 2,
146937  /* xCreate */ fts3CreateMethod,
146938  /* xConnect */ fts3ConnectMethod,
146939  /* xBestIndex */ fts3BestIndexMethod,
146940  /* xDisconnect */ fts3DisconnectMethod,
146941  /* xDestroy */ fts3DestroyMethod,
146942  /* xOpen */ fts3OpenMethod,
146943  /* xClose */ fts3CloseMethod,
146944  /* xFilter */ fts3FilterMethod,
146945  /* xNext */ fts3NextMethod,
146946  /* xEof */ fts3EofMethod,
146947  /* xColumn */ fts3ColumnMethod,
146948  /* xRowid */ fts3RowidMethod,
146949  /* xUpdate */ fts3UpdateMethod,
146950  /* xBegin */ fts3BeginMethod,
146951  /* xSync */ fts3SyncMethod,
146952  /* xCommit */ fts3CommitMethod,
146953  /* xRollback */ fts3RollbackMethod,
146954  /* xFindFunction */ fts3FindFunctionMethod,
146955  /* xRename */ fts3RenameMethod,
146956  /* xSavepoint */ fts3SavepointMethod,
146957  /* xRelease */ fts3ReleaseMethod,
146958  /* xRollbackTo */ fts3RollbackToMethod,
146959 };
146960 
146961 /*
146962 ** This function is registered as the module destructor (called when an
146963 ** FTS3 enabled database connection is closed). It frees the memory
146964 ** allocated for the tokenizer hash table.
146965 */
146966 static void hashDestroy(void *p){
146967  Fts3Hash *pHash = (Fts3Hash *)p;
146968  sqlite3Fts3HashClear(pHash);
146969  sqlite3_free(pHash);
146970 }
146971 
146972 /*
146973 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
146974 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
146975 ** respectively. The following three forward declarations are for functions
146976 ** declared in these files used to retrieve the respective implementations.
146977 **
146978 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
146979 ** to by the argument to point to the "simple" tokenizer implementation.
146980 ** And so on.
146981 */
146982 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
146983 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
146984 #ifndef SQLITE_DISABLE_FTS3_UNICODE
146985 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
146986 #endif
146987 #ifdef SQLITE_ENABLE_ICU
146988 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
146989 #endif
146990 
146991 /*
146992 ** Initialize the fts3 extension. If this extension is built as part
146993 ** of the sqlite library, then this function is called directly by
146994 ** SQLite. If fts3 is built as a dynamically loadable extension, this
146995 ** function is called by the sqlite3_extension_init() entry point.
146996 */
146997 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
146998  int rc = SQLITE_OK;
146999  Fts3Hash *pHash = 0;
147000  const sqlite3_tokenizer_module *pSimple = 0;
147001  const sqlite3_tokenizer_module *pPorter = 0;
147002 #ifndef SQLITE_DISABLE_FTS3_UNICODE
147003  const sqlite3_tokenizer_module *pUnicode = 0;
147004 #endif
147005 
147006 #ifdef SQLITE_ENABLE_ICU
147007  const sqlite3_tokenizer_module *pIcu = 0;
147008  sqlite3Fts3IcuTokenizerModule(&pIcu);
147009 #endif
147010 
147011 #ifndef SQLITE_DISABLE_FTS3_UNICODE
147012  sqlite3Fts3UnicodeTokenizer(&pUnicode);
147013 #endif
147014 
147015 #ifdef SQLITE_TEST
147016  rc = sqlite3Fts3InitTerm(db);
147017  if( rc!=SQLITE_OK ) return rc;
147018 #endif
147019 
147020  rc = sqlite3Fts3InitAux(db);
147021  if( rc!=SQLITE_OK ) return rc;
147022 
147023  sqlite3Fts3SimpleTokenizerModule(&pSimple);
147024  sqlite3Fts3PorterTokenizerModule(&pPorter);
147025 
147026  /* Allocate and initialize the hash-table used to store tokenizers. */
147027  pHash = sqlite3_malloc(sizeof(Fts3Hash));
147028  if( !pHash ){
147029  rc = SQLITE_NOMEM;
147030  }else{
147031  sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
147032  }
147033 
147034  /* Load the built-in tokenizers into the hash table */
147035  if( rc==SQLITE_OK ){
147036  if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
147037  || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
147038 
147039 #ifndef SQLITE_DISABLE_FTS3_UNICODE
147040  || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
147041 #endif
147042 #ifdef SQLITE_ENABLE_ICU
147043  || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
147044 #endif
147045  ){
147046  rc = SQLITE_NOMEM;
147047  }
147048  }
147049 
147050 #ifdef SQLITE_TEST
147051  if( rc==SQLITE_OK ){
147052  rc = sqlite3Fts3ExprInitTestInterface(db);
147053  }
147054 #endif
147055 
147056  /* Create the virtual table wrapper around the hash-table and overload
147057  ** the two scalar functions. If this is successful, register the
147058  ** module with sqlite.
147059  */
147060  if( SQLITE_OK==rc
147061  && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
147062  && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
147063  && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
147064  && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
147065  && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
147066  && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
147067  ){
147068  rc = sqlite3_create_module_v2(
147069  db, "fts3", &fts3Module, (void *)pHash, hashDestroy
147070  );
147071  if( rc==SQLITE_OK ){
147072  rc = sqlite3_create_module_v2(
147073  db, "fts4", &fts3Module, (void *)pHash, 0
147074  );
147075  }
147076  if( rc==SQLITE_OK ){
147077  rc = sqlite3Fts3InitTok(db, (void *)pHash);
147078  }
147079  return rc;
147080  }
147081 
147082 
147083  /* An error has occurred. Delete the hash table and return the error code. */
147084  assert( rc!=SQLITE_OK );
147085  if( pHash ){
147086  sqlite3Fts3HashClear(pHash);
147087  sqlite3_free(pHash);
147088  }
147089  return rc;
147090 }
147091 
147092 /*
147093 ** Allocate an Fts3MultiSegReader for each token in the expression headed
147094 ** by pExpr.
147095 **
147096 ** An Fts3SegReader object is a cursor that can seek or scan a range of
147097 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
147098 ** Fts3SegReader objects internally to provide an interface to seek or scan
147099 ** within the union of all segments of a b-tree. Hence the name.
147100 **
147101 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
147102 ** segment b-tree (if the term is not a prefix or it is a prefix for which
147103 ** there exists prefix b-tree of the right length) then it may be traversed
147104 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
147105 ** doclist and then traversed.
147106 */
147107 static void fts3EvalAllocateReaders(
147108  Fts3Cursor *pCsr, /* FTS cursor handle */
147109  Fts3Expr *pExpr, /* Allocate readers for this expression */
147110  int *pnToken, /* OUT: Total number of tokens in phrase. */
147111  int *pnOr, /* OUT: Total number of OR nodes in expr. */
147112  int *pRc /* IN/OUT: Error code */
147113 ){
147114  if( pExpr && SQLITE_OK==*pRc ){
147115  if( pExpr->eType==FTSQUERY_PHRASE ){
147116  int i;
147117  int nToken = pExpr->pPhrase->nToken;
147118  *pnToken += nToken;
147119  for(i=0; i<nToken; i++){
147120  Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
147121  int rc = fts3TermSegReaderCursor(pCsr,
147122  pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
147123  );
147124  if( rc!=SQLITE_OK ){
147125  *pRc = rc;
147126  return;
147127  }
147128  }
147129  assert( pExpr->pPhrase->iDoclistToken==0 );
147130  pExpr->pPhrase->iDoclistToken = -1;
147131  }else{
147132  *pnOr += (pExpr->eType==FTSQUERY_OR);
147133  fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
147134  fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
147135  }
147136  }
147137 }
147138 
147139 /*
147140 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
147141 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
147142 **
147143 ** This function assumes that pList points to a buffer allocated using
147144 ** sqlite3_malloc(). This function takes responsibility for eventually
147145 ** freeing the buffer.
147146 **
147147 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
147148 */
147149 static int fts3EvalPhraseMergeToken(
147150  Fts3Table *pTab, /* FTS Table pointer */
147151  Fts3Phrase *p, /* Phrase to merge pList/nList into */
147152  int iToken, /* Token pList/nList corresponds to */
147153  char *pList, /* Pointer to doclist */
147154  int nList /* Number of bytes in pList */
147155 ){
147156  int rc = SQLITE_OK;
147157  assert( iToken!=p->iDoclistToken );
147158 
147159  if( pList==0 ){
147160  sqlite3_free(p->doclist.aAll);
147161  p->doclist.aAll = 0;
147162  p->doclist.nAll = 0;
147163  }
147164 
147165  else if( p->iDoclistToken<0 ){
147166  p->doclist.aAll = pList;
147167  p->doclist.nAll = nList;
147168  }
147169 
147170  else if( p->doclist.aAll==0 ){
147171  sqlite3_free(pList);
147172  }
147173 
147174  else {
147175  char *pLeft;
147176  char *pRight;
147177  int nLeft;
147178  int nRight;
147179  int nDiff;
147180 
147181  if( p->iDoclistToken<iToken ){
147182  pLeft = p->doclist.aAll;
147183  nLeft = p->doclist.nAll;
147184  pRight = pList;
147185  nRight = nList;
147186  nDiff = iToken - p->iDoclistToken;
147187  }else{
147188  pRight = p->doclist.aAll;
147189  nRight = p->doclist.nAll;
147190  pLeft = pList;
147191  nLeft = nList;
147192  nDiff = p->iDoclistToken - iToken;
147193  }
147194 
147195  rc = fts3DoclistPhraseMerge(
147196  pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
147197  );
147198  sqlite3_free(pLeft);
147199  p->doclist.aAll = pRight;
147200  p->doclist.nAll = nRight;
147201  }
147202 
147203  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
147204  return rc;
147205 }
147206 
147207 /*
147208 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
147209 ** does not take deferred tokens into account.
147210 **
147211 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
147212 */
147213 static int fts3EvalPhraseLoad(
147214  Fts3Cursor *pCsr, /* FTS Cursor handle */
147215  Fts3Phrase *p /* Phrase object */
147216 ){
147217  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147218  int iToken;
147219  int rc = SQLITE_OK;
147220 
147221  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
147222  Fts3PhraseToken *pToken = &p->aToken[iToken];
147223  assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
147224 
147225  if( pToken->pSegcsr ){
147226  int nThis = 0;
147227  char *pThis = 0;
147228  rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
147229  if( rc==SQLITE_OK ){
147230  rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
147231  }
147232  }
147233  assert( pToken->pSegcsr==0 );
147234  }
147235 
147236  return rc;
147237 }
147238 
147239 /*
147240 ** This function is called on each phrase after the position lists for
147241 ** any deferred tokens have been loaded into memory. It updates the phrases
147242 ** current position list to include only those positions that are really
147243 ** instances of the phrase (after considering deferred tokens). If this
147244 ** means that the phrase does not appear in the current row, doclist.pList
147245 ** and doclist.nList are both zeroed.
147246 **
147247 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
147248 */
147249 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
147250  int iToken; /* Used to iterate through phrase tokens */
147251  char *aPoslist = 0; /* Position list for deferred tokens */
147252  int nPoslist = 0; /* Number of bytes in aPoslist */
147253  int iPrev = -1; /* Token number of previous deferred token */
147254 
147255  assert( pPhrase->doclist.bFreeList==0 );
147256 
147257  for(iToken=0; iToken<pPhrase->nToken; iToken++){
147258  Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
147259  Fts3DeferredToken *pDeferred = pToken->pDeferred;
147260 
147261  if( pDeferred ){
147262  char *pList;
147263  int nList;
147264  int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
147265  if( rc!=SQLITE_OK ) return rc;
147266 
147267  if( pList==0 ){
147268  sqlite3_free(aPoslist);
147269  pPhrase->doclist.pList = 0;
147270  pPhrase->doclist.nList = 0;
147271  return SQLITE_OK;
147272 
147273  }else if( aPoslist==0 ){
147274  aPoslist = pList;
147275  nPoslist = nList;
147276 
147277  }else{
147278  char *aOut = pList;
147279  char *p1 = aPoslist;
147280  char *p2 = aOut;
147281 
147282  assert( iPrev>=0 );
147283  fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
147284  sqlite3_free(aPoslist);
147285  aPoslist = pList;
147286  nPoslist = (int)(aOut - aPoslist);
147287  if( nPoslist==0 ){
147288  sqlite3_free(aPoslist);
147289  pPhrase->doclist.pList = 0;
147290  pPhrase->doclist.nList = 0;
147291  return SQLITE_OK;
147292  }
147293  }
147294  iPrev = iToken;
147295  }
147296  }
147297 
147298  if( iPrev>=0 ){
147299  int nMaxUndeferred = pPhrase->iDoclistToken;
147300  if( nMaxUndeferred<0 ){
147301  pPhrase->doclist.pList = aPoslist;
147302  pPhrase->doclist.nList = nPoslist;
147303  pPhrase->doclist.iDocid = pCsr->iPrevId;
147304  pPhrase->doclist.bFreeList = 1;
147305  }else{
147306  int nDistance;
147307  char *p1;
147308  char *p2;
147309  char *aOut;
147310 
147311  if( nMaxUndeferred>iPrev ){
147312  p1 = aPoslist;
147313  p2 = pPhrase->doclist.pList;
147314  nDistance = nMaxUndeferred - iPrev;
147315  }else{
147316  p1 = pPhrase->doclist.pList;
147317  p2 = aPoslist;
147318  nDistance = iPrev - nMaxUndeferred;
147319  }
147320 
147321  aOut = (char *)sqlite3_malloc(nPoslist+8);
147322  if( !aOut ){
147323  sqlite3_free(aPoslist);
147324  return SQLITE_NOMEM;
147325  }
147326 
147327  pPhrase->doclist.pList = aOut;
147328  if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
147329  pPhrase->doclist.bFreeList = 1;
147330  pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
147331  }else{
147332  sqlite3_free(aOut);
147333  pPhrase->doclist.pList = 0;
147334  pPhrase->doclist.nList = 0;
147335  }
147336  sqlite3_free(aPoslist);
147337  }
147338  }
147339 
147340  return SQLITE_OK;
147341 }
147342 
147343 /*
147344 ** Maximum number of tokens a phrase may have to be considered for the
147345 ** incremental doclists strategy.
147346 */
147347 #define MAX_INCR_PHRASE_TOKENS 4
147348 
147349 /*
147350 ** This function is called for each Fts3Phrase in a full-text query
147351 ** expression to initialize the mechanism for returning rows. Once this
147352 ** function has been called successfully on an Fts3Phrase, it may be
147353 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
147354 **
147355 ** If parameter bOptOk is true, then the phrase may (or may not) use the
147356 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
147357 ** memory within this call.
147358 **
147359 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
147360 */
147361 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
147362  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147363  int rc = SQLITE_OK; /* Error code */
147364  int i;
147365 
147366  /* Determine if doclists may be loaded from disk incrementally. This is
147367  ** possible if the bOptOk argument is true, the FTS doclists will be
147368  ** scanned in forward order, and the phrase consists of
147369  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
147370  ** tokens or prefix tokens that cannot use a prefix-index. */
147371  int bHaveIncr = 0;
147372  int bIncrOk = (bOptOk
147373  && pCsr->bDesc==pTab->bDescIdx
147374  && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
147375 #ifdef SQLITE_TEST
147376  && pTab->bNoIncrDoclist==0
147377 #endif
147378  );
147379  for(i=0; bIncrOk==1 && i<p->nToken; i++){
147380  Fts3PhraseToken *pToken = &p->aToken[i];
147381  if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
147382  bIncrOk = 0;
147383  }
147384  if( pToken->pSegcsr ) bHaveIncr = 1;
147385  }
147386 
147387  if( bIncrOk && bHaveIncr ){
147388  /* Use the incremental approach. */
147389  int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
147390  for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
147391  Fts3PhraseToken *pToken = &p->aToken[i];
147392  Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
147393  if( pSegcsr ){
147394  rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
147395  }
147396  }
147397  p->bIncr = 1;
147398  }else{
147399  /* Load the full doclist for the phrase into memory. */
147400  rc = fts3EvalPhraseLoad(pCsr, p);
147401  p->bIncr = 0;
147402  }
147403 
147404  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
147405  return rc;
147406 }
147407 
147408 /*
147409 ** This function is used to iterate backwards (from the end to start)
147410 ** through doclists. It is used by this module to iterate through phrase
147411 ** doclists in reverse and by the fts3_write.c module to iterate through
147412 ** pending-terms lists when writing to databases with "order=desc".
147413 **
147414 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
147415 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
147416 ** function iterates from the end of the doclist to the beginning.
147417 */
147418 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
147419  int bDescIdx, /* True if the doclist is desc */
147420  char *aDoclist, /* Pointer to entire doclist */
147421  int nDoclist, /* Length of aDoclist in bytes */
147422  char **ppIter, /* IN/OUT: Iterator pointer */
147423  sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
147424  int *pnList, /* OUT: List length pointer */
147425  u8 *pbEof /* OUT: End-of-file flag */
147426 ){
147427  char *p = *ppIter;
147428 
147429  assert( nDoclist>0 );
147430  assert( *pbEof==0 );
147431  assert( p || *piDocid==0 );
147432  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
147433 
147434  if( p==0 ){
147435  sqlite3_int64 iDocid = 0;
147436  char *pNext = 0;
147437  char *pDocid = aDoclist;
147438  char *pEnd = &aDoclist[nDoclist];
147439  int iMul = 1;
147440 
147441  while( pDocid<pEnd ){
147442  sqlite3_int64 iDelta;
147443  pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
147444  iDocid += (iMul * iDelta);
147445  pNext = pDocid;
147446  fts3PoslistCopy(0, &pDocid);
147447  while( pDocid<pEnd && *pDocid==0 ) pDocid++;
147448  iMul = (bDescIdx ? -1 : 1);
147449  }
147450 
147451  *pnList = (int)(pEnd - pNext);
147452  *ppIter = pNext;
147453  *piDocid = iDocid;
147454  }else{
147455  int iMul = (bDescIdx ? -1 : 1);
147456  sqlite3_int64 iDelta;
147457  fts3GetReverseVarint(&p, aDoclist, &iDelta);
147458  *piDocid -= (iMul * iDelta);
147459 
147460  if( p==aDoclist ){
147461  *pbEof = 1;
147462  }else{
147463  char *pSave = p;
147464  fts3ReversePoslist(aDoclist, &p);
147465  *pnList = (int)(pSave - p);
147466  }
147467  *ppIter = p;
147468  }
147469 }
147470 
147471 /*
147472 ** Iterate forwards through a doclist.
147473 */
147474 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
147475  int bDescIdx, /* True if the doclist is desc */
147476  char *aDoclist, /* Pointer to entire doclist */
147477  int nDoclist, /* Length of aDoclist in bytes */
147478  char **ppIter, /* IN/OUT: Iterator pointer */
147479  sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
147480  u8 *pbEof /* OUT: End-of-file flag */
147481 ){
147482  char *p = *ppIter;
147483 
147484  assert( nDoclist>0 );
147485  assert( *pbEof==0 );
147486  assert( p || *piDocid==0 );
147487  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
147488 
147489  if( p==0 ){
147490  p = aDoclist;
147491  p += sqlite3Fts3GetVarint(p, piDocid);
147492  }else{
147493  fts3PoslistCopy(0, &p);
147494  while( p<&aDoclist[nDoclist] && *p==0 ) p++;
147495  if( p>=&aDoclist[nDoclist] ){
147496  *pbEof = 1;
147497  }else{
147498  sqlite3_int64 iVar;
147499  p += sqlite3Fts3GetVarint(p, &iVar);
147500  *piDocid += ((bDescIdx ? -1 : 1) * iVar);
147501  }
147502  }
147503 
147504  *ppIter = p;
147505 }
147506 
147507 /*
147508 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
147509 ** to true if EOF is reached.
147510 */
147511 static void fts3EvalDlPhraseNext(
147512  Fts3Table *pTab,
147513  Fts3Doclist *pDL,
147514  u8 *pbEof
147515 ){
147516  char *pIter; /* Used to iterate through aAll */
147517  char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
147518 
147519  if( pDL->pNextDocid ){
147520  pIter = pDL->pNextDocid;
147521  }else{
147522  pIter = pDL->aAll;
147523  }
147524 
147525  if( pIter>=pEnd ){
147526  /* We have already reached the end of this doclist. EOF. */
147527  *pbEof = 1;
147528  }else{
147529  sqlite3_int64 iDelta;
147530  pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
147531  if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
147532  pDL->iDocid += iDelta;
147533  }else{
147534  pDL->iDocid -= iDelta;
147535  }
147536  pDL->pList = pIter;
147537  fts3PoslistCopy(0, &pIter);
147538  pDL->nList = (int)(pIter - pDL->pList);
147539 
147540  /* pIter now points just past the 0x00 that terminates the position-
147541  ** list for document pDL->iDocid. However, if this position-list was
147542  ** edited in place by fts3EvalNearTrim(), then pIter may not actually
147543  ** point to the start of the next docid value. The following line deals
147544  ** with this case by advancing pIter past the zero-padding added by
147545  ** fts3EvalNearTrim(). */
147546  while( pIter<pEnd && *pIter==0 ) pIter++;
147547 
147548  pDL->pNextDocid = pIter;
147549  assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
147550  *pbEof = 0;
147551  }
147552 }
147553 
147554 /*
147555 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
147556 */
147557 typedef struct TokenDoclist TokenDoclist;
147558 struct TokenDoclist {
147559  int bIgnore;
147560  sqlite3_int64 iDocid;
147561  char *pList;
147562  int nList;
147563 };
147564 
147565 /*
147566 ** Token pToken is an incrementally loaded token that is part of a
147567 ** multi-token phrase. Advance it to the next matching document in the
147568 ** database and populate output variable *p with the details of the new
147569 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
147570 **
147571 ** If an error occurs, return an SQLite error code. Otherwise, return
147572 ** SQLITE_OK.
147573 */
147574 static int incrPhraseTokenNext(
147575  Fts3Table *pTab, /* Virtual table handle */
147576  Fts3Phrase *pPhrase, /* Phrase to advance token of */
147577  int iToken, /* Specific token to advance */
147578  TokenDoclist *p, /* OUT: Docid and doclist for new entry */
147579  u8 *pbEof /* OUT: True if iterator is at EOF */
147580 ){
147581  int rc = SQLITE_OK;
147582 
147583  if( pPhrase->iDoclistToken==iToken ){
147584  assert( p->bIgnore==0 );
147585  assert( pPhrase->aToken[iToken].pSegcsr==0 );
147586  fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
147587  p->pList = pPhrase->doclist.pList;
147588  p->nList = pPhrase->doclist.nList;
147589  p->iDocid = pPhrase->doclist.iDocid;
147590  }else{
147591  Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
147592  assert( pToken->pDeferred==0 );
147593  assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
147594  if( pToken->pSegcsr ){
147595  assert( p->bIgnore==0 );
147596  rc = sqlite3Fts3MsrIncrNext(
147597  pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
147598  );
147599  if( p->pList==0 ) *pbEof = 1;
147600  }else{
147601  p->bIgnore = 1;
147602  }
147603  }
147604 
147605  return rc;
147606 }
147607 
147608 
147609 /*
147610 ** The phrase iterator passed as the second argument:
147611 **
147612 ** * features at least one token that uses an incremental doclist, and
147613 **
147614 ** * does not contain any deferred tokens.
147615 **
147616 ** Advance it to the next matching documnent in the database and populate
147617 ** the Fts3Doclist.pList and nList fields.
147618 **
147619 ** If there is no "next" entry and no error occurs, then *pbEof is set to
147620 ** 1 before returning. Otherwise, if no error occurs and the iterator is
147621 ** successfully advanced, *pbEof is set to 0.
147622 **
147623 ** If an error occurs, return an SQLite error code. Otherwise, return
147624 ** SQLITE_OK.
147625 */
147626 static int fts3EvalIncrPhraseNext(
147627  Fts3Cursor *pCsr, /* FTS Cursor handle */
147628  Fts3Phrase *p, /* Phrase object to advance to next docid */
147629  u8 *pbEof /* OUT: Set to 1 if EOF */
147630 ){
147631  int rc = SQLITE_OK;
147632  Fts3Doclist *pDL = &p->doclist;
147633  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147634  u8 bEof = 0;
147635 
147636  /* This is only called if it is guaranteed that the phrase has at least
147637  ** one incremental token. In which case the bIncr flag is set. */
147638  assert( p->bIncr==1 );
147639 
147640  if( p->nToken==1 && p->bIncr ){
147641  rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
147642  &pDL->iDocid, &pDL->pList, &pDL->nList
147643  );
147644  if( pDL->pList==0 ) bEof = 1;
147645  }else{
147646  int bDescDoclist = pCsr->bDesc;
147647  struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
147648 
147649  memset(a, 0, sizeof(a));
147650  assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
147651  assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
147652 
147653  while( bEof==0 ){
147654  int bMaxSet = 0;
147655  sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
147656  int i; /* Used to iterate through tokens */
147657 
147658  /* Advance the iterator for each token in the phrase once. */
147659  for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
147660  rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
147661  if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
147662  iMax = a[i].iDocid;
147663  bMaxSet = 1;
147664  }
147665  }
147666  assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
147667  assert( rc!=SQLITE_OK || bMaxSet );
147668 
147669  /* Keep advancing iterators until they all point to the same document */
147670  for(i=0; i<p->nToken; i++){
147671  while( rc==SQLITE_OK && bEof==0
147672  && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
147673  ){
147674  rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
147675  if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
147676  iMax = a[i].iDocid;
147677  i = 0;
147678  }
147679  }
147680  }
147681 
147682  /* Check if the current entries really are a phrase match */
147683  if( bEof==0 ){
147684  int nList = 0;
147685  int nByte = a[p->nToken-1].nList;
147686  char *aDoclist = sqlite3_malloc(nByte+1);
147687  if( !aDoclist ) return SQLITE_NOMEM;
147688  memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
147689 
147690  for(i=0; i<(p->nToken-1); i++){
147691  if( a[i].bIgnore==0 ){
147692  char *pL = a[i].pList;
147693  char *pR = aDoclist;
147694  char *pOut = aDoclist;
147695  int nDist = p->nToken-1-i;
147696  int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
147697  if( res==0 ) break;
147698  nList = (int)(pOut - aDoclist);
147699  }
147700  }
147701  if( i==(p->nToken-1) ){
147702  pDL->iDocid = iMax;
147703  pDL->pList = aDoclist;
147704  pDL->nList = nList;
147705  pDL->bFreeList = 1;
147706  break;
147707  }
147708  sqlite3_free(aDoclist);
147709  }
147710  }
147711  }
147712 
147713  *pbEof = bEof;
147714  return rc;
147715 }
147716 
147717 /*
147718 ** Attempt to move the phrase iterator to point to the next matching docid.
147719 ** If an error occurs, return an SQLite error code. Otherwise, return
147720 ** SQLITE_OK.
147721 **
147722 ** If there is no "next" entry and no error occurs, then *pbEof is set to
147723 ** 1 before returning. Otherwise, if no error occurs and the iterator is
147724 ** successfully advanced, *pbEof is set to 0.
147725 */
147726 static int fts3EvalPhraseNext(
147727  Fts3Cursor *pCsr, /* FTS Cursor handle */
147728  Fts3Phrase *p, /* Phrase object to advance to next docid */
147729  u8 *pbEof /* OUT: Set to 1 if EOF */
147730 ){
147731  int rc = SQLITE_OK;
147732  Fts3Doclist *pDL = &p->doclist;
147733  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147734 
147735  if( p->bIncr ){
147736  rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
147737  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
147738  sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
147739  &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
147740  );
147741  pDL->pList = pDL->pNextDocid;
147742  }else{
147743  fts3EvalDlPhraseNext(pTab, pDL, pbEof);
147744  }
147745 
147746  return rc;
147747 }
147748 
147749 /*
147750 **
147751 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
147752 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
147753 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
147754 ** expressions for which all descendent tokens are deferred.
147755 **
147756 ** If parameter bOptOk is zero, then it is guaranteed that the
147757 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
147758 ** each phrase in the expression (subject to deferred token processing).
147759 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
147760 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
147761 **
147762 ** If an error occurs within this function, *pRc is set to an SQLite error
147763 ** code before returning.
147764 */
147765 static void fts3EvalStartReaders(
147766  Fts3Cursor *pCsr, /* FTS Cursor handle */
147767  Fts3Expr *pExpr, /* Expression to initialize phrases in */
147768  int *pRc /* IN/OUT: Error code */
147769 ){
147770  if( pExpr && SQLITE_OK==*pRc ){
147771  if( pExpr->eType==FTSQUERY_PHRASE ){
147772  int nToken = pExpr->pPhrase->nToken;
147773  if( nToken ){
147774  int i;
147775  for(i=0; i<nToken; i++){
147776  if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
147777  }
147778  pExpr->bDeferred = (i==nToken);
147779  }
147780  *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
147781  }else{
147782  fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
147783  fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
147784  pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
147785  }
147786  }
147787 }
147788 
147789 /*
147790 ** An array of the following structures is assembled as part of the process
147791 ** of selecting tokens to defer before the query starts executing (as part
147792 ** of the xFilter() method). There is one element in the array for each
147793 ** token in the FTS expression.
147794 **
147795 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
147796 ** to phrases that are connected only by AND and NEAR operators (not OR or
147797 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
147798 ** separately. The root of a tokens AND/NEAR cluster is stored in
147799 ** Fts3TokenAndCost.pRoot.
147800 */
147801 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
147802 struct Fts3TokenAndCost {
147803  Fts3Phrase *pPhrase; /* The phrase the token belongs to */
147804  int iToken; /* Position of token in phrase */
147805  Fts3PhraseToken *pToken; /* The token itself */
147806  Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
147807  int nOvfl; /* Number of overflow pages to load doclist */
147808  int iCol; /* The column the token must match */
147809 };
147810 
147811 /*
147812 ** This function is used to populate an allocated Fts3TokenAndCost array.
147813 **
147814 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
147815 ** Otherwise, if an error occurs during execution, *pRc is set to an
147816 ** SQLite error code.
147817 */
147818 static void fts3EvalTokenCosts(
147819  Fts3Cursor *pCsr, /* FTS Cursor handle */
147820  Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
147821  Fts3Expr *pExpr, /* Expression to consider */
147822  Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
147823  Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
147824  int *pRc /* IN/OUT: Error code */
147825 ){
147826  if( *pRc==SQLITE_OK ){
147827  if( pExpr->eType==FTSQUERY_PHRASE ){
147828  Fts3Phrase *pPhrase = pExpr->pPhrase;
147829  int i;
147830  for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
147831  Fts3TokenAndCost *pTC = (*ppTC)++;
147832  pTC->pPhrase = pPhrase;
147833  pTC->iToken = i;
147834  pTC->pRoot = pRoot;
147835  pTC->pToken = &pPhrase->aToken[i];
147836  pTC->iCol = pPhrase->iColumn;
147837  *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
147838  }
147839  }else if( pExpr->eType!=FTSQUERY_NOT ){
147840  assert( pExpr->eType==FTSQUERY_OR
147841  || pExpr->eType==FTSQUERY_AND
147842  || pExpr->eType==FTSQUERY_NEAR
147843  );
147844  assert( pExpr->pLeft && pExpr->pRight );
147845  if( pExpr->eType==FTSQUERY_OR ){
147846  pRoot = pExpr->pLeft;
147847  **ppOr = pRoot;
147848  (*ppOr)++;
147849  }
147850  fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
147851  if( pExpr->eType==FTSQUERY_OR ){
147852  pRoot = pExpr->pRight;
147853  **ppOr = pRoot;
147854  (*ppOr)++;
147855  }
147856  fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
147857  }
147858  }
147859 }
147860 
147861 /*
147862 ** Determine the average document (row) size in pages. If successful,
147863 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
147864 ** an SQLite error code.
147865 **
147866 ** The average document size in pages is calculated by first calculating
147867 ** determining the average size in bytes, B. If B is less than the amount
147868 ** of data that will fit on a single leaf page of an intkey table in
147869 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
147870 ** the number of overflow pages consumed by a record B bytes in size.
147871 */
147872 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
147873  if( pCsr->nRowAvg==0 ){
147874  /* The average document size, which is required to calculate the cost
147875  ** of each doclist, has not yet been determined. Read the required
147876  ** data from the %_stat table to calculate it.
147877  **
147878  ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
147879  ** varints, where nCol is the number of columns in the FTS3 table.
147880  ** The first varint is the number of documents currently stored in
147881  ** the table. The following nCol varints contain the total amount of
147882  ** data stored in all rows of each column of the table, from left
147883  ** to right.
147884  */
147885  int rc;
147886  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
147887  sqlite3_stmt *pStmt;
147888  sqlite3_int64 nDoc = 0;
147889  sqlite3_int64 nByte = 0;
147890  const char *pEnd;
147891  const char *a;
147892 
147893  rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
147894  if( rc!=SQLITE_OK ) return rc;
147895  a = sqlite3_column_blob(pStmt, 0);
147896  assert( a );
147897 
147898  pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
147899  a += sqlite3Fts3GetVarint(a, &nDoc);
147900  while( a<pEnd ){
147901  a += sqlite3Fts3GetVarint(a, &nByte);
147902  }
147903  if( nDoc==0 || nByte==0 ){
147904  sqlite3_reset(pStmt);
147905  return FTS_CORRUPT_VTAB;
147906  }
147907 
147908  pCsr->nDoc = nDoc;
147909  pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
147910  assert( pCsr->nRowAvg>0 );
147911  rc = sqlite3_reset(pStmt);
147912  if( rc!=SQLITE_OK ) return rc;
147913  }
147914 
147915  *pnPage = pCsr->nRowAvg;
147916  return SQLITE_OK;
147917 }
147918 
147919 /*
147920 ** This function is called to select the tokens (if any) that will be
147921 ** deferred. The array aTC[] has already been populated when this is
147922 ** called.
147923 **
147924 ** This function is called once for each AND/NEAR cluster in the
147925 ** expression. Each invocation determines which tokens to defer within
147926 ** the cluster with root node pRoot. See comments above the definition
147927 ** of struct Fts3TokenAndCost for more details.
147928 **
147929 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
147930 ** called on each token to defer. Otherwise, an SQLite error code is
147931 ** returned.
147932 */
147933 static int fts3EvalSelectDeferred(
147934  Fts3Cursor *pCsr, /* FTS Cursor handle */
147935  Fts3Expr *pRoot, /* Consider tokens with this root node */
147936  Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
147937  int nTC /* Number of entries in aTC[] */
147938 ){
147939  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147940  int nDocSize = 0; /* Number of pages per doc loaded */
147941  int rc = SQLITE_OK; /* Return code */
147942  int ii; /* Iterator variable for various purposes */
147943  int nOvfl = 0; /* Total overflow pages used by doclists */
147944  int nToken = 0; /* Total number of tokens in cluster */
147945 
147946  int nMinEst = 0; /* The minimum count for any phrase so far. */
147947  int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
147948 
147949  /* Tokens are never deferred for FTS tables created using the content=xxx
147950  ** option. The reason being that it is not guaranteed that the content
147951  ** table actually contains the same data as the index. To prevent this from
147952  ** causing any problems, the deferred token optimization is completely
147953  ** disabled for content=xxx tables. */
147954  if( pTab->zContentTbl ){
147955  return SQLITE_OK;
147956  }
147957 
147958  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
147959  ** associated with the tokens spill onto overflow pages, or if there is
147960  ** only 1 token, exit early. No tokens to defer in this case. */
147961  for(ii=0; ii<nTC; ii++){
147962  if( aTC[ii].pRoot==pRoot ){
147963  nOvfl += aTC[ii].nOvfl;
147964  nToken++;
147965  }
147966  }
147967  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
147968 
147969  /* Obtain the average docsize (in pages). */
147970  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
147971  assert( rc!=SQLITE_OK || nDocSize>0 );
147972 
147973 
147974  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
147975  ** of the number of overflow pages that will be loaded by the pager layer
147976  ** to retrieve the entire doclist for the token from the full-text index.
147977  ** Load the doclists for tokens that are either:
147978  **
147979  ** a. The cheapest token in the entire query (i.e. the one visited by the
147980  ** first iteration of this loop), or
147981  **
147982  ** b. Part of a multi-token phrase.
147983  **
147984  ** After each token doclist is loaded, merge it with the others from the
147985  ** same phrase and count the number of documents that the merged doclist
147986  ** contains. Set variable "nMinEst" to the smallest number of documents in
147987  ** any phrase doclist for which 1 or more token doclists have been loaded.
147988  ** Let nOther be the number of other phrases for which it is certain that
147989  ** one or more tokens will not be deferred.
147990  **
147991  ** Then, for each token, defer it if loading the doclist would result in
147992  ** loading N or more overflow pages into memory, where N is computed as:
147993  **
147994  ** (nMinEst + 4^nOther - 1) / (4^nOther)
147995  */
147996  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
147997  int iTC; /* Used to iterate through aTC[] array. */
147998  Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
147999 
148000  /* Set pTC to point to the cheapest remaining token. */
148001  for(iTC=0; iTC<nTC; iTC++){
148002  if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
148003  && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
148004  ){
148005  pTC = &aTC[iTC];
148006  }
148007  }
148008  assert( pTC );
148009 
148010  if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
148011  /* The number of overflow pages to load for this (and therefore all
148012  ** subsequent) tokens is greater than the estimated number of pages
148013  ** that will be loaded if all subsequent tokens are deferred.
148014  */
148015  Fts3PhraseToken *pToken = pTC->pToken;
148016  rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
148017  fts3SegReaderCursorFree(pToken->pSegcsr);
148018  pToken->pSegcsr = 0;
148019  }else{
148020  /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
148021  ** for-loop. Except, limit the value to 2^24 to prevent it from
148022  ** overflowing the 32-bit integer it is stored in. */
148023  if( ii<12 ) nLoad4 = nLoad4*4;
148024 
148025  if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
148026  /* Either this is the cheapest token in the entire query, or it is
148027  ** part of a multi-token phrase. Either way, the entire doclist will
148028  ** (eventually) be loaded into memory. It may as well be now. */
148029  Fts3PhraseToken *pToken = pTC->pToken;
148030  int nList = 0;
148031  char *pList = 0;
148032  rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
148033  assert( rc==SQLITE_OK || pList==0 );
148034  if( rc==SQLITE_OK ){
148035  rc = fts3EvalPhraseMergeToken(
148036  pTab, pTC->pPhrase, pTC->iToken,pList,nList
148037  );
148038  }
148039  if( rc==SQLITE_OK ){
148040  int nCount;
148041  nCount = fts3DoclistCountDocids(
148042  pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
148043  );
148044  if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
148045  }
148046  }
148047  }
148048  pTC->pToken = 0;
148049  }
148050 
148051  return rc;
148052 }
148053 
148054 /*
148055 ** This function is called from within the xFilter method. It initializes
148056 ** the full-text query currently stored in pCsr->pExpr. To iterate through
148057 ** the results of a query, the caller does:
148058 **
148059 ** fts3EvalStart(pCsr);
148060 ** while( 1 ){
148061 ** fts3EvalNext(pCsr);
148062 ** if( pCsr->bEof ) break;
148063 ** ... return row pCsr->iPrevId to the caller ...
148064 ** }
148065 */
148066 static int fts3EvalStart(Fts3Cursor *pCsr){
148067  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148068  int rc = SQLITE_OK;
148069  int nToken = 0;
148070  int nOr = 0;
148071 
148072  /* Allocate a MultiSegReader for each token in the expression. */
148073  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
148074 
148075  /* Determine which, if any, tokens in the expression should be deferred. */
148076 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
148077  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
148078  Fts3TokenAndCost *aTC;
148079  Fts3Expr **apOr;
148080  aTC = (Fts3TokenAndCost *)sqlite3_malloc(
148081  sizeof(Fts3TokenAndCost) * nToken
148082  + sizeof(Fts3Expr *) * nOr * 2
148083  );
148084  apOr = (Fts3Expr **)&aTC[nToken];
148085 
148086  if( !aTC ){
148087  rc = SQLITE_NOMEM;
148088  }else{
148089  int ii;
148090  Fts3TokenAndCost *pTC = aTC;
148091  Fts3Expr **ppOr = apOr;
148092 
148093  fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
148094  nToken = (int)(pTC-aTC);
148095  nOr = (int)(ppOr-apOr);
148096 
148097  if( rc==SQLITE_OK ){
148098  rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
148099  for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
148100  rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
148101  }
148102  }
148103 
148104  sqlite3_free(aTC);
148105  }
148106  }
148107 #endif
148108 
148109  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
148110  return rc;
148111 }
148112 
148113 /*
148114 ** Invalidate the current position list for phrase pPhrase.
148115 */
148116 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
148117  if( pPhrase->doclist.bFreeList ){
148118  sqlite3_free(pPhrase->doclist.pList);
148119  }
148120  pPhrase->doclist.pList = 0;
148121  pPhrase->doclist.nList = 0;
148122  pPhrase->doclist.bFreeList = 0;
148123 }
148124 
148125 /*
148126 ** This function is called to edit the position list associated with
148127 ** the phrase object passed as the fifth argument according to a NEAR
148128 ** condition. For example:
148129 **
148130 ** abc NEAR/5 "def ghi"
148131 **
148132 ** Parameter nNear is passed the NEAR distance of the expression (5 in
148133 ** the example above). When this function is called, *paPoslist points to
148134 ** the position list, and *pnToken is the number of phrase tokens in, the
148135 ** phrase on the other side of the NEAR operator to pPhrase. For example,
148136 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
148137 ** the position list associated with phrase "abc".
148138 **
148139 ** All positions in the pPhrase position list that are not sufficiently
148140 ** close to a position in the *paPoslist position list are removed. If this
148141 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
148142 **
148143 ** Before returning, *paPoslist is set to point to the position lsit
148144 ** associated with pPhrase. And *pnToken is set to the number of tokens in
148145 ** pPhrase.
148146 */
148147 static int fts3EvalNearTrim(
148148  int nNear, /* NEAR distance. As in "NEAR/nNear". */
148149  char *aTmp, /* Temporary space to use */
148150  char **paPoslist, /* IN/OUT: Position list */
148151  int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
148152  Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
148153 ){
148154  int nParam1 = nNear + pPhrase->nToken;
148155  int nParam2 = nNear + *pnToken;
148156  int nNew;
148157  char *p2;
148158  char *pOut;
148159  int res;
148160 
148161  assert( pPhrase->doclist.pList );
148162 
148163  p2 = pOut = pPhrase->doclist.pList;
148164  res = fts3PoslistNearMerge(
148165  &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
148166  );
148167  if( res ){
148168  nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
148169  assert( pPhrase->doclist.pList[nNew]=='\0' );
148170  assert( nNew<=pPhrase->doclist.nList && nNew>0 );
148171  memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
148172  pPhrase->doclist.nList = nNew;
148173  *paPoslist = pPhrase->doclist.pList;
148174  *pnToken = pPhrase->nToken;
148175  }
148176 
148177  return res;
148178 }
148179 
148180 /*
148181 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
148182 ** Otherwise, it advances the expression passed as the second argument to
148183 ** point to the next matching row in the database. Expressions iterate through
148184 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
148185 ** or descending if it is non-zero.
148186 **
148187 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
148188 ** successful, the following variables in pExpr are set:
148189 **
148190 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
148191 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
148192 **
148193 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
148194 ** at EOF, then the following variables are populated with the position list
148195 ** for the phrase for the visited row:
148196 **
148197 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
148198 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
148199 **
148200 ** It says above that this function advances the expression to the next
148201 ** matching row. This is usually true, but there are the following exceptions:
148202 **
148203 ** 1. Deferred tokens are not taken into account. If a phrase consists
148204 ** entirely of deferred tokens, it is assumed to match every row in
148205 ** the db. In this case the position-list is not populated at all.
148206 **
148207 ** Or, if a phrase contains one or more deferred tokens and one or
148208 ** more non-deferred tokens, then the expression is advanced to the
148209 ** next possible match, considering only non-deferred tokens. In other
148210 ** words, if the phrase is "A B C", and "B" is deferred, the expression
148211 ** is advanced to the next row that contains an instance of "A * C",
148212 ** where "*" may match any single token. The position list in this case
148213 ** is populated as for "A * C" before returning.
148214 **
148215 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
148216 ** advanced to point to the next row that matches "x AND y".
148217 **
148218 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
148219 ** really a match, taking into account deferred tokens and NEAR operators.
148220 */
148221 static void fts3EvalNextRow(
148222  Fts3Cursor *pCsr, /* FTS Cursor handle */
148223  Fts3Expr *pExpr, /* Expr. to advance to next matching row */
148224  int *pRc /* IN/OUT: Error code */
148225 ){
148226  if( *pRc==SQLITE_OK ){
148227  int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
148228  assert( pExpr->bEof==0 );
148229  pExpr->bStart = 1;
148230 
148231  switch( pExpr->eType ){
148232  case FTSQUERY_NEAR:
148233  case FTSQUERY_AND: {
148234  Fts3Expr *pLeft = pExpr->pLeft;
148235  Fts3Expr *pRight = pExpr->pRight;
148236  assert( !pLeft->bDeferred || !pRight->bDeferred );
148237 
148238  if( pLeft->bDeferred ){
148239  /* LHS is entirely deferred. So we assume it matches every row.
148240  ** Advance the RHS iterator to find the next row visited. */
148241  fts3EvalNextRow(pCsr, pRight, pRc);
148242  pExpr->iDocid = pRight->iDocid;
148243  pExpr->bEof = pRight->bEof;
148244  }else if( pRight->bDeferred ){
148245  /* RHS is entirely deferred. So we assume it matches every row.
148246  ** Advance the LHS iterator to find the next row visited. */
148247  fts3EvalNextRow(pCsr, pLeft, pRc);
148248  pExpr->iDocid = pLeft->iDocid;
148249  pExpr->bEof = pLeft->bEof;
148250  }else{
148251  /* Neither the RHS or LHS are deferred. */
148252  fts3EvalNextRow(pCsr, pLeft, pRc);
148253  fts3EvalNextRow(pCsr, pRight, pRc);
148254  while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
148255  sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
148256  if( iDiff==0 ) break;
148257  if( iDiff<0 ){
148258  fts3EvalNextRow(pCsr, pLeft, pRc);
148259  }else{
148260  fts3EvalNextRow(pCsr, pRight, pRc);
148261  }
148262  }
148263  pExpr->iDocid = pLeft->iDocid;
148264  pExpr->bEof = (pLeft->bEof || pRight->bEof);
148265  if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
148266  if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
148267  Fts3Doclist *pDl = &pRight->pPhrase->doclist;
148268  while( *pRc==SQLITE_OK && pRight->bEof==0 ){
148269  memset(pDl->pList, 0, pDl->nList);
148270  fts3EvalNextRow(pCsr, pRight, pRc);
148271  }
148272  }
148273  if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
148274  Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
148275  while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
148276  memset(pDl->pList, 0, pDl->nList);
148277  fts3EvalNextRow(pCsr, pLeft, pRc);
148278  }
148279  }
148280  }
148281  }
148282  break;
148283  }
148284 
148285  case FTSQUERY_OR: {
148286  Fts3Expr *pLeft = pExpr->pLeft;
148287  Fts3Expr *pRight = pExpr->pRight;
148288  sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
148289 
148290  assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
148291  assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
148292 
148293  if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
148294  fts3EvalNextRow(pCsr, pLeft, pRc);
148295  }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
148296  fts3EvalNextRow(pCsr, pRight, pRc);
148297  }else{
148298  fts3EvalNextRow(pCsr, pLeft, pRc);
148299  fts3EvalNextRow(pCsr, pRight, pRc);
148300  }
148301 
148302  pExpr->bEof = (pLeft->bEof && pRight->bEof);
148303  iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
148304  if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
148305  pExpr->iDocid = pLeft->iDocid;
148306  }else{
148307  pExpr->iDocid = pRight->iDocid;
148308  }
148309 
148310  break;
148311  }
148312 
148313  case FTSQUERY_NOT: {
148314  Fts3Expr *pLeft = pExpr->pLeft;
148315  Fts3Expr *pRight = pExpr->pRight;
148316 
148317  if( pRight->bStart==0 ){
148318  fts3EvalNextRow(pCsr, pRight, pRc);
148319  assert( *pRc!=SQLITE_OK || pRight->bStart );
148320  }
148321 
148322  fts3EvalNextRow(pCsr, pLeft, pRc);
148323  if( pLeft->bEof==0 ){
148324  while( !*pRc
148325  && !pRight->bEof
148326  && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
148327  ){
148328  fts3EvalNextRow(pCsr, pRight, pRc);
148329  }
148330  }
148331  pExpr->iDocid = pLeft->iDocid;
148332  pExpr->bEof = pLeft->bEof;
148333  break;
148334  }
148335 
148336  default: {
148337  Fts3Phrase *pPhrase = pExpr->pPhrase;
148338  fts3EvalInvalidatePoslist(pPhrase);
148339  *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
148340  pExpr->iDocid = pPhrase->doclist.iDocid;
148341  break;
148342  }
148343  }
148344  }
148345 }
148346 
148347 /*
148348 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
148349 ** cluster, then this function returns 1 immediately.
148350 **
148351 ** Otherwise, it checks if the current row really does match the NEAR
148352 ** expression, using the data currently stored in the position lists
148353 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
148354 **
148355 ** If the current row is a match, the position list associated with each
148356 ** phrase in the NEAR expression is edited in place to contain only those
148357 ** phrase instances sufficiently close to their peers to satisfy all NEAR
148358 ** constraints. In this case it returns 1. If the NEAR expression does not
148359 ** match the current row, 0 is returned. The position lists may or may not
148360 ** be edited if 0 is returned.
148361 */
148362 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
148363  int res = 1;
148364 
148365  /* The following block runs if pExpr is the root of a NEAR query.
148366  ** For example, the query:
148367  **
148368  ** "w" NEAR "x" NEAR "y" NEAR "z"
148369  **
148370  ** which is represented in tree form as:
148371  **
148372  ** |
148373  ** +--NEAR--+ <-- root of NEAR query
148374  ** | |
148375  ** +--NEAR--+ "z"
148376  ** | |
148377  ** +--NEAR--+ "y"
148378  ** | |
148379  ** "w" "x"
148380  **
148381  ** The right-hand child of a NEAR node is always a phrase. The
148382  ** left-hand child may be either a phrase or a NEAR node. There are
148383  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
148384  */
148385  if( *pRc==SQLITE_OK
148386  && pExpr->eType==FTSQUERY_NEAR
148387  && pExpr->bEof==0
148388  && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
148389  ){
148390  Fts3Expr *p;
148391  int nTmp = 0; /* Bytes of temp space */
148392  char *aTmp; /* Temp space for PoslistNearMerge() */
148393 
148394  /* Allocate temporary working space. */
148395  for(p=pExpr; p->pLeft; p=p->pLeft){
148396  nTmp += p->pRight->pPhrase->doclist.nList;
148397  }
148398  nTmp += p->pPhrase->doclist.nList;
148399  if( nTmp==0 ){
148400  res = 0;
148401  }else{
148402  aTmp = sqlite3_malloc(nTmp*2);
148403  if( !aTmp ){
148404  *pRc = SQLITE_NOMEM;
148405  res = 0;
148406  }else{
148407  char *aPoslist = p->pPhrase->doclist.pList;
148408  int nToken = p->pPhrase->nToken;
148409 
148410  for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
148411  Fts3Phrase *pPhrase = p->pRight->pPhrase;
148412  int nNear = p->nNear;
148413  res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
148414  }
148415 
148416  aPoslist = pExpr->pRight->pPhrase->doclist.pList;
148417  nToken = pExpr->pRight->pPhrase->nToken;
148418  for(p=pExpr->pLeft; p && res; p=p->pLeft){
148419  int nNear;
148420  Fts3Phrase *pPhrase;
148421  assert( p->pParent && p->pParent->pLeft==p );
148422  nNear = p->pParent->nNear;
148423  pPhrase = (
148424  p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
148425  );
148426  res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
148427  }
148428  }
148429 
148430  sqlite3_free(aTmp);
148431  }
148432  }
148433 
148434  return res;
148435 }
148436 
148437 /*
148438 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
148439 ** Assuming no error occurs or has occurred, It returns non-zero if the
148440 ** expression passed as the second argument matches the row that pCsr
148441 ** currently points to, or zero if it does not.
148442 **
148443 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
148444 ** If an error occurs during execution of this function, *pRc is set to
148445 ** the appropriate SQLite error code. In this case the returned value is
148446 ** undefined.
148447 */
148448 static int fts3EvalTestExpr(
148449  Fts3Cursor *pCsr, /* FTS cursor handle */
148450  Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
148451  int *pRc /* IN/OUT: Error code */
148452 ){
148453  int bHit = 1; /* Return value */
148454  if( *pRc==SQLITE_OK ){
148455  switch( pExpr->eType ){
148456  case FTSQUERY_NEAR:
148457  case FTSQUERY_AND:
148458  bHit = (
148459  fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
148460  && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
148461  && fts3EvalNearTest(pExpr, pRc)
148462  );
148463 
148464  /* If the NEAR expression does not match any rows, zero the doclist for
148465  ** all phrases involved in the NEAR. This is because the snippet(),
148466  ** offsets() and matchinfo() functions are not supposed to recognize
148467  ** any instances of phrases that are part of unmatched NEAR queries.
148468  ** For example if this expression:
148469  **
148470  ** ... MATCH 'a OR (b NEAR c)'
148471  **
148472  ** is matched against a row containing:
148473  **
148474  ** 'a b d e'
148475  **
148476  ** then any snippet() should ony highlight the "a" term, not the "b"
148477  ** (as "b" is part of a non-matching NEAR clause).
148478  */
148479  if( bHit==0
148480  && pExpr->eType==FTSQUERY_NEAR
148481  && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
148482  ){
148483  Fts3Expr *p;
148484  for(p=pExpr; p->pPhrase==0; p=p->pLeft){
148485  if( p->pRight->iDocid==pCsr->iPrevId ){
148486  fts3EvalInvalidatePoslist(p->pRight->pPhrase);
148487  }
148488  }
148489  if( p->iDocid==pCsr->iPrevId ){
148490  fts3EvalInvalidatePoslist(p->pPhrase);
148491  }
148492  }
148493 
148494  break;
148495 
148496  case FTSQUERY_OR: {
148497  int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
148498  int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
148499  bHit = bHit1 || bHit2;
148500  break;
148501  }
148502 
148503  case FTSQUERY_NOT:
148504  bHit = (
148505  fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
148506  && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
148507  );
148508  break;
148509 
148510  default: {
148511 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
148512  if( pCsr->pDeferred
148513  && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
148514  ){
148515  Fts3Phrase *pPhrase = pExpr->pPhrase;
148516  assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
148517  if( pExpr->bDeferred ){
148518  fts3EvalInvalidatePoslist(pPhrase);
148519  }
148520  *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
148521  bHit = (pPhrase->doclist.pList!=0);
148522  pExpr->iDocid = pCsr->iPrevId;
148523  }else
148524 #endif
148525  {
148526  bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
148527  }
148528  break;
148529  }
148530  }
148531  }
148532  return bHit;
148533 }
148534 
148535 /*
148536 ** This function is called as the second part of each xNext operation when
148537 ** iterating through the results of a full-text query. At this point the
148538 ** cursor points to a row that matches the query expression, with the
148539 ** following caveats:
148540 **
148541 ** * Up until this point, "NEAR" operators in the expression have been
148542 ** treated as "AND".
148543 **
148544 ** * Deferred tokens have not yet been considered.
148545 **
148546 ** If *pRc is not SQLITE_OK when this function is called, it immediately
148547 ** returns 0. Otherwise, it tests whether or not after considering NEAR
148548 ** operators and deferred tokens the current row is still a match for the
148549 ** expression. It returns 1 if both of the following are true:
148550 **
148551 ** 1. *pRc is SQLITE_OK when this function returns, and
148552 **
148553 ** 2. After scanning the current FTS table row for the deferred tokens,
148554 ** it is determined that the row does *not* match the query.
148555 **
148556 ** Or, if no error occurs and it seems the current row does match the FTS
148557 ** query, return 0.
148558 */
148559 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
148560  int rc = *pRc;
148561  int bMiss = 0;
148562  if( rc==SQLITE_OK ){
148563 
148564  /* If there are one or more deferred tokens, load the current row into
148565  ** memory and scan it to determine the position list for each deferred
148566  ** token. Then, see if this row is really a match, considering deferred
148567  ** tokens and NEAR operators (neither of which were taken into account
148568  ** earlier, by fts3EvalNextRow()).
148569  */
148570  if( pCsr->pDeferred ){
148571  rc = fts3CursorSeek(0, pCsr);
148572  if( rc==SQLITE_OK ){
148573  rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
148574  }
148575  }
148576  bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
148577 
148578  /* Free the position-lists accumulated for each deferred token above. */
148579  sqlite3Fts3FreeDeferredDoclists(pCsr);
148580  *pRc = rc;
148581  }
148582  return (rc==SQLITE_OK && bMiss);
148583 }
148584 
148585 /*
148586 ** Advance to the next document that matches the FTS expression in
148587 ** Fts3Cursor.pExpr.
148588 */
148589 static int fts3EvalNext(Fts3Cursor *pCsr){
148590  int rc = SQLITE_OK; /* Return Code */
148591  Fts3Expr *pExpr = pCsr->pExpr;
148592  assert( pCsr->isEof==0 );
148593  if( pExpr==0 ){
148594  pCsr->isEof = 1;
148595  }else{
148596  do {
148597  if( pCsr->isRequireSeek==0 ){
148598  sqlite3_reset(pCsr->pStmt);
148599  }
148600  assert( sqlite3_data_count(pCsr->pStmt)==0 );
148601  fts3EvalNextRow(pCsr, pExpr, &rc);
148602  pCsr->isEof = pExpr->bEof;
148603  pCsr->isRequireSeek = 1;
148604  pCsr->isMatchinfoNeeded = 1;
148605  pCsr->iPrevId = pExpr->iDocid;
148606  }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
148607  }
148608 
148609  /* Check if the cursor is past the end of the docid range specified
148610  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
148611  if( rc==SQLITE_OK && (
148612  (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
148613  || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
148614  )){
148615  pCsr->isEof = 1;
148616  }
148617 
148618  return rc;
148619 }
148620 
148621 /*
148622 ** Restart interation for expression pExpr so that the next call to
148623 ** fts3EvalNext() visits the first row. Do not allow incremental
148624 ** loading or merging of phrase doclists for this iteration.
148625 **
148626 ** If *pRc is other than SQLITE_OK when this function is called, it is
148627 ** a no-op. If an error occurs within this function, *pRc is set to an
148628 ** SQLite error code before returning.
148629 */
148630 static void fts3EvalRestart(
148631  Fts3Cursor *pCsr,
148632  Fts3Expr *pExpr,
148633  int *pRc
148634 ){
148635  if( pExpr && *pRc==SQLITE_OK ){
148636  Fts3Phrase *pPhrase = pExpr->pPhrase;
148637 
148638  if( pPhrase ){
148639  fts3EvalInvalidatePoslist(pPhrase);
148640  if( pPhrase->bIncr ){
148641  int i;
148642  for(i=0; i<pPhrase->nToken; i++){
148643  Fts3PhraseToken *pToken = &pPhrase->aToken[i];
148644  assert( pToken->pDeferred==0 );
148645  if( pToken->pSegcsr ){
148646  sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
148647  }
148648  }
148649  *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
148650  }
148651  pPhrase->doclist.pNextDocid = 0;
148652  pPhrase->doclist.iDocid = 0;
148653  pPhrase->pOrPoslist = 0;
148654  }
148655 
148656  pExpr->iDocid = 0;
148657  pExpr->bEof = 0;
148658  pExpr->bStart = 0;
148659 
148660  fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
148661  fts3EvalRestart(pCsr, pExpr->pRight, pRc);
148662  }
148663 }
148664 
148665 /*
148666 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
148667 ** expression rooted at pExpr, the cursor iterates through all rows matched
148668 ** by pExpr, calling this function for each row. This function increments
148669 ** the values in Fts3Expr.aMI[] according to the position-list currently
148670 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
148671 ** expression nodes.
148672 */
148673 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
148674  if( pExpr ){
148675  Fts3Phrase *pPhrase = pExpr->pPhrase;
148676  if( pPhrase && pPhrase->doclist.pList ){
148677  int iCol = 0;
148678  char *p = pPhrase->doclist.pList;
148679 
148680  assert( *p );
148681  while( 1 ){
148682  u8 c = 0;
148683  int iCnt = 0;
148684  while( 0xFE & (*p | c) ){
148685  if( (c&0x80)==0 ) iCnt++;
148686  c = *p++ & 0x80;
148687  }
148688 
148689  /* aMI[iCol*3 + 1] = Number of occurrences
148690  ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
148691  */
148692  pExpr->aMI[iCol*3 + 1] += iCnt;
148693  pExpr->aMI[iCol*3 + 2] += (iCnt>0);
148694  if( *p==0x00 ) break;
148695  p++;
148696  p += fts3GetVarint32(p, &iCol);
148697  }
148698  }
148699 
148700  fts3EvalUpdateCounts(pExpr->pLeft);
148701  fts3EvalUpdateCounts(pExpr->pRight);
148702  }
148703 }
148704 
148705 /*
148706 ** Expression pExpr must be of type FTSQUERY_PHRASE.
148707 **
148708 ** If it is not already allocated and populated, this function allocates and
148709 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
148710 ** of a NEAR expression, then it also allocates and populates the same array
148711 ** for all other phrases that are part of the NEAR expression.
148712 **
148713 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
148714 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
148715 */
148716 static int fts3EvalGatherStats(
148717  Fts3Cursor *pCsr, /* Cursor object */
148718  Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
148719 ){
148720  int rc = SQLITE_OK; /* Return code */
148721 
148722  assert( pExpr->eType==FTSQUERY_PHRASE );
148723  if( pExpr->aMI==0 ){
148724  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148725  Fts3Expr *pRoot; /* Root of NEAR expression */
148726  Fts3Expr *p; /* Iterator used for several purposes */
148727 
148728  sqlite3_int64 iPrevId = pCsr->iPrevId;
148729  sqlite3_int64 iDocid;
148730  u8 bEof;
148731 
148732  /* Find the root of the NEAR expression */
148733  pRoot = pExpr;
148734  while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
148735  pRoot = pRoot->pParent;
148736  }
148737  iDocid = pRoot->iDocid;
148738  bEof = pRoot->bEof;
148739  assert( pRoot->bStart );
148740 
148741  /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
148742  for(p=pRoot; p; p=p->pLeft){
148743  Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
148744  assert( pE->aMI==0 );
148745  pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
148746  if( !pE->aMI ) return SQLITE_NOMEM;
148747  memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
148748  }
148749 
148750  fts3EvalRestart(pCsr, pRoot, &rc);
148751 
148752  while( pCsr->isEof==0 && rc==SQLITE_OK ){
148753 
148754  do {
148755  /* Ensure the %_content statement is reset. */
148756  if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
148757  assert( sqlite3_data_count(pCsr->pStmt)==0 );
148758 
148759  /* Advance to the next document */
148760  fts3EvalNextRow(pCsr, pRoot, &rc);
148761  pCsr->isEof = pRoot->bEof;
148762  pCsr->isRequireSeek = 1;
148763  pCsr->isMatchinfoNeeded = 1;
148764  pCsr->iPrevId = pRoot->iDocid;
148765  }while( pCsr->isEof==0
148766  && pRoot->eType==FTSQUERY_NEAR
148767  && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
148768  );
148769 
148770  if( rc==SQLITE_OK && pCsr->isEof==0 ){
148771  fts3EvalUpdateCounts(pRoot);
148772  }
148773  }
148774 
148775  pCsr->isEof = 0;
148776  pCsr->iPrevId = iPrevId;
148777 
148778  if( bEof ){
148779  pRoot->bEof = bEof;
148780  }else{
148781  /* Caution: pRoot may iterate through docids in ascending or descending
148782  ** order. For this reason, even though it seems more defensive, the
148783  ** do loop can not be written:
148784  **
148785  ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
148786  */
148787  fts3EvalRestart(pCsr, pRoot, &rc);
148788  do {
148789  fts3EvalNextRow(pCsr, pRoot, &rc);
148790  assert( pRoot->bEof==0 );
148791  }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
148792  }
148793  }
148794  return rc;
148795 }
148796 
148797 /*
148798 ** This function is used by the matchinfo() module to query a phrase
148799 ** expression node for the following information:
148800 **
148801 ** 1. The total number of occurrences of the phrase in each column of
148802 ** the FTS table (considering all rows), and
148803 **
148804 ** 2. For each column, the number of rows in the table for which the
148805 ** column contains at least one instance of the phrase.
148806 **
148807 ** If no error occurs, SQLITE_OK is returned and the values for each column
148808 ** written into the array aiOut as follows:
148809 **
148810 ** aiOut[iCol*3 + 1] = Number of occurrences
148811 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
148812 **
148813 ** Caveats:
148814 **
148815 ** * If a phrase consists entirely of deferred tokens, then all output
148816 ** values are set to the number of documents in the table. In other
148817 ** words we assume that very common tokens occur exactly once in each
148818 ** column of each row of the table.
148819 **
148820 ** * If a phrase contains some deferred tokens (and some non-deferred
148821 ** tokens), count the potential occurrence identified by considering
148822 ** the non-deferred tokens instead of actual phrase occurrences.
148823 **
148824 ** * If the phrase is part of a NEAR expression, then only phrase instances
148825 ** that meet the NEAR constraint are included in the counts.
148826 */
148827 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
148828  Fts3Cursor *pCsr, /* FTS cursor handle */
148829  Fts3Expr *pExpr, /* Phrase expression */
148830  u32 *aiOut /* Array to write results into (see above) */
148831 ){
148832  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148833  int rc = SQLITE_OK;
148834  int iCol;
148835 
148836  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
148837  assert( pCsr->nDoc>0 );
148838  for(iCol=0; iCol<pTab->nColumn; iCol++){
148839  aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
148840  aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
148841  }
148842  }else{
148843  rc = fts3EvalGatherStats(pCsr, pExpr);
148844  if( rc==SQLITE_OK ){
148845  assert( pExpr->aMI );
148846  for(iCol=0; iCol<pTab->nColumn; iCol++){
148847  aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
148848  aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
148849  }
148850  }
148851  }
148852 
148853  return rc;
148854 }
148855 
148856 /*
148857 ** The expression pExpr passed as the second argument to this function
148858 ** must be of type FTSQUERY_PHRASE.
148859 **
148860 ** The returned value is either NULL or a pointer to a buffer containing
148861 ** a position-list indicating the occurrences of the phrase in column iCol
148862 ** of the current row.
148863 **
148864 ** More specifically, the returned buffer contains 1 varint for each
148865 ** occurrence of the phrase in the column, stored using the normal (delta+2)
148866 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
148867 ** if the requested column contains "a b X c d X X" and the position-list
148868 ** for 'X' is requested, the buffer returned may contain:
148869 **
148870 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
148871 **
148872 ** This function works regardless of whether or not the phrase is deferred,
148873 ** incremental, or neither.
148874 */
148875 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
148876  Fts3Cursor *pCsr, /* FTS3 cursor object */
148877  Fts3Expr *pExpr, /* Phrase to return doclist for */
148878  int iCol, /* Column to return position list for */
148879  char **ppOut /* OUT: Pointer to position list */
148880 ){
148881  Fts3Phrase *pPhrase = pExpr->pPhrase;
148882  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148883  char *pIter;
148884  int iThis;
148885  sqlite3_int64 iDocid;
148886 
148887  /* If this phrase is applies specifically to some column other than
148888  ** column iCol, return a NULL pointer. */
148889  *ppOut = 0;
148890  assert( iCol>=0 && iCol<pTab->nColumn );
148891  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
148892  return SQLITE_OK;
148893  }
148894 
148895  iDocid = pExpr->iDocid;
148896  pIter = pPhrase->doclist.pList;
148897  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
148898  int rc = SQLITE_OK;
148899  int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
148900  int bOr = 0;
148901  u8 bTreeEof = 0;
148902  Fts3Expr *p; /* Used to iterate from pExpr to root */
148903  Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
148904  int bMatch;
148905 
148906  /* Check if this phrase descends from an OR expression node. If not,
148907  ** return NULL. Otherwise, the entry that corresponds to docid
148908  ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
148909  ** tree that the node is part of has been marked as EOF, but the node
148910  ** itself is not EOF, then it may point to an earlier entry. */
148911  pNear = pExpr;
148912  for(p=pExpr->pParent; p; p=p->pParent){
148913  if( p->eType==FTSQUERY_OR ) bOr = 1;
148914  if( p->eType==FTSQUERY_NEAR ) pNear = p;
148915  if( p->bEof ) bTreeEof = 1;
148916  }
148917  if( bOr==0 ) return SQLITE_OK;
148918 
148919  /* This is the descendent of an OR node. In this case we cannot use
148920  ** an incremental phrase. Load the entire doclist for the phrase
148921  ** into memory in this case. */
148922  if( pPhrase->bIncr ){
148923  int bEofSave = pNear->bEof;
148924  fts3EvalRestart(pCsr, pNear, &rc);
148925  while( rc==SQLITE_OK && !pNear->bEof ){
148926  fts3EvalNextRow(pCsr, pNear, &rc);
148927  if( bEofSave==0 && pNear->iDocid==iDocid ) break;
148928  }
148929  assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
148930  }
148931  if( bTreeEof ){
148932  while( rc==SQLITE_OK && !pNear->bEof ){
148933  fts3EvalNextRow(pCsr, pNear, &rc);
148934  }
148935  }
148936  if( rc!=SQLITE_OK ) return rc;
148937 
148938  bMatch = 1;
148939  for(p=pNear; p; p=p->pLeft){
148940  u8 bEof = 0;
148941  Fts3Expr *pTest = p;
148942  Fts3Phrase *pPh;
148943  assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
148944  if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
148945  assert( pTest->eType==FTSQUERY_PHRASE );
148946  pPh = pTest->pPhrase;
148947 
148948  pIter = pPh->pOrPoslist;
148949  iDocid = pPh->iOrDocid;
148950  if( pCsr->bDesc==bDescDoclist ){
148951  bEof = !pPh->doclist.nAll ||
148952  (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
148953  while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
148954  sqlite3Fts3DoclistNext(
148955  bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
148956  &pIter, &iDocid, &bEof
148957  );
148958  }
148959  }else{
148960  bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
148961  while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
148962  int dummy;
148963  sqlite3Fts3DoclistPrev(
148964  bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
148965  &pIter, &iDocid, &dummy, &bEof
148966  );
148967  }
148968  }
148969  pPh->pOrPoslist = pIter;
148970  pPh->iOrDocid = iDocid;
148971  if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
148972  }
148973 
148974  if( bMatch ){
148975  pIter = pPhrase->pOrPoslist;
148976  }else{
148977  pIter = 0;
148978  }
148979  }
148980  if( pIter==0 ) return SQLITE_OK;
148981 
148982  if( *pIter==0x01 ){
148983  pIter++;
148984  pIter += fts3GetVarint32(pIter, &iThis);
148985  }else{
148986  iThis = 0;
148987  }
148988  while( iThis<iCol ){
148989  fts3ColumnlistCopy(0, &pIter);
148990  if( *pIter==0x00 ) return SQLITE_OK;
148991  pIter++;
148992  pIter += fts3GetVarint32(pIter, &iThis);
148993  }
148994  if( *pIter==0x00 ){
148995  pIter = 0;
148996  }
148997 
148998  *ppOut = ((iCol==iThis)?pIter:0);
148999  return SQLITE_OK;
149000 }
149001 
149002 /*
149003 ** Free all components of the Fts3Phrase structure that were allocated by
149004 ** the eval module. Specifically, this means to free:
149005 **
149006 ** * the contents of pPhrase->doclist, and
149007 ** * any Fts3MultiSegReader objects held by phrase tokens.
149008 */
149009 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
149010  if( pPhrase ){
149011  int i;
149012  sqlite3_free(pPhrase->doclist.aAll);
149013  fts3EvalInvalidatePoslist(pPhrase);
149014  memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
149015  for(i=0; i<pPhrase->nToken; i++){
149016  fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
149017  pPhrase->aToken[i].pSegcsr = 0;
149018  }
149019  }
149020 }
149021 
149022 
149023 /*
149024 ** Return SQLITE_CORRUPT_VTAB.
149025 */
149026 #ifdef SQLITE_DEBUG
149027 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
149028  return SQLITE_CORRUPT_VTAB;
149029 }
149030 #endif
149031 
149032 #if !SQLITE_CORE
149033 /*
149034 ** Initialize API pointer table, if required.
149035 */
149036 #ifdef _WIN32
149037 __declspec(dllexport)
149038 #endif
149039 SQLITE_API int sqlite3_fts3_init(
149040  sqlite3 *db,
149041  char **pzErrMsg,
149042  const sqlite3_api_routines *pApi
149043 ){
149044  SQLITE_EXTENSION_INIT2(pApi)
149045  return sqlite3Fts3Init(db);
149046 }
149047 #endif
149048 
149049 #endif
149050 
149051 /************** End of fts3.c ************************************************/
149052 /************** Begin file fts3_aux.c ****************************************/
149053 /*
149054 ** 2011 Jan 27
149055 **
149056 ** The author disclaims copyright to this source code. In place of
149057 ** a legal notice, here is a blessing:
149058 **
149059 ** May you do good and not evil.
149060 ** May you find forgiveness for yourself and forgive others.
149061 ** May you share freely, never taking more than you give.
149062 **
149063 ******************************************************************************
149064 **
149065 */
149066 /* #include "fts3Int.h" */
149067 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149068 
149069 /* #include <string.h> */
149070 /* #include <assert.h> */
149071 
149072 typedef struct Fts3auxTable Fts3auxTable;
149073 typedef struct Fts3auxCursor Fts3auxCursor;
149074 
149075 struct Fts3auxTable {
149076  sqlite3_vtab base; /* Base class used by SQLite core */
149077  Fts3Table *pFts3Tab;
149078 };
149079 
149080 struct Fts3auxCursor {
149081  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
149082  Fts3MultiSegReader csr; /* Must be right after "base" */
149083  Fts3SegFilter filter;
149084  char *zStop;
149085  int nStop; /* Byte-length of string zStop */
149086  int iLangid; /* Language id to query */
149087  int isEof; /* True if cursor is at EOF */
149088  sqlite3_int64 iRowid; /* Current rowid */
149089 
149090  int iCol; /* Current value of 'col' column */
149091  int nStat; /* Size of aStat[] array */
149092  struct Fts3auxColstats {
149093  sqlite3_int64 nDoc; /* 'documents' values for current csr row */
149094  sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
149095  } *aStat;
149096 };
149097 
149098 /*
149099 ** Schema of the terms table.
149100 */
149101 #define FTS3_AUX_SCHEMA \
149102  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
149103 
149104 /*
149105 ** This function does all the work for both the xConnect and xCreate methods.
149106 ** These tables have no persistent representation of their own, so xConnect
149107 ** and xCreate are identical operations.
149108 */
149109 static int fts3auxConnectMethod(
149110  sqlite3 *db, /* Database connection */
149111  void *pUnused, /* Unused */
149112  int argc, /* Number of elements in argv array */
149113  const char * const *argv, /* xCreate/xConnect argument array */
149114  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
149115  char **pzErr /* OUT: sqlite3_malloc'd error message */
149116 ){
149117  char const *zDb; /* Name of database (e.g. "main") */
149118  char const *zFts3; /* Name of fts3 table */
149119  int nDb; /* Result of strlen(zDb) */
149120  int nFts3; /* Result of strlen(zFts3) */
149121  int nByte; /* Bytes of space to allocate here */
149122  int rc; /* value returned by declare_vtab() */
149123  Fts3auxTable *p; /* Virtual table object to return */
149124 
149125  UNUSED_PARAMETER(pUnused);
149126 
149127  /* The user should invoke this in one of two forms:
149128  **
149129  ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
149130  ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
149131  */
149132  if( argc!=4 && argc!=5 ) goto bad_args;
149133 
149134  zDb = argv[1];
149135  nDb = (int)strlen(zDb);
149136  if( argc==5 ){
149137  if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
149138  zDb = argv[3];
149139  nDb = (int)strlen(zDb);
149140  zFts3 = argv[4];
149141  }else{
149142  goto bad_args;
149143  }
149144  }else{
149145  zFts3 = argv[3];
149146  }
149147  nFts3 = (int)strlen(zFts3);
149148 
149149  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
149150  if( rc!=SQLITE_OK ) return rc;
149151 
149152  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
149153  p = (Fts3auxTable *)sqlite3_malloc(nByte);
149154  if( !p ) return SQLITE_NOMEM;
149155  memset(p, 0, nByte);
149156 
149157  p->pFts3Tab = (Fts3Table *)&p[1];
149158  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
149159  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
149160  p->pFts3Tab->db = db;
149161  p->pFts3Tab->nIndex = 1;
149162 
149163  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
149164  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
149165  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
149166 
149167  *ppVtab = (sqlite3_vtab *)p;
149168  return SQLITE_OK;
149169 
149170  bad_args:
149171  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
149172  return SQLITE_ERROR;
149173 }
149174 
149175 /*
149176 ** This function does the work for both the xDisconnect and xDestroy methods.
149177 ** These tables have no persistent representation of their own, so xDisconnect
149178 ** and xDestroy are identical operations.
149179 */
149180 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
149181  Fts3auxTable *p = (Fts3auxTable *)pVtab;
149182  Fts3Table *pFts3 = p->pFts3Tab;
149183  int i;
149184 
149185  /* Free any prepared statements held */
149186  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
149187  sqlite3_finalize(pFts3->aStmt[i]);
149188  }
149189  sqlite3_free(pFts3->zSegmentsTbl);
149190  sqlite3_free(p);
149191  return SQLITE_OK;
149192 }
149193 
149194 #define FTS4AUX_EQ_CONSTRAINT 1
149195 #define FTS4AUX_GE_CONSTRAINT 2
149196 #define FTS4AUX_LE_CONSTRAINT 4
149197 
149198 /*
149199 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
149200 */
149201 static int fts3auxBestIndexMethod(
149202  sqlite3_vtab *pVTab,
149203  sqlite3_index_info *pInfo
149204 ){
149205  int i;
149206  int iEq = -1;
149207  int iGe = -1;
149208  int iLe = -1;
149209  int iLangid = -1;
149210  int iNext = 1; /* Next free argvIndex value */
149211 
149212  UNUSED_PARAMETER(pVTab);
149213 
149214  /* This vtab delivers always results in "ORDER BY term ASC" order. */
149215  if( pInfo->nOrderBy==1
149216  && pInfo->aOrderBy[0].iColumn==0
149217  && pInfo->aOrderBy[0].desc==0
149218  ){
149219  pInfo->orderByConsumed = 1;
149220  }
149221 
149222  /* Search for equality and range constraints on the "term" column.
149223  ** And equality constraints on the hidden "languageid" column. */
149224  for(i=0; i<pInfo->nConstraint; i++){
149225  if( pInfo->aConstraint[i].usable ){
149226  int op = pInfo->aConstraint[i].op;
149227  int iCol = pInfo->aConstraint[i].iColumn;
149228 
149229  if( iCol==0 ){
149230  if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
149231  if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
149232  if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
149233  if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
149234  if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
149235  }
149236  if( iCol==4 ){
149237  if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
149238  }
149239  }
149240  }
149241 
149242  if( iEq>=0 ){
149243  pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
149244  pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
149245  pInfo->estimatedCost = 5;
149246  }else{
149247  pInfo->idxNum = 0;
149248  pInfo->estimatedCost = 20000;
149249  if( iGe>=0 ){
149250  pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
149251  pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
149252  pInfo->estimatedCost /= 2;
149253  }
149254  if( iLe>=0 ){
149255  pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
149256  pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
149257  pInfo->estimatedCost /= 2;
149258  }
149259  }
149260  if( iLangid>=0 ){
149261  pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
149262  pInfo->estimatedCost--;
149263  }
149264 
149265  return SQLITE_OK;
149266 }
149267 
149268 /*
149269 ** xOpen - Open a cursor.
149270 */
149271 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
149272  Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
149273 
149274  UNUSED_PARAMETER(pVTab);
149275 
149276  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
149277  if( !pCsr ) return SQLITE_NOMEM;
149278  memset(pCsr, 0, sizeof(Fts3auxCursor));
149279 
149280  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
149281  return SQLITE_OK;
149282 }
149283 
149284 /*
149285 ** xClose - Close a cursor.
149286 */
149287 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
149288  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
149289  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149290 
149291  sqlite3Fts3SegmentsClose(pFts3);
149292  sqlite3Fts3SegReaderFinish(&pCsr->csr);
149293  sqlite3_free((void *)pCsr->filter.zTerm);
149294  sqlite3_free(pCsr->zStop);
149295  sqlite3_free(pCsr->aStat);
149296  sqlite3_free(pCsr);
149297  return SQLITE_OK;
149298 }
149299 
149300 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
149301  if( nSize>pCsr->nStat ){
149302  struct Fts3auxColstats *aNew;
149303  aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
149304  sizeof(struct Fts3auxColstats) * nSize
149305  );
149306  if( aNew==0 ) return SQLITE_NOMEM;
149307  memset(&aNew[pCsr->nStat], 0,
149308  sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
149309  );
149310  pCsr->aStat = aNew;
149311  pCsr->nStat = nSize;
149312  }
149313  return SQLITE_OK;
149314 }
149315 
149316 /*
149317 ** xNext - Advance the cursor to the next row, if any.
149318 */
149319 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
149320  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149321  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
149322  int rc;
149323 
149324  /* Increment our pretend rowid value. */
149325  pCsr->iRowid++;
149326 
149327  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
149328  if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
149329  }
149330 
149331  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
149332  if( rc==SQLITE_ROW ){
149333  int i = 0;
149334  int nDoclist = pCsr->csr.nDoclist;
149335  char *aDoclist = pCsr->csr.aDoclist;
149336  int iCol;
149337 
149338  int eState = 0;
149339 
149340  if( pCsr->zStop ){
149341  int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
149342  int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
149343  if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
149344  pCsr->isEof = 1;
149345  return SQLITE_OK;
149346  }
149347  }
149348 
149349  if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
149350  memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
149351  iCol = 0;
149352 
149353  while( i<nDoclist ){
149354  sqlite3_int64 v = 0;
149355 
149356  i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
149357  switch( eState ){
149358  /* State 0. In this state the integer just read was a docid. */
149359  case 0:
149360  pCsr->aStat[0].nDoc++;
149361  eState = 1;
149362  iCol = 0;
149363  break;
149364 
149365  /* State 1. In this state we are expecting either a 1, indicating
149366  ** that the following integer will be a column number, or the
149367  ** start of a position list for column 0.
149368  **
149369  ** The only difference between state 1 and state 2 is that if the
149370  ** integer encountered in state 1 is not 0 or 1, then we need to
149371  ** increment the column 0 "nDoc" count for this term.
149372  */
149373  case 1:
149374  assert( iCol==0 );
149375  if( v>1 ){
149376  pCsr->aStat[1].nDoc++;
149377  }
149378  eState = 2;
149379  /* fall through */
149380 
149381  case 2:
149382  if( v==0 ){ /* 0x00. Next integer will be a docid. */
149383  eState = 0;
149384  }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
149385  eState = 3;
149386  }else{ /* 2 or greater. A position. */
149387  pCsr->aStat[iCol+1].nOcc++;
149388  pCsr->aStat[0].nOcc++;
149389  }
149390  break;
149391 
149392  /* State 3. The integer just read is a column number. */
149393  default: assert( eState==3 );
149394  iCol = (int)v;
149395  if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
149396  pCsr->aStat[iCol+1].nDoc++;
149397  eState = 2;
149398  break;
149399  }
149400  }
149401 
149402  pCsr->iCol = 0;
149403  rc = SQLITE_OK;
149404  }else{
149405  pCsr->isEof = 1;
149406  }
149407  return rc;
149408 }
149409 
149410 /*
149411 ** xFilter - Initialize a cursor to point at the start of its data.
149412 */
149413 static int fts3auxFilterMethod(
149414  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
149415  int idxNum, /* Strategy index */
149416  const char *idxStr, /* Unused */
149417  int nVal, /* Number of elements in apVal */
149418  sqlite3_value **apVal /* Arguments for the indexing scheme */
149419 ){
149420  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149421  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
149422  int rc;
149423  int isScan = 0;
149424  int iLangVal = 0; /* Language id to query */
149425 
149426  int iEq = -1; /* Index of term=? value in apVal */
149427  int iGe = -1; /* Index of term>=? value in apVal */
149428  int iLe = -1; /* Index of term<=? value in apVal */
149429  int iLangid = -1; /* Index of languageid=? value in apVal */
149430  int iNext = 0;
149431 
149432  UNUSED_PARAMETER(nVal);
149433  UNUSED_PARAMETER(idxStr);
149434 
149435  assert( idxStr==0 );
149436  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
149437  || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
149438  || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
149439  );
149440 
149441  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
149442  iEq = iNext++;
149443  }else{
149444  isScan = 1;
149445  if( idxNum & FTS4AUX_GE_CONSTRAINT ){
149446  iGe = iNext++;
149447  }
149448  if( idxNum & FTS4AUX_LE_CONSTRAINT ){
149449  iLe = iNext++;
149450  }
149451  }
149452  if( iNext<nVal ){
149453  iLangid = iNext++;
149454  }
149455 
149456  /* In case this cursor is being reused, close and zero it. */
149457  testcase(pCsr->filter.zTerm);
149458  sqlite3Fts3SegReaderFinish(&pCsr->csr);
149459  sqlite3_free((void *)pCsr->filter.zTerm);
149460  sqlite3_free(pCsr->aStat);
149461  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
149462 
149463  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
149464  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
149465 
149466  if( iEq>=0 || iGe>=0 ){
149467  const unsigned char *zStr = sqlite3_value_text(apVal[0]);
149468  assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
149469  if( zStr ){
149470  pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
149471  pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
149472  if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
149473  }
149474  }
149475 
149476  if( iLe>=0 ){
149477  pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
149478  pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
149479  if( pCsr->zStop==0 ) return SQLITE_NOMEM;
149480  }
149481 
149482  if( iLangid>=0 ){
149483  iLangVal = sqlite3_value_int(apVal[iLangid]);
149484 
149485  /* If the user specified a negative value for the languageid, use zero
149486  ** instead. This works, as the "languageid=?" constraint will also
149487  ** be tested by the VDBE layer. The test will always be false (since
149488  ** this module will not return a row with a negative languageid), and
149489  ** so the overall query will return zero rows. */
149490  if( iLangVal<0 ) iLangVal = 0;
149491  }
149492  pCsr->iLangid = iLangVal;
149493 
149494  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
149495  pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
149496  );
149497  if( rc==SQLITE_OK ){
149498  rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
149499  }
149500 
149501  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
149502  return rc;
149503 }
149504 
149505 /*
149506 ** xEof - Return true if the cursor is at EOF, or false otherwise.
149507 */
149508 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
149509  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149510  return pCsr->isEof;
149511 }
149512 
149513 /*
149514 ** xColumn - Return a column value.
149515 */
149516 static int fts3auxColumnMethod(
149517  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
149518  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
149519  int iCol /* Index of column to read value from */
149520 ){
149521  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
149522 
149523  assert( p->isEof==0 );
149524  switch( iCol ){
149525  case 0: /* term */
149526  sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
149527  break;
149528 
149529  case 1: /* col */
149530  if( p->iCol ){
149531  sqlite3_result_int(pCtx, p->iCol-1);
149532  }else{
149533  sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
149534  }
149535  break;
149536 
149537  case 2: /* documents */
149538  sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
149539  break;
149540 
149541  case 3: /* occurrences */
149542  sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
149543  break;
149544 
149545  default: /* languageid */
149546  assert( iCol==4 );
149547  sqlite3_result_int(pCtx, p->iLangid);
149548  break;
149549  }
149550 
149551  return SQLITE_OK;
149552 }
149553 
149554 /*
149555 ** xRowid - Return the current rowid for the cursor.
149556 */
149557 static int fts3auxRowidMethod(
149558  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
149559  sqlite_int64 *pRowid /* OUT: Rowid value */
149560 ){
149561  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149562  *pRowid = pCsr->iRowid;
149563  return SQLITE_OK;
149564 }
149565 
149566 /*
149567 ** Register the fts3aux module with database connection db. Return SQLITE_OK
149568 ** if successful or an error code if sqlite3_create_module() fails.
149569 */
149570 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
149571  static const sqlite3_module fts3aux_module = {
149572  0, /* iVersion */
149573  fts3auxConnectMethod, /* xCreate */
149574  fts3auxConnectMethod, /* xConnect */
149575  fts3auxBestIndexMethod, /* xBestIndex */
149576  fts3auxDisconnectMethod, /* xDisconnect */
149577  fts3auxDisconnectMethod, /* xDestroy */
149578  fts3auxOpenMethod, /* xOpen */
149579  fts3auxCloseMethod, /* xClose */
149580  fts3auxFilterMethod, /* xFilter */
149581  fts3auxNextMethod, /* xNext */
149582  fts3auxEofMethod, /* xEof */
149583  fts3auxColumnMethod, /* xColumn */
149584  fts3auxRowidMethod, /* xRowid */
149585  0, /* xUpdate */
149586  0, /* xBegin */
149587  0, /* xSync */
149588  0, /* xCommit */
149589  0, /* xRollback */
149590  0, /* xFindFunction */
149591  0, /* xRename */
149592  0, /* xSavepoint */
149593  0, /* xRelease */
149594  0 /* xRollbackTo */
149595  };
149596  int rc; /* Return code */
149597 
149598  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
149599  return rc;
149600 }
149601 
149602 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149603 
149604 /************** End of fts3_aux.c ********************************************/
149605 /************** Begin file fts3_expr.c ***************************************/
149606 /*
149607 ** 2008 Nov 28
149608 **
149609 ** The author disclaims copyright to this source code. In place of
149610 ** a legal notice, here is a blessing:
149611 **
149612 ** May you do good and not evil.
149613 ** May you find forgiveness for yourself and forgive others.
149614 ** May you share freely, never taking more than you give.
149615 **
149616 ******************************************************************************
149617 **
149618 ** This module contains code that implements a parser for fts3 query strings
149619 ** (the right-hand argument to the MATCH operator). Because the supported
149620 ** syntax is relatively simple, the whole tokenizer/parser system is
149621 ** hand-coded.
149622 */
149623 /* #include "fts3Int.h" */
149624 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149625 
149626 /*
149627 ** By default, this module parses the legacy syntax that has been
149628 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
149629 ** is defined, then it uses the new syntax. The differences between
149630 ** the new and the old syntaxes are:
149631 **
149632 ** a) The new syntax supports parenthesis. The old does not.
149633 **
149634 ** b) The new syntax supports the AND and NOT operators. The old does not.
149635 **
149636 ** c) The old syntax supports the "-" token qualifier. This is not
149637 ** supported by the new syntax (it is replaced by the NOT operator).
149638 **
149639 ** d) When using the old syntax, the OR operator has a greater precedence
149640 ** than an implicit AND. When using the new, both implicity and explicit
149641 ** AND operators have a higher precedence than OR.
149642 **
149643 ** If compiled with SQLITE_TEST defined, then this module exports the
149644 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
149645 ** to zero causes the module to use the old syntax. If it is set to
149646 ** non-zero the new syntax is activated. This is so both syntaxes can
149647 ** be tested using a single build of testfixture.
149648 **
149649 ** The following describes the syntax supported by the fts3 MATCH
149650 ** operator in a similar format to that used by the lemon parser
149651 ** generator. This module does not use actually lemon, it uses a
149652 ** custom parser.
149653 **
149654 ** query ::= andexpr (OR andexpr)*.
149655 **
149656 ** andexpr ::= notexpr (AND? notexpr)*.
149657 **
149658 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
149659 ** notexpr ::= LP query RP.
149660 **
149661 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
149662 **
149663 ** distance_opt ::= .
149664 ** distance_opt ::= / INTEGER.
149665 **
149666 ** phrase ::= TOKEN.
149667 ** phrase ::= COLUMN:TOKEN.
149668 ** phrase ::= "TOKEN TOKEN TOKEN...".
149669 */
149670 
149671 #ifdef SQLITE_TEST
149672 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
149673 #else
149674 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
149675 # define sqlite3_fts3_enable_parentheses 1
149676 # else
149677 # define sqlite3_fts3_enable_parentheses 0
149678 # endif
149679 #endif
149680 
149681 /*
149682 ** Default span for NEAR operators.
149683 */
149684 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
149685 
149686 /* #include <string.h> */
149687 /* #include <assert.h> */
149688 
149689 /*
149690 ** isNot:
149691 ** This variable is used by function getNextNode(). When getNextNode() is
149692 ** called, it sets ParseContext.isNot to true if the 'next node' is a
149693 ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
149694 ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
149695 ** zero.
149696 */
149697 typedef struct ParseContext ParseContext;
149698 struct ParseContext {
149699  sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
149700  int iLangid; /* Language id used with tokenizer */
149701  const char **azCol; /* Array of column names for fts3 table */
149702  int bFts4; /* True to allow FTS4-only syntax */
149703  int nCol; /* Number of entries in azCol[] */
149704  int iDefaultCol; /* Default column to query */
149705  int isNot; /* True if getNextNode() sees a unary - */
149706  sqlite3_context *pCtx; /* Write error message here */
149707  int nNest; /* Number of nested brackets */
149708 };
149709 
149710 /*
149711 ** This function is equivalent to the standard isspace() function.
149712 **
149713 ** The standard isspace() can be awkward to use safely, because although it
149714 ** is defined to accept an argument of type int, its behavior when passed
149715 ** an integer that falls outside of the range of the unsigned char type
149716 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
149717 ** is defined to accept an argument of type char, and always returns 0 for
149718 ** any values that fall outside of the range of the unsigned char type (i.e.
149719 ** negative values).
149720 */
149721 static int fts3isspace(char c){
149722  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
149723 }
149724 
149725 /*
149726 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
149727 ** zero the memory before returning a pointer to it. If unsuccessful,
149728 ** return NULL.
149729 */
149730 static void *fts3MallocZero(int nByte){
149731  void *pRet = sqlite3_malloc(nByte);
149732  if( pRet ) memset(pRet, 0, nByte);
149733  return pRet;
149734 }
149735 
149736 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
149737  sqlite3_tokenizer *pTokenizer,
149738  int iLangid,
149739  const char *z,
149740  int n,
149741  sqlite3_tokenizer_cursor **ppCsr
149742 ){
149743  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
149744  sqlite3_tokenizer_cursor *pCsr = 0;
149745  int rc;
149746 
149747  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
149748  assert( rc==SQLITE_OK || pCsr==0 );
149749  if( rc==SQLITE_OK ){
149750  pCsr->pTokenizer = pTokenizer;
149751  if( pModule->iVersion>=1 ){
149752  rc = pModule->xLanguageid(pCsr, iLangid);
149753  if( rc!=SQLITE_OK ){
149754  pModule->xClose(pCsr);
149755  pCsr = 0;
149756  }
149757  }
149758  }
149759  *ppCsr = pCsr;
149760  return rc;
149761 }
149762 
149763 /*
149764 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
149765 ** call fts3ExprParse(). So this forward declaration is required.
149766 */
149767 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
149768 
149769 /*
149770 ** Extract the next token from buffer z (length n) using the tokenizer
149771 ** and other information (column names etc.) in pParse. Create an Fts3Expr
149772 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
149773 ** single token and set *ppExpr to point to it. If the end of the buffer is
149774 ** reached before a token is found, set *ppExpr to zero. It is the
149775 ** responsibility of the caller to eventually deallocate the allocated
149776 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
149777 **
149778 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
149779 ** fails.
149780 */
149781 static int getNextToken(
149782  ParseContext *pParse, /* fts3 query parse context */
149783  int iCol, /* Value for Fts3Phrase.iColumn */
149784  const char *z, int n, /* Input string */
149785  Fts3Expr **ppExpr, /* OUT: expression */
149786  int *pnConsumed /* OUT: Number of bytes consumed */
149787 ){
149788  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
149789  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
149790  int rc;
149791  sqlite3_tokenizer_cursor *pCursor;
149792  Fts3Expr *pRet = 0;
149793  int i = 0;
149794 
149795  /* Set variable i to the maximum number of bytes of input to tokenize. */
149796  for(i=0; i<n; i++){
149797  if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
149798  if( z[i]=='"' ) break;
149799  }
149800 
149801  *pnConsumed = i;
149802  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
149803  if( rc==SQLITE_OK ){
149804  const char *zToken;
149805  int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
149806  int nByte; /* total space to allocate */
149807 
149808  rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
149809  if( rc==SQLITE_OK ){
149810  nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
149811  pRet = (Fts3Expr *)fts3MallocZero(nByte);
149812  if( !pRet ){
149813  rc = SQLITE_NOMEM;
149814  }else{
149815  pRet->eType = FTSQUERY_PHRASE;
149816  pRet->pPhrase = (Fts3Phrase *)&pRet[1];
149817  pRet->pPhrase->nToken = 1;
149818  pRet->pPhrase->iColumn = iCol;
149819  pRet->pPhrase->aToken[0].n = nToken;
149820  pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
149821  memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
149822 
149823  if( iEnd<n && z[iEnd]=='*' ){
149824  pRet->pPhrase->aToken[0].isPrefix = 1;
149825  iEnd++;
149826  }
149827 
149828  while( 1 ){
149829  if( !sqlite3_fts3_enable_parentheses
149830  && iStart>0 && z[iStart-1]=='-'
149831  ){
149832  pParse->isNot = 1;
149833  iStart--;
149834  }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
149835  pRet->pPhrase->aToken[0].bFirst = 1;
149836  iStart--;
149837  }else{
149838  break;
149839  }
149840  }
149841 
149842  }
149843  *pnConsumed = iEnd;
149844  }else if( i && rc==SQLITE_DONE ){
149845  rc = SQLITE_OK;
149846  }
149847 
149848  pModule->xClose(pCursor);
149849  }
149850 
149851  *ppExpr = pRet;
149852  return rc;
149853 }
149854 
149855 
149856 /*
149857 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
149858 ** then free the old allocation.
149859 */
149860 static void *fts3ReallocOrFree(void *pOrig, int nNew){
149861  void *pRet = sqlite3_realloc(pOrig, nNew);
149862  if( !pRet ){
149863  sqlite3_free(pOrig);
149864  }
149865  return pRet;
149866 }
149867 
149868 /*
149869 ** Buffer zInput, length nInput, contains the contents of a quoted string
149870 ** that appeared as part of an fts3 query expression. Neither quote character
149871 ** is included in the buffer. This function attempts to tokenize the entire
149872 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
149873 ** containing the results.
149874 **
149875 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
149876 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
149877 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
149878 ** to 0.
149879 */
149880 static int getNextString(
149881  ParseContext *pParse, /* fts3 query parse context */
149882  const char *zInput, int nInput, /* Input string */
149883  Fts3Expr **ppExpr /* OUT: expression */
149884 ){
149885  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
149886  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
149887  int rc;
149888  Fts3Expr *p = 0;
149889  sqlite3_tokenizer_cursor *pCursor = 0;
149890  char *zTemp = 0;
149891  int nTemp = 0;
149892 
149893  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
149894  int nToken = 0;
149895 
149896  /* The final Fts3Expr data structure, including the Fts3Phrase,
149897  ** Fts3PhraseToken structures token buffers are all stored as a single
149898  ** allocation so that the expression can be freed with a single call to
149899  ** sqlite3_free(). Setting this up requires a two pass approach.
149900  **
149901  ** The first pass, in the block below, uses a tokenizer cursor to iterate
149902  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
149903  ** to assemble data in two dynamic buffers:
149904  **
149905  ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
149906  ** structure, followed by the array of Fts3PhraseToken
149907  ** structures. This pass only populates the Fts3PhraseToken array.
149908  **
149909  ** Buffer zTemp: Contains copies of all tokens.
149910  **
149911  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
149912  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
149913  ** structures.
149914  */
149915  rc = sqlite3Fts3OpenTokenizer(
149916  pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
149917  if( rc==SQLITE_OK ){
149918  int ii;
149919  for(ii=0; rc==SQLITE_OK; ii++){
149920  const char *zByte;
149921  int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
149922  rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
149923  if( rc==SQLITE_OK ){
149924  Fts3PhraseToken *pToken;
149925 
149926  p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
149927  if( !p ) goto no_mem;
149928 
149929  zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
149930  if( !zTemp ) goto no_mem;
149931 
149932  assert( nToken==ii );
149933  pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
149934  memset(pToken, 0, sizeof(Fts3PhraseToken));
149935 
149936  memcpy(&zTemp[nTemp], zByte, nByte);
149937  nTemp += nByte;
149938 
149939  pToken->n = nByte;
149940  pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
149941  pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
149942  nToken = ii+1;
149943  }
149944  }
149945 
149946  pModule->xClose(pCursor);
149947  pCursor = 0;
149948  }
149949 
149950  if( rc==SQLITE_DONE ){
149951  int jj;
149952  char *zBuf = 0;
149953 
149954  p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
149955  if( !p ) goto no_mem;
149956  memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
149957  p->eType = FTSQUERY_PHRASE;
149958  p->pPhrase = (Fts3Phrase *)&p[1];
149959  p->pPhrase->iColumn = pParse->iDefaultCol;
149960  p->pPhrase->nToken = nToken;
149961 
149962  zBuf = (char *)&p->pPhrase->aToken[nToken];
149963  if( zTemp ){
149964  memcpy(zBuf, zTemp, nTemp);
149965  sqlite3_free(zTemp);
149966  }else{
149967  assert( nTemp==0 );
149968  }
149969 
149970  for(jj=0; jj<p->pPhrase->nToken; jj++){
149971  p->pPhrase->aToken[jj].z = zBuf;
149972  zBuf += p->pPhrase->aToken[jj].n;
149973  }
149974  rc = SQLITE_OK;
149975  }
149976 
149977  *ppExpr = p;
149978  return rc;
149979 no_mem:
149980 
149981  if( pCursor ){
149982  pModule->xClose(pCursor);
149983  }
149984  sqlite3_free(zTemp);
149985  sqlite3_free(p);
149986  *ppExpr = 0;
149987  return SQLITE_NOMEM;
149988 }
149989 
149990 /*
149991 ** The output variable *ppExpr is populated with an allocated Fts3Expr
149992 ** structure, or set to 0 if the end of the input buffer is reached.
149993 **
149994 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
149995 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
149996 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
149997 */
149998 static int getNextNode(
149999  ParseContext *pParse, /* fts3 query parse context */
150000  const char *z, int n, /* Input string */
150001  Fts3Expr **ppExpr, /* OUT: expression */
150002  int *pnConsumed /* OUT: Number of bytes consumed */
150003 ){
150004  static const struct Fts3Keyword {
150005  char *z; /* Keyword text */
150006  unsigned char n; /* Length of the keyword */
150007  unsigned char parenOnly; /* Only valid in paren mode */
150008  unsigned char eType; /* Keyword code */
150009  } aKeyword[] = {
150010  { "OR" , 2, 0, FTSQUERY_OR },
150011  { "AND", 3, 1, FTSQUERY_AND },
150012  { "NOT", 3, 1, FTSQUERY_NOT },
150013  { "NEAR", 4, 0, FTSQUERY_NEAR }
150014  };
150015  int ii;
150016  int iCol;
150017  int iColLen;
150018  int rc;
150019  Fts3Expr *pRet = 0;
150020 
150021  const char *zInput = z;
150022  int nInput = n;
150023 
150024  pParse->isNot = 0;
150025 
150026  /* Skip over any whitespace before checking for a keyword, an open or
150027  ** close bracket, or a quoted string.
150028  */
150029  while( nInput>0 && fts3isspace(*zInput) ){
150030  nInput--;
150031  zInput++;
150032  }
150033  if( nInput==0 ){
150034  return SQLITE_DONE;
150035  }
150036 
150037  /* See if we are dealing with a keyword. */
150038  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
150039  const struct Fts3Keyword *pKey = &aKeyword[ii];
150040 
150041  if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
150042  continue;
150043  }
150044 
150045  if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
150046  int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
150047  int nKey = pKey->n;
150048  char cNext;
150049 
150050  /* If this is a "NEAR" keyword, check for an explicit nearness. */
150051  if( pKey->eType==FTSQUERY_NEAR ){
150052  assert( nKey==4 );
150053  if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
150054  nNear = 0;
150055  for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
150056  nNear = nNear * 10 + (zInput[nKey] - '0');
150057  }
150058  }
150059  }
150060 
150061  /* At this point this is probably a keyword. But for that to be true,
150062  ** the next byte must contain either whitespace, an open or close
150063  ** parenthesis, a quote character, or EOF.
150064  */
150065  cNext = zInput[nKey];
150066  if( fts3isspace(cNext)
150067  || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
150068  ){
150069  pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
150070  if( !pRet ){
150071  return SQLITE_NOMEM;
150072  }
150073  pRet->eType = pKey->eType;
150074  pRet->nNear = nNear;
150075  *ppExpr = pRet;
150076  *pnConsumed = (int)((zInput - z) + nKey);
150077  return SQLITE_OK;
150078  }
150079 
150080  /* Turns out that wasn't a keyword after all. This happens if the
150081  ** user has supplied a token such as "ORacle". Continue.
150082  */
150083  }
150084  }
150085 
150086  /* See if we are dealing with a quoted phrase. If this is the case, then
150087  ** search for the closing quote and pass the whole string to getNextString()
150088  ** for processing. This is easy to do, as fts3 has no syntax for escaping
150089  ** a quote character embedded in a string.
150090  */
150091  if( *zInput=='"' ){
150092  for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
150093  *pnConsumed = (int)((zInput - z) + ii + 1);
150094  if( ii==nInput ){
150095  return SQLITE_ERROR;
150096  }
150097  return getNextString(pParse, &zInput[1], ii-1, ppExpr);
150098  }
150099 
150100  if( sqlite3_fts3_enable_parentheses ){
150101  if( *zInput=='(' ){
150102  int nConsumed = 0;
150103  pParse->nNest++;
150104  rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
150105  if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
150106  *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
150107  return rc;
150108  }else if( *zInput==')' ){
150109  pParse->nNest--;
150110  *pnConsumed = (int)((zInput - z) + 1);
150111  *ppExpr = 0;
150112  return SQLITE_DONE;
150113  }
150114  }
150115 
150116  /* If control flows to this point, this must be a regular token, or
150117  ** the end of the input. Read a regular token using the sqlite3_tokenizer
150118  ** interface. Before doing so, figure out if there is an explicit
150119  ** column specifier for the token.
150120  **
150121  ** TODO: Strangely, it is not possible to associate a column specifier
150122  ** with a quoted phrase, only with a single token. Not sure if this was
150123  ** an implementation artifact or an intentional decision when fts3 was
150124  ** first implemented. Whichever it was, this module duplicates the
150125  ** limitation.
150126  */
150127  iCol = pParse->iDefaultCol;
150128  iColLen = 0;
150129  for(ii=0; ii<pParse->nCol; ii++){
150130  const char *zStr = pParse->azCol[ii];
150131  int nStr = (int)strlen(zStr);
150132  if( nInput>nStr && zInput[nStr]==':'
150133  && sqlite3_strnicmp(zStr, zInput, nStr)==0
150134  ){
150135  iCol = ii;
150136  iColLen = (int)((zInput - z) + nStr + 1);
150137  break;
150138  }
150139  }
150140  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
150141  *pnConsumed += iColLen;
150142  return rc;
150143 }
150144 
150145 /*
150146 ** The argument is an Fts3Expr structure for a binary operator (any type
150147 ** except an FTSQUERY_PHRASE). Return an integer value representing the
150148 ** precedence of the operator. Lower values have a higher precedence (i.e.
150149 ** group more tightly). For example, in the C language, the == operator
150150 ** groups more tightly than ||, and would therefore have a higher precedence.
150151 **
150152 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
150153 ** is defined), the order of the operators in precedence from highest to
150154 ** lowest is:
150155 **
150156 ** NEAR
150157 ** NOT
150158 ** AND (including implicit ANDs)
150159 ** OR
150160 **
150161 ** Note that when using the old query syntax, the OR operator has a higher
150162 ** precedence than the AND operator.
150163 */
150164 static int opPrecedence(Fts3Expr *p){
150165  assert( p->eType!=FTSQUERY_PHRASE );
150166  if( sqlite3_fts3_enable_parentheses ){
150167  return p->eType;
150168  }else if( p->eType==FTSQUERY_NEAR ){
150169  return 1;
150170  }else if( p->eType==FTSQUERY_OR ){
150171  return 2;
150172  }
150173  assert( p->eType==FTSQUERY_AND );
150174  return 3;
150175 }
150176 
150177 /*
150178 ** Argument ppHead contains a pointer to the current head of a query
150179 ** expression tree being parsed. pPrev is the expression node most recently
150180 ** inserted into the tree. This function adds pNew, which is always a binary
150181 ** operator node, into the expression tree based on the relative precedence
150182 ** of pNew and the existing nodes of the tree. This may result in the head
150183 ** of the tree changing, in which case *ppHead is set to the new root node.
150184 */
150185 static void insertBinaryOperator(
150186  Fts3Expr **ppHead, /* Pointer to the root node of a tree */
150187  Fts3Expr *pPrev, /* Node most recently inserted into the tree */
150188  Fts3Expr *pNew /* New binary node to insert into expression tree */
150189 ){
150190  Fts3Expr *pSplit = pPrev;
150191  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
150192  pSplit = pSplit->pParent;
150193  }
150194 
150195  if( pSplit->pParent ){
150196  assert( pSplit->pParent->pRight==pSplit );
150197  pSplit->pParent->pRight = pNew;
150198  pNew->pParent = pSplit->pParent;
150199  }else{
150200  *ppHead = pNew;
150201  }
150202  pNew->pLeft = pSplit;
150203  pSplit->pParent = pNew;
150204 }
150205 
150206 /*
150207 ** Parse the fts3 query expression found in buffer z, length n. This function
150208 ** returns either when the end of the buffer is reached or an unmatched
150209 ** closing bracket - ')' - is encountered.
150210 **
150211 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
150212 ** parsed form of the expression and *pnConsumed is set to the number of
150213 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
150214 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
150215 */
150216 static int fts3ExprParse(
150217  ParseContext *pParse, /* fts3 query parse context */
150218  const char *z, int n, /* Text of MATCH query */
150219  Fts3Expr **ppExpr, /* OUT: Parsed query structure */
150220  int *pnConsumed /* OUT: Number of bytes consumed */
150221 ){
150222  Fts3Expr *pRet = 0;
150223  Fts3Expr *pPrev = 0;
150224  Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
150225  int nIn = n;
150226  const char *zIn = z;
150227  int rc = SQLITE_OK;
150228  int isRequirePhrase = 1;
150229 
150230  while( rc==SQLITE_OK ){
150231  Fts3Expr *p = 0;
150232  int nByte = 0;
150233 
150234  rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
150235  assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
150236  if( rc==SQLITE_OK ){
150237  if( p ){
150238  int isPhrase;
150239 
150240  if( !sqlite3_fts3_enable_parentheses
150241  && p->eType==FTSQUERY_PHRASE && pParse->isNot
150242  ){
150243  /* Create an implicit NOT operator. */
150244  Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
150245  if( !pNot ){
150246  sqlite3Fts3ExprFree(p);
150247  rc = SQLITE_NOMEM;
150248  goto exprparse_out;
150249  }
150250  pNot->eType = FTSQUERY_NOT;
150251  pNot->pRight = p;
150252  p->pParent = pNot;
150253  if( pNotBranch ){
150254  pNot->pLeft = pNotBranch;
150255  pNotBranch->pParent = pNot;
150256  }
150257  pNotBranch = pNot;
150258  p = pPrev;
150259  }else{
150260  int eType = p->eType;
150261  isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
150262 
150263  /* The isRequirePhrase variable is set to true if a phrase or
150264  ** an expression contained in parenthesis is required. If a
150265  ** binary operator (AND, OR, NOT or NEAR) is encounted when
150266  ** isRequirePhrase is set, this is a syntax error.
150267  */
150268  if( !isPhrase && isRequirePhrase ){
150269  sqlite3Fts3ExprFree(p);
150270  rc = SQLITE_ERROR;
150271  goto exprparse_out;
150272  }
150273 
150274  if( isPhrase && !isRequirePhrase ){
150275  /* Insert an implicit AND operator. */
150276  Fts3Expr *pAnd;
150277  assert( pRet && pPrev );
150278  pAnd = fts3MallocZero(sizeof(Fts3Expr));
150279  if( !pAnd ){
150280  sqlite3Fts3ExprFree(p);
150281  rc = SQLITE_NOMEM;
150282  goto exprparse_out;
150283  }
150284  pAnd->eType = FTSQUERY_AND;
150285  insertBinaryOperator(&pRet, pPrev, pAnd);
150286  pPrev = pAnd;
150287  }
150288 
150289  /* This test catches attempts to make either operand of a NEAR
150290  ** operator something other than a phrase. For example, either of
150291  ** the following:
150292  **
150293  ** (bracketed expression) NEAR phrase
150294  ** phrase NEAR (bracketed expression)
150295  **
150296  ** Return an error in either case.
150297  */
150298  if( pPrev && (
150299  (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
150300  || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
150301  )){
150302  sqlite3Fts3ExprFree(p);
150303  rc = SQLITE_ERROR;
150304  goto exprparse_out;
150305  }
150306 
150307  if( isPhrase ){
150308  if( pRet ){
150309  assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
150310  pPrev->pRight = p;
150311  p->pParent = pPrev;
150312  }else{
150313  pRet = p;
150314  }
150315  }else{
150316  insertBinaryOperator(&pRet, pPrev, p);
150317  }
150318  isRequirePhrase = !isPhrase;
150319  }
150320  pPrev = p;
150321  }
150322  assert( nByte>0 );
150323  }
150324  assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
150325  nIn -= nByte;
150326  zIn += nByte;
150327  }
150328 
150329  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
150330  rc = SQLITE_ERROR;
150331  }
150332 
150333  if( rc==SQLITE_DONE ){
150334  rc = SQLITE_OK;
150335  if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
150336  if( !pRet ){
150337  rc = SQLITE_ERROR;
150338  }else{
150339  Fts3Expr *pIter = pNotBranch;
150340  while( pIter->pLeft ){
150341  pIter = pIter->pLeft;
150342  }
150343  pIter->pLeft = pRet;
150344  pRet->pParent = pIter;
150345  pRet = pNotBranch;
150346  }
150347  }
150348  }
150349  *pnConsumed = n - nIn;
150350 
150351 exprparse_out:
150352  if( rc!=SQLITE_OK ){
150353  sqlite3Fts3ExprFree(pRet);
150354  sqlite3Fts3ExprFree(pNotBranch);
150355  pRet = 0;
150356  }
150357  *ppExpr = pRet;
150358  return rc;
150359 }
150360 
150361 /*
150362 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
150363 ** as the only argument is more than nMaxDepth.
150364 */
150365 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
150366  int rc = SQLITE_OK;
150367  if( p ){
150368  if( nMaxDepth<0 ){
150369  rc = SQLITE_TOOBIG;
150370  }else{
150371  rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
150372  if( rc==SQLITE_OK ){
150373  rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
150374  }
150375  }
150376  }
150377  return rc;
150378 }
150379 
150380 /*
150381 ** This function attempts to transform the expression tree at (*pp) to
150382 ** an equivalent but more balanced form. The tree is modified in place.
150383 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
150384 ** new root expression node.
150385 **
150386 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
150387 **
150388 ** Otherwise, if an error occurs, an SQLite error code is returned and
150389 ** expression (*pp) freed.
150390 */
150391 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
150392  int rc = SQLITE_OK; /* Return code */
150393  Fts3Expr *pRoot = *pp; /* Initial root node */
150394  Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
150395  int eType = pRoot->eType; /* Type of node in this tree */
150396 
150397  if( nMaxDepth==0 ){
150398  rc = SQLITE_ERROR;
150399  }
150400 
150401  if( rc==SQLITE_OK ){
150402  if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
150403  Fts3Expr **apLeaf;
150404  apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
150405  if( 0==apLeaf ){
150406  rc = SQLITE_NOMEM;
150407  }else{
150408  memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
150409  }
150410 
150411  if( rc==SQLITE_OK ){
150412  int i;
150413  Fts3Expr *p;
150414 
150415  /* Set $p to point to the left-most leaf in the tree of eType nodes. */
150416  for(p=pRoot; p->eType==eType; p=p->pLeft){
150417  assert( p->pParent==0 || p->pParent->pLeft==p );
150418  assert( p->pLeft && p->pRight );
150419  }
150420 
150421  /* This loop runs once for each leaf in the tree of eType nodes. */
150422  while( 1 ){
150423  int iLvl;
150424  Fts3Expr *pParent = p->pParent; /* Current parent of p */
150425 
150426  assert( pParent==0 || pParent->pLeft==p );
150427  p->pParent = 0;
150428  if( pParent ){
150429  pParent->pLeft = 0;
150430  }else{
150431  pRoot = 0;
150432  }
150433  rc = fts3ExprBalance(&p, nMaxDepth-1);
150434  if( rc!=SQLITE_OK ) break;
150435 
150436  for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
150437  if( apLeaf[iLvl]==0 ){
150438  apLeaf[iLvl] = p;
150439  p = 0;
150440  }else{
150441  assert( pFree );
150442  pFree->pLeft = apLeaf[iLvl];
150443  pFree->pRight = p;
150444  pFree->pLeft->pParent = pFree;
150445  pFree->pRight->pParent = pFree;
150446 
150447  p = pFree;
150448  pFree = pFree->pParent;
150449  p->pParent = 0;
150450  apLeaf[iLvl] = 0;
150451  }
150452  }
150453  if( p ){
150454  sqlite3Fts3ExprFree(p);
150455  rc = SQLITE_TOOBIG;
150456  break;
150457  }
150458 
150459  /* If that was the last leaf node, break out of the loop */
150460  if( pParent==0 ) break;
150461 
150462  /* Set $p to point to the next leaf in the tree of eType nodes */
150463  for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
150464 
150465  /* Remove pParent from the original tree. */
150466  assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
150467  pParent->pRight->pParent = pParent->pParent;
150468  if( pParent->pParent ){
150469  pParent->pParent->pLeft = pParent->pRight;
150470  }else{
150471  assert( pParent==pRoot );
150472  pRoot = pParent->pRight;
150473  }
150474 
150475  /* Link pParent into the free node list. It will be used as an
150476  ** internal node of the new tree. */
150477  pParent->pParent = pFree;
150478  pFree = pParent;
150479  }
150480 
150481  if( rc==SQLITE_OK ){
150482  p = 0;
150483  for(i=0; i<nMaxDepth; i++){
150484  if( apLeaf[i] ){
150485  if( p==0 ){
150486  p = apLeaf[i];
150487  p->pParent = 0;
150488  }else{
150489  assert( pFree!=0 );
150490  pFree->pRight = p;
150491  pFree->pLeft = apLeaf[i];
150492  pFree->pLeft->pParent = pFree;
150493  pFree->pRight->pParent = pFree;
150494 
150495  p = pFree;
150496  pFree = pFree->pParent;
150497  p->pParent = 0;
150498  }
150499  }
150500  }
150501  pRoot = p;
150502  }else{
150503  /* An error occurred. Delete the contents of the apLeaf[] array
150504  ** and pFree list. Everything else is cleaned up by the call to
150505  ** sqlite3Fts3ExprFree(pRoot) below. */
150506  Fts3Expr *pDel;
150507  for(i=0; i<nMaxDepth; i++){
150508  sqlite3Fts3ExprFree(apLeaf[i]);
150509  }
150510  while( (pDel=pFree)!=0 ){
150511  pFree = pDel->pParent;
150512  sqlite3_free(pDel);
150513  }
150514  }
150515 
150516  assert( pFree==0 );
150517  sqlite3_free( apLeaf );
150518  }
150519  }else if( eType==FTSQUERY_NOT ){
150520  Fts3Expr *pLeft = pRoot->pLeft;
150521  Fts3Expr *pRight = pRoot->pRight;
150522 
150523  pRoot->pLeft = 0;
150524  pRoot->pRight = 0;
150525  pLeft->pParent = 0;
150526  pRight->pParent = 0;
150527 
150528  rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
150529  if( rc==SQLITE_OK ){
150530  rc = fts3ExprBalance(&pRight, nMaxDepth-1);
150531  }
150532 
150533  if( rc!=SQLITE_OK ){
150534  sqlite3Fts3ExprFree(pRight);
150535  sqlite3Fts3ExprFree(pLeft);
150536  }else{
150537  assert( pLeft && pRight );
150538  pRoot->pLeft = pLeft;
150539  pLeft->pParent = pRoot;
150540  pRoot->pRight = pRight;
150541  pRight->pParent = pRoot;
150542  }
150543  }
150544  }
150545 
150546  if( rc!=SQLITE_OK ){
150547  sqlite3Fts3ExprFree(pRoot);
150548  pRoot = 0;
150549  }
150550  *pp = pRoot;
150551  return rc;
150552 }
150553 
150554 /*
150555 ** This function is similar to sqlite3Fts3ExprParse(), with the following
150556 ** differences:
150557 **
150558 ** 1. It does not do expression rebalancing.
150559 ** 2. It does not check that the expression does not exceed the
150560 ** maximum allowable depth.
150561 ** 3. Even if it fails, *ppExpr may still be set to point to an
150562 ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
150563 ** in this case.
150564 */
150565 static int fts3ExprParseUnbalanced(
150566  sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
150567  int iLangid, /* Language id for tokenizer */
150568  char **azCol, /* Array of column names for fts3 table */
150569  int bFts4, /* True to allow FTS4-only syntax */
150570  int nCol, /* Number of entries in azCol[] */
150571  int iDefaultCol, /* Default column to query */
150572  const char *z, int n, /* Text of MATCH query */
150573  Fts3Expr **ppExpr /* OUT: Parsed query structure */
150574 ){
150575  int nParsed;
150576  int rc;
150577  ParseContext sParse;
150578 
150579  memset(&sParse, 0, sizeof(ParseContext));
150580  sParse.pTokenizer = pTokenizer;
150581  sParse.iLangid = iLangid;
150582  sParse.azCol = (const char **)azCol;
150583  sParse.nCol = nCol;
150584  sParse.iDefaultCol = iDefaultCol;
150585  sParse.bFts4 = bFts4;
150586  if( z==0 ){
150587  *ppExpr = 0;
150588  return SQLITE_OK;
150589  }
150590  if( n<0 ){
150591  n = (int)strlen(z);
150592  }
150593  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
150594  assert( rc==SQLITE_OK || *ppExpr==0 );
150595 
150596  /* Check for mismatched parenthesis */
150597  if( rc==SQLITE_OK && sParse.nNest ){
150598  rc = SQLITE_ERROR;
150599  }
150600 
150601  return rc;
150602 }
150603 
150604 /*
150605 ** Parameters z and n contain a pointer to and length of a buffer containing
150606 ** an fts3 query expression, respectively. This function attempts to parse the
150607 ** query expression and create a tree of Fts3Expr structures representing the
150608 ** parsed expression. If successful, *ppExpr is set to point to the head
150609 ** of the parsed expression tree and SQLITE_OK is returned. If an error
150610 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
150611 ** error) is returned and *ppExpr is set to 0.
150612 **
150613 ** If parameter n is a negative number, then z is assumed to point to a
150614 ** nul-terminated string and the length is determined using strlen().
150615 **
150616 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
150617 ** use to normalize query tokens while parsing the expression. The azCol[]
150618 ** array, which is assumed to contain nCol entries, should contain the names
150619 ** of each column in the target fts3 table, in order from left to right.
150620 ** Column names must be nul-terminated strings.
150621 **
150622 ** The iDefaultCol parameter should be passed the index of the table column
150623 ** that appears on the left-hand-side of the MATCH operator (the default
150624 ** column to match against for tokens for which a column name is not explicitly
150625 ** specified as part of the query string), or -1 if tokens may by default
150626 ** match any table column.
150627 */
150628 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
150629  sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
150630  int iLangid, /* Language id for tokenizer */
150631  char **azCol, /* Array of column names for fts3 table */
150632  int bFts4, /* True to allow FTS4-only syntax */
150633  int nCol, /* Number of entries in azCol[] */
150634  int iDefaultCol, /* Default column to query */
150635  const char *z, int n, /* Text of MATCH query */
150636  Fts3Expr **ppExpr, /* OUT: Parsed query structure */
150637  char **pzErr /* OUT: Error message (sqlite3_malloc) */
150638 ){
150639  int rc = fts3ExprParseUnbalanced(
150640  pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
150641  );
150642 
150643  /* Rebalance the expression. And check that its depth does not exceed
150644  ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
150645  if( rc==SQLITE_OK && *ppExpr ){
150646  rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
150647  if( rc==SQLITE_OK ){
150648  rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
150649  }
150650  }
150651 
150652  if( rc!=SQLITE_OK ){
150653  sqlite3Fts3ExprFree(*ppExpr);
150654  *ppExpr = 0;
150655  if( rc==SQLITE_TOOBIG ){
150656  sqlite3Fts3ErrMsg(pzErr,
150657  "FTS expression tree is too large (maximum depth %d)",
150658  SQLITE_FTS3_MAX_EXPR_DEPTH
150659  );
150660  rc = SQLITE_ERROR;
150661  }else if( rc==SQLITE_ERROR ){
150662  sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
150663  }
150664  }
150665 
150666  return rc;
150667 }
150668 
150669 /*
150670 ** Free a single node of an expression tree.
150671 */
150672 static void fts3FreeExprNode(Fts3Expr *p){
150673  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
150674  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
150675  sqlite3_free(p->aMI);
150676  sqlite3_free(p);
150677 }
150678 
150679 /*
150680 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
150681 **
150682 ** This function would be simpler if it recursively called itself. But
150683 ** that would mean passing a sufficiently large expression to ExprParse()
150684 ** could cause a stack overflow.
150685 */
150686 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
150687  Fts3Expr *p;
150688  assert( pDel==0 || pDel->pParent==0 );
150689  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
150690  assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
150691  }
150692  while( p ){
150693  Fts3Expr *pParent = p->pParent;
150694  fts3FreeExprNode(p);
150695  if( pParent && p==pParent->pLeft && pParent->pRight ){
150696  p = pParent->pRight;
150697  while( p && (p->pLeft || p->pRight) ){
150698  assert( p==p->pParent->pRight || p==p->pParent->pLeft );
150699  p = (p->pLeft ? p->pLeft : p->pRight);
150700  }
150701  }else{
150702  p = pParent;
150703  }
150704  }
150705 }
150706 
150707 /****************************************************************************
150708 *****************************************************************************
150709 ** Everything after this point is just test code.
150710 */
150711 
150712 #ifdef SQLITE_TEST
150713 
150714 /* #include <stdio.h> */
150715 
150716 /*
150717 ** Function to query the hash-table of tokenizers (see README.tokenizers).
150718 */
150719 static int queryTestTokenizer(
150720  sqlite3 *db,
150721  const char *zName,
150722  const sqlite3_tokenizer_module **pp
150723 ){
150724  int rc;
150725  sqlite3_stmt *pStmt;
150726  const char zSql[] = "SELECT fts3_tokenizer(?)";
150727 
150728  *pp = 0;
150729  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150730  if( rc!=SQLITE_OK ){
150731  return rc;
150732  }
150733 
150734  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
150735  if( SQLITE_ROW==sqlite3_step(pStmt) ){
150736  if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
150737  memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
150738  }
150739  }
150740 
150741  return sqlite3_finalize(pStmt);
150742 }
150743 
150744 /*
150745 ** Return a pointer to a buffer containing a text representation of the
150746 ** expression passed as the first argument. The buffer is obtained from
150747 ** sqlite3_malloc(). It is the responsibility of the caller to use
150748 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
150749 ** NULL is returned.
150750 **
150751 ** If the second argument is not NULL, then its contents are prepended to
150752 ** the returned expression text and then freed using sqlite3_free().
150753 */
150754 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
150755  if( pExpr==0 ){
150756  return sqlite3_mprintf("");
150757  }
150758  switch( pExpr->eType ){
150759  case FTSQUERY_PHRASE: {
150760  Fts3Phrase *pPhrase = pExpr->pPhrase;
150761  int i;
150762  zBuf = sqlite3_mprintf(
150763  "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
150764  for(i=0; zBuf && i<pPhrase->nToken; i++){
150765  zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
150766  pPhrase->aToken[i].n, pPhrase->aToken[i].z,
150767  (pPhrase->aToken[i].isPrefix?"+":"")
150768  );
150769  }
150770  return zBuf;
150771  }
150772 
150773  case FTSQUERY_NEAR:
150774  zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
150775  break;
150776  case FTSQUERY_NOT:
150777  zBuf = sqlite3_mprintf("%zNOT ", zBuf);
150778  break;
150779  case FTSQUERY_AND:
150780  zBuf = sqlite3_mprintf("%zAND ", zBuf);
150781  break;
150782  case FTSQUERY_OR:
150783  zBuf = sqlite3_mprintf("%zOR ", zBuf);
150784  break;
150785  }
150786 
150787  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
150788  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
150789  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
150790 
150791  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
150792  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
150793 
150794  return zBuf;
150795 }
150796 
150797 /*
150798 ** This is the implementation of a scalar SQL function used to test the
150799 ** expression parser. It should be called as follows:
150800 **
150801 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
150802 **
150803 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
150804 ** to parse the query expression (see README.tokenizers). The second argument
150805 ** is the query expression to parse. Each subsequent argument is the name
150806 ** of a column of the fts3 table that the query expression may refer to.
150807 ** For example:
150808 **
150809 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
150810 */
150811 static void fts3ExprTest(
150812  sqlite3_context *context,
150813  int argc,
150814  sqlite3_value **argv
150815 ){
150816  sqlite3_tokenizer_module const *pModule = 0;
150817  sqlite3_tokenizer *pTokenizer = 0;
150818  int rc;
150819  char **azCol = 0;
150820  const char *zExpr;
150821  int nExpr;
150822  int nCol;
150823  int ii;
150824  Fts3Expr *pExpr;
150825  char *zBuf = 0;
150826  sqlite3 *db = sqlite3_context_db_handle(context);
150827 
150828  if( argc<3 ){
150829  sqlite3_result_error(context,
150830  "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
150831  );
150832  return;
150833  }
150834 
150835  rc = queryTestTokenizer(db,
150836  (const char *)sqlite3_value_text(argv[0]), &pModule);
150837  if( rc==SQLITE_NOMEM ){
150838  sqlite3_result_error_nomem(context);
150839  goto exprtest_out;
150840  }else if( !pModule ){
150841  sqlite3_result_error(context, "No such tokenizer module", -1);
150842  goto exprtest_out;
150843  }
150844 
150845  rc = pModule->xCreate(0, 0, &pTokenizer);
150846  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
150847  if( rc==SQLITE_NOMEM ){
150848  sqlite3_result_error_nomem(context);
150849  goto exprtest_out;
150850  }
150851  pTokenizer->pModule = pModule;
150852 
150853  zExpr = (const char *)sqlite3_value_text(argv[1]);
150854  nExpr = sqlite3_value_bytes(argv[1]);
150855  nCol = argc-2;
150856  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
150857  if( !azCol ){
150858  sqlite3_result_error_nomem(context);
150859  goto exprtest_out;
150860  }
150861  for(ii=0; ii<nCol; ii++){
150862  azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
150863  }
150864 
150865  if( sqlite3_user_data(context) ){
150866  char *zDummy = 0;
150867  rc = sqlite3Fts3ExprParse(
150868  pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
150869  );
150870  assert( rc==SQLITE_OK || pExpr==0 );
150871  sqlite3_free(zDummy);
150872  }else{
150873  rc = fts3ExprParseUnbalanced(
150874  pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
150875  );
150876  }
150877 
150878  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
150879  sqlite3Fts3ExprFree(pExpr);
150880  sqlite3_result_error(context, "Error parsing expression", -1);
150881  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
150882  sqlite3_result_error_nomem(context);
150883  }else{
150884  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
150885  sqlite3_free(zBuf);
150886  }
150887 
150888  sqlite3Fts3ExprFree(pExpr);
150889 
150890 exprtest_out:
150891  if( pModule && pTokenizer ){
150892  rc = pModule->xDestroy(pTokenizer);
150893  }
150894  sqlite3_free(azCol);
150895 }
150896 
150897 /*
150898 ** Register the query expression parser test function fts3_exprtest()
150899 ** with database connection db.
150900 */
150901 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
150902  int rc = sqlite3_create_function(
150903  db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
150904  );
150905  if( rc==SQLITE_OK ){
150906  rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
150907  -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
150908  );
150909  }
150910  return rc;
150911 }
150912 
150913 #endif
150914 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150915 
150916 /************** End of fts3_expr.c *******************************************/
150917 /************** Begin file fts3_hash.c ***************************************/
150918 /*
150919 ** 2001 September 22
150920 **
150921 ** The author disclaims copyright to this source code. In place of
150922 ** a legal notice, here is a blessing:
150923 **
150924 ** May you do good and not evil.
150925 ** May you find forgiveness for yourself and forgive others.
150926 ** May you share freely, never taking more than you give.
150927 **
150928 *************************************************************************
150929 ** This is the implementation of generic hash-tables used in SQLite.
150930 ** We've modified it slightly to serve as a standalone hash table
150931 ** implementation for the full-text indexing module.
150932 */
150933 
150934 /*
150935 ** The code in this file is only compiled if:
150936 **
150937 ** * The FTS3 module is being built as an extension
150938 ** (in which case SQLITE_CORE is not defined), or
150939 **
150940 ** * The FTS3 module is being built into the core of
150941 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
150942 */
150943 /* #include "fts3Int.h" */
150944 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
150945 
150946 /* #include <assert.h> */
150947 /* #include <stdlib.h> */
150948 /* #include <string.h> */
150949 
150950 /* #include "fts3_hash.h" */
150951 
150952 /*
150953 ** Malloc and Free functions
150954 */
150955 static void *fts3HashMalloc(int n){
150956  void *p = sqlite3_malloc(n);
150957  if( p ){
150958  memset(p, 0, n);
150959  }
150960  return p;
150961 }
150962 static void fts3HashFree(void *p){
150963  sqlite3_free(p);
150964 }
150965 
150966 /* Turn bulk memory into a hash table object by initializing the
150967 ** fields of the Hash structure.
150968 **
150969 ** "pNew" is a pointer to the hash table that is to be initialized.
150970 ** keyClass is one of the constants
150971 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
150972 ** determines what kind of key the hash table will use. "copyKey" is
150973 ** true if the hash table should make its own private copy of keys and
150974 ** false if it should just use the supplied pointer.
150975 */
150976 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
150977  assert( pNew!=0 );
150978  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
150979  pNew->keyClass = keyClass;
150980  pNew->copyKey = copyKey;
150981  pNew->first = 0;
150982  pNew->count = 0;
150983  pNew->htsize = 0;
150984  pNew->ht = 0;
150985 }
150986 
150987 /* Remove all entries from a hash table. Reclaim all memory.
150988 ** Call this routine to delete a hash table or to reset a hash table
150989 ** to the empty state.
150990 */
150991 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
150992  Fts3HashElem *elem; /* For looping over all elements of the table */
150993 
150994  assert( pH!=0 );
150995  elem = pH->first;
150996  pH->first = 0;
150997  fts3HashFree(pH->ht);
150998  pH->ht = 0;
150999  pH->htsize = 0;
151000  while( elem ){
151001  Fts3HashElem *next_elem = elem->next;
151002  if( pH->copyKey && elem->pKey ){
151003  fts3HashFree(elem->pKey);
151004  }
151005  fts3HashFree(elem);
151006  elem = next_elem;
151007  }
151008  pH->count = 0;
151009 }
151010 
151011 /*
151012 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
151013 */
151014 static int fts3StrHash(const void *pKey, int nKey){
151015  const char *z = (const char *)pKey;
151016  unsigned h = 0;
151017  if( nKey<=0 ) nKey = (int) strlen(z);
151018  while( nKey > 0 ){
151019  h = (h<<3) ^ h ^ *z++;
151020  nKey--;
151021  }
151022  return (int)(h & 0x7fffffff);
151023 }
151024 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
151025  if( n1!=n2 ) return 1;
151026  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
151027 }
151028 
151029 /*
151030 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
151031 */
151032 static int fts3BinHash(const void *pKey, int nKey){
151033  int h = 0;
151034  const char *z = (const char *)pKey;
151035  while( nKey-- > 0 ){
151036  h = (h<<3) ^ h ^ *(z++);
151037  }
151038  return h & 0x7fffffff;
151039 }
151040 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
151041  if( n1!=n2 ) return 1;
151042  return memcmp(pKey1,pKey2,n1);
151043 }
151044 
151045 /*
151046 ** Return a pointer to the appropriate hash function given the key class.
151047 **
151048 ** The C syntax in this function definition may be unfamilar to some
151049 ** programmers, so we provide the following additional explanation:
151050 **
151051 ** The name of the function is "ftsHashFunction". The function takes a
151052 ** single parameter "keyClass". The return value of ftsHashFunction()
151053 ** is a pointer to another function. Specifically, the return value
151054 ** of ftsHashFunction() is a pointer to a function that takes two parameters
151055 ** with types "const void*" and "int" and returns an "int".
151056 */
151057 static int (*ftsHashFunction(int keyClass))(const void*,int){
151058  if( keyClass==FTS3_HASH_STRING ){
151059  return &fts3StrHash;
151060  }else{
151061  assert( keyClass==FTS3_HASH_BINARY );
151062  return &fts3BinHash;
151063  }
151064 }
151065 
151066 /*
151067 ** Return a pointer to the appropriate hash function given the key class.
151068 **
151069 ** For help in interpreted the obscure C code in the function definition,
151070 ** see the header comment on the previous function.
151071 */
151072 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
151073  if( keyClass==FTS3_HASH_STRING ){
151074  return &fts3StrCompare;
151075  }else{
151076  assert( keyClass==FTS3_HASH_BINARY );
151077  return &fts3BinCompare;
151078  }
151079 }
151080 
151081 /* Link an element into the hash table
151082 */
151083 static void fts3HashInsertElement(
151084  Fts3Hash *pH, /* The complete hash table */
151085  struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
151086  Fts3HashElem *pNew /* The element to be inserted */
151087 ){
151088  Fts3HashElem *pHead; /* First element already in pEntry */
151089  pHead = pEntry->chain;
151090  if( pHead ){
151091  pNew->next = pHead;
151092  pNew->prev = pHead->prev;
151093  if( pHead->prev ){ pHead->prev->next = pNew; }
151094  else { pH->first = pNew; }
151095  pHead->prev = pNew;
151096  }else{
151097  pNew->next = pH->first;
151098  if( pH->first ){ pH->first->prev = pNew; }
151099  pNew->prev = 0;
151100  pH->first = pNew;
151101  }
151102  pEntry->count++;
151103  pEntry->chain = pNew;
151104 }
151105 
151106 
151107 /* Resize the hash table so that it cantains "new_size" buckets.
151108 ** "new_size" must be a power of 2. The hash table might fail
151109 ** to resize if sqliteMalloc() fails.
151110 **
151111 ** Return non-zero if a memory allocation error occurs.
151112 */
151113 static int fts3Rehash(Fts3Hash *pH, int new_size){
151114  struct _fts3ht *new_ht; /* The new hash table */
151115  Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
151116  int (*xHash)(const void*,int); /* The hash function */
151117 
151118  assert( (new_size & (new_size-1))==0 );
151119  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
151120  if( new_ht==0 ) return 1;
151121  fts3HashFree(pH->ht);
151122  pH->ht = new_ht;
151123  pH->htsize = new_size;
151124  xHash = ftsHashFunction(pH->keyClass);
151125  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
151126  int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
151127  next_elem = elem->next;
151128  fts3HashInsertElement(pH, &new_ht[h], elem);
151129  }
151130  return 0;
151131 }
151132 
151133 /* This function (for internal use only) locates an element in an
151134 ** hash table that matches the given key. The hash for this key has
151135 ** already been computed and is passed as the 4th parameter.
151136 */
151137 static Fts3HashElem *fts3FindElementByHash(
151138  const Fts3Hash *pH, /* The pH to be searched */
151139  const void *pKey, /* The key we are searching for */
151140  int nKey,
151141  int h /* The hash for this key. */
151142 ){
151143  Fts3HashElem *elem; /* Used to loop thru the element list */
151144  int count; /* Number of elements left to test */
151145  int (*xCompare)(const void*,int,const void*,int); /* comparison function */
151146 
151147  if( pH->ht ){
151148  struct _fts3ht *pEntry = &pH->ht[h];
151149  elem = pEntry->chain;
151150  count = pEntry->count;
151151  xCompare = ftsCompareFunction(pH->keyClass);
151152  while( count-- && elem ){
151153  if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
151154  return elem;
151155  }
151156  elem = elem->next;
151157  }
151158  }
151159  return 0;
151160 }
151161 
151162 /* Remove a single entry from the hash table given a pointer to that
151163 ** element and a hash on the element's key.
151164 */
151165 static void fts3RemoveElementByHash(
151166  Fts3Hash *pH, /* The pH containing "elem" */
151167  Fts3HashElem* elem, /* The element to be removed from the pH */
151168  int h /* Hash value for the element */
151169 ){
151170  struct _fts3ht *pEntry;
151171  if( elem->prev ){
151172  elem->prev->next = elem->next;
151173  }else{
151174  pH->first = elem->next;
151175  }
151176  if( elem->next ){
151177  elem->next->prev = elem->prev;
151178  }
151179  pEntry = &pH->ht[h];
151180  if( pEntry->chain==elem ){
151181  pEntry->chain = elem->next;
151182  }
151183  pEntry->count--;
151184  if( pEntry->count<=0 ){
151185  pEntry->chain = 0;
151186  }
151187  if( pH->copyKey && elem->pKey ){
151188  fts3HashFree(elem->pKey);
151189  }
151190  fts3HashFree( elem );
151191  pH->count--;
151192  if( pH->count<=0 ){
151193  assert( pH->first==0 );
151194  assert( pH->count==0 );
151195  fts3HashClear(pH);
151196  }
151197 }
151198 
151199 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
151200  const Fts3Hash *pH,
151201  const void *pKey,
151202  int nKey
151203 ){
151204  int h; /* A hash on key */
151205  int (*xHash)(const void*,int); /* The hash function */
151206 
151207  if( pH==0 || pH->ht==0 ) return 0;
151208  xHash = ftsHashFunction(pH->keyClass);
151209  assert( xHash!=0 );
151210  h = (*xHash)(pKey,nKey);
151211  assert( (pH->htsize & (pH->htsize-1))==0 );
151212  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
151213 }
151214 
151215 /*
151216 ** Attempt to locate an element of the hash table pH with a key
151217 ** that matches pKey,nKey. Return the data for this element if it is
151218 ** found, or NULL if there is no match.
151219 */
151220 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
151221  Fts3HashElem *pElem; /* The element that matches key (if any) */
151222 
151223  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
151224  return pElem ? pElem->data : 0;
151225 }
151226 
151227 /* Insert an element into the hash table pH. The key is pKey,nKey
151228 ** and the data is "data".
151229 **
151230 ** If no element exists with a matching key, then a new
151231 ** element is created. A copy of the key is made if the copyKey
151232 ** flag is set. NULL is returned.
151233 **
151234 ** If another element already exists with the same key, then the
151235 ** new data replaces the old data and the old data is returned.
151236 ** The key is not copied in this instance. If a malloc fails, then
151237 ** the new data is returned and the hash table is unchanged.
151238 **
151239 ** If the "data" parameter to this function is NULL, then the
151240 ** element corresponding to "key" is removed from the hash table.
151241 */
151242 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
151243  Fts3Hash *pH, /* The hash table to insert into */
151244  const void *pKey, /* The key */
151245  int nKey, /* Number of bytes in the key */
151246  void *data /* The data */
151247 ){
151248  int hraw; /* Raw hash value of the key */
151249  int h; /* the hash of the key modulo hash table size */
151250  Fts3HashElem *elem; /* Used to loop thru the element list */
151251  Fts3HashElem *new_elem; /* New element added to the pH */
151252  int (*xHash)(const void*,int); /* The hash function */
151253 
151254  assert( pH!=0 );
151255  xHash = ftsHashFunction(pH->keyClass);
151256  assert( xHash!=0 );
151257  hraw = (*xHash)(pKey, nKey);
151258  assert( (pH->htsize & (pH->htsize-1))==0 );
151259  h = hraw & (pH->htsize-1);
151260  elem = fts3FindElementByHash(pH,pKey,nKey,h);
151261  if( elem ){
151262  void *old_data = elem->data;
151263  if( data==0 ){
151264  fts3RemoveElementByHash(pH,elem,h);
151265  }else{
151266  elem->data = data;
151267  }
151268  return old_data;
151269  }
151270  if( data==0 ) return 0;
151271  if( (pH->htsize==0 && fts3Rehash(pH,8))
151272  || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
151273  ){
151274  pH->count = 0;
151275  return data;
151276  }
151277  assert( pH->htsize>0 );
151278  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
151279  if( new_elem==0 ) return data;
151280  if( pH->copyKey && pKey!=0 ){
151281  new_elem->pKey = fts3HashMalloc( nKey );
151282  if( new_elem->pKey==0 ){
151283  fts3HashFree(new_elem);
151284  return data;
151285  }
151286  memcpy((void*)new_elem->pKey, pKey, nKey);
151287  }else{
151288  new_elem->pKey = (void*)pKey;
151289  }
151290  new_elem->nKey = nKey;
151291  pH->count++;
151292  assert( pH->htsize>0 );
151293  assert( (pH->htsize & (pH->htsize-1))==0 );
151294  h = hraw & (pH->htsize-1);
151295  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
151296  new_elem->data = data;
151297  return 0;
151298 }
151299 
151300 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151301 
151302 /************** End of fts3_hash.c *******************************************/
151303 /************** Begin file fts3_porter.c *************************************/
151304 /*
151305 ** 2006 September 30
151306 **
151307 ** The author disclaims copyright to this source code. In place of
151308 ** a legal notice, here is a blessing:
151309 **
151310 ** May you do good and not evil.
151311 ** May you find forgiveness for yourself and forgive others.
151312 ** May you share freely, never taking more than you give.
151313 **
151314 *************************************************************************
151315 ** Implementation of the full-text-search tokenizer that implements
151316 ** a Porter stemmer.
151317 */
151318 
151319 /*
151320 ** The code in this file is only compiled if:
151321 **
151322 ** * The FTS3 module is being built as an extension
151323 ** (in which case SQLITE_CORE is not defined), or
151324 **
151325 ** * The FTS3 module is being built into the core of
151326 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
151327 */
151328 /* #include "fts3Int.h" */
151329 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151330 
151331 /* #include <assert.h> */
151332 /* #include <stdlib.h> */
151333 /* #include <stdio.h> */
151334 /* #include <string.h> */
151335 
151336 /* #include "fts3_tokenizer.h" */
151337 
151338 /*
151339 ** Class derived from sqlite3_tokenizer
151340 */
151341 typedef struct porter_tokenizer {
151342  sqlite3_tokenizer base; /* Base class */
151343 } porter_tokenizer;
151344 
151345 /*
151346 ** Class derived from sqlite3_tokenizer_cursor
151347 */
151348 typedef struct porter_tokenizer_cursor {
151349  sqlite3_tokenizer_cursor base;
151350  const char *zInput; /* input we are tokenizing */
151351  int nInput; /* size of the input */
151352  int iOffset; /* current position in zInput */
151353  int iToken; /* index of next token to be returned */
151354  char *zToken; /* storage for current token */
151355  int nAllocated; /* space allocated to zToken buffer */
151356 } porter_tokenizer_cursor;
151357 
151358 
151359 /*
151360 ** Create a new tokenizer instance.
151361 */
151362 static int porterCreate(
151363  int argc, const char * const *argv,
151364  sqlite3_tokenizer **ppTokenizer
151365 ){
151366  porter_tokenizer *t;
151367 
151368  UNUSED_PARAMETER(argc);
151369  UNUSED_PARAMETER(argv);
151370 
151371  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
151372  if( t==NULL ) return SQLITE_NOMEM;
151373  memset(t, 0, sizeof(*t));
151374  *ppTokenizer = &t->base;
151375  return SQLITE_OK;
151376 }
151377 
151378 /*
151379 ** Destroy a tokenizer
151380 */
151381 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
151382  sqlite3_free(pTokenizer);
151383  return SQLITE_OK;
151384 }
151385 
151386 /*
151387 ** Prepare to begin tokenizing a particular string. The input
151388 ** string to be tokenized is zInput[0..nInput-1]. A cursor
151389 ** used to incrementally tokenize this string is returned in
151390 ** *ppCursor.
151391 */
151392 static int porterOpen(
151393  sqlite3_tokenizer *pTokenizer, /* The tokenizer */
151394  const char *zInput, int nInput, /* String to be tokenized */
151395  sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
151396 ){
151397  porter_tokenizer_cursor *c;
151398 
151399  UNUSED_PARAMETER(pTokenizer);
151400 
151401  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
151402  if( c==NULL ) return SQLITE_NOMEM;
151403 
151404  c->zInput = zInput;
151405  if( zInput==0 ){
151406  c->nInput = 0;
151407  }else if( nInput<0 ){
151408  c->nInput = (int)strlen(zInput);
151409  }else{
151410  c->nInput = nInput;
151411  }
151412  c->iOffset = 0; /* start tokenizing at the beginning */
151413  c->iToken = 0;
151414  c->zToken = NULL; /* no space allocated, yet. */
151415  c->nAllocated = 0;
151416 
151417  *ppCursor = &c->base;
151418  return SQLITE_OK;
151419 }
151420 
151421 /*
151422 ** Close a tokenization cursor previously opened by a call to
151423 ** porterOpen() above.
151424 */
151425 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
151426  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
151427  sqlite3_free(c->zToken);
151428  sqlite3_free(c);
151429  return SQLITE_OK;
151430 }
151431 /*
151432 ** Vowel or consonant
151433 */
151434 static const char cType[] = {
151435  0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
151436  1, 1, 1, 2, 1
151437 };
151438 
151439 /*
151440 ** isConsonant() and isVowel() determine if their first character in
151441 ** the string they point to is a consonant or a vowel, according
151442 ** to Porter ruls.
151443 **
151444 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
151445 ** 'Y' is a consonant unless it follows another consonant,
151446 ** in which case it is a vowel.
151447 **
151448 ** In these routine, the letters are in reverse order. So the 'y' rule
151449 ** is that 'y' is a consonant unless it is followed by another
151450 ** consonent.
151451 */
151452 static int isVowel(const char*);
151453 static int isConsonant(const char *z){
151454  int j;
151455  char x = *z;
151456  if( x==0 ) return 0;
151457  assert( x>='a' && x<='z' );
151458  j = cType[x-'a'];
151459  if( j<2 ) return j;
151460  return z[1]==0 || isVowel(z + 1);
151461 }
151462 static int isVowel(const char *z){
151463  int j;
151464  char x = *z;
151465  if( x==0 ) return 0;
151466  assert( x>='a' && x<='z' );
151467  j = cType[x-'a'];
151468  if( j<2 ) return 1-j;
151469  return isConsonant(z + 1);
151470 }
151471 
151472 /*
151473 ** Let any sequence of one or more vowels be represented by V and let
151474 ** C be sequence of one or more consonants. Then every word can be
151475 ** represented as:
151476 **
151477 ** [C] (VC){m} [V]
151478 **
151479 ** In prose: A word is an optional consonant followed by zero or
151480 ** vowel-consonant pairs followed by an optional vowel. "m" is the
151481 ** number of vowel consonant pairs. This routine computes the value
151482 ** of m for the first i bytes of a word.
151483 **
151484 ** Return true if the m-value for z is 1 or more. In other words,
151485 ** return true if z contains at least one vowel that is followed
151486 ** by a consonant.
151487 **
151488 ** In this routine z[] is in reverse order. So we are really looking
151489 ** for an instance of a consonant followed by a vowel.
151490 */
151491 static int m_gt_0(const char *z){
151492  while( isVowel(z) ){ z++; }
151493  if( *z==0 ) return 0;
151494  while( isConsonant(z) ){ z++; }
151495  return *z!=0;
151496 }
151497 
151498 /* Like mgt0 above except we are looking for a value of m which is
151499 ** exactly 1
151500 */
151501 static int m_eq_1(const char *z){
151502  while( isVowel(z) ){ z++; }
151503  if( *z==0 ) return 0;
151504  while( isConsonant(z) ){ z++; }
151505  if( *z==0 ) return 0;
151506  while( isVowel(z) ){ z++; }
151507  if( *z==0 ) return 1;
151508  while( isConsonant(z) ){ z++; }
151509  return *z==0;
151510 }
151511 
151512 /* Like mgt0 above except we are looking for a value of m>1 instead
151513 ** or m>0
151514 */
151515 static int m_gt_1(const char *z){
151516  while( isVowel(z) ){ z++; }
151517  if( *z==0 ) return 0;
151518  while( isConsonant(z) ){ z++; }
151519  if( *z==0 ) return 0;
151520  while( isVowel(z) ){ z++; }
151521  if( *z==0 ) return 0;
151522  while( isConsonant(z) ){ z++; }
151523  return *z!=0;
151524 }
151525 
151526 /*
151527 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
151528 */
151529 static int hasVowel(const char *z){
151530  while( isConsonant(z) ){ z++; }
151531  return *z!=0;
151532 }
151533 
151534 /*
151535 ** Return TRUE if the word ends in a double consonant.
151536 **
151537 ** The text is reversed here. So we are really looking at
151538 ** the first two characters of z[].
151539 */
151540 static int doubleConsonant(const char *z){
151541  return isConsonant(z) && z[0]==z[1];
151542 }
151543 
151544 /*
151545 ** Return TRUE if the word ends with three letters which
151546 ** are consonant-vowel-consonent and where the final consonant
151547 ** is not 'w', 'x', or 'y'.
151548 **
151549 ** The word is reversed here. So we are really checking the
151550 ** first three letters and the first one cannot be in [wxy].
151551 */
151552 static int star_oh(const char *z){
151553  return
151554  isConsonant(z) &&
151555  z[0]!='w' && z[0]!='x' && z[0]!='y' &&
151556  isVowel(z+1) &&
151557  isConsonant(z+2);
151558 }
151559 
151560 /*
151561 ** If the word ends with zFrom and xCond() is true for the stem
151562 ** of the word that preceeds the zFrom ending, then change the
151563 ** ending to zTo.
151564 **
151565 ** The input word *pz and zFrom are both in reverse order. zTo
151566 ** is in normal order.
151567 **
151568 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
151569 ** match. Not that TRUE is returned even if xCond() fails and
151570 ** no substitution occurs.
151571 */
151572 static int stem(
151573  char **pz, /* The word being stemmed (Reversed) */
151574  const char *zFrom, /* If the ending matches this... (Reversed) */
151575  const char *zTo, /* ... change the ending to this (not reversed) */
151576  int (*xCond)(const char*) /* Condition that must be true */
151577 ){
151578  char *z = *pz;
151579  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
151580  if( *zFrom!=0 ) return 0;
151581  if( xCond && !xCond(z) ) return 1;
151582  while( *zTo ){
151583  *(--z) = *(zTo++);
151584  }
151585  *pz = z;
151586  return 1;
151587 }
151588 
151589 /*
151590 ** This is the fallback stemmer used when the porter stemmer is
151591 ** inappropriate. The input word is copied into the output with
151592 ** US-ASCII case folding. If the input word is too long (more
151593 ** than 20 bytes if it contains no digits or more than 6 bytes if
151594 ** it contains digits) then word is truncated to 20 or 6 bytes
151595 ** by taking 10 or 3 bytes from the beginning and end.
151596 */
151597 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
151598  int i, mx, j;
151599  int hasDigit = 0;
151600  for(i=0; i<nIn; i++){
151601  char c = zIn[i];
151602  if( c>='A' && c<='Z' ){
151603  zOut[i] = c - 'A' + 'a';
151604  }else{
151605  if( c>='0' && c<='9' ) hasDigit = 1;
151606  zOut[i] = c;
151607  }
151608  }
151609  mx = hasDigit ? 3 : 10;
151610  if( nIn>mx*2 ){
151611  for(j=mx, i=nIn-mx; i<nIn; i++, j++){
151612  zOut[j] = zOut[i];
151613  }
151614  i = j;
151615  }
151616  zOut[i] = 0;
151617  *pnOut = i;
151618 }
151619 
151620 
151621 /*
151622 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
151623 ** zOut is at least big enough to hold nIn bytes. Write the actual
151624 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
151625 **
151626 ** Any upper-case characters in the US-ASCII character set ([A-Z])
151627 ** are converted to lower case. Upper-case UTF characters are
151628 ** unchanged.
151629 **
151630 ** Words that are longer than about 20 bytes are stemmed by retaining
151631 ** a few bytes from the beginning and the end of the word. If the
151632 ** word contains digits, 3 bytes are taken from the beginning and
151633 ** 3 bytes from the end. For long words without digits, 10 bytes
151634 ** are taken from each end. US-ASCII case folding still applies.
151635 **
151636 ** If the input word contains not digits but does characters not
151637 ** in [a-zA-Z] then no stemming is attempted and this routine just
151638 ** copies the input into the input into the output with US-ASCII
151639 ** case folding.
151640 **
151641 ** Stemming never increases the length of the word. So there is
151642 ** no chance of overflowing the zOut buffer.
151643 */
151644 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
151645  int i, j;
151646  char zReverse[28];
151647  char *z, *z2;
151648  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
151649  /* The word is too big or too small for the porter stemmer.
151650  ** Fallback to the copy stemmer */
151651  copy_stemmer(zIn, nIn, zOut, pnOut);
151652  return;
151653  }
151654  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
151655  char c = zIn[i];
151656  if( c>='A' && c<='Z' ){
151657  zReverse[j] = c + 'a' - 'A';
151658  }else if( c>='a' && c<='z' ){
151659  zReverse[j] = c;
151660  }else{
151661  /* The use of a character not in [a-zA-Z] means that we fallback
151662  ** to the copy stemmer */
151663  copy_stemmer(zIn, nIn, zOut, pnOut);
151664  return;
151665  }
151666  }
151667  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
151668  z = &zReverse[j+1];
151669 
151670 
151671  /* Step 1a */
151672  if( z[0]=='s' ){
151673  if(
151674  !stem(&z, "sess", "ss", 0) &&
151675  !stem(&z, "sei", "i", 0) &&
151676  !stem(&z, "ss", "ss", 0)
151677  ){
151678  z++;
151679  }
151680  }
151681 
151682  /* Step 1b */
151683  z2 = z;
151684  if( stem(&z, "dee", "ee", m_gt_0) ){
151685  /* Do nothing. The work was all in the test */
151686  }else if(
151687  (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
151688  && z!=z2
151689  ){
151690  if( stem(&z, "ta", "ate", 0) ||
151691  stem(&z, "lb", "ble", 0) ||
151692  stem(&z, "zi", "ize", 0) ){
151693  /* Do nothing. The work was all in the test */
151694  }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
151695  z++;
151696  }else if( m_eq_1(z) && star_oh(z) ){
151697  *(--z) = 'e';
151698  }
151699  }
151700 
151701  /* Step 1c */
151702  if( z[0]=='y' && hasVowel(z+1) ){
151703  z[0] = 'i';
151704  }
151705 
151706  /* Step 2 */
151707  switch( z[1] ){
151708  case 'a':
151709  if( !stem(&z, "lanoita", "ate", m_gt_0) ){
151710  stem(&z, "lanoit", "tion", m_gt_0);
151711  }
151712  break;
151713  case 'c':
151714  if( !stem(&z, "icne", "ence", m_gt_0) ){
151715  stem(&z, "icna", "ance", m_gt_0);
151716  }
151717  break;
151718  case 'e':
151719  stem(&z, "rezi", "ize", m_gt_0);
151720  break;
151721  case 'g':
151722  stem(&z, "igol", "log", m_gt_0);
151723  break;
151724  case 'l':
151725  if( !stem(&z, "ilb", "ble", m_gt_0)
151726  && !stem(&z, "illa", "al", m_gt_0)
151727  && !stem(&z, "iltne", "ent", m_gt_0)
151728  && !stem(&z, "ile", "e", m_gt_0)
151729  ){
151730  stem(&z, "ilsuo", "ous", m_gt_0);
151731  }
151732  break;
151733  case 'o':
151734  if( !stem(&z, "noitazi", "ize", m_gt_0)
151735  && !stem(&z, "noita", "ate", m_gt_0)
151736  ){
151737  stem(&z, "rota", "ate", m_gt_0);
151738  }
151739  break;
151740  case 's':
151741  if( !stem(&z, "msila", "al", m_gt_0)
151742  && !stem(&z, "ssenevi", "ive", m_gt_0)
151743  && !stem(&z, "ssenluf", "ful", m_gt_0)
151744  ){
151745  stem(&z, "ssensuo", "ous", m_gt_0);
151746  }
151747  break;
151748  case 't':
151749  if( !stem(&z, "itila", "al", m_gt_0)
151750  && !stem(&z, "itivi", "ive", m_gt_0)
151751  ){
151752  stem(&z, "itilib", "ble", m_gt_0);
151753  }
151754  break;
151755  }
151756 
151757  /* Step 3 */
151758  switch( z[0] ){
151759  case 'e':
151760  if( !stem(&z, "etaci", "ic", m_gt_0)
151761  && !stem(&z, "evita", "", m_gt_0)
151762  ){
151763  stem(&z, "ezila", "al", m_gt_0);
151764  }
151765  break;
151766  case 'i':
151767  stem(&z, "itici", "ic", m_gt_0);
151768  break;
151769  case 'l':
151770  if( !stem(&z, "laci", "ic", m_gt_0) ){
151771  stem(&z, "luf", "", m_gt_0);
151772  }
151773  break;
151774  case 's':
151775  stem(&z, "ssen", "", m_gt_0);
151776  break;
151777  }
151778 
151779  /* Step 4 */
151780  switch( z[1] ){
151781  case 'a':
151782  if( z[0]=='l' && m_gt_1(z+2) ){
151783  z += 2;
151784  }
151785  break;
151786  case 'c':
151787  if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
151788  z += 4;
151789  }
151790  break;
151791  case 'e':
151792  if( z[0]=='r' && m_gt_1(z+2) ){
151793  z += 2;
151794  }
151795  break;
151796  case 'i':
151797  if( z[0]=='c' && m_gt_1(z+2) ){
151798  z += 2;
151799  }
151800  break;
151801  case 'l':
151802  if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
151803  z += 4;
151804  }
151805  break;
151806  case 'n':
151807  if( z[0]=='t' ){
151808  if( z[2]=='a' ){
151809  if( m_gt_1(z+3) ){
151810  z += 3;
151811  }
151812  }else if( z[2]=='e' ){
151813  if( !stem(&z, "tneme", "", m_gt_1)
151814  && !stem(&z, "tnem", "", m_gt_1)
151815  ){
151816  stem(&z, "tne", "", m_gt_1);
151817  }
151818  }
151819  }
151820  break;
151821  case 'o':
151822  if( z[0]=='u' ){
151823  if( m_gt_1(z+2) ){
151824  z += 2;
151825  }
151826  }else if( z[3]=='s' || z[3]=='t' ){
151827  stem(&z, "noi", "", m_gt_1);
151828  }
151829  break;
151830  case 's':
151831  if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
151832  z += 3;
151833  }
151834  break;
151835  case 't':
151836  if( !stem(&z, "eta", "", m_gt_1) ){
151837  stem(&z, "iti", "", m_gt_1);
151838  }
151839  break;
151840  case 'u':
151841  if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
151842  z += 3;
151843  }
151844  break;
151845  case 'v':
151846  case 'z':
151847  if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
151848  z += 3;
151849  }
151850  break;
151851  }
151852 
151853  /* Step 5a */
151854  if( z[0]=='e' ){
151855  if( m_gt_1(z+1) ){
151856  z++;
151857  }else if( m_eq_1(z+1) && !star_oh(z+1) ){
151858  z++;
151859  }
151860  }
151861 
151862  /* Step 5b */
151863  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
151864  z++;
151865  }
151866 
151867  /* z[] is now the stemmed word in reverse order. Flip it back
151868  ** around into forward order and return.
151869  */
151870  *pnOut = i = (int)strlen(z);
151871  zOut[i] = 0;
151872  while( *z ){
151873  zOut[--i] = *(z++);
151874  }
151875 }
151876 
151877 /*
151878 ** Characters that can be part of a token. We assume any character
151879 ** whose value is greater than 0x80 (any UTF character) can be
151880 ** part of a token. In other words, delimiters all must have
151881 ** values of 0x7f or lower.
151882 */
151883 static const char porterIdChar[] = {
151884 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
151885  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
151886  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
151887  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
151888  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
151889  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
151890 };
151891 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
151892 
151893 /*
151894 ** Extract the next token from a tokenization cursor. The cursor must
151895 ** have been opened by a prior call to porterOpen().
151896 */
151897 static int porterNext(
151898  sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
151899  const char **pzToken, /* OUT: *pzToken is the token text */
151900  int *pnBytes, /* OUT: Number of bytes in token */
151901  int *piStartOffset, /* OUT: Starting offset of token */
151902  int *piEndOffset, /* OUT: Ending offset of token */
151903  int *piPosition /* OUT: Position integer of token */
151904 ){
151905  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
151906  const char *z = c->zInput;
151907 
151908  while( c->iOffset<c->nInput ){
151909  int iStartOffset, ch;
151910 
151911  /* Scan past delimiter characters */
151912  while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
151913  c->iOffset++;
151914  }
151915 
151916  /* Count non-delimiter characters. */
151917  iStartOffset = c->iOffset;
151918  while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
151919  c->iOffset++;
151920  }
151921 
151922  if( c->iOffset>iStartOffset ){
151923  int n = c->iOffset-iStartOffset;
151924  if( n>c->nAllocated ){
151925  char *pNew;
151926  c->nAllocated = n+20;
151927  pNew = sqlite3_realloc(c->zToken, c->nAllocated);
151928  if( !pNew ) return SQLITE_NOMEM;
151929  c->zToken = pNew;
151930  }
151931  porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
151932  *pzToken = c->zToken;
151933  *piStartOffset = iStartOffset;
151934  *piEndOffset = c->iOffset;
151935  *piPosition = c->iToken++;
151936  return SQLITE_OK;
151937  }
151938  }
151939  return SQLITE_DONE;
151940 }
151941 
151942 /*
151943 ** The set of routines that implement the porter-stemmer tokenizer
151944 */
151945 static const sqlite3_tokenizer_module porterTokenizerModule = {
151946  0,
151947  porterCreate,
151948  porterDestroy,
151949  porterOpen,
151950  porterClose,
151951  porterNext,
151952  0
151953 };
151954 
151955 /*
151956 ** Allocate a new porter tokenizer. Return a pointer to the new
151957 ** tokenizer in *ppModule
151958 */
151959 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
151960  sqlite3_tokenizer_module const**ppModule
151961 ){
151962  *ppModule = &porterTokenizerModule;
151963 }
151964 
151965 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151966 
151967 /************** End of fts3_porter.c *****************************************/
151968 /************** Begin file fts3_tokenizer.c **********************************/
151969 /*
151970 ** 2007 June 22
151971 **
151972 ** The author disclaims copyright to this source code. In place of
151973 ** a legal notice, here is a blessing:
151974 **
151975 ** May you do good and not evil.
151976 ** May you find forgiveness for yourself and forgive others.
151977 ** May you share freely, never taking more than you give.
151978 **
151979 ******************************************************************************
151980 **
151981 ** This is part of an SQLite module implementing full-text search.
151982 ** This particular file implements the generic tokenizer interface.
151983 */
151984 
151985 /*
151986 ** The code in this file is only compiled if:
151987 **
151988 ** * The FTS3 module is being built as an extension
151989 ** (in which case SQLITE_CORE is not defined), or
151990 **
151991 ** * The FTS3 module is being built into the core of
151992 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
151993 */
151994 /* #include "fts3Int.h" */
151995 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151996 
151997 /* #include <assert.h> */
151998 /* #include <string.h> */
151999 
152000 /*
152001 ** Return true if the two-argument version of fts3_tokenizer()
152002 ** has been activated via a prior call to sqlite3_db_config(db,
152003 ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
152004 */
152005 static int fts3TokenizerEnabled(sqlite3_context *context){
152006  sqlite3 *db = sqlite3_context_db_handle(context);
152007  int isEnabled = 0;
152008  sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
152009  return isEnabled;
152010 }
152011 
152012 /*
152013 ** Implementation of the SQL scalar function for accessing the underlying
152014 ** hash table. This function may be called as follows:
152015 **
152016 ** SELECT <function-name>(<key-name>);
152017 ** SELECT <function-name>(<key-name>, <pointer>);
152018 **
152019 ** where <function-name> is the name passed as the second argument
152020 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
152021 **
152022 ** If the <pointer> argument is specified, it must be a blob value
152023 ** containing a pointer to be stored as the hash data corresponding
152024 ** to the string <key-name>. If <pointer> is not specified, then
152025 ** the string <key-name> must already exist in the has table. Otherwise,
152026 ** an error is returned.
152027 **
152028 ** Whether or not the <pointer> argument is specified, the value returned
152029 ** is a blob containing the pointer stored as the hash data corresponding
152030 ** to string <key-name> (after the hash-table is updated, if applicable).
152031 */
152032 static void fts3TokenizerFunc(
152033  sqlite3_context *context,
152034  int argc,
152035  sqlite3_value **argv
152036 ){
152037  Fts3Hash *pHash;
152038  void *pPtr = 0;
152039  const unsigned char *zName;
152040  int nName;
152041 
152042  assert( argc==1 || argc==2 );
152043 
152044  pHash = (Fts3Hash *)sqlite3_user_data(context);
152045 
152046  zName = sqlite3_value_text(argv[0]);
152047  nName = sqlite3_value_bytes(argv[0])+1;
152048 
152049  if( argc==2 ){
152050  if( fts3TokenizerEnabled(context) ){
152051  void *pOld;
152052  int n = sqlite3_value_bytes(argv[1]);
152053  if( zName==0 || n!=sizeof(pPtr) ){
152054  sqlite3_result_error(context, "argument type mismatch", -1);
152055  return;
152056  }
152057  pPtr = *(void **)sqlite3_value_blob(argv[1]);
152058  pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
152059  if( pOld==pPtr ){
152060  sqlite3_result_error(context, "out of memory", -1);
152061  }
152062  }else{
152063  sqlite3_result_error(context, "fts3tokenize disabled", -1);
152064  return;
152065  }
152066  }else{
152067  if( zName ){
152068  pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
152069  }
152070  if( !pPtr ){
152071  char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
152072  sqlite3_result_error(context, zErr, -1);
152073  sqlite3_free(zErr);
152074  return;
152075  }
152076  }
152077  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
152078 }
152079 
152080 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
152081  static const char isFtsIdChar[] = {
152082  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
152083  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
152084  0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
152085  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
152086  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
152087  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
152088  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
152089  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
152090  };
152091  return (c&0x80 || isFtsIdChar[(int)(c)]);
152092 }
152093 
152094 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
152095  const char *z1;
152096  const char *z2 = 0;
152097 
152098  /* Find the start of the next token. */
152099  z1 = zStr;
152100  while( z2==0 ){
152101  char c = *z1;
152102  switch( c ){
152103  case '\0': return 0; /* No more tokens here */
152104  case '\'':
152105  case '"':
152106  case '`': {
152107  z2 = z1;
152108  while( *++z2 && (*z2!=c || *++z2==c) );
152109  break;
152110  }
152111  case '[':
152112  z2 = &z1[1];
152113  while( *z2 && z2[0]!=']' ) z2++;
152114  if( *z2 ) z2++;
152115  break;
152116 
152117  default:
152118  if( sqlite3Fts3IsIdChar(*z1) ){
152119  z2 = &z1[1];
152120  while( sqlite3Fts3IsIdChar(*z2) ) z2++;
152121  }else{
152122  z1++;
152123  }
152124  }
152125  }
152126 
152127  *pn = (int)(z2-z1);
152128  return z1;
152129 }
152130 
152131 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
152132  Fts3Hash *pHash, /* Tokenizer hash table */
152133  const char *zArg, /* Tokenizer name */
152134  sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
152135  char **pzErr /* OUT: Set to malloced error message */
152136 ){
152137  int rc;
152138  char *z = (char *)zArg;
152139  int n = 0;
152140  char *zCopy;
152141  char *zEnd; /* Pointer to nul-term of zCopy */
152142  sqlite3_tokenizer_module *m;
152143 
152144  zCopy = sqlite3_mprintf("%s", zArg);
152145  if( !zCopy ) return SQLITE_NOMEM;
152146  zEnd = &zCopy[strlen(zCopy)];
152147 
152148  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
152149  if( z==0 ){
152150  assert( n==0 );
152151  z = zCopy;
152152  }
152153  z[n] = '\0';
152154  sqlite3Fts3Dequote(z);
152155 
152156  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
152157  if( !m ){
152158  sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
152159  rc = SQLITE_ERROR;
152160  }else{
152161  char const **aArg = 0;
152162  int iArg = 0;
152163  z = &z[n+1];
152164  while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
152165  int nNew = sizeof(char *)*(iArg+1);
152166  char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
152167  if( !aNew ){
152168  sqlite3_free(zCopy);
152169  sqlite3_free((void *)aArg);
152170  return SQLITE_NOMEM;
152171  }
152172  aArg = aNew;
152173  aArg[iArg++] = z;
152174  z[n] = '\0';
152175  sqlite3Fts3Dequote(z);
152176  z = &z[n+1];
152177  }
152178  rc = m->xCreate(iArg, aArg, ppTok);
152179  assert( rc!=SQLITE_OK || *ppTok );
152180  if( rc!=SQLITE_OK ){
152181  sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
152182  }else{
152183  (*ppTok)->pModule = m;
152184  }
152185  sqlite3_free((void *)aArg);
152186  }
152187 
152188  sqlite3_free(zCopy);
152189  return rc;
152190 }
152191 
152192 
152193 #ifdef SQLITE_TEST
152194 
152195 #if defined(INCLUDE_SQLITE_TCL_H)
152196 # include "sqlite_tcl.h"
152197 #else
152198 # include "tcl.h"
152199 #endif
152200 /* #include <string.h> */
152201 
152202 /*
152203 ** Implementation of a special SQL scalar function for testing tokenizers
152204 ** designed to be used in concert with the Tcl testing framework. This
152205 ** function must be called with two or more arguments:
152206 **
152207 ** SELECT <function-name>(<key-name>, ..., <input-string>);
152208 **
152209 ** where <function-name> is the name passed as the second argument
152210 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
152211 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
152212 **
152213 ** The return value is a string that may be interpreted as a Tcl
152214 ** list. For each token in the <input-string>, three elements are
152215 ** added to the returned list. The first is the token position, the
152216 ** second is the token text (folded, stemmed, etc.) and the third is the
152217 ** substring of <input-string> associated with the token. For example,
152218 ** using the built-in "simple" tokenizer:
152219 **
152220 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
152221 **
152222 ** will return the string:
152223 **
152224 ** "{0 i I 1 dont don't 2 see see 3 how how}"
152225 **
152226 */
152227 static void testFunc(
152228  sqlite3_context *context,
152229  int argc,
152230  sqlite3_value **argv
152231 ){
152232  Fts3Hash *pHash;
152233  sqlite3_tokenizer_module *p;
152234  sqlite3_tokenizer *pTokenizer = 0;
152235  sqlite3_tokenizer_cursor *pCsr = 0;
152236 
152237  const char *zErr = 0;
152238 
152239  const char *zName;
152240  int nName;
152241  const char *zInput;
152242  int nInput;
152243 
152244  const char *azArg[64];
152245 
152246  const char *zToken;
152247  int nToken = 0;
152248  int iStart = 0;
152249  int iEnd = 0;
152250  int iPos = 0;
152251  int i;
152252 
152253  Tcl_Obj *pRet;
152254 
152255  if( argc<2 ){
152256  sqlite3_result_error(context, "insufficient arguments", -1);
152257  return;
152258  }
152259 
152260  nName = sqlite3_value_bytes(argv[0]);
152261  zName = (const char *)sqlite3_value_text(argv[0]);
152262  nInput = sqlite3_value_bytes(argv[argc-1]);
152263  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
152264 
152265  pHash = (Fts3Hash *)sqlite3_user_data(context);
152266  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
152267 
152268  if( !p ){
152269  char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
152270  sqlite3_result_error(context, zErr2, -1);
152271  sqlite3_free(zErr2);
152272  return;
152273  }
152274 
152275  pRet = Tcl_NewObj();
152276  Tcl_IncrRefCount(pRet);
152277 
152278  for(i=1; i<argc-1; i++){
152279  azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
152280  }
152281 
152282  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
152283  zErr = "error in xCreate()";
152284  goto finish;
152285  }
152286  pTokenizer->pModule = p;
152287  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
152288  zErr = "error in xOpen()";
152289  goto finish;
152290  }
152291 
152292  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
152293  Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
152294  Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
152295  zToken = &zInput[iStart];
152296  nToken = iEnd-iStart;
152297  Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
152298  }
152299 
152300  if( SQLITE_OK!=p->xClose(pCsr) ){
152301  zErr = "error in xClose()";
152302  goto finish;
152303  }
152304  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
152305  zErr = "error in xDestroy()";
152306  goto finish;
152307  }
152308 
152309 finish:
152310  if( zErr ){
152311  sqlite3_result_error(context, zErr, -1);
152312  }else{
152313  sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
152314  }
152315  Tcl_DecrRefCount(pRet);
152316 }
152317 
152318 static
152319 int registerTokenizer(
152320  sqlite3 *db,
152321  char *zName,
152322  const sqlite3_tokenizer_module *p
152323 ){
152324  int rc;
152325  sqlite3_stmt *pStmt;
152326  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
152327 
152328  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
152329  if( rc!=SQLITE_OK ){
152330  return rc;
152331  }
152332 
152333  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
152334  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
152335  sqlite3_step(pStmt);
152336 
152337  return sqlite3_finalize(pStmt);
152338 }
152339 
152340 
152341 static
152342 int queryTokenizer(
152343  sqlite3 *db,
152344  char *zName,
152345  const sqlite3_tokenizer_module **pp
152346 ){
152347  int rc;
152348  sqlite3_stmt *pStmt;
152349  const char zSql[] = "SELECT fts3_tokenizer(?)";
152350 
152351  *pp = 0;
152352  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
152353  if( rc!=SQLITE_OK ){
152354  return rc;
152355  }
152356 
152357  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
152358  if( SQLITE_ROW==sqlite3_step(pStmt) ){
152359  if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
152360  memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
152361  }
152362  }
152363 
152364  return sqlite3_finalize(pStmt);
152365 }
152366 
152367 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
152368 
152369 /*
152370 ** Implementation of the scalar function fts3_tokenizer_internal_test().
152371 ** This function is used for testing only, it is not included in the
152372 ** build unless SQLITE_TEST is defined.
152373 **
152374 ** The purpose of this is to test that the fts3_tokenizer() function
152375 ** can be used as designed by the C-code in the queryTokenizer and
152376 ** registerTokenizer() functions above. These two functions are repeated
152377 ** in the README.tokenizer file as an example, so it is important to
152378 ** test them.
152379 **
152380 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
152381 ** function with no arguments. An assert() will fail if a problem is
152382 ** detected. i.e.:
152383 **
152384 ** SELECT fts3_tokenizer_internal_test();
152385 **
152386 */
152387 static void intTestFunc(
152388  sqlite3_context *context,
152389  int argc,
152390  sqlite3_value **argv
152391 ){
152392  int rc;
152393  const sqlite3_tokenizer_module *p1;
152394  const sqlite3_tokenizer_module *p2;
152395  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
152396 
152397  UNUSED_PARAMETER(argc);
152398  UNUSED_PARAMETER(argv);
152399 
152400  /* Test the query function */
152401  sqlite3Fts3SimpleTokenizerModule(&p1);
152402  rc = queryTokenizer(db, "simple", &p2);
152403  assert( rc==SQLITE_OK );
152404  assert( p1==p2 );
152405  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
152406  assert( rc==SQLITE_ERROR );
152407  assert( p2==0 );
152408  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
152409 
152410  /* Test the storage function */
152411  if( fts3TokenizerEnabled(context) ){
152412  rc = registerTokenizer(db, "nosuchtokenizer", p1);
152413  assert( rc==SQLITE_OK );
152414  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
152415  assert( rc==SQLITE_OK );
152416  assert( p2==p1 );
152417  }
152418 
152419  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
152420 }
152421 
152422 #endif
152423 
152424 /*
152425 ** Set up SQL objects in database db used to access the contents of
152426 ** the hash table pointed to by argument pHash. The hash table must
152427 ** been initialized to use string keys, and to take a private copy
152428 ** of the key when a value is inserted. i.e. by a call similar to:
152429 **
152430 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
152431 **
152432 ** This function adds a scalar function (see header comment above
152433 ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
152434 ** defined at compilation time, a temporary virtual table (see header
152435 ** comment above struct HashTableVtab) to the database schema. Both
152436 ** provide read/write access to the contents of *pHash.
152437 **
152438 ** The third argument to this function, zName, is used as the name
152439 ** of both the scalar and, if created, the virtual table.
152440 */
152441 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
152442  sqlite3 *db,
152443  Fts3Hash *pHash,
152444  const char *zName
152445 ){
152446  int rc = SQLITE_OK;
152447  void *p = (void *)pHash;
152448  const int any = SQLITE_ANY;
152449 
152450 #ifdef SQLITE_TEST
152451  char *zTest = 0;
152452  char *zTest2 = 0;
152453  void *pdb = (void *)db;
152454  zTest = sqlite3_mprintf("%s_test", zName);
152455  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
152456  if( !zTest || !zTest2 ){
152457  rc = SQLITE_NOMEM;
152458  }
152459 #endif
152460 
152461  if( SQLITE_OK==rc ){
152462  rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
152463  }
152464  if( SQLITE_OK==rc ){
152465  rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
152466  }
152467 #ifdef SQLITE_TEST
152468  if( SQLITE_OK==rc ){
152469  rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
152470  }
152471  if( SQLITE_OK==rc ){
152472  rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
152473  }
152474 #endif
152475 
152476 #ifdef SQLITE_TEST
152477  sqlite3_free(zTest);
152478  sqlite3_free(zTest2);
152479 #endif
152480 
152481  return rc;
152482 }
152483 
152484 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
152485 
152486 /************** End of fts3_tokenizer.c **************************************/
152487 /************** Begin file fts3_tokenizer1.c *********************************/
152488 /*
152489 ** 2006 Oct 10
152490 **
152491 ** The author disclaims copyright to this source code. In place of
152492 ** a legal notice, here is a blessing:
152493 **
152494 ** May you do good and not evil.
152495 ** May you find forgiveness for yourself and forgive others.
152496 ** May you share freely, never taking more than you give.
152497 **
152498 ******************************************************************************
152499 **
152500 ** Implementation of the "simple" full-text-search tokenizer.
152501 */
152502 
152503 /*
152504 ** The code in this file is only compiled if:
152505 **
152506 ** * The FTS3 module is being built as an extension
152507 ** (in which case SQLITE_CORE is not defined), or
152508 **
152509 ** * The FTS3 module is being built into the core of
152510 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
152511 */
152512 /* #include "fts3Int.h" */
152513 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
152514 
152515 /* #include <assert.h> */
152516 /* #include <stdlib.h> */
152517 /* #include <stdio.h> */
152518 /* #include <string.h> */
152519 
152520 /* #include "fts3_tokenizer.h" */
152521 
152522 typedef struct simple_tokenizer {
152523  sqlite3_tokenizer base;
152524  char delim[128]; /* flag ASCII delimiters */
152525 } simple_tokenizer;
152526 
152527 typedef struct simple_tokenizer_cursor {
152528  sqlite3_tokenizer_cursor base;
152529  const char *pInput; /* input we are tokenizing */
152530  int nBytes; /* size of the input */
152531  int iOffset; /* current position in pInput */
152532  int iToken; /* index of next token to be returned */
152533  char *pToken; /* storage for current token */
152534  int nTokenAllocated; /* space allocated to zToken buffer */
152535 } simple_tokenizer_cursor;
152536 
152537 
152538 static int simpleDelim(simple_tokenizer *t, unsigned char c){
152539  return c<0x80 && t->delim[c];
152540 }
152541 static int fts3_isalnum(int x){
152542  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
152543 }
152544 
152545 /*
152546 ** Create a new tokenizer instance.
152547 */
152548 static int simpleCreate(
152549  int argc, const char * const *argv,
152550  sqlite3_tokenizer **ppTokenizer
152551 ){
152552  simple_tokenizer *t;
152553 
152554  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
152555  if( t==NULL ) return SQLITE_NOMEM;
152556  memset(t, 0, sizeof(*t));
152557 
152558  /* TODO(shess) Delimiters need to remain the same from run to run,
152559  ** else we need to reindex. One solution would be a meta-table to
152560  ** track such information in the database, then we'd only want this
152561  ** information on the initial create.
152562  */
152563  if( argc>1 ){
152564  int i, n = (int)strlen(argv[1]);
152565  for(i=0; i<n; i++){
152566  unsigned char ch = argv[1][i];
152567  /* We explicitly don't support UTF-8 delimiters for now. */
152568  if( ch>=0x80 ){
152569  sqlite3_free(t);
152570  return SQLITE_ERROR;
152571  }
152572  t->delim[ch] = 1;
152573  }
152574  } else {
152575  /* Mark non-alphanumeric ASCII characters as delimiters */
152576  int i;
152577  for(i=1; i<0x80; i++){
152578  t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
152579  }
152580  }
152581 
152582  *ppTokenizer = &t->base;
152583  return SQLITE_OK;
152584 }
152585 
152586 /*
152587 ** Destroy a tokenizer
152588 */
152589 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
152590  sqlite3_free(pTokenizer);
152591  return SQLITE_OK;
152592 }
152593 
152594 /*
152595 ** Prepare to begin tokenizing a particular string. The input
152596 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
152597 ** used to incrementally tokenize this string is returned in
152598 ** *ppCursor.
152599 */
152600 static int simpleOpen(
152601  sqlite3_tokenizer *pTokenizer, /* The tokenizer */
152602  const char *pInput, int nBytes, /* String to be tokenized */
152603  sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
152604 ){
152605  simple_tokenizer_cursor *c;
152606 
152607  UNUSED_PARAMETER(pTokenizer);
152608 
152609  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
152610  if( c==NULL ) return SQLITE_NOMEM;
152611 
152612  c->pInput = pInput;
152613  if( pInput==0 ){
152614  c->nBytes = 0;
152615  }else if( nBytes<0 ){
152616  c->nBytes = (int)strlen(pInput);
152617  }else{
152618  c->nBytes = nBytes;
152619  }
152620  c->iOffset = 0; /* start tokenizing at the beginning */
152621  c->iToken = 0;
152622  c->pToken = NULL; /* no space allocated, yet. */
152623  c->nTokenAllocated = 0;
152624 
152625  *ppCursor = &c->base;
152626  return SQLITE_OK;
152627 }
152628 
152629 /*
152630 ** Close a tokenization cursor previously opened by a call to
152631 ** simpleOpen() above.
152632 */
152633 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
152634  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
152635  sqlite3_free(c->pToken);
152636  sqlite3_free(c);
152637  return SQLITE_OK;
152638 }
152639 
152640 /*
152641 ** Extract the next token from a tokenization cursor. The cursor must
152642 ** have been opened by a prior call to simpleOpen().
152643 */
152644 static int simpleNext(
152645  sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
152646  const char **ppToken, /* OUT: *ppToken is the token text */
152647  int *pnBytes, /* OUT: Number of bytes in token */
152648  int *piStartOffset, /* OUT: Starting offset of token */
152649  int *piEndOffset, /* OUT: Ending offset of token */
152650  int *piPosition /* OUT: Position integer of token */
152651 ){
152652  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
152653  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
152654  unsigned char *p = (unsigned char *)c->pInput;
152655 
152656  while( c->iOffset<c->nBytes ){
152657  int iStartOffset;
152658 
152659  /* Scan past delimiter characters */
152660  while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
152661  c->iOffset++;
152662  }
152663 
152664  /* Count non-delimiter characters. */
152665  iStartOffset = c->iOffset;
152666  while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
152667  c->iOffset++;
152668  }
152669 
152670  if( c->iOffset>iStartOffset ){
152671  int i, n = c->iOffset-iStartOffset;
152672  if( n>c->nTokenAllocated ){
152673  char *pNew;
152674  c->nTokenAllocated = n+20;
152675  pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
152676  if( !pNew ) return SQLITE_NOMEM;
152677  c->pToken = pNew;
152678  }
152679  for(i=0; i<n; i++){
152680  /* TODO(shess) This needs expansion to handle UTF-8
152681  ** case-insensitivity.
152682  */
152683  unsigned char ch = p[iStartOffset+i];
152684  c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
152685  }
152686  *ppToken = c->pToken;
152687  *pnBytes = n;
152688  *piStartOffset = iStartOffset;
152689  *piEndOffset = c->iOffset;
152690  *piPosition = c->iToken++;
152691 
152692  return SQLITE_OK;
152693  }
152694  }
152695  return SQLITE_DONE;
152696 }
152697 
152698 /*
152699 ** The set of routines that implement the simple tokenizer
152700 */
152701 static const sqlite3_tokenizer_module simpleTokenizerModule = {
152702  0,
152703  simpleCreate,
152704  simpleDestroy,
152705  simpleOpen,
152706  simpleClose,
152707  simpleNext,
152708  0,
152709 };
152710 
152711 /*
152712 ** Allocate a new simple tokenizer. Return a pointer to the new
152713 ** tokenizer in *ppModule
152714 */
152715 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
152716  sqlite3_tokenizer_module const**ppModule
152717 ){
152718  *ppModule = &simpleTokenizerModule;
152719 }
152720 
152721 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
152722 
152723 /************** End of fts3_tokenizer1.c *************************************/
152724 /************** Begin file fts3_tokenize_vtab.c ******************************/
152725 /*
152726 ** 2013 Apr 22
152727 **
152728 ** The author disclaims copyright to this source code. In place of
152729 ** a legal notice, here is a blessing:
152730 **
152731 ** May you do good and not evil.
152732 ** May you find forgiveness for yourself and forgive others.
152733 ** May you share freely, never taking more than you give.
152734 **
152735 ******************************************************************************
152736 **
152737 ** This file contains code for the "fts3tokenize" virtual table module.
152738 ** An fts3tokenize virtual table is created as follows:
152739 **
152740 ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
152741 ** <tokenizer-name>, <arg-1>, ...
152742 ** );
152743 **
152744 ** The table created has the following schema:
152745 **
152746 ** CREATE TABLE <tbl>(input, token, start, end, position)
152747 **
152748 ** When queried, the query must include a WHERE clause of type:
152749 **
152750 ** input = <string>
152751 **
152752 ** The virtual table module tokenizes this <string>, using the FTS3
152753 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
152754 ** statement and returns one row for each token in the result. With
152755 ** fields set as follows:
152756 **
152757 ** input: Always set to a copy of <string>
152758 ** token: A token from the input.
152759 ** start: Byte offset of the token within the input <string>.
152760 ** end: Byte offset of the byte immediately following the end of the
152761 ** token within the input string.
152762 ** pos: Token offset of token within input.
152763 **
152764 */
152765 /* #include "fts3Int.h" */
152766 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
152767 
152768 /* #include <string.h> */
152769 /* #include <assert.h> */
152770 
152771 typedef struct Fts3tokTable Fts3tokTable;
152772 typedef struct Fts3tokCursor Fts3tokCursor;
152773 
152774 /*
152775 ** Virtual table structure.
152776 */
152777 struct Fts3tokTable {
152778  sqlite3_vtab base; /* Base class used by SQLite core */
152779  const sqlite3_tokenizer_module *pMod;
152780  sqlite3_tokenizer *pTok;
152781 };
152782 
152783 /*
152784 ** Virtual table cursor structure.
152785 */
152786 struct Fts3tokCursor {
152787  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
152788  char *zInput; /* Input string */
152789  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
152790  int iRowid; /* Current 'rowid' value */
152791  const char *zToken; /* Current 'token' value */
152792  int nToken; /* Size of zToken in bytes */
152793  int iStart; /* Current 'start' value */
152794  int iEnd; /* Current 'end' value */
152795  int iPos; /* Current 'pos' value */
152796 };
152797 
152798 /*
152799 ** Query FTS for the tokenizer implementation named zName.
152800 */
152801 static int fts3tokQueryTokenizer(
152802  Fts3Hash *pHash,
152803  const char *zName,
152804  const sqlite3_tokenizer_module **pp,
152805  char **pzErr
152806 ){
152807  sqlite3_tokenizer_module *p;
152808  int nName = (int)strlen(zName);
152809 
152810  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
152811  if( !p ){
152812  sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
152813  return SQLITE_ERROR;
152814  }
152815 
152816  *pp = p;
152817  return SQLITE_OK;
152818 }
152819 
152820 /*
152821 ** The second argument, argv[], is an array of pointers to nul-terminated
152822 ** strings. This function makes a copy of the array and strings into a
152823 ** single block of memory. It then dequotes any of the strings that appear
152824 ** to be quoted.
152825 **
152826 ** If successful, output parameter *pazDequote is set to point at the
152827 ** array of dequoted strings and SQLITE_OK is returned. The caller is
152828 ** responsible for eventually calling sqlite3_free() to free the array
152829 ** in this case. Or, if an error occurs, an SQLite error code is returned.
152830 ** The final value of *pazDequote is undefined in this case.
152831 */
152832 static int fts3tokDequoteArray(
152833  int argc, /* Number of elements in argv[] */
152834  const char * const *argv, /* Input array */
152835  char ***pazDequote /* Output array */
152836 ){
152837  int rc = SQLITE_OK; /* Return code */
152838  if( argc==0 ){
152839  *pazDequote = 0;
152840  }else{
152841  int i;
152842  int nByte = 0;
152843  char **azDequote;
152844 
152845  for(i=0; i<argc; i++){
152846  nByte += (int)(strlen(argv[i]) + 1);
152847  }
152848 
152849  *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
152850  if( azDequote==0 ){
152851  rc = SQLITE_NOMEM;
152852  }else{
152853  char *pSpace = (char *)&azDequote[argc];
152854  for(i=0; i<argc; i++){
152855  int n = (int)strlen(argv[i]);
152856  azDequote[i] = pSpace;
152857  memcpy(pSpace, argv[i], n+1);
152858  sqlite3Fts3Dequote(pSpace);
152859  pSpace += (n+1);
152860  }
152861  }
152862  }
152863 
152864  return rc;
152865 }
152866 
152867 /*
152868 ** Schema of the tokenizer table.
152869 */
152870 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
152871 
152872 /*
152873 ** This function does all the work for both the xConnect and xCreate methods.
152874 ** These tables have no persistent representation of their own, so xConnect
152875 ** and xCreate are identical operations.
152876 **
152877 ** argv[0]: module name
152878 ** argv[1]: database name
152879 ** argv[2]: table name
152880 ** argv[3]: first argument (tokenizer name)
152881 */
152882 static int fts3tokConnectMethod(
152883  sqlite3 *db, /* Database connection */
152884  void *pHash, /* Hash table of tokenizers */
152885  int argc, /* Number of elements in argv array */
152886  const char * const *argv, /* xCreate/xConnect argument array */
152887  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
152888  char **pzErr /* OUT: sqlite3_malloc'd error message */
152889 ){
152890  Fts3tokTable *pTab = 0;
152891  const sqlite3_tokenizer_module *pMod = 0;
152892  sqlite3_tokenizer *pTok = 0;
152893  int rc;
152894  char **azDequote = 0;
152895  int nDequote;
152896 
152897  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
152898  if( rc!=SQLITE_OK ) return rc;
152899 
152900  nDequote = argc-3;
152901  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
152902 
152903  if( rc==SQLITE_OK ){
152904  const char *zModule;
152905  if( nDequote<1 ){
152906  zModule = "simple";
152907  }else{
152908  zModule = azDequote[0];
152909  }
152910  rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
152911  }
152912 
152913  assert( (rc==SQLITE_OK)==(pMod!=0) );
152914  if( rc==SQLITE_OK ){
152915  const char * const *azArg = (const char * const *)&azDequote[1];
152916  rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
152917  }
152918 
152919  if( rc==SQLITE_OK ){
152920  pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
152921  if( pTab==0 ){
152922  rc = SQLITE_NOMEM;
152923  }
152924  }
152925 
152926  if( rc==SQLITE_OK ){
152927  memset(pTab, 0, sizeof(Fts3tokTable));
152928  pTab->pMod = pMod;
152929  pTab->pTok = pTok;
152930  *ppVtab = &pTab->base;
152931  }else{
152932  if( pTok ){
152933  pMod->xDestroy(pTok);
152934  }
152935  }
152936 
152937  sqlite3_free(azDequote);
152938  return rc;
152939 }
152940 
152941 /*
152942 ** This function does the work for both the xDisconnect and xDestroy methods.
152943 ** These tables have no persistent representation of their own, so xDisconnect
152944 ** and xDestroy are identical operations.
152945 */
152946 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
152947  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
152948 
152949  pTab->pMod->xDestroy(pTab->pTok);
152950  sqlite3_free(pTab);
152951  return SQLITE_OK;
152952 }
152953 
152954 /*
152955 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
152956 */
152957 static int fts3tokBestIndexMethod(
152958  sqlite3_vtab *pVTab,
152959  sqlite3_index_info *pInfo
152960 ){
152961  int i;
152962  UNUSED_PARAMETER(pVTab);
152963 
152964  for(i=0; i<pInfo->nConstraint; i++){
152965  if( pInfo->aConstraint[i].usable
152966  && pInfo->aConstraint[i].iColumn==0
152967  && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
152968  ){
152969  pInfo->idxNum = 1;
152970  pInfo->aConstraintUsage[i].argvIndex = 1;
152971  pInfo->aConstraintUsage[i].omit = 1;
152972  pInfo->estimatedCost = 1;
152973  return SQLITE_OK;
152974  }
152975  }
152976 
152977  pInfo->idxNum = 0;
152978  assert( pInfo->estimatedCost>1000000.0 );
152979 
152980  return SQLITE_OK;
152981 }
152982 
152983 /*
152984 ** xOpen - Open a cursor.
152985 */
152986 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
152987  Fts3tokCursor *pCsr;
152988  UNUSED_PARAMETER(pVTab);
152989 
152990  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
152991  if( pCsr==0 ){
152992  return SQLITE_NOMEM;
152993  }
152994  memset(pCsr, 0, sizeof(Fts3tokCursor));
152995 
152996  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
152997  return SQLITE_OK;
152998 }
152999 
153000 /*
153001 ** Reset the tokenizer cursor passed as the only argument. As if it had
153002 ** just been returned by fts3tokOpenMethod().
153003 */
153004 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
153005  if( pCsr->pCsr ){
153006  Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
153007  pTab->pMod->xClose(pCsr->pCsr);
153008  pCsr->pCsr = 0;
153009  }
153010  sqlite3_free(pCsr->zInput);
153011  pCsr->zInput = 0;
153012  pCsr->zToken = 0;
153013  pCsr->nToken = 0;
153014  pCsr->iStart = 0;
153015  pCsr->iEnd = 0;
153016  pCsr->iPos = 0;
153017  pCsr->iRowid = 0;
153018 }
153019 
153020 /*
153021 ** xClose - Close a cursor.
153022 */
153023 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
153024  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153025 
153026  fts3tokResetCursor(pCsr);
153027  sqlite3_free(pCsr);
153028  return SQLITE_OK;
153029 }
153030 
153031 /*
153032 ** xNext - Advance the cursor to the next row, if any.
153033 */
153034 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
153035  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153036  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
153037  int rc; /* Return code */
153038 
153039  pCsr->iRowid++;
153040  rc = pTab->pMod->xNext(pCsr->pCsr,
153041  &pCsr->zToken, &pCsr->nToken,
153042  &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
153043  );
153044 
153045  if( rc!=SQLITE_OK ){
153046  fts3tokResetCursor(pCsr);
153047  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
153048  }
153049 
153050  return rc;
153051 }
153052 
153053 /*
153054 ** xFilter - Initialize a cursor to point at the start of its data.
153055 */
153056 static int fts3tokFilterMethod(
153057  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
153058  int idxNum, /* Strategy index */
153059  const char *idxStr, /* Unused */
153060  int nVal, /* Number of elements in apVal */
153061  sqlite3_value **apVal /* Arguments for the indexing scheme */
153062 ){
153063  int rc = SQLITE_ERROR;
153064  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153065  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
153066  UNUSED_PARAMETER(idxStr);
153067  UNUSED_PARAMETER(nVal);
153068 
153069  fts3tokResetCursor(pCsr);
153070  if( idxNum==1 ){
153071  const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
153072  int nByte = sqlite3_value_bytes(apVal[0]);
153073  pCsr->zInput = sqlite3_malloc(nByte+1);
153074  if( pCsr->zInput==0 ){
153075  rc = SQLITE_NOMEM;
153076  }else{
153077  memcpy(pCsr->zInput, zByte, nByte);
153078  pCsr->zInput[nByte] = 0;
153079  rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
153080  if( rc==SQLITE_OK ){
153081  pCsr->pCsr->pTokenizer = pTab->pTok;
153082  }
153083  }
153084  }
153085 
153086  if( rc!=SQLITE_OK ) return rc;
153087  return fts3tokNextMethod(pCursor);
153088 }
153089 
153090 /*
153091 ** xEof - Return true if the cursor is at EOF, or false otherwise.
153092 */
153093 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
153094  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153095  return (pCsr->zToken==0);
153096 }
153097 
153098 /*
153099 ** xColumn - Return a column value.
153100 */
153101 static int fts3tokColumnMethod(
153102  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
153103  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
153104  int iCol /* Index of column to read value from */
153105 ){
153106  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153107 
153108  /* CREATE TABLE x(input, token, start, end, position) */
153109  switch( iCol ){
153110  case 0:
153111  sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
153112  break;
153113  case 1:
153114  sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
153115  break;
153116  case 2:
153117  sqlite3_result_int(pCtx, pCsr->iStart);
153118  break;
153119  case 3:
153120  sqlite3_result_int(pCtx, pCsr->iEnd);
153121  break;
153122  default:
153123  assert( iCol==4 );
153124  sqlite3_result_int(pCtx, pCsr->iPos);
153125  break;
153126  }
153127  return SQLITE_OK;
153128 }
153129 
153130 /*
153131 ** xRowid - Return the current rowid for the cursor.
153132 */
153133 static int fts3tokRowidMethod(
153134  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
153135  sqlite_int64 *pRowid /* OUT: Rowid value */
153136 ){
153137  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153138  *pRowid = (sqlite3_int64)pCsr->iRowid;
153139  return SQLITE_OK;
153140 }
153141 
153142 /*
153143 ** Register the fts3tok module with database connection db. Return SQLITE_OK
153144 ** if successful or an error code if sqlite3_create_module() fails.
153145 */
153146 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
153147  static const sqlite3_module fts3tok_module = {
153148  0, /* iVersion */
153149  fts3tokConnectMethod, /* xCreate */
153150  fts3tokConnectMethod, /* xConnect */
153151  fts3tokBestIndexMethod, /* xBestIndex */
153152  fts3tokDisconnectMethod, /* xDisconnect */
153153  fts3tokDisconnectMethod, /* xDestroy */
153154  fts3tokOpenMethod, /* xOpen */
153155  fts3tokCloseMethod, /* xClose */
153156  fts3tokFilterMethod, /* xFilter */
153157  fts3tokNextMethod, /* xNext */
153158  fts3tokEofMethod, /* xEof */
153159  fts3tokColumnMethod, /* xColumn */
153160  fts3tokRowidMethod, /* xRowid */
153161  0, /* xUpdate */
153162  0, /* xBegin */
153163  0, /* xSync */
153164  0, /* xCommit */
153165  0, /* xRollback */
153166  0, /* xFindFunction */
153167  0, /* xRename */
153168  0, /* xSavepoint */
153169  0, /* xRelease */
153170  0 /* xRollbackTo */
153171  };
153172  int rc; /* Return code */
153173 
153174  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
153175  return rc;
153176 }
153177 
153178 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
153179 
153180 /************** End of fts3_tokenize_vtab.c **********************************/
153181 /************** Begin file fts3_write.c **************************************/
153182 /*
153183 ** 2009 Oct 23
153184 **
153185 ** The author disclaims copyright to this source code. In place of
153186 ** a legal notice, here is a blessing:
153187 **
153188 ** May you do good and not evil.
153189 ** May you find forgiveness for yourself and forgive others.
153190 ** May you share freely, never taking more than you give.
153191 **
153192 ******************************************************************************
153193 **
153194 ** This file is part of the SQLite FTS3 extension module. Specifically,
153195 ** this file contains code to insert, update and delete rows from FTS3
153196 ** tables. It also contains code to merge FTS3 b-tree segments. Some
153197 ** of the sub-routines used to merge segments are also used by the query
153198 ** code in fts3.c.
153199 */
153200 
153201 /* #include "fts3Int.h" */
153202 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153203 
153204 /* #include <string.h> */
153205 /* #include <assert.h> */
153206 /* #include <stdlib.h> */
153207 
153208 
153209 #define FTS_MAX_APPENDABLE_HEIGHT 16
153210 
153211 /*
153212 ** When full-text index nodes are loaded from disk, the buffer that they
153213 ** are loaded into has the following number of bytes of padding at the end
153214 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
153215 ** of 920 bytes is allocated for it.
153216 **
153217 ** This means that if we have a pointer into a buffer containing node data,
153218 ** it is always safe to read up to two varints from it without risking an
153219 ** overread, even if the node data is corrupted.
153220 */
153221 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
153222 
153223 /*
153224 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
153225 ** memory incrementally instead of all at once. This can be a big performance
153226 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
153227 ** method before retrieving all query results (as may happen, for example,
153228 ** if a query has a LIMIT clause).
153229 **
153230 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
153231 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
153232 ** The code is written so that the hard lower-limit for each of these values
153233 ** is 1. Clearly such small values would be inefficient, but can be useful
153234 ** for testing purposes.
153235 **
153236 ** If this module is built with SQLITE_TEST defined, these constants may
153237 ** be overridden at runtime for testing purposes. File fts3_test.c contains
153238 ** a Tcl interface to read and write the values.
153239 */
153240 #ifdef SQLITE_TEST
153241 int test_fts3_node_chunksize = (4*1024);
153242 int test_fts3_node_chunk_threshold = (4*1024)*4;
153243 # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
153244 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
153245 #else
153246 # define FTS3_NODE_CHUNKSIZE (4*1024)
153247 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
153248 #endif
153249 
153250 /*
153251 ** The two values that may be meaningfully bound to the :1 parameter in
153252 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
153253 */
153254 #define FTS_STAT_DOCTOTAL 0
153255 #define FTS_STAT_INCRMERGEHINT 1
153256 #define FTS_STAT_AUTOINCRMERGE 2
153257 
153258 /*
153259 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
153260 ** and incremental merge operation that takes place. This is used for
153261 ** debugging FTS only, it should not usually be turned on in production
153262 ** systems.
153263 */
153264 #ifdef FTS3_LOG_MERGES
153265 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
153266  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
153267 }
153268 #else
153269 #define fts3LogMerge(x, y)
153270 #endif
153271 
153272 
153273 typedef struct PendingList PendingList;
153274 typedef struct SegmentNode SegmentNode;
153275 typedef struct SegmentWriter SegmentWriter;
153276 
153277 /*
153278 ** An instance of the following data structure is used to build doclists
153279 ** incrementally. See function fts3PendingListAppend() for details.
153280 */
153281 struct PendingList {
153282  int nData;
153283  char *aData;
153284  int nSpace;
153285  sqlite3_int64 iLastDocid;
153286  sqlite3_int64 iLastCol;
153287  sqlite3_int64 iLastPos;
153288 };
153289 
153290 
153291 /*
153292 ** Each cursor has a (possibly empty) linked list of the following objects.
153293 */
153294 struct Fts3DeferredToken {
153295  Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
153296  int iCol; /* Column token must occur in */
153297  Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
153298  PendingList *pList; /* Doclist is assembled here */
153299 };
153300 
153301 /*
153302 ** An instance of this structure is used to iterate through the terms on
153303 ** a contiguous set of segment b-tree leaf nodes. Although the details of
153304 ** this structure are only manipulated by code in this file, opaque handles
153305 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
153306 ** terms when querying the full-text index. See functions:
153307 **
153308 ** sqlite3Fts3SegReaderNew()
153309 ** sqlite3Fts3SegReaderFree()
153310 ** sqlite3Fts3SegReaderIterate()
153311 **
153312 ** Methods used to manipulate Fts3SegReader structures:
153313 **
153314 ** fts3SegReaderNext()
153315 ** fts3SegReaderFirstDocid()
153316 ** fts3SegReaderNextDocid()
153317 */
153318 struct Fts3SegReader {
153319  int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
153320  u8 bLookup; /* True for a lookup only */
153321  u8 rootOnly; /* True for a root-only reader */
153322 
153323  sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
153324  sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
153325  sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
153326  sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
153327 
153328  char *aNode; /* Pointer to node data (or NULL) */
153329  int nNode; /* Size of buffer at aNode (or 0) */
153330  int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
153331  sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
153332 
153333  Fts3HashElem **ppNextElem;
153334 
153335  /* Variables set by fts3SegReaderNext(). These may be read directly
153336  ** by the caller. They are valid from the time SegmentReaderNew() returns
153337  ** until SegmentReaderNext() returns something other than SQLITE_OK
153338  ** (i.e. SQLITE_DONE).
153339  */
153340  int nTerm; /* Number of bytes in current term */
153341  char *zTerm; /* Pointer to current term */
153342  int nTermAlloc; /* Allocated size of zTerm buffer */
153343  char *aDoclist; /* Pointer to doclist of current entry */
153344  int nDoclist; /* Size of doclist in current entry */
153345 
153346  /* The following variables are used by fts3SegReaderNextDocid() to iterate
153347  ** through the current doclist (aDoclist/nDoclist).
153348  */
153349  char *pOffsetList;
153350  int nOffsetList; /* For descending pending seg-readers only */
153351  sqlite3_int64 iDocid;
153352 };
153353 
153354 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
153355 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
153356 
153357 /*
153358 ** An instance of this structure is used to create a segment b-tree in the
153359 ** database. The internal details of this type are only accessed by the
153360 ** following functions:
153361 **
153362 ** fts3SegWriterAdd()
153363 ** fts3SegWriterFlush()
153364 ** fts3SegWriterFree()
153365 */
153366 struct SegmentWriter {
153367  SegmentNode *pTree; /* Pointer to interior tree structure */
153368  sqlite3_int64 iFirst; /* First slot in %_segments written */
153369  sqlite3_int64 iFree; /* Next free slot in %_segments */
153370  char *zTerm; /* Pointer to previous term buffer */
153371  int nTerm; /* Number of bytes in zTerm */
153372  int nMalloc; /* Size of malloc'd buffer at zMalloc */
153373  char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
153374  int nSize; /* Size of allocation at aData */
153375  int nData; /* Bytes of data in aData */
153376  char *aData; /* Pointer to block from malloc() */
153377  i64 nLeafData; /* Number of bytes of leaf data written */
153378 };
153379 
153380 /*
153381 ** Type SegmentNode is used by the following three functions to create
153382 ** the interior part of the segment b+-tree structures (everything except
153383 ** the leaf nodes). These functions and type are only ever used by code
153384 ** within the fts3SegWriterXXX() family of functions described above.
153385 **
153386 ** fts3NodeAddTerm()
153387 ** fts3NodeWrite()
153388 ** fts3NodeFree()
153389 **
153390 ** When a b+tree is written to the database (either as a result of a merge
153391 ** or the pending-terms table being flushed), leaves are written into the
153392 ** database file as soon as they are completely populated. The interior of
153393 ** the tree is assembled in memory and written out only once all leaves have
153394 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
153395 ** very large, meaning that the interior of the tree consumes relatively
153396 ** little memory.
153397 */
153398 struct SegmentNode {
153399  SegmentNode *pParent; /* Parent node (or NULL for root node) */
153400  SegmentNode *pRight; /* Pointer to right-sibling */
153401  SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
153402  int nEntry; /* Number of terms written to node so far */
153403  char *zTerm; /* Pointer to previous term buffer */
153404  int nTerm; /* Number of bytes in zTerm */
153405  int nMalloc; /* Size of malloc'd buffer at zMalloc */
153406  char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
153407  int nData; /* Bytes of valid data so far */
153408  char *aData; /* Node data */
153409 };
153410 
153411 /*
153412 ** Valid values for the second argument to fts3SqlStmt().
153413 */
153414 #define SQL_DELETE_CONTENT 0
153415 #define SQL_IS_EMPTY 1
153416 #define SQL_DELETE_ALL_CONTENT 2
153417 #define SQL_DELETE_ALL_SEGMENTS 3
153418 #define SQL_DELETE_ALL_SEGDIR 4
153419 #define SQL_DELETE_ALL_DOCSIZE 5
153420 #define SQL_DELETE_ALL_STAT 6
153421 #define SQL_SELECT_CONTENT_BY_ROWID 7
153422 #define SQL_NEXT_SEGMENT_INDEX 8
153423 #define SQL_INSERT_SEGMENTS 9
153424 #define SQL_NEXT_SEGMENTS_ID 10
153425 #define SQL_INSERT_SEGDIR 11
153426 #define SQL_SELECT_LEVEL 12
153427 #define SQL_SELECT_LEVEL_RANGE 13
153428 #define SQL_SELECT_LEVEL_COUNT 14
153429 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
153430 #define SQL_DELETE_SEGDIR_LEVEL 16
153431 #define SQL_DELETE_SEGMENTS_RANGE 17
153432 #define SQL_CONTENT_INSERT 18
153433 #define SQL_DELETE_DOCSIZE 19
153434 #define SQL_REPLACE_DOCSIZE 20
153435 #define SQL_SELECT_DOCSIZE 21
153436 #define SQL_SELECT_STAT 22
153437 #define SQL_REPLACE_STAT 23
153438 
153439 #define SQL_SELECT_ALL_PREFIX_LEVEL 24
153440 #define SQL_DELETE_ALL_TERMS_SEGDIR 25
153441 #define SQL_DELETE_SEGDIR_RANGE 26
153442 #define SQL_SELECT_ALL_LANGID 27
153443 #define SQL_FIND_MERGE_LEVEL 28
153444 #define SQL_MAX_LEAF_NODE_ESTIMATE 29
153445 #define SQL_DELETE_SEGDIR_ENTRY 30
153446 #define SQL_SHIFT_SEGDIR_ENTRY 31
153447 #define SQL_SELECT_SEGDIR 32
153448 #define SQL_CHOMP_SEGDIR 33
153449 #define SQL_SEGMENT_IS_APPENDABLE 34
153450 #define SQL_SELECT_INDEXES 35
153451 #define SQL_SELECT_MXLEVEL 36
153452 
153453 #define SQL_SELECT_LEVEL_RANGE2 37
153454 #define SQL_UPDATE_LEVEL_IDX 38
153455 #define SQL_UPDATE_LEVEL 39
153456 
153457 /*
153458 ** This function is used to obtain an SQLite prepared statement handle
153459 ** for the statement identified by the second argument. If successful,
153460 ** *pp is set to the requested statement handle and SQLITE_OK returned.
153461 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
153462 **
153463 ** If argument apVal is not NULL, then it must point to an array with
153464 ** at least as many entries as the requested statement has bound
153465 ** parameters. The values are bound to the statements parameters before
153466 ** returning.
153467 */
153468 static int fts3SqlStmt(
153469  Fts3Table *p, /* Virtual table handle */
153470  int eStmt, /* One of the SQL_XXX constants above */
153471  sqlite3_stmt **pp, /* OUT: Statement handle */
153472  sqlite3_value **apVal /* Values to bind to statement */
153473 ){
153474  const char *azSql[] = {
153475 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
153476 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
153477 /* 2 */ "DELETE FROM %Q.'%q_content'",
153478 /* 3 */ "DELETE FROM %Q.'%q_segments'",
153479 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
153480 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
153481 /* 6 */ "DELETE FROM %Q.'%q_stat'",
153482 /* 7 */ "SELECT %s WHERE rowid=?",
153483 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
153484 /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
153485 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
153486 /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
153487 
153488  /* Return segments in order from oldest to newest.*/
153489 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
153490  "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
153491 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
153492  "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
153493  "ORDER BY level DESC, idx ASC",
153494 
153495 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
153496 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
153497 
153498 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
153499 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
153500 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
153501 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
153502 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
153503 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
153504 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
153505 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
153506 /* 24 */ "",
153507 /* 25 */ "",
153508 
153509 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
153510 /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
153511 
153512 /* This statement is used to determine which level to read the input from
153513 ** when performing an incremental merge. It returns the absolute level number
153514 ** of the oldest level in the db that contains at least ? segments. Or,
153515 ** if no level in the FTS index contains more than ? segments, the statement
153516 ** returns zero rows. */
153517 /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
153518  " GROUP BY level HAVING cnt>=?"
153519  " ORDER BY (level %% 1024) ASC LIMIT 1",
153520 
153521 /* Estimate the upper limit on the number of leaf nodes in a new segment
153522 ** created by merging the oldest :2 segments from absolute level :1. See
153523 ** function sqlite3Fts3Incrmerge() for details. */
153524 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
153525  " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
153526 
153527 /* SQL_DELETE_SEGDIR_ENTRY
153528 ** Delete the %_segdir entry on absolute level :1 with index :2. */
153529 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
153530 
153531 /* SQL_SHIFT_SEGDIR_ENTRY
153532 ** Modify the idx value for the segment with idx=:3 on absolute level :2
153533 ** to :1. */
153534 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
153535 
153536 /* SQL_SELECT_SEGDIR
153537 ** Read a single entry from the %_segdir table. The entry from absolute
153538 ** level :1 with index value :2. */
153539 /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
153540  "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
153541 
153542 /* SQL_CHOMP_SEGDIR
153543 ** Update the start_block (:1) and root (:2) fields of the %_segdir
153544 ** entry located on absolute level :3 with index :4. */
153545 /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
153546  "WHERE level = ? AND idx = ?",
153547 
153548 /* SQL_SEGMENT_IS_APPENDABLE
153549 ** Return a single row if the segment with end_block=? is appendable. Or
153550 ** no rows otherwise. */
153551 /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
153552 
153553 /* SQL_SELECT_INDEXES
153554 ** Return the list of valid segment indexes for absolute level ? */
153555 /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
153556 
153557 /* SQL_SELECT_MXLEVEL
153558 ** Return the largest relative level in the FTS index or indexes. */
153559 /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
153560 
153561  /* Return segments in order from oldest to newest.*/
153562 /* 37 */ "SELECT level, idx, end_block "
153563  "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
153564  "ORDER BY level DESC, idx ASC",
153565 
153566  /* Update statements used while promoting segments */
153567 /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
153568  "WHERE level=? AND idx=?",
153569 /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
153570 
153571  };
153572  int rc = SQLITE_OK;
153573  sqlite3_stmt *pStmt;
153574 
153575  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
153576  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
153577 
153578  pStmt = p->aStmt[eStmt];
153579  if( !pStmt ){
153580  char *zSql;
153581  if( eStmt==SQL_CONTENT_INSERT ){
153582  zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
153583  }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
153584  zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
153585  }else{
153586  zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
153587  }
153588  if( !zSql ){
153589  rc = SQLITE_NOMEM;
153590  }else{
153591  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
153592  sqlite3_free(zSql);
153593  assert( rc==SQLITE_OK || pStmt==0 );
153594  p->aStmt[eStmt] = pStmt;
153595  }
153596  }
153597  if( apVal ){
153598  int i;
153599  int nParam = sqlite3_bind_parameter_count(pStmt);
153600  for(i=0; rc==SQLITE_OK && i<nParam; i++){
153601  rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
153602  }
153603  }
153604  *pp = pStmt;
153605  return rc;
153606 }
153607 
153608 
153609 static int fts3SelectDocsize(
153610  Fts3Table *pTab, /* FTS3 table handle */
153611  sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
153612  sqlite3_stmt **ppStmt /* OUT: Statement handle */
153613 ){
153614  sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
153615  int rc; /* Return code */
153616 
153617  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
153618  if( rc==SQLITE_OK ){
153619  sqlite3_bind_int64(pStmt, 1, iDocid);
153620  rc = sqlite3_step(pStmt);
153621  if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
153622  rc = sqlite3_reset(pStmt);
153623  if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
153624  pStmt = 0;
153625  }else{
153626  rc = SQLITE_OK;
153627  }
153628  }
153629 
153630  *ppStmt = pStmt;
153631  return rc;
153632 }
153633 
153634 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
153635  Fts3Table *pTab, /* Fts3 table handle */
153636  sqlite3_stmt **ppStmt /* OUT: Statement handle */
153637 ){
153638  sqlite3_stmt *pStmt = 0;
153639  int rc;
153640  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
153641  if( rc==SQLITE_OK ){
153642  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
153643  if( sqlite3_step(pStmt)!=SQLITE_ROW
153644  || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
153645  ){
153646  rc = sqlite3_reset(pStmt);
153647  if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
153648  pStmt = 0;
153649  }
153650  }
153651  *ppStmt = pStmt;
153652  return rc;
153653 }
153654 
153655 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
153656  Fts3Table *pTab, /* Fts3 table handle */
153657  sqlite3_int64 iDocid, /* Docid to read size data for */
153658  sqlite3_stmt **ppStmt /* OUT: Statement handle */
153659 ){
153660  return fts3SelectDocsize(pTab, iDocid, ppStmt);
153661 }
153662 
153663 /*
153664 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
153665 ** array apVal[] to the SQL statement identified by eStmt, the statement
153666 ** is executed.
153667 **
153668 ** Returns SQLITE_OK if the statement is successfully executed, or an
153669 ** SQLite error code otherwise.
153670 */
153671 static void fts3SqlExec(
153672  int *pRC, /* Result code */
153673  Fts3Table *p, /* The FTS3 table */
153674  int eStmt, /* Index of statement to evaluate */
153675  sqlite3_value **apVal /* Parameters to bind */
153676 ){
153677  sqlite3_stmt *pStmt;
153678  int rc;
153679  if( *pRC ) return;
153680  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
153681  if( rc==SQLITE_OK ){
153682  sqlite3_step(pStmt);
153683  rc = sqlite3_reset(pStmt);
153684  }
153685  *pRC = rc;
153686 }
153687 
153688 
153689 /*
153690 ** This function ensures that the caller has obtained an exclusive
153691 ** shared-cache table-lock on the %_segdir table. This is required before
153692 ** writing data to the fts3 table. If this lock is not acquired first, then
153693 ** the caller may end up attempting to take this lock as part of committing
153694 ** a transaction, causing SQLite to return SQLITE_LOCKED or
153695 ** LOCKED_SHAREDCACHEto a COMMIT command.
153696 **
153697 ** It is best to avoid this because if FTS3 returns any error when
153698 ** committing a transaction, the whole transaction will be rolled back.
153699 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
153700 ** It can still happen if the user locks the underlying tables directly
153701 ** instead of accessing them via FTS.
153702 */
153703 static int fts3Writelock(Fts3Table *p){
153704  int rc = SQLITE_OK;
153705 
153706  if( p->nPendingData==0 ){
153707  sqlite3_stmt *pStmt;
153708  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
153709  if( rc==SQLITE_OK ){
153710  sqlite3_bind_null(pStmt, 1);
153711  sqlite3_step(pStmt);
153712  rc = sqlite3_reset(pStmt);
153713  }
153714  }
153715 
153716  return rc;
153717 }
153718 
153719 /*
153720 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
153721 ** Within each language id, a separate index is maintained to store the
153722 ** document terms, and each configured prefix size (configured the FTS
153723 ** "prefix=" option). And each index consists of multiple levels ("relative
153724 ** levels").
153725 **
153726 ** All three of these values (the language id, the specific index and the
153727 ** level within the index) are encoded in 64-bit integer values stored
153728 ** in the %_segdir table on disk. This function is used to convert three
153729 ** separate component values into the single 64-bit integer value that
153730 ** can be used to query the %_segdir table.
153731 **
153732 ** Specifically, each language-id/index combination is allocated 1024
153733 ** 64-bit integer level values ("absolute levels"). The main terms index
153734 ** for language-id 0 is allocate values 0-1023. The first prefix index
153735 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
153736 ** Language 1 indexes are allocated immediately following language 0.
153737 **
153738 ** So, for a system with nPrefix prefix indexes configured, the block of
153739 ** absolute levels that corresponds to language-id iLangid and index
153740 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
153741 */
153742 static sqlite3_int64 getAbsoluteLevel(
153743  Fts3Table *p, /* FTS3 table handle */
153744  int iLangid, /* Language id */
153745  int iIndex, /* Index in p->aIndex[] */
153746  int iLevel /* Level of segments */
153747 ){
153748  sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
153749  assert( iLangid>=0 );
153750  assert( p->nIndex>0 );
153751  assert( iIndex>=0 && iIndex<p->nIndex );
153752 
153753  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
153754  return iBase + iLevel;
153755 }
153756 
153757 /*
153758 ** Set *ppStmt to a statement handle that may be used to iterate through
153759 ** all rows in the %_segdir table, from oldest to newest. If successful,
153760 ** return SQLITE_OK. If an error occurs while preparing the statement,
153761 ** return an SQLite error code.
153762 **
153763 ** There is only ever one instance of this SQL statement compiled for
153764 ** each FTS3 table.
153765 **
153766 ** The statement returns the following columns from the %_segdir table:
153767 **
153768 ** 0: idx
153769 ** 1: start_block
153770 ** 2: leaves_end_block
153771 ** 3: end_block
153772 ** 4: root
153773 */
153774 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
153775  Fts3Table *p, /* FTS3 table */
153776  int iLangid, /* Language being queried */
153777  int iIndex, /* Index for p->aIndex[] */
153778  int iLevel, /* Level to select (relative level) */
153779  sqlite3_stmt **ppStmt /* OUT: Compiled statement */
153780 ){
153781  int rc;
153782  sqlite3_stmt *pStmt = 0;
153783 
153784  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
153785  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
153786  assert( iIndex>=0 && iIndex<p->nIndex );
153787 
153788  if( iLevel<0 ){
153789  /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
153790  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
153791  if( rc==SQLITE_OK ){
153792  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
153793  sqlite3_bind_int64(pStmt, 2,
153794  getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
153795  );
153796  }
153797  }else{
153798  /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
153799  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
153800  if( rc==SQLITE_OK ){
153801  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
153802  }
153803  }
153804  *ppStmt = pStmt;
153805  return rc;
153806 }
153807 
153808 
153809 /*
153810 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
153811 ** if successful, or an SQLite error code otherwise.
153812 **
153813 ** This function also serves to allocate the PendingList structure itself.
153814 ** For example, to create a new PendingList structure containing two
153815 ** varints:
153816 **
153817 ** PendingList *p = 0;
153818 ** fts3PendingListAppendVarint(&p, 1);
153819 ** fts3PendingListAppendVarint(&p, 2);
153820 */
153821 static int fts3PendingListAppendVarint(
153822  PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
153823  sqlite3_int64 i /* Value to append to data */
153824 ){
153825  PendingList *p = *pp;
153826 
153827  /* Allocate or grow the PendingList as required. */
153828  if( !p ){
153829  p = sqlite3_malloc(sizeof(*p) + 100);
153830  if( !p ){
153831  return SQLITE_NOMEM;
153832  }
153833  p->nSpace = 100;
153834  p->aData = (char *)&p[1];
153835  p->nData = 0;
153836  }
153837  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
153838  int nNew = p->nSpace * 2;
153839  p = sqlite3_realloc(p, sizeof(*p) + nNew);
153840  if( !p ){
153841  sqlite3_free(*pp);
153842  *pp = 0;
153843  return SQLITE_NOMEM;
153844  }
153845  p->nSpace = nNew;
153846  p->aData = (char *)&p[1];
153847  }
153848 
153849  /* Append the new serialized varint to the end of the list. */
153850  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
153851  p->aData[p->nData] = '\0';
153852  *pp = p;
153853  return SQLITE_OK;
153854 }
153855 
153856 /*
153857 ** Add a docid/column/position entry to a PendingList structure. Non-zero
153858 ** is returned if the structure is sqlite3_realloced as part of adding
153859 ** the entry. Otherwise, zero.
153860 **
153861 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
153862 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
153863 ** it is set to SQLITE_OK.
153864 */
153865 static int fts3PendingListAppend(
153866  PendingList **pp, /* IN/OUT: PendingList structure */
153867  sqlite3_int64 iDocid, /* Docid for entry to add */
153868  sqlite3_int64 iCol, /* Column for entry to add */
153869  sqlite3_int64 iPos, /* Position of term for entry to add */
153870  int *pRc /* OUT: Return code */
153871 ){
153872  PendingList *p = *pp;
153873  int rc = SQLITE_OK;
153874 
153875  assert( !p || p->iLastDocid<=iDocid );
153876 
153877  if( !p || p->iLastDocid!=iDocid ){
153878  sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
153879  if( p ){
153880  assert( p->nData<p->nSpace );
153881  assert( p->aData[p->nData]==0 );
153882  p->nData++;
153883  }
153884  if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
153885  goto pendinglistappend_out;
153886  }
153887  p->iLastCol = -1;
153888  p->iLastPos = 0;
153889  p->iLastDocid = iDocid;
153890  }
153891  if( iCol>0 && p->iLastCol!=iCol ){
153892  if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
153893  || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
153894  ){
153895  goto pendinglistappend_out;
153896  }
153897  p->iLastCol = iCol;
153898  p->iLastPos = 0;
153899  }
153900  if( iCol>=0 ){
153901  assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
153902  rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
153903  if( rc==SQLITE_OK ){
153904  p->iLastPos = iPos;
153905  }
153906  }
153907 
153908  pendinglistappend_out:
153909  *pRc = rc;
153910  if( p!=*pp ){
153911  *pp = p;
153912  return 1;
153913  }
153914  return 0;
153915 }
153916 
153917 /*
153918 ** Free a PendingList object allocated by fts3PendingListAppend().
153919 */
153920 static void fts3PendingListDelete(PendingList *pList){
153921  sqlite3_free(pList);
153922 }
153923 
153924 /*
153925 ** Add an entry to one of the pending-terms hash tables.
153926 */
153927 static int fts3PendingTermsAddOne(
153928  Fts3Table *p,
153929  int iCol,
153930  int iPos,
153931  Fts3Hash *pHash, /* Pending terms hash table to add entry to */
153932  const char *zToken,
153933  int nToken
153934 ){
153935  PendingList *pList;
153936  int rc = SQLITE_OK;
153937 
153938  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
153939  if( pList ){
153940  p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
153941  }
153942  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
153943  if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
153944  /* Malloc failed while inserting the new entry. This can only
153945  ** happen if there was no previous entry for this token.
153946  */
153947  assert( 0==fts3HashFind(pHash, zToken, nToken) );
153948  sqlite3_free(pList);
153949  rc = SQLITE_NOMEM;
153950  }
153951  }
153952  if( rc==SQLITE_OK ){
153953  p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
153954  }
153955  return rc;
153956 }
153957 
153958 /*
153959 ** Tokenize the nul-terminated string zText and add all tokens to the
153960 ** pending-terms hash-table. The docid used is that currently stored in
153961 ** p->iPrevDocid, and the column is specified by argument iCol.
153962 **
153963 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
153964 */
153965 static int fts3PendingTermsAdd(
153966  Fts3Table *p, /* Table into which text will be inserted */
153967  int iLangid, /* Language id to use */
153968  const char *zText, /* Text of document to be inserted */
153969  int iCol, /* Column into which text is being inserted */
153970  u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
153971 ){
153972  int rc;
153973  int iStart = 0;
153974  int iEnd = 0;
153975  int iPos = 0;
153976  int nWord = 0;
153977 
153978  char const *zToken;
153979  int nToken = 0;
153980 
153981  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
153982  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
153983  sqlite3_tokenizer_cursor *pCsr;
153984  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
153985  const char**,int*,int*,int*,int*);
153986 
153987  assert( pTokenizer && pModule );
153988 
153989  /* If the user has inserted a NULL value, this function may be called with
153990  ** zText==0. In this case, add zero token entries to the hash table and
153991  ** return early. */
153992  if( zText==0 ){
153993  *pnWord = 0;
153994  return SQLITE_OK;
153995  }
153996 
153997  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
153998  if( rc!=SQLITE_OK ){
153999  return rc;
154000  }
154001 
154002  xNext = pModule->xNext;
154003  while( SQLITE_OK==rc
154004  && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
154005  ){
154006  int i;
154007  if( iPos>=nWord ) nWord = iPos+1;
154008 
154009  /* Positions cannot be negative; we use -1 as a terminator internally.
154010  ** Tokens must have a non-zero length.
154011  */
154012  if( iPos<0 || !zToken || nToken<=0 ){
154013  rc = SQLITE_ERROR;
154014  break;
154015  }
154016 
154017  /* Add the term to the terms index */
154018  rc = fts3PendingTermsAddOne(
154019  p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
154020  );
154021 
154022  /* Add the term to each of the prefix indexes that it is not too
154023  ** short for. */
154024  for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
154025  struct Fts3Index *pIndex = &p->aIndex[i];
154026  if( nToken<pIndex->nPrefix ) continue;
154027  rc = fts3PendingTermsAddOne(
154028  p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
154029  );
154030  }
154031  }
154032 
154033  pModule->xClose(pCsr);
154034  *pnWord += nWord;
154035  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
154036 }
154037 
154038 /*
154039 ** Calling this function indicates that subsequent calls to
154040 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
154041 ** contents of the document with docid iDocid.
154042 */
154043 static int fts3PendingTermsDocid(
154044  Fts3Table *p, /* Full-text table handle */
154045  int bDelete, /* True if this op is a delete */
154046  int iLangid, /* Language id of row being written */
154047  sqlite_int64 iDocid /* Docid of row being written */
154048 ){
154049  assert( iLangid>=0 );
154050  assert( bDelete==1 || bDelete==0 );
154051 
154052  /* TODO(shess) Explore whether partially flushing the buffer on
154053  ** forced-flush would provide better performance. I suspect that if
154054  ** we ordered the doclists by size and flushed the largest until the
154055  ** buffer was half empty, that would let the less frequent terms
154056  ** generate longer doclists.
154057  */
154058  if( iDocid<p->iPrevDocid
154059  || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
154060  || p->iPrevLangid!=iLangid
154061  || p->nPendingData>p->nMaxPendingData
154062  ){
154063  int rc = sqlite3Fts3PendingTermsFlush(p);
154064  if( rc!=SQLITE_OK ) return rc;
154065  }
154066  p->iPrevDocid = iDocid;
154067  p->iPrevLangid = iLangid;
154068  p->bPrevDelete = bDelete;
154069  return SQLITE_OK;
154070 }
154071 
154072 /*
154073 ** Discard the contents of the pending-terms hash tables.
154074 */
154075 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
154076  int i;
154077  for(i=0; i<p->nIndex; i++){
154078  Fts3HashElem *pElem;
154079  Fts3Hash *pHash = &p->aIndex[i].hPending;
154080  for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
154081  PendingList *pList = (PendingList *)fts3HashData(pElem);
154082  fts3PendingListDelete(pList);
154083  }
154084  fts3HashClear(pHash);
154085  }
154086  p->nPendingData = 0;
154087 }
154088 
154089 /*
154090 ** This function is called by the xUpdate() method as part of an INSERT
154091 ** operation. It adds entries for each term in the new record to the
154092 ** pendingTerms hash table.
154093 **
154094 ** Argument apVal is the same as the similarly named argument passed to
154095 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
154096 */
154097 static int fts3InsertTerms(
154098  Fts3Table *p,
154099  int iLangid,
154100  sqlite3_value **apVal,
154101  u32 *aSz
154102 ){
154103  int i; /* Iterator variable */
154104  for(i=2; i<p->nColumn+2; i++){
154105  int iCol = i-2;
154106  if( p->abNotindexed[iCol]==0 ){
154107  const char *zText = (const char *)sqlite3_value_text(apVal[i]);
154108  int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
154109  if( rc!=SQLITE_OK ){
154110  return rc;
154111  }
154112  aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
154113  }
154114  }
154115  return SQLITE_OK;
154116 }
154117 
154118 /*
154119 ** This function is called by the xUpdate() method for an INSERT operation.
154120 ** The apVal parameter is passed a copy of the apVal argument passed by
154121 ** SQLite to the xUpdate() method. i.e:
154122 **
154123 ** apVal[0] Not used for INSERT.
154124 ** apVal[1] rowid
154125 ** apVal[2] Left-most user-defined column
154126 ** ...
154127 ** apVal[p->nColumn+1] Right-most user-defined column
154128 ** apVal[p->nColumn+2] Hidden column with same name as table
154129 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
154130 ** apVal[p->nColumn+4] Hidden languageid column
154131 */
154132 static int fts3InsertData(
154133  Fts3Table *p, /* Full-text table */
154134  sqlite3_value **apVal, /* Array of values to insert */
154135  sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
154136 ){
154137  int rc; /* Return code */
154138  sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
154139 
154140  if( p->zContentTbl ){
154141  sqlite3_value *pRowid = apVal[p->nColumn+3];
154142  if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
154143  pRowid = apVal[1];
154144  }
154145  if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
154146  return SQLITE_CONSTRAINT;
154147  }
154148  *piDocid = sqlite3_value_int64(pRowid);
154149  return SQLITE_OK;
154150  }
154151 
154152  /* Locate the statement handle used to insert data into the %_content
154153  ** table. The SQL for this statement is:
154154  **
154155  ** INSERT INTO %_content VALUES(?, ?, ?, ...)
154156  **
154157  ** The statement features N '?' variables, where N is the number of user
154158  ** defined columns in the FTS3 table, plus one for the docid field.
154159  */
154160  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
154161  if( rc==SQLITE_OK && p->zLanguageid ){
154162  rc = sqlite3_bind_int(
154163  pContentInsert, p->nColumn+2,
154164  sqlite3_value_int(apVal[p->nColumn+4])
154165  );
154166  }
154167  if( rc!=SQLITE_OK ) return rc;
154168 
154169  /* There is a quirk here. The users INSERT statement may have specified
154170  ** a value for the "rowid" field, for the "docid" field, or for both.
154171  ** Which is a problem, since "rowid" and "docid" are aliases for the
154172  ** same value. For example:
154173  **
154174  ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
154175  **
154176  ** In FTS3, this is an error. It is an error to specify non-NULL values
154177  ** for both docid and some other rowid alias.
154178  */
154179  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
154180  if( SQLITE_NULL==sqlite3_value_type(apVal[0])
154181  && SQLITE_NULL!=sqlite3_value_type(apVal[1])
154182  ){
154183  /* A rowid/docid conflict. */
154184  return SQLITE_ERROR;
154185  }
154186  rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
154187  if( rc!=SQLITE_OK ) return rc;
154188  }
154189 
154190  /* Execute the statement to insert the record. Set *piDocid to the
154191  ** new docid value.
154192  */
154193  sqlite3_step(pContentInsert);
154194  rc = sqlite3_reset(pContentInsert);
154195 
154196  *piDocid = sqlite3_last_insert_rowid(p->db);
154197  return rc;
154198 }
154199 
154200 
154201 
154202 /*
154203 ** Remove all data from the FTS3 table. Clear the hash table containing
154204 ** pending terms.
154205 */
154206 static int fts3DeleteAll(Fts3Table *p, int bContent){
154207  int rc = SQLITE_OK; /* Return code */
154208 
154209  /* Discard the contents of the pending-terms hash table. */
154210  sqlite3Fts3PendingTermsClear(p);
154211 
154212  /* Delete everything from the shadow tables. Except, leave %_content as
154213  ** is if bContent is false. */
154214  assert( p->zContentTbl==0 || bContent==0 );
154215  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
154216  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
154217  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
154218  if( p->bHasDocsize ){
154219  fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
154220  }
154221  if( p->bHasStat ){
154222  fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
154223  }
154224  return rc;
154225 }
154226 
154227 /*
154228 **
154229 */
154230 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
154231  int iLangid = 0;
154232  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
154233  return iLangid;
154234 }
154235 
154236 /*
154237 ** The first element in the apVal[] array is assumed to contain the docid
154238 ** (an integer) of a row about to be deleted. Remove all terms from the
154239 ** full-text index.
154240 */
154241 static void fts3DeleteTerms(
154242  int *pRC, /* Result code */
154243  Fts3Table *p, /* The FTS table to delete from */
154244  sqlite3_value *pRowid, /* The docid to be deleted */
154245  u32 *aSz, /* Sizes of deleted document written here */
154246  int *pbFound /* OUT: Set to true if row really does exist */
154247 ){
154248  int rc;
154249  sqlite3_stmt *pSelect;
154250 
154251  assert( *pbFound==0 );
154252  if( *pRC ) return;
154253  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
154254  if( rc==SQLITE_OK ){
154255  if( SQLITE_ROW==sqlite3_step(pSelect) ){
154256  int i;
154257  int iLangid = langidFromSelect(p, pSelect);
154258  i64 iDocid = sqlite3_column_int64(pSelect, 0);
154259  rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
154260  for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
154261  int iCol = i-1;
154262  if( p->abNotindexed[iCol]==0 ){
154263  const char *zText = (const char *)sqlite3_column_text(pSelect, i);
154264  rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
154265  aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
154266  }
154267  }
154268  if( rc!=SQLITE_OK ){
154269  sqlite3_reset(pSelect);
154270  *pRC = rc;
154271  return;
154272  }
154273  *pbFound = 1;
154274  }
154275  rc = sqlite3_reset(pSelect);
154276  }else{
154277  sqlite3_reset(pSelect);
154278  }
154279  *pRC = rc;
154280 }
154281 
154282 /*
154283 ** Forward declaration to account for the circular dependency between
154284 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
154285 */
154286 static int fts3SegmentMerge(Fts3Table *, int, int, int);
154287 
154288 /*
154289 ** This function allocates a new level iLevel index in the segdir table.
154290 ** Usually, indexes are allocated within a level sequentially starting
154291 ** with 0, so the allocated index is one greater than the value returned
154292 ** by:
154293 **
154294 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
154295 **
154296 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
154297 ** level, they are merged into a single level (iLevel+1) segment and the
154298 ** allocated index is 0.
154299 **
154300 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
154301 ** returned. Otherwise, an SQLite error code is returned.
154302 */
154303 static int fts3AllocateSegdirIdx(
154304  Fts3Table *p,
154305  int iLangid, /* Language id */
154306  int iIndex, /* Index for p->aIndex */
154307  int iLevel,
154308  int *piIdx
154309 ){
154310  int rc; /* Return Code */
154311  sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
154312  int iNext = 0; /* Result of query pNextIdx */
154313 
154314  assert( iLangid>=0 );
154315  assert( p->nIndex>=1 );
154316 
154317  /* Set variable iNext to the next available segdir index at level iLevel. */
154318  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
154319  if( rc==SQLITE_OK ){
154320  sqlite3_bind_int64(
154321  pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
154322  );
154323  if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
154324  iNext = sqlite3_column_int(pNextIdx, 0);
154325  }
154326  rc = sqlite3_reset(pNextIdx);
154327  }
154328 
154329  if( rc==SQLITE_OK ){
154330  /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
154331  ** full, merge all segments in level iLevel into a single iLevel+1
154332  ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
154333  ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
154334  */
154335  if( iNext>=FTS3_MERGE_COUNT ){
154336  fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
154337  rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
154338  *piIdx = 0;
154339  }else{
154340  *piIdx = iNext;
154341  }
154342  }
154343 
154344  return rc;
154345 }
154346 
154347 /*
154348 ** The %_segments table is declared as follows:
154349 **
154350 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
154351 **
154352 ** This function reads data from a single row of the %_segments table. The
154353 ** specific row is identified by the iBlockid parameter. If paBlob is not
154354 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
154355 ** with the contents of the blob stored in the "block" column of the
154356 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
154357 ** to the size of the blob in bytes before returning.
154358 **
154359 ** If an error occurs, or the table does not contain the specified row,
154360 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
154361 ** paBlob is non-NULL, then it is the responsibility of the caller to
154362 ** eventually free the returned buffer.
154363 **
154364 ** This function may leave an open sqlite3_blob* handle in the
154365 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
154366 ** to this function. The handle may be closed by calling the
154367 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
154368 ** performance improvement, but the blob handle should always be closed
154369 ** before control is returned to the user (to prevent a lock being held
154370 ** on the database file for longer than necessary). Thus, any virtual table
154371 ** method (xFilter etc.) that may directly or indirectly call this function
154372 ** must call sqlite3Fts3SegmentsClose() before returning.
154373 */
154374 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
154375  Fts3Table *p, /* FTS3 table handle */
154376  sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
154377  char **paBlob, /* OUT: Blob data in malloc'd buffer */
154378  int *pnBlob, /* OUT: Size of blob data */
154379  int *pnLoad /* OUT: Bytes actually loaded */
154380 ){
154381  int rc; /* Return code */
154382 
154383  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
154384  assert( pnBlob );
154385 
154386  if( p->pSegments ){
154387  rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
154388  }else{
154389  if( 0==p->zSegmentsTbl ){
154390  p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
154391  if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
154392  }
154393  rc = sqlite3_blob_open(
154394  p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
154395  );
154396  }
154397 
154398  if( rc==SQLITE_OK ){
154399  int nByte = sqlite3_blob_bytes(p->pSegments);
154400  *pnBlob = nByte;
154401  if( paBlob ){
154402  char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
154403  if( !aByte ){
154404  rc = SQLITE_NOMEM;
154405  }else{
154406  if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
154407  nByte = FTS3_NODE_CHUNKSIZE;
154408  *pnLoad = nByte;
154409  }
154410  rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
154411  memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
154412  if( rc!=SQLITE_OK ){
154413  sqlite3_free(aByte);
154414  aByte = 0;
154415  }
154416  }
154417  *paBlob = aByte;
154418  }
154419  }
154420 
154421  return rc;
154422 }
154423 
154424 /*
154425 ** Close the blob handle at p->pSegments, if it is open. See comments above
154426 ** the sqlite3Fts3ReadBlock() function for details.
154427 */
154428 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
154429  sqlite3_blob_close(p->pSegments);
154430  p->pSegments = 0;
154431 }
154432 
154433 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
154434  int nRead; /* Number of bytes to read */
154435  int rc; /* Return code */
154436 
154437  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
154438  rc = sqlite3_blob_read(
154439  pReader->pBlob,
154440  &pReader->aNode[pReader->nPopulate],
154441  nRead,
154442  pReader->nPopulate
154443  );
154444 
154445  if( rc==SQLITE_OK ){
154446  pReader->nPopulate += nRead;
154447  memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
154448  if( pReader->nPopulate==pReader->nNode ){
154449  sqlite3_blob_close(pReader->pBlob);
154450  pReader->pBlob = 0;
154451  pReader->nPopulate = 0;
154452  }
154453  }
154454  return rc;
154455 }
154456 
154457 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
154458  int rc = SQLITE_OK;
154459  assert( !pReader->pBlob
154460  || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
154461  );
154462  while( pReader->pBlob && rc==SQLITE_OK
154463  && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
154464  ){
154465  rc = fts3SegReaderIncrRead(pReader);
154466  }
154467  return rc;
154468 }
154469 
154470 /*
154471 ** Set an Fts3SegReader cursor to point at EOF.
154472 */
154473 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
154474  if( !fts3SegReaderIsRootOnly(pSeg) ){
154475  sqlite3_free(pSeg->aNode);
154476  sqlite3_blob_close(pSeg->pBlob);
154477  pSeg->pBlob = 0;
154478  }
154479  pSeg->aNode = 0;
154480 }
154481 
154482 /*
154483 ** Move the iterator passed as the first argument to the next term in the
154484 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
154485 ** SQLITE_DONE. Otherwise, an SQLite error code.
154486 */
154487 static int fts3SegReaderNext(
154488  Fts3Table *p,
154489  Fts3SegReader *pReader,
154490  int bIncr
154491 ){
154492  int rc; /* Return code of various sub-routines */
154493  char *pNext; /* Cursor variable */
154494  int nPrefix; /* Number of bytes in term prefix */
154495  int nSuffix; /* Number of bytes in term suffix */
154496 
154497  if( !pReader->aDoclist ){
154498  pNext = pReader->aNode;
154499  }else{
154500  pNext = &pReader->aDoclist[pReader->nDoclist];
154501  }
154502 
154503  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
154504 
154505  if( fts3SegReaderIsPending(pReader) ){
154506  Fts3HashElem *pElem = *(pReader->ppNextElem);
154507  sqlite3_free(pReader->aNode);
154508  pReader->aNode = 0;
154509  if( pElem ){
154510  char *aCopy;
154511  PendingList *pList = (PendingList *)fts3HashData(pElem);
154512  int nCopy = pList->nData+1;
154513  pReader->zTerm = (char *)fts3HashKey(pElem);
154514  pReader->nTerm = fts3HashKeysize(pElem);
154515  aCopy = (char*)sqlite3_malloc(nCopy);
154516  if( !aCopy ) return SQLITE_NOMEM;
154517  memcpy(aCopy, pList->aData, nCopy);
154518  pReader->nNode = pReader->nDoclist = nCopy;
154519  pReader->aNode = pReader->aDoclist = aCopy;
154520  pReader->ppNextElem++;
154521  assert( pReader->aNode );
154522  }
154523  return SQLITE_OK;
154524  }
154525 
154526  fts3SegReaderSetEof(pReader);
154527 
154528  /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
154529  ** blocks have already been traversed. */
154530  assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
154531  if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
154532  return SQLITE_OK;
154533  }
154534 
154535  rc = sqlite3Fts3ReadBlock(
154536  p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
154537  (bIncr ? &pReader->nPopulate : 0)
154538  );
154539  if( rc!=SQLITE_OK ) return rc;
154540  assert( pReader->pBlob==0 );
154541  if( bIncr && pReader->nPopulate<pReader->nNode ){
154542  pReader->pBlob = p->pSegments;
154543  p->pSegments = 0;
154544  }
154545  pNext = pReader->aNode;
154546  }
154547 
154548  assert( !fts3SegReaderIsPending(pReader) );
154549 
154550  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
154551  if( rc!=SQLITE_OK ) return rc;
154552 
154553  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
154554  ** safe (no risk of overread) even if the node data is corrupted. */
154555  pNext += fts3GetVarint32(pNext, &nPrefix);
154556  pNext += fts3GetVarint32(pNext, &nSuffix);
154557  if( nPrefix<0 || nSuffix<=0
154558  || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
154559  ){
154560  return FTS_CORRUPT_VTAB;
154561  }
154562 
154563  if( nPrefix+nSuffix>pReader->nTermAlloc ){
154564  int nNew = (nPrefix+nSuffix)*2;
154565  char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
154566  if( !zNew ){
154567  return SQLITE_NOMEM;
154568  }
154569  pReader->zTerm = zNew;
154570  pReader->nTermAlloc = nNew;
154571  }
154572 
154573  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
154574  if( rc!=SQLITE_OK ) return rc;
154575 
154576  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
154577  pReader->nTerm = nPrefix+nSuffix;
154578  pNext += nSuffix;
154579  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
154580  pReader->aDoclist = pNext;
154581  pReader->pOffsetList = 0;
154582 
154583  /* Check that the doclist does not appear to extend past the end of the
154584  ** b-tree node. And that the final byte of the doclist is 0x00. If either
154585  ** of these statements is untrue, then the data structure is corrupt.
154586  */
154587  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
154588  || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
154589  ){
154590  return FTS_CORRUPT_VTAB;
154591  }
154592  return SQLITE_OK;
154593 }
154594 
154595 /*
154596 ** Set the SegReader to point to the first docid in the doclist associated
154597 ** with the current term.
154598 */
154599 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
154600  int rc = SQLITE_OK;
154601  assert( pReader->aDoclist );
154602  assert( !pReader->pOffsetList );
154603  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
154604  u8 bEof = 0;
154605  pReader->iDocid = 0;
154606  pReader->nOffsetList = 0;
154607  sqlite3Fts3DoclistPrev(0,
154608  pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
154609  &pReader->iDocid, &pReader->nOffsetList, &bEof
154610  );
154611  }else{
154612  rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
154613  if( rc==SQLITE_OK ){
154614  int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
154615  pReader->pOffsetList = &pReader->aDoclist[n];
154616  }
154617  }
154618  return rc;
154619 }
154620 
154621 /*
154622 ** Advance the SegReader to point to the next docid in the doclist
154623 ** associated with the current term.
154624 **
154625 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
154626 ** *ppOffsetList is set to point to the first column-offset list
154627 ** in the doclist entry (i.e. immediately past the docid varint).
154628 ** *pnOffsetList is set to the length of the set of column-offset
154629 ** lists, not including the nul-terminator byte. For example:
154630 */
154631 static int fts3SegReaderNextDocid(
154632  Fts3Table *pTab,
154633  Fts3SegReader *pReader, /* Reader to advance to next docid */
154634  char **ppOffsetList, /* OUT: Pointer to current position-list */
154635  int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
154636 ){
154637  int rc = SQLITE_OK;
154638  char *p = pReader->pOffsetList;
154639  char c = 0;
154640 
154641  assert( p );
154642 
154643  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
154644  /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
154645  ** Pending-terms doclists are always built up in ascending order, so
154646  ** we have to iterate through them backwards here. */
154647  u8 bEof = 0;
154648  if( ppOffsetList ){
154649  *ppOffsetList = pReader->pOffsetList;
154650  *pnOffsetList = pReader->nOffsetList - 1;
154651  }
154652  sqlite3Fts3DoclistPrev(0,
154653  pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
154654  &pReader->nOffsetList, &bEof
154655  );
154656  if( bEof ){
154657  pReader->pOffsetList = 0;
154658  }else{
154659  pReader->pOffsetList = p;
154660  }
154661  }else{
154662  char *pEnd = &pReader->aDoclist[pReader->nDoclist];
154663 
154664  /* Pointer p currently points at the first byte of an offset list. The
154665  ** following block advances it to point one byte past the end of
154666  ** the same offset list. */
154667  while( 1 ){
154668 
154669  /* The following line of code (and the "p++" below the while() loop) is
154670  ** normally all that is required to move pointer p to the desired
154671  ** position. The exception is if this node is being loaded from disk
154672  ** incrementally and pointer "p" now points to the first byte past
154673  ** the populated part of pReader->aNode[].
154674  */
154675  while( *p | c ) c = *p++ & 0x80;
154676  assert( *p==0 );
154677 
154678  if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
154679  rc = fts3SegReaderIncrRead(pReader);
154680  if( rc!=SQLITE_OK ) return rc;
154681  }
154682  p++;
154683 
154684  /* If required, populate the output variables with a pointer to and the
154685  ** size of the previous offset-list.
154686  */
154687  if( ppOffsetList ){
154688  *ppOffsetList = pReader->pOffsetList;
154689  *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
154690  }
154691 
154692  /* List may have been edited in place by fts3EvalNearTrim() */
154693  while( p<pEnd && *p==0 ) p++;
154694 
154695  /* If there are no more entries in the doclist, set pOffsetList to
154696  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
154697  ** Fts3SegReader.pOffsetList to point to the next offset list before
154698  ** returning.
154699  */
154700  if( p>=pEnd ){
154701  pReader->pOffsetList = 0;
154702  }else{
154703  rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
154704  if( rc==SQLITE_OK ){
154705  sqlite3_int64 iDelta;
154706  pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
154707  if( pTab->bDescIdx ){
154708  pReader->iDocid -= iDelta;
154709  }else{
154710  pReader->iDocid += iDelta;
154711  }
154712  }
154713  }
154714  }
154715 
154716  return SQLITE_OK;
154717 }
154718 
154719 
154720 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
154721  Fts3Cursor *pCsr,
154722  Fts3MultiSegReader *pMsr,
154723  int *pnOvfl
154724 ){
154725  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
154726  int nOvfl = 0;
154727  int ii;
154728  int rc = SQLITE_OK;
154729  int pgsz = p->nPgsz;
154730 
154731  assert( p->bFts4 );
154732  assert( pgsz>0 );
154733 
154734  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
154735  Fts3SegReader *pReader = pMsr->apSegment[ii];
154736  if( !fts3SegReaderIsPending(pReader)
154737  && !fts3SegReaderIsRootOnly(pReader)
154738  ){
154739  sqlite3_int64 jj;
154740  for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
154741  int nBlob;
154742  rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
154743  if( rc!=SQLITE_OK ) break;
154744  if( (nBlob+35)>pgsz ){
154745  nOvfl += (nBlob + 34)/pgsz;
154746  }
154747  }
154748  }
154749  }
154750  *pnOvfl = nOvfl;
154751  return rc;
154752 }
154753 
154754 /*
154755 ** Free all allocations associated with the iterator passed as the
154756 ** second argument.
154757 */
154758 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
154759  if( pReader ){
154760  if( !fts3SegReaderIsPending(pReader) ){
154761  sqlite3_free(pReader->zTerm);
154762  }
154763  if( !fts3SegReaderIsRootOnly(pReader) ){
154764  sqlite3_free(pReader->aNode);
154765  }
154766  sqlite3_blob_close(pReader->pBlob);
154767  }
154768  sqlite3_free(pReader);
154769 }
154770 
154771 /*
154772 ** Allocate a new SegReader object.
154773 */
154774 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
154775  int iAge, /* Segment "age". */
154776  int bLookup, /* True for a lookup only */
154777  sqlite3_int64 iStartLeaf, /* First leaf to traverse */
154778  sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
154779  sqlite3_int64 iEndBlock, /* Final block of segment */
154780  const char *zRoot, /* Buffer containing root node */
154781  int nRoot, /* Size of buffer containing root node */
154782  Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
154783 ){
154784  Fts3SegReader *pReader; /* Newly allocated SegReader object */
154785  int nExtra = 0; /* Bytes to allocate segment root node */
154786 
154787  assert( iStartLeaf<=iEndLeaf );
154788  if( iStartLeaf==0 ){
154789  nExtra = nRoot + FTS3_NODE_PADDING;
154790  }
154791 
154792  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
154793  if( !pReader ){
154794  return SQLITE_NOMEM;
154795  }
154796  memset(pReader, 0, sizeof(Fts3SegReader));
154797  pReader->iIdx = iAge;
154798  pReader->bLookup = bLookup!=0;
154799  pReader->iStartBlock = iStartLeaf;
154800  pReader->iLeafEndBlock = iEndLeaf;
154801  pReader->iEndBlock = iEndBlock;
154802 
154803  if( nExtra ){
154804  /* The entire segment is stored in the root node. */
154805  pReader->aNode = (char *)&pReader[1];
154806  pReader->rootOnly = 1;
154807  pReader->nNode = nRoot;
154808  memcpy(pReader->aNode, zRoot, nRoot);
154809  memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
154810  }else{
154811  pReader->iCurrentBlock = iStartLeaf-1;
154812  }
154813  *ppReader = pReader;
154814  return SQLITE_OK;
154815 }
154816 
154817 /*
154818 ** This is a comparison function used as a qsort() callback when sorting
154819 ** an array of pending terms by term. This occurs as part of flushing
154820 ** the contents of the pending-terms hash table to the database.
154821 */
154822 static int SQLITE_CDECL fts3CompareElemByTerm(
154823  const void *lhs,
154824  const void *rhs
154825 ){
154826  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
154827  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
154828  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
154829  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
154830 
154831  int n = (n1<n2 ? n1 : n2);
154832  int c = memcmp(z1, z2, n);
154833  if( c==0 ){
154834  c = n1 - n2;
154835  }
154836  return c;
154837 }
154838 
154839 /*
154840 ** This function is used to allocate an Fts3SegReader that iterates through
154841 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
154842 **
154843 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
154844 ** through each term in the pending-terms table. Or, if isPrefixIter is
154845 ** non-zero, it iterates through each term and its prefixes. For example, if
154846 ** the pending terms hash table contains the terms "sqlite", "mysql" and
154847 ** "firebird", then the iterator visits the following 'terms' (in the order
154848 ** shown):
154849 **
154850 ** f fi fir fire fireb firebi firebir firebird
154851 ** m my mys mysq mysql
154852 ** s sq sql sqli sqlit sqlite
154853 **
154854 ** Whereas if isPrefixIter is zero, the terms visited are:
154855 **
154856 ** firebird mysql sqlite
154857 */
154858 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
154859  Fts3Table *p, /* Virtual table handle */
154860  int iIndex, /* Index for p->aIndex */
154861  const char *zTerm, /* Term to search for */
154862  int nTerm, /* Size of buffer zTerm */
154863  int bPrefix, /* True for a prefix iterator */
154864  Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
154865 ){
154866  Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
154867  Fts3HashElem *pE; /* Iterator variable */
154868  Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
154869  int nElem = 0; /* Size of array at aElem */
154870  int rc = SQLITE_OK; /* Return Code */
154871  Fts3Hash *pHash;
154872 
154873  pHash = &p->aIndex[iIndex].hPending;
154874  if( bPrefix ){
154875  int nAlloc = 0; /* Size of allocated array at aElem */
154876 
154877  for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
154878  char *zKey = (char *)fts3HashKey(pE);
154879  int nKey = fts3HashKeysize(pE);
154880  if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
154881  if( nElem==nAlloc ){
154882  Fts3HashElem **aElem2;
154883  nAlloc += 16;
154884  aElem2 = (Fts3HashElem **)sqlite3_realloc(
154885  aElem, nAlloc*sizeof(Fts3HashElem *)
154886  );
154887  if( !aElem2 ){
154888  rc = SQLITE_NOMEM;
154889  nElem = 0;
154890  break;
154891  }
154892  aElem = aElem2;
154893  }
154894 
154895  aElem[nElem++] = pE;
154896  }
154897  }
154898 
154899  /* If more than one term matches the prefix, sort the Fts3HashElem
154900  ** objects in term order using qsort(). This uses the same comparison
154901  ** callback as is used when flushing terms to disk.
154902  */
154903  if( nElem>1 ){
154904  qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
154905  }
154906 
154907  }else{
154908  /* The query is a simple term lookup that matches at most one term in
154909  ** the index. All that is required is a straight hash-lookup.
154910  **
154911  ** Because the stack address of pE may be accessed via the aElem pointer
154912  ** below, the "Fts3HashElem *pE" must be declared so that it is valid
154913  ** within this entire function, not just this "else{...}" block.
154914  */
154915  pE = fts3HashFindElem(pHash, zTerm, nTerm);
154916  if( pE ){
154917  aElem = &pE;
154918  nElem = 1;
154919  }
154920  }
154921 
154922  if( nElem>0 ){
154923  int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
154924  pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
154925  if( !pReader ){
154926  rc = SQLITE_NOMEM;
154927  }else{
154928  memset(pReader, 0, nByte);
154929  pReader->iIdx = 0x7FFFFFFF;
154930  pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
154931  memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
154932  }
154933  }
154934 
154935  if( bPrefix ){
154936  sqlite3_free(aElem);
154937  }
154938  *ppReader = pReader;
154939  return rc;
154940 }
154941 
154942 /*
154943 ** Compare the entries pointed to by two Fts3SegReader structures.
154944 ** Comparison is as follows:
154945 **
154946 ** 1) EOF is greater than not EOF.
154947 **
154948 ** 2) The current terms (if any) are compared using memcmp(). If one
154949 ** term is a prefix of another, the longer term is considered the
154950 ** larger.
154951 **
154952 ** 3) By segment age. An older segment is considered larger.
154953 */
154954 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
154955  int rc;
154956  if( pLhs->aNode && pRhs->aNode ){
154957  int rc2 = pLhs->nTerm - pRhs->nTerm;
154958  if( rc2<0 ){
154959  rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
154960  }else{
154961  rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
154962  }
154963  if( rc==0 ){
154964  rc = rc2;
154965  }
154966  }else{
154967  rc = (pLhs->aNode==0) - (pRhs->aNode==0);
154968  }
154969  if( rc==0 ){
154970  rc = pRhs->iIdx - pLhs->iIdx;
154971  }
154972  assert( rc!=0 );
154973  return rc;
154974 }
154975 
154976 /*
154977 ** A different comparison function for SegReader structures. In this
154978 ** version, it is assumed that each SegReader points to an entry in
154979 ** a doclist for identical terms. Comparison is made as follows:
154980 **
154981 ** 1) EOF (end of doclist in this case) is greater than not EOF.
154982 **
154983 ** 2) By current docid.
154984 **
154985 ** 3) By segment age. An older segment is considered larger.
154986 */
154987 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
154988  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
154989  if( rc==0 ){
154990  if( pLhs->iDocid==pRhs->iDocid ){
154991  rc = pRhs->iIdx - pLhs->iIdx;
154992  }else{
154993  rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
154994  }
154995  }
154996  assert( pLhs->aNode && pRhs->aNode );
154997  return rc;
154998 }
154999 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
155000  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
155001  if( rc==0 ){
155002  if( pLhs->iDocid==pRhs->iDocid ){
155003  rc = pRhs->iIdx - pLhs->iIdx;
155004  }else{
155005  rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
155006  }
155007  }
155008  assert( pLhs->aNode && pRhs->aNode );
155009  return rc;
155010 }
155011 
155012 /*
155013 ** Compare the term that the Fts3SegReader object passed as the first argument
155014 ** points to with the term specified by arguments zTerm and nTerm.
155015 **
155016 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
155017 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
155018 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
155019 */
155020 static int fts3SegReaderTermCmp(
155021  Fts3SegReader *pSeg, /* Segment reader object */
155022  const char *zTerm, /* Term to compare to */
155023  int nTerm /* Size of term zTerm in bytes */
155024 ){
155025  int res = 0;
155026  if( pSeg->aNode ){
155027  if( pSeg->nTerm>nTerm ){
155028  res = memcmp(pSeg->zTerm, zTerm, nTerm);
155029  }else{
155030  res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
155031  }
155032  if( res==0 ){
155033  res = pSeg->nTerm-nTerm;
155034  }
155035  }
155036  return res;
155037 }
155038 
155039 /*
155040 ** Argument apSegment is an array of nSegment elements. It is known that
155041 ** the final (nSegment-nSuspect) members are already in sorted order
155042 ** (according to the comparison function provided). This function shuffles
155043 ** the array around until all entries are in sorted order.
155044 */
155045 static void fts3SegReaderSort(
155046  Fts3SegReader **apSegment, /* Array to sort entries of */
155047  int nSegment, /* Size of apSegment array */
155048  int nSuspect, /* Unsorted entry count */
155049  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
155050 ){
155051  int i; /* Iterator variable */
155052 
155053  assert( nSuspect<=nSegment );
155054 
155055  if( nSuspect==nSegment ) nSuspect--;
155056  for(i=nSuspect-1; i>=0; i--){
155057  int j;
155058  for(j=i; j<(nSegment-1); j++){
155059  Fts3SegReader *pTmp;
155060  if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
155061  pTmp = apSegment[j+1];
155062  apSegment[j+1] = apSegment[j];
155063  apSegment[j] = pTmp;
155064  }
155065  }
155066 
155067 #ifndef NDEBUG
155068  /* Check that the list really is sorted now. */
155069  for(i=0; i<(nSuspect-1); i++){
155070  assert( xCmp(apSegment[i], apSegment[i+1])<0 );
155071  }
155072 #endif
155073 }
155074 
155075 /*
155076 ** Insert a record into the %_segments table.
155077 */
155078 static int fts3WriteSegment(
155079  Fts3Table *p, /* Virtual table handle */
155080  sqlite3_int64 iBlock, /* Block id for new block */
155081  char *z, /* Pointer to buffer containing block data */
155082  int n /* Size of buffer z in bytes */
155083 ){
155084  sqlite3_stmt *pStmt;
155085  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
155086  if( rc==SQLITE_OK ){
155087  sqlite3_bind_int64(pStmt, 1, iBlock);
155088  sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
155089  sqlite3_step(pStmt);
155090  rc = sqlite3_reset(pStmt);
155091  }
155092  return rc;
155093 }
155094 
155095 /*
155096 ** Find the largest relative level number in the table. If successful, set
155097 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
155098 ** set *pnMax to zero and return an SQLite error code.
155099 */
155100 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
155101  int rc;
155102  int mxLevel = 0;
155103  sqlite3_stmt *pStmt = 0;
155104 
155105  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
155106  if( rc==SQLITE_OK ){
155107  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155108  mxLevel = sqlite3_column_int(pStmt, 0);
155109  }
155110  rc = sqlite3_reset(pStmt);
155111  }
155112  *pnMax = mxLevel;
155113  return rc;
155114 }
155115 
155116 /*
155117 ** Insert a record into the %_segdir table.
155118 */
155119 static int fts3WriteSegdir(
155120  Fts3Table *p, /* Virtual table handle */
155121  sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
155122  int iIdx, /* Value for "idx" field */
155123  sqlite3_int64 iStartBlock, /* Value for "start_block" field */
155124  sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
155125  sqlite3_int64 iEndBlock, /* Value for "end_block" field */
155126  sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
155127  char *zRoot, /* Blob value for "root" field */
155128  int nRoot /* Number of bytes in buffer zRoot */
155129 ){
155130  sqlite3_stmt *pStmt;
155131  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
155132  if( rc==SQLITE_OK ){
155133  sqlite3_bind_int64(pStmt, 1, iLevel);
155134  sqlite3_bind_int(pStmt, 2, iIdx);
155135  sqlite3_bind_int64(pStmt, 3, iStartBlock);
155136  sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
155137  if( nLeafData==0 ){
155138  sqlite3_bind_int64(pStmt, 5, iEndBlock);
155139  }else{
155140  char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
155141  if( !zEnd ) return SQLITE_NOMEM;
155142  sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
155143  }
155144  sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
155145  sqlite3_step(pStmt);
155146  rc = sqlite3_reset(pStmt);
155147  }
155148  return rc;
155149 }
155150 
155151 /*
155152 ** Return the size of the common prefix (if any) shared by zPrev and
155153 ** zNext, in bytes. For example,
155154 **
155155 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
155156 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
155157 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
155158 */
155159 static int fts3PrefixCompress(
155160  const char *zPrev, /* Buffer containing previous term */
155161  int nPrev, /* Size of buffer zPrev in bytes */
155162  const char *zNext, /* Buffer containing next term */
155163  int nNext /* Size of buffer zNext in bytes */
155164 ){
155165  int n;
155166  UNUSED_PARAMETER(nNext);
155167  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
155168  return n;
155169 }
155170 
155171 /*
155172 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
155173 ** (according to memcmp) than the previous term.
155174 */
155175 static int fts3NodeAddTerm(
155176  Fts3Table *p, /* Virtual table handle */
155177  SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
155178  int isCopyTerm, /* True if zTerm/nTerm is transient */
155179  const char *zTerm, /* Pointer to buffer containing term */
155180  int nTerm /* Size of term in bytes */
155181 ){
155182  SegmentNode *pTree = *ppTree;
155183  int rc;
155184  SegmentNode *pNew;
155185 
155186  /* First try to append the term to the current node. Return early if
155187  ** this is possible.
155188  */
155189  if( pTree ){
155190  int nData = pTree->nData; /* Current size of node in bytes */
155191  int nReq = nData; /* Required space after adding zTerm */
155192  int nPrefix; /* Number of bytes of prefix compression */
155193  int nSuffix; /* Suffix length */
155194 
155195  nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
155196  nSuffix = nTerm-nPrefix;
155197 
155198  nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
155199  if( nReq<=p->nNodeSize || !pTree->zTerm ){
155200 
155201  if( nReq>p->nNodeSize ){
155202  /* An unusual case: this is the first term to be added to the node
155203  ** and the static node buffer (p->nNodeSize bytes) is not large
155204  ** enough. Use a separately malloced buffer instead This wastes
155205  ** p->nNodeSize bytes, but since this scenario only comes about when
155206  ** the database contain two terms that share a prefix of almost 2KB,
155207  ** this is not expected to be a serious problem.
155208  */
155209  assert( pTree->aData==(char *)&pTree[1] );
155210  pTree->aData = (char *)sqlite3_malloc(nReq);
155211  if( !pTree->aData ){
155212  return SQLITE_NOMEM;
155213  }
155214  }
155215 
155216  if( pTree->zTerm ){
155217  /* There is no prefix-length field for first term in a node */
155218  nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
155219  }
155220 
155221  nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
155222  memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
155223  pTree->nData = nData + nSuffix;
155224  pTree->nEntry++;
155225 
155226  if( isCopyTerm ){
155227  if( pTree->nMalloc<nTerm ){
155228  char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
155229  if( !zNew ){
155230  return SQLITE_NOMEM;
155231  }
155232  pTree->nMalloc = nTerm*2;
155233  pTree->zMalloc = zNew;
155234  }
155235  pTree->zTerm = pTree->zMalloc;
155236  memcpy(pTree->zTerm, zTerm, nTerm);
155237  pTree->nTerm = nTerm;
155238  }else{
155239  pTree->zTerm = (char *)zTerm;
155240  pTree->nTerm = nTerm;
155241  }
155242  return SQLITE_OK;
155243  }
155244  }
155245 
155246  /* If control flows to here, it was not possible to append zTerm to the
155247  ** current node. Create a new node (a right-sibling of the current node).
155248  ** If this is the first node in the tree, the term is added to it.
155249  **
155250  ** Otherwise, the term is not added to the new node, it is left empty for
155251  ** now. Instead, the term is inserted into the parent of pTree. If pTree
155252  ** has no parent, one is created here.
155253  */
155254  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
155255  if( !pNew ){
155256  return SQLITE_NOMEM;
155257  }
155258  memset(pNew, 0, sizeof(SegmentNode));
155259  pNew->nData = 1 + FTS3_VARINT_MAX;
155260  pNew->aData = (char *)&pNew[1];
155261 
155262  if( pTree ){
155263  SegmentNode *pParent = pTree->pParent;
155264  rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
155265  if( pTree->pParent==0 ){
155266  pTree->pParent = pParent;
155267  }
155268  pTree->pRight = pNew;
155269  pNew->pLeftmost = pTree->pLeftmost;
155270  pNew->pParent = pParent;
155271  pNew->zMalloc = pTree->zMalloc;
155272  pNew->nMalloc = pTree->nMalloc;
155273  pTree->zMalloc = 0;
155274  }else{
155275  pNew->pLeftmost = pNew;
155276  rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
155277  }
155278 
155279  *ppTree = pNew;
155280  return rc;
155281 }
155282 
155283 /*
155284 ** Helper function for fts3NodeWrite().
155285 */
155286 static int fts3TreeFinishNode(
155287  SegmentNode *pTree,
155288  int iHeight,
155289  sqlite3_int64 iLeftChild
155290 ){
155291  int nStart;
155292  assert( iHeight>=1 && iHeight<128 );
155293  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
155294  pTree->aData[nStart] = (char)iHeight;
155295  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
155296  return nStart;
155297 }
155298 
155299 /*
155300 ** Write the buffer for the segment node pTree and all of its peers to the
155301 ** database. Then call this function recursively to write the parent of
155302 ** pTree and its peers to the database.
155303 **
155304 ** Except, if pTree is a root node, do not write it to the database. Instead,
155305 ** set output variables *paRoot and *pnRoot to contain the root node.
155306 **
155307 ** If successful, SQLITE_OK is returned and output variable *piLast is
155308 ** set to the largest blockid written to the database (or zero if no
155309 ** blocks were written to the db). Otherwise, an SQLite error code is
155310 ** returned.
155311 */
155312 static int fts3NodeWrite(
155313  Fts3Table *p, /* Virtual table handle */
155314  SegmentNode *pTree, /* SegmentNode handle */
155315  int iHeight, /* Height of this node in tree */
155316  sqlite3_int64 iLeaf, /* Block id of first leaf node */
155317  sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
155318  sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
155319  char **paRoot, /* OUT: Data for root node */
155320  int *pnRoot /* OUT: Size of root node in bytes */
155321 ){
155322  int rc = SQLITE_OK;
155323 
155324  if( !pTree->pParent ){
155325  /* Root node of the tree. */
155326  int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
155327  *piLast = iFree-1;
155328  *pnRoot = pTree->nData - nStart;
155329  *paRoot = &pTree->aData[nStart];
155330  }else{
155331  SegmentNode *pIter;
155332  sqlite3_int64 iNextFree = iFree;
155333  sqlite3_int64 iNextLeaf = iLeaf;
155334  for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
155335  int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
155336  int nWrite = pIter->nData - nStart;
155337 
155338  rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
155339  iNextFree++;
155340  iNextLeaf += (pIter->nEntry+1);
155341  }
155342  if( rc==SQLITE_OK ){
155343  assert( iNextLeaf==iFree );
155344  rc = fts3NodeWrite(
155345  p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
155346  );
155347  }
155348  }
155349 
155350  return rc;
155351 }
155352 
155353 /*
155354 ** Free all memory allocations associated with the tree pTree.
155355 */
155356 static void fts3NodeFree(SegmentNode *pTree){
155357  if( pTree ){
155358  SegmentNode *p = pTree->pLeftmost;
155359  fts3NodeFree(p->pParent);
155360  while( p ){
155361  SegmentNode *pRight = p->pRight;
155362  if( p->aData!=(char *)&p[1] ){
155363  sqlite3_free(p->aData);
155364  }
155365  assert( pRight==0 || p->zMalloc==0 );
155366  sqlite3_free(p->zMalloc);
155367  sqlite3_free(p);
155368  p = pRight;
155369  }
155370  }
155371 }
155372 
155373 /*
155374 ** Add a term to the segment being constructed by the SegmentWriter object
155375 ** *ppWriter. When adding the first term to a segment, *ppWriter should
155376 ** be passed NULL. This function will allocate a new SegmentWriter object
155377 ** and return it via the input/output variable *ppWriter in this case.
155378 **
155379 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
155380 */
155381 static int fts3SegWriterAdd(
155382  Fts3Table *p, /* Virtual table handle */
155383  SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
155384  int isCopyTerm, /* True if buffer zTerm must be copied */
155385  const char *zTerm, /* Pointer to buffer containing term */
155386  int nTerm, /* Size of term in bytes */
155387  const char *aDoclist, /* Pointer to buffer containing doclist */
155388  int nDoclist /* Size of doclist in bytes */
155389 ){
155390  int nPrefix; /* Size of term prefix in bytes */
155391  int nSuffix; /* Size of term suffix in bytes */
155392  int nReq; /* Number of bytes required on leaf page */
155393  int nData;
155394  SegmentWriter *pWriter = *ppWriter;
155395 
155396  if( !pWriter ){
155397  int rc;
155398  sqlite3_stmt *pStmt;
155399 
155400  /* Allocate the SegmentWriter structure */
155401  pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
155402  if( !pWriter ) return SQLITE_NOMEM;
155403  memset(pWriter, 0, sizeof(SegmentWriter));
155404  *ppWriter = pWriter;
155405 
155406  /* Allocate a buffer in which to accumulate data */
155407  pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
155408  if( !pWriter->aData ) return SQLITE_NOMEM;
155409  pWriter->nSize = p->nNodeSize;
155410 
155411  /* Find the next free blockid in the %_segments table */
155412  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
155413  if( rc!=SQLITE_OK ) return rc;
155414  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155415  pWriter->iFree = sqlite3_column_int64(pStmt, 0);
155416  pWriter->iFirst = pWriter->iFree;
155417  }
155418  rc = sqlite3_reset(pStmt);
155419  if( rc!=SQLITE_OK ) return rc;
155420  }
155421  nData = pWriter->nData;
155422 
155423  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
155424  nSuffix = nTerm-nPrefix;
155425 
155426  /* Figure out how many bytes are required by this new entry */
155427  nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
155428  sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
155429  nSuffix + /* Term suffix */
155430  sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
155431  nDoclist; /* Doclist data */
155432 
155433  if( nData>0 && nData+nReq>p->nNodeSize ){
155434  int rc;
155435 
155436  /* The current leaf node is full. Write it out to the database. */
155437  rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
155438  if( rc!=SQLITE_OK ) return rc;
155439  p->nLeafAdd++;
155440 
155441  /* Add the current term to the interior node tree. The term added to
155442  ** the interior tree must:
155443  **
155444  ** a) be greater than the largest term on the leaf node just written
155445  ** to the database (still available in pWriter->zTerm), and
155446  **
155447  ** b) be less than or equal to the term about to be added to the new
155448  ** leaf node (zTerm/nTerm).
155449  **
155450  ** In other words, it must be the prefix of zTerm 1 byte longer than
155451  ** the common prefix (if any) of zTerm and pWriter->zTerm.
155452  */
155453  assert( nPrefix<nTerm );
155454  rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
155455  if( rc!=SQLITE_OK ) return rc;
155456 
155457  nData = 0;
155458  pWriter->nTerm = 0;
155459 
155460  nPrefix = 0;
155461  nSuffix = nTerm;
155462  nReq = 1 + /* varint containing prefix size */
155463  sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
155464  nTerm + /* Term suffix */
155465  sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
155466  nDoclist; /* Doclist data */
155467  }
155468 
155469  /* Increase the total number of bytes written to account for the new entry. */
155470  pWriter->nLeafData += nReq;
155471 
155472  /* If the buffer currently allocated is too small for this entry, realloc
155473  ** the buffer to make it large enough.
155474  */
155475  if( nReq>pWriter->nSize ){
155476  char *aNew = sqlite3_realloc(pWriter->aData, nReq);
155477  if( !aNew ) return SQLITE_NOMEM;
155478  pWriter->aData = aNew;
155479  pWriter->nSize = nReq;
155480  }
155481  assert( nData+nReq<=pWriter->nSize );
155482 
155483  /* Append the prefix-compressed term and doclist to the buffer. */
155484  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
155485  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
155486  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
155487  nData += nSuffix;
155488  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
155489  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
155490  pWriter->nData = nData + nDoclist;
155491 
155492  /* Save the current term so that it can be used to prefix-compress the next.
155493  ** If the isCopyTerm parameter is true, then the buffer pointed to by
155494  ** zTerm is transient, so take a copy of the term data. Otherwise, just
155495  ** store a copy of the pointer.
155496  */
155497  if( isCopyTerm ){
155498  if( nTerm>pWriter->nMalloc ){
155499  char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
155500  if( !zNew ){
155501  return SQLITE_NOMEM;
155502  }
155503  pWriter->nMalloc = nTerm*2;
155504  pWriter->zMalloc = zNew;
155505  pWriter->zTerm = zNew;
155506  }
155507  assert( pWriter->zTerm==pWriter->zMalloc );
155508  memcpy(pWriter->zTerm, zTerm, nTerm);
155509  }else{
155510  pWriter->zTerm = (char *)zTerm;
155511  }
155512  pWriter->nTerm = nTerm;
155513 
155514  return SQLITE_OK;
155515 }
155516 
155517 /*
155518 ** Flush all data associated with the SegmentWriter object pWriter to the
155519 ** database. This function must be called after all terms have been added
155520 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
155521 ** returned. Otherwise, an SQLite error code.
155522 */
155523 static int fts3SegWriterFlush(
155524  Fts3Table *p, /* Virtual table handle */
155525  SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
155526  sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
155527  int iIdx /* Value for 'idx' column of %_segdir */
155528 ){
155529  int rc; /* Return code */
155530  if( pWriter->pTree ){
155531  sqlite3_int64 iLast = 0; /* Largest block id written to database */
155532  sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
155533  char *zRoot = NULL; /* Pointer to buffer containing root node */
155534  int nRoot = 0; /* Size of buffer zRoot */
155535 
155536  iLastLeaf = pWriter->iFree;
155537  rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
155538  if( rc==SQLITE_OK ){
155539  rc = fts3NodeWrite(p, pWriter->pTree, 1,
155540  pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
155541  }
155542  if( rc==SQLITE_OK ){
155543  rc = fts3WriteSegdir(p, iLevel, iIdx,
155544  pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
155545  }
155546  }else{
155547  /* The entire tree fits on the root node. Write it to the segdir table. */
155548  rc = fts3WriteSegdir(p, iLevel, iIdx,
155549  0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
155550  }
155551  p->nLeafAdd++;
155552  return rc;
155553 }
155554 
155555 /*
155556 ** Release all memory held by the SegmentWriter object passed as the
155557 ** first argument.
155558 */
155559 static void fts3SegWriterFree(SegmentWriter *pWriter){
155560  if( pWriter ){
155561  sqlite3_free(pWriter->aData);
155562  sqlite3_free(pWriter->zMalloc);
155563  fts3NodeFree(pWriter->pTree);
155564  sqlite3_free(pWriter);
155565  }
155566 }
155567 
155568 /*
155569 ** The first value in the apVal[] array is assumed to contain an integer.
155570 ** This function tests if there exist any documents with docid values that
155571 ** are different from that integer. i.e. if deleting the document with docid
155572 ** pRowid would mean the FTS3 table were empty.
155573 **
155574 ** If successful, *pisEmpty is set to true if the table is empty except for
155575 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
155576 ** error occurs, an SQLite error code is returned.
155577 */
155578 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
155579  sqlite3_stmt *pStmt;
155580  int rc;
155581  if( p->zContentTbl ){
155582  /* If using the content=xxx option, assume the table is never empty */
155583  *pisEmpty = 0;
155584  rc = SQLITE_OK;
155585  }else{
155586  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
155587  if( rc==SQLITE_OK ){
155588  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155589  *pisEmpty = sqlite3_column_int(pStmt, 0);
155590  }
155591  rc = sqlite3_reset(pStmt);
155592  }
155593  }
155594  return rc;
155595 }
155596 
155597 /*
155598 ** Set *pnMax to the largest segment level in the database for the index
155599 ** iIndex.
155600 **
155601 ** Segment levels are stored in the 'level' column of the %_segdir table.
155602 **
155603 ** Return SQLITE_OK if successful, or an SQLite error code if not.
155604 */
155605 static int fts3SegmentMaxLevel(
155606  Fts3Table *p,
155607  int iLangid,
155608  int iIndex,
155609  sqlite3_int64 *pnMax
155610 ){
155611  sqlite3_stmt *pStmt;
155612  int rc;
155613  assert( iIndex>=0 && iIndex<p->nIndex );
155614 
155615  /* Set pStmt to the compiled version of:
155616  **
155617  ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
155618  **
155619  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
155620  */
155621  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
155622  if( rc!=SQLITE_OK ) return rc;
155623  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
155624  sqlite3_bind_int64(pStmt, 2,
155625  getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
155626  );
155627  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155628  *pnMax = sqlite3_column_int64(pStmt, 0);
155629  }
155630  return sqlite3_reset(pStmt);
155631 }
155632 
155633 /*
155634 ** iAbsLevel is an absolute level that may be assumed to exist within
155635 ** the database. This function checks if it is the largest level number
155636 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
155637 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
155638 ** is returned. If an error occurs, an error code is returned and the
155639 ** final value of *pbMax is undefined.
155640 */
155641 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
155642 
155643  /* Set pStmt to the compiled version of:
155644  **
155645  ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
155646  **
155647  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
155648  */
155649  sqlite3_stmt *pStmt;
155650  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
155651  if( rc!=SQLITE_OK ) return rc;
155652  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
155653  sqlite3_bind_int64(pStmt, 2,
155654  ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
155655  );
155656 
155657  *pbMax = 0;
155658  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155659  *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
155660  }
155661  return sqlite3_reset(pStmt);
155662 }
155663 
155664 /*
155665 ** Delete all entries in the %_segments table associated with the segment
155666 ** opened with seg-reader pSeg. This function does not affect the contents
155667 ** of the %_segdir table.
155668 */
155669 static int fts3DeleteSegment(
155670  Fts3Table *p, /* FTS table handle */
155671  Fts3SegReader *pSeg /* Segment to delete */
155672 ){
155673  int rc = SQLITE_OK; /* Return code */
155674  if( pSeg->iStartBlock ){
155675  sqlite3_stmt *pDelete; /* SQL statement to delete rows */
155676  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
155677  if( rc==SQLITE_OK ){
155678  sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
155679  sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
155680  sqlite3_step(pDelete);
155681  rc = sqlite3_reset(pDelete);
155682  }
155683  }
155684  return rc;
155685 }
155686 
155687 /*
155688 ** This function is used after merging multiple segments into a single large
155689 ** segment to delete the old, now redundant, segment b-trees. Specifically,
155690 ** it:
155691 **
155692 ** 1) Deletes all %_segments entries for the segments associated with
155693 ** each of the SegReader objects in the array passed as the third
155694 ** argument, and
155695 **
155696 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
155697 ** entries regardless of level if (iLevel<0).
155698 **
155699 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
155700 */
155701 static int fts3DeleteSegdir(
155702  Fts3Table *p, /* Virtual table handle */
155703  int iLangid, /* Language id */
155704  int iIndex, /* Index for p->aIndex */
155705  int iLevel, /* Level of %_segdir entries to delete */
155706  Fts3SegReader **apSegment, /* Array of SegReader objects */
155707  int nReader /* Size of array apSegment */
155708 ){
155709  int rc = SQLITE_OK; /* Return Code */
155710  int i; /* Iterator variable */
155711  sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
155712 
155713  for(i=0; rc==SQLITE_OK && i<nReader; i++){
155714  rc = fts3DeleteSegment(p, apSegment[i]);
155715  }
155716  if( rc!=SQLITE_OK ){
155717  return rc;
155718  }
155719 
155720  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
155721  if( iLevel==FTS3_SEGCURSOR_ALL ){
155722  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
155723  if( rc==SQLITE_OK ){
155724  sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
155725  sqlite3_bind_int64(pDelete, 2,
155726  getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
155727  );
155728  }
155729  }else{
155730  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
155731  if( rc==SQLITE_OK ){
155732  sqlite3_bind_int64(
155733  pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
155734  );
155735  }
155736  }
155737 
155738  if( rc==SQLITE_OK ){
155739  sqlite3_step(pDelete);
155740  rc = sqlite3_reset(pDelete);
155741  }
155742 
155743  return rc;
155744 }
155745 
155746 /*
155747 ** When this function is called, buffer *ppList (size *pnList bytes) contains
155748 ** a position list that may (or may not) feature multiple columns. This
155749 ** function adjusts the pointer *ppList and the length *pnList so that they
155750 ** identify the subset of the position list that corresponds to column iCol.
155751 **
155752 ** If there are no entries in the input position list for column iCol, then
155753 ** *pnList is set to zero before returning.
155754 **
155755 ** If parameter bZero is non-zero, then any part of the input list following
155756 ** the end of the output list is zeroed before returning.
155757 */
155758 static void fts3ColumnFilter(
155759  int iCol, /* Column to filter on */
155760  int bZero, /* Zero out anything following *ppList */
155761  char **ppList, /* IN/OUT: Pointer to position list */
155762  int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
155763 ){
155764  char *pList = *ppList;
155765  int nList = *pnList;
155766  char *pEnd = &pList[nList];
155767  int iCurrent = 0;
155768  char *p = pList;
155769 
155770  assert( iCol>=0 );
155771  while( 1 ){
155772  char c = 0;
155773  while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
155774 
155775  if( iCol==iCurrent ){
155776  nList = (int)(p - pList);
155777  break;
155778  }
155779 
155780  nList -= (int)(p - pList);
155781  pList = p;
155782  if( nList==0 ){
155783  break;
155784  }
155785  p = &pList[1];
155786  p += fts3GetVarint32(p, &iCurrent);
155787  }
155788 
155789  if( bZero && &pList[nList]!=pEnd ){
155790  memset(&pList[nList], 0, pEnd - &pList[nList]);
155791  }
155792  *ppList = pList;
155793  *pnList = nList;
155794 }
155795 
155796 /*
155797 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
155798 ** existing data). Grow the buffer if required.
155799 **
155800 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
155801 ** trying to resize the buffer, return SQLITE_NOMEM.
155802 */
155803 static int fts3MsrBufferData(
155804  Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
155805  char *pList,
155806  int nList
155807 ){
155808  if( nList>pMsr->nBuffer ){
155809  char *pNew;
155810  pMsr->nBuffer = nList*2;
155811  pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
155812  if( !pNew ) return SQLITE_NOMEM;
155813  pMsr->aBuffer = pNew;
155814  }
155815 
155816  memcpy(pMsr->aBuffer, pList, nList);
155817  return SQLITE_OK;
155818 }
155819 
155820 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
155821  Fts3Table *p, /* Virtual table handle */
155822  Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
155823  sqlite3_int64 *piDocid, /* OUT: Docid value */
155824  char **paPoslist, /* OUT: Pointer to position list */
155825  int *pnPoslist /* OUT: Size of position list in bytes */
155826 ){
155827  int nMerge = pMsr->nAdvance;
155828  Fts3SegReader **apSegment = pMsr->apSegment;
155829  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
155830  p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
155831  );
155832 
155833  if( nMerge==0 ){
155834  *paPoslist = 0;
155835  return SQLITE_OK;
155836  }
155837 
155838  while( 1 ){
155839  Fts3SegReader *pSeg;
155840  pSeg = pMsr->apSegment[0];
155841 
155842  if( pSeg->pOffsetList==0 ){
155843  *paPoslist = 0;
155844  break;
155845  }else{
155846  int rc;
155847  char *pList;
155848  int nList;
155849  int j;
155850  sqlite3_int64 iDocid = apSegment[0]->iDocid;
155851 
155852  rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
155853  j = 1;
155854  while( rc==SQLITE_OK
155855  && j<nMerge
155856  && apSegment[j]->pOffsetList
155857  && apSegment[j]->iDocid==iDocid
155858  ){
155859  rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
155860  j++;
155861  }
155862  if( rc!=SQLITE_OK ) return rc;
155863  fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
155864 
155865  if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
155866  rc = fts3MsrBufferData(pMsr, pList, nList+1);
155867  if( rc!=SQLITE_OK ) return rc;
155868  assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
155869  pList = pMsr->aBuffer;
155870  }
155871 
155872  if( pMsr->iColFilter>=0 ){
155873  fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
155874  }
155875 
155876  if( nList>0 ){
155877  *paPoslist = pList;
155878  *piDocid = iDocid;
155879  *pnPoslist = nList;
155880  break;
155881  }
155882  }
155883  }
155884 
155885  return SQLITE_OK;
155886 }
155887 
155888 static int fts3SegReaderStart(
155889  Fts3Table *p, /* Virtual table handle */
155890  Fts3MultiSegReader *pCsr, /* Cursor object */
155891  const char *zTerm, /* Term searched for (or NULL) */
155892  int nTerm /* Length of zTerm in bytes */
155893 ){
155894  int i;
155895  int nSeg = pCsr->nSegment;
155896 
155897  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
155898  ** for, then advance each segment iterator until it points to a term of
155899  ** equal or greater value than the specified term. This prevents many
155900  ** unnecessary merge/sort operations for the case where single segment
155901  ** b-tree leaf nodes contain more than one term.
155902  */
155903  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
155904  int res = 0;
155905  Fts3SegReader *pSeg = pCsr->apSegment[i];
155906  do {
155907  int rc = fts3SegReaderNext(p, pSeg, 0);
155908  if( rc!=SQLITE_OK ) return rc;
155909  }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
155910 
155911  if( pSeg->bLookup && res!=0 ){
155912  fts3SegReaderSetEof(pSeg);
155913  }
155914  }
155915  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
155916 
155917  return SQLITE_OK;
155918 }
155919 
155920 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
155921  Fts3Table *p, /* Virtual table handle */
155922  Fts3MultiSegReader *pCsr, /* Cursor object */
155923  Fts3SegFilter *pFilter /* Restrictions on range of iteration */
155924 ){
155925  pCsr->pFilter = pFilter;
155926  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
155927 }
155928 
155929 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
155930  Fts3Table *p, /* Virtual table handle */
155931  Fts3MultiSegReader *pCsr, /* Cursor object */
155932  int iCol, /* Column to match on. */
155933  const char *zTerm, /* Term to iterate through a doclist for */
155934  int nTerm /* Number of bytes in zTerm */
155935 ){
155936  int i;
155937  int rc;
155938  int nSegment = pCsr->nSegment;
155939  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
155940  p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
155941  );
155942 
155943  assert( pCsr->pFilter==0 );
155944  assert( zTerm && nTerm>0 );
155945 
155946  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
155947  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
155948  if( rc!=SQLITE_OK ) return rc;
155949 
155950  /* Determine how many of the segments actually point to zTerm/nTerm. */
155951  for(i=0; i<nSegment; i++){
155952  Fts3SegReader *pSeg = pCsr->apSegment[i];
155953  if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
155954  break;
155955  }
155956  }
155957  pCsr->nAdvance = i;
155958 
155959  /* Advance each of the segments to point to the first docid. */
155960  for(i=0; i<pCsr->nAdvance; i++){
155961  rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
155962  if( rc!=SQLITE_OK ) return rc;
155963  }
155964  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
155965 
155966  assert( iCol<0 || iCol<p->nColumn );
155967  pCsr->iColFilter = iCol;
155968 
155969  return SQLITE_OK;
155970 }
155971 
155972 /*
155973 ** This function is called on a MultiSegReader that has been started using
155974 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
155975 ** have been made. Calling this function puts the MultiSegReader in such
155976 ** a state that if the next two calls are:
155977 **
155978 ** sqlite3Fts3SegReaderStart()
155979 ** sqlite3Fts3SegReaderStep()
155980 **
155981 ** then the entire doclist for the term is available in
155982 ** MultiSegReader.aDoclist/nDoclist.
155983 */
155984 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
155985  int i; /* Used to iterate through segment-readers */
155986 
155987  assert( pCsr->zTerm==0 );
155988  assert( pCsr->nTerm==0 );
155989  assert( pCsr->aDoclist==0 );
155990  assert( pCsr->nDoclist==0 );
155991 
155992  pCsr->nAdvance = 0;
155993  pCsr->bRestart = 1;
155994  for(i=0; i<pCsr->nSegment; i++){
155995  pCsr->apSegment[i]->pOffsetList = 0;
155996  pCsr->apSegment[i]->nOffsetList = 0;
155997  pCsr->apSegment[i]->iDocid = 0;
155998  }
155999 
156000  return SQLITE_OK;
156001 }
156002 
156003 
156004 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
156005  Fts3Table *p, /* Virtual table handle */
156006  Fts3MultiSegReader *pCsr /* Cursor object */
156007 ){
156008  int rc = SQLITE_OK;
156009 
156010  int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
156011  int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
156012  int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
156013  int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
156014  int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
156015  int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
156016 
156017  Fts3SegReader **apSegment = pCsr->apSegment;
156018  int nSegment = pCsr->nSegment;
156019  Fts3SegFilter *pFilter = pCsr->pFilter;
156020  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
156021  p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
156022  );
156023 
156024  if( pCsr->nSegment==0 ) return SQLITE_OK;
156025 
156026  do {
156027  int nMerge;
156028  int i;
156029 
156030  /* Advance the first pCsr->nAdvance entries in the apSegment[] array
156031  ** forward. Then sort the list in order of current term again.
156032  */
156033  for(i=0; i<pCsr->nAdvance; i++){
156034  Fts3SegReader *pSeg = apSegment[i];
156035  if( pSeg->bLookup ){
156036  fts3SegReaderSetEof(pSeg);
156037  }else{
156038  rc = fts3SegReaderNext(p, pSeg, 0);
156039  }
156040  if( rc!=SQLITE_OK ) return rc;
156041  }
156042  fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
156043  pCsr->nAdvance = 0;
156044 
156045  /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
156046  assert( rc==SQLITE_OK );
156047  if( apSegment[0]->aNode==0 ) break;
156048 
156049  pCsr->nTerm = apSegment[0]->nTerm;
156050  pCsr->zTerm = apSegment[0]->zTerm;
156051 
156052  /* If this is a prefix-search, and if the term that apSegment[0] points
156053  ** to does not share a suffix with pFilter->zTerm/nTerm, then all
156054  ** required callbacks have been made. In this case exit early.
156055  **
156056  ** Similarly, if this is a search for an exact match, and the first term
156057  ** of segment apSegment[0] is not a match, exit early.
156058  */
156059  if( pFilter->zTerm && !isScan ){
156060  if( pCsr->nTerm<pFilter->nTerm
156061  || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
156062  || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
156063  ){
156064  break;
156065  }
156066  }
156067 
156068  nMerge = 1;
156069  while( nMerge<nSegment
156070  && apSegment[nMerge]->aNode
156071  && apSegment[nMerge]->nTerm==pCsr->nTerm
156072  && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
156073  ){
156074  nMerge++;
156075  }
156076 
156077  assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
156078  if( nMerge==1
156079  && !isIgnoreEmpty
156080  && !isFirst
156081  && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
156082  ){
156083  pCsr->nDoclist = apSegment[0]->nDoclist;
156084  if( fts3SegReaderIsPending(apSegment[0]) ){
156085  rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
156086  pCsr->aDoclist = pCsr->aBuffer;
156087  }else{
156088  pCsr->aDoclist = apSegment[0]->aDoclist;
156089  }
156090  if( rc==SQLITE_OK ) rc = SQLITE_ROW;
156091  }else{
156092  int nDoclist = 0; /* Size of doclist */
156093  sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
156094 
156095  /* The current term of the first nMerge entries in the array
156096  ** of Fts3SegReader objects is the same. The doclists must be merged
156097  ** and a single term returned with the merged doclist.
156098  */
156099  for(i=0; i<nMerge; i++){
156100  fts3SegReaderFirstDocid(p, apSegment[i]);
156101  }
156102  fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
156103  while( apSegment[0]->pOffsetList ){
156104  int j; /* Number of segments that share a docid */
156105  char *pList = 0;
156106  int nList = 0;
156107  int nByte;
156108  sqlite3_int64 iDocid = apSegment[0]->iDocid;
156109  fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
156110  j = 1;
156111  while( j<nMerge
156112  && apSegment[j]->pOffsetList
156113  && apSegment[j]->iDocid==iDocid
156114  ){
156115  fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
156116  j++;
156117  }
156118 
156119  if( isColFilter ){
156120  fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
156121  }
156122 
156123  if( !isIgnoreEmpty || nList>0 ){
156124 
156125  /* Calculate the 'docid' delta value to write into the merged
156126  ** doclist. */
156127  sqlite3_int64 iDelta;
156128  if( p->bDescIdx && nDoclist>0 ){
156129  iDelta = iPrev - iDocid;
156130  }else{
156131  iDelta = iDocid - iPrev;
156132  }
156133  assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
156134  assert( nDoclist>0 || iDelta==iDocid );
156135 
156136  nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
156137  if( nDoclist+nByte>pCsr->nBuffer ){
156138  char *aNew;
156139  pCsr->nBuffer = (nDoclist+nByte)*2;
156140  aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
156141  if( !aNew ){
156142  return SQLITE_NOMEM;
156143  }
156144  pCsr->aBuffer = aNew;
156145  }
156146 
156147  if( isFirst ){
156148  char *a = &pCsr->aBuffer[nDoclist];
156149  int nWrite;
156150 
156151  nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
156152  if( nWrite ){
156153  iPrev = iDocid;
156154  nDoclist += nWrite;
156155  }
156156  }else{
156157  nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
156158  iPrev = iDocid;
156159  if( isRequirePos ){
156160  memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
156161  nDoclist += nList;
156162  pCsr->aBuffer[nDoclist++] = '\0';
156163  }
156164  }
156165  }
156166 
156167  fts3SegReaderSort(apSegment, nMerge, j, xCmp);
156168  }
156169  if( nDoclist>0 ){
156170  pCsr->aDoclist = pCsr->aBuffer;
156171  pCsr->nDoclist = nDoclist;
156172  rc = SQLITE_ROW;
156173  }
156174  }
156175  pCsr->nAdvance = nMerge;
156176  }while( rc==SQLITE_OK );
156177 
156178  return rc;
156179 }
156180 
156181 
156182 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
156183  Fts3MultiSegReader *pCsr /* Cursor object */
156184 ){
156185  if( pCsr ){
156186  int i;
156187  for(i=0; i<pCsr->nSegment; i++){
156188  sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
156189  }
156190  sqlite3_free(pCsr->apSegment);
156191  sqlite3_free(pCsr->aBuffer);
156192 
156193  pCsr->nSegment = 0;
156194  pCsr->apSegment = 0;
156195  pCsr->aBuffer = 0;
156196  }
156197 }
156198 
156199 /*
156200 ** Decode the "end_block" field, selected by column iCol of the SELECT
156201 ** statement passed as the first argument.
156202 **
156203 ** The "end_block" field may contain either an integer, or a text field
156204 ** containing the text representation of two non-negative integers separated
156205 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
156206 ** to the integer value and *pnByte to zero before returning. In the second,
156207 ** set *piEndBlock to the first value and *pnByte to the second.
156208 */
156209 static void fts3ReadEndBlockField(
156210  sqlite3_stmt *pStmt,
156211  int iCol,
156212  i64 *piEndBlock,
156213  i64 *pnByte
156214 ){
156215  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
156216  if( zText ){
156217  int i;
156218  int iMul = 1;
156219  i64 iVal = 0;
156220  for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
156221  iVal = iVal*10 + (zText[i] - '0');
156222  }
156223  *piEndBlock = iVal;
156224  while( zText[i]==' ' ) i++;
156225  iVal = 0;
156226  if( zText[i]=='-' ){
156227  i++;
156228  iMul = -1;
156229  }
156230  for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
156231  iVal = iVal*10 + (zText[i] - '0');
156232  }
156233  *pnByte = (iVal * (i64)iMul);
156234  }
156235 }
156236 
156237 
156238 /*
156239 ** A segment of size nByte bytes has just been written to absolute level
156240 ** iAbsLevel. Promote any segments that should be promoted as a result.
156241 */
156242 static int fts3PromoteSegments(
156243  Fts3Table *p, /* FTS table handle */
156244  sqlite3_int64 iAbsLevel, /* Absolute level just updated */
156245  sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
156246 ){
156247  int rc = SQLITE_OK;
156248  sqlite3_stmt *pRange;
156249 
156250  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
156251 
156252  if( rc==SQLITE_OK ){
156253  int bOk = 0;
156254  i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
156255  i64 nLimit = (nByte*3)/2;
156256 
156257  /* Loop through all entries in the %_segdir table corresponding to
156258  ** segments in this index on levels greater than iAbsLevel. If there is
156259  ** at least one such segment, and it is possible to determine that all
156260  ** such segments are smaller than nLimit bytes in size, they will be
156261  ** promoted to level iAbsLevel. */
156262  sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
156263  sqlite3_bind_int64(pRange, 2, iLast);
156264  while( SQLITE_ROW==sqlite3_step(pRange) ){
156265  i64 nSize = 0, dummy;
156266  fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
156267  if( nSize<=0 || nSize>nLimit ){
156268  /* If nSize==0, then the %_segdir.end_block field does not not
156269  ** contain a size value. This happens if it was written by an
156270  ** old version of FTS. In this case it is not possible to determine
156271  ** the size of the segment, and so segment promotion does not
156272  ** take place. */
156273  bOk = 0;
156274  break;
156275  }
156276  bOk = 1;
156277  }
156278  rc = sqlite3_reset(pRange);
156279 
156280  if( bOk ){
156281  int iIdx = 0;
156282  sqlite3_stmt *pUpdate1 = 0;
156283  sqlite3_stmt *pUpdate2 = 0;
156284 
156285  if( rc==SQLITE_OK ){
156286  rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
156287  }
156288  if( rc==SQLITE_OK ){
156289  rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
156290  }
156291 
156292  if( rc==SQLITE_OK ){
156293 
156294  /* Loop through all %_segdir entries for segments in this index with
156295  ** levels equal to or greater than iAbsLevel. As each entry is visited,
156296  ** updated it to set (level = -1) and (idx = N), where N is 0 for the
156297  ** oldest segment in the range, 1 for the next oldest, and so on.
156298  **
156299  ** In other words, move all segments being promoted to level -1,
156300  ** setting the "idx" fields as appropriate to keep them in the same
156301  ** order. The contents of level -1 (which is never used, except
156302  ** transiently here), will be moved back to level iAbsLevel below. */
156303  sqlite3_bind_int64(pRange, 1, iAbsLevel);
156304  while( SQLITE_ROW==sqlite3_step(pRange) ){
156305  sqlite3_bind_int(pUpdate1, 1, iIdx++);
156306  sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
156307  sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
156308  sqlite3_step(pUpdate1);
156309  rc = sqlite3_reset(pUpdate1);
156310  if( rc!=SQLITE_OK ){
156311  sqlite3_reset(pRange);
156312  break;
156313  }
156314  }
156315  }
156316  if( rc==SQLITE_OK ){
156317  rc = sqlite3_reset(pRange);
156318  }
156319 
156320  /* Move level -1 to level iAbsLevel */
156321  if( rc==SQLITE_OK ){
156322  sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
156323  sqlite3_step(pUpdate2);
156324  rc = sqlite3_reset(pUpdate2);
156325  }
156326  }
156327  }
156328 
156329 
156330  return rc;
156331 }
156332 
156333 /*
156334 ** Merge all level iLevel segments in the database into a single
156335 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
156336 ** single segment with a level equal to the numerically largest level
156337 ** currently present in the database.
156338 **
156339 ** If this function is called with iLevel<0, but there is only one
156340 ** segment in the database, SQLITE_DONE is returned immediately.
156341 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
156342 ** an SQLite error code is returned.
156343 */
156344 static int fts3SegmentMerge(
156345  Fts3Table *p,
156346  int iLangid, /* Language id to merge */
156347  int iIndex, /* Index in p->aIndex[] to merge */
156348  int iLevel /* Level to merge */
156349 ){
156350  int rc; /* Return code */
156351  int iIdx = 0; /* Index of new segment */
156352  sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
156353  SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
156354  Fts3SegFilter filter; /* Segment term filter condition */
156355  Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
156356  int bIgnoreEmpty = 0; /* True to ignore empty segments */
156357  i64 iMaxLevel = 0; /* Max level number for this index/langid */
156358 
156359  assert( iLevel==FTS3_SEGCURSOR_ALL
156360  || iLevel==FTS3_SEGCURSOR_PENDING
156361  || iLevel>=0
156362  );
156363  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
156364  assert( iIndex>=0 && iIndex<p->nIndex );
156365 
156366  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
156367  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
156368 
156369  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
156370  rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
156371  if( rc!=SQLITE_OK ) goto finished;
156372  }
156373 
156374  if( iLevel==FTS3_SEGCURSOR_ALL ){
156375  /* This call is to merge all segments in the database to a single
156376  ** segment. The level of the new segment is equal to the numerically
156377  ** greatest segment level currently present in the database for this
156378  ** index. The idx of the new segment is always 0. */
156379  if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
156380  rc = SQLITE_DONE;
156381  goto finished;
156382  }
156383  iNewLevel = iMaxLevel;
156384  bIgnoreEmpty = 1;
156385 
156386  }else{
156387  /* This call is to merge all segments at level iLevel. find the next
156388  ** available segment index at level iLevel+1. The call to
156389  ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
156390  ** a single iLevel+2 segment if necessary. */
156391  assert( FTS3_SEGCURSOR_PENDING==-1 );
156392  iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
156393  rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
156394  bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
156395  }
156396  if( rc!=SQLITE_OK ) goto finished;
156397 
156398  assert( csr.nSegment>0 );
156399  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
156400  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
156401 
156402  memset(&filter, 0, sizeof(Fts3SegFilter));
156403  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
156404  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
156405 
156406  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
156407  while( SQLITE_OK==rc ){
156408  rc = sqlite3Fts3SegReaderStep(p, &csr);
156409  if( rc!=SQLITE_ROW ) break;
156410  rc = fts3SegWriterAdd(p, &pWriter, 1,
156411  csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
156412  }
156413  if( rc!=SQLITE_OK ) goto finished;
156414  assert( pWriter || bIgnoreEmpty );
156415 
156416  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
156417  rc = fts3DeleteSegdir(
156418  p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
156419  );
156420  if( rc!=SQLITE_OK ) goto finished;
156421  }
156422  if( pWriter ){
156423  rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
156424  if( rc==SQLITE_OK ){
156425  if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
156426  rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
156427  }
156428  }
156429  }
156430 
156431  finished:
156432  fts3SegWriterFree(pWriter);
156433  sqlite3Fts3SegReaderFinish(&csr);
156434  return rc;
156435 }
156436 
156437 
156438 /*
156439 ** Flush the contents of pendingTerms to level 0 segments.
156440 */
156441 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
156442  int rc = SQLITE_OK;
156443  int i;
156444 
156445  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
156446  rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
156447  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
156448  }
156449  sqlite3Fts3PendingTermsClear(p);
156450 
156451  /* Determine the auto-incr-merge setting if unknown. If enabled,
156452  ** estimate the number of leaf blocks of content to be written
156453  */
156454  if( rc==SQLITE_OK && p->bHasStat
156455  && p->nAutoincrmerge==0xff && p->nLeafAdd>0
156456  ){
156457  sqlite3_stmt *pStmt = 0;
156458  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
156459  if( rc==SQLITE_OK ){
156460  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
156461  rc = sqlite3_step(pStmt);
156462  if( rc==SQLITE_ROW ){
156463  p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
156464  if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
156465  }else if( rc==SQLITE_DONE ){
156466  p->nAutoincrmerge = 0;
156467  }
156468  rc = sqlite3_reset(pStmt);
156469  }
156470  }
156471  return rc;
156472 }
156473 
156474 /*
156475 ** Encode N integers as varints into a blob.
156476 */
156477 static void fts3EncodeIntArray(
156478  int N, /* The number of integers to encode */
156479  u32 *a, /* The integer values */
156480  char *zBuf, /* Write the BLOB here */
156481  int *pNBuf /* Write number of bytes if zBuf[] used here */
156482 ){
156483  int i, j;
156484  for(i=j=0; i<N; i++){
156485  j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
156486  }
156487  *pNBuf = j;
156488 }
156489 
156490 /*
156491 ** Decode a blob of varints into N integers
156492 */
156493 static void fts3DecodeIntArray(
156494  int N, /* The number of integers to decode */
156495  u32 *a, /* Write the integer values */
156496  const char *zBuf, /* The BLOB containing the varints */
156497  int nBuf /* size of the BLOB */
156498 ){
156499  int i, j;
156500  UNUSED_PARAMETER(nBuf);
156501  for(i=j=0; i<N; i++){
156502  sqlite3_int64 x;
156503  j += sqlite3Fts3GetVarint(&zBuf[j], &x);
156504  assert(j<=nBuf);
156505  a[i] = (u32)(x & 0xffffffff);
156506  }
156507 }
156508 
156509 /*
156510 ** Insert the sizes (in tokens) for each column of the document
156511 ** with docid equal to p->iPrevDocid. The sizes are encoded as
156512 ** a blob of varints.
156513 */
156514 static void fts3InsertDocsize(
156515  int *pRC, /* Result code */
156516  Fts3Table *p, /* Table into which to insert */
156517  u32 *aSz /* Sizes of each column, in tokens */
156518 ){
156519  char *pBlob; /* The BLOB encoding of the document size */
156520  int nBlob; /* Number of bytes in the BLOB */
156521  sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
156522  int rc; /* Result code from subfunctions */
156523 
156524  if( *pRC ) return;
156525  pBlob = sqlite3_malloc( 10*p->nColumn );
156526  if( pBlob==0 ){
156527  *pRC = SQLITE_NOMEM;
156528  return;
156529  }
156530  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
156531  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
156532  if( rc ){
156533  sqlite3_free(pBlob);
156534  *pRC = rc;
156535  return;
156536  }
156537  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
156538  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
156539  sqlite3_step(pStmt);
156540  *pRC = sqlite3_reset(pStmt);
156541 }
156542 
156543 /*
156544 ** Record 0 of the %_stat table contains a blob consisting of N varints,
156545 ** where N is the number of user defined columns in the fts3 table plus
156546 ** two. If nCol is the number of user defined columns, then values of the
156547 ** varints are set as follows:
156548 **
156549 ** Varint 0: Total number of rows in the table.
156550 **
156551 ** Varint 1..nCol: For each column, the total number of tokens stored in
156552 ** the column for all rows of the table.
156553 **
156554 ** Varint 1+nCol: The total size, in bytes, of all text values in all
156555 ** columns of all rows of the table.
156556 **
156557 */
156558 static void fts3UpdateDocTotals(
156559  int *pRC, /* The result code */
156560  Fts3Table *p, /* Table being updated */
156561  u32 *aSzIns, /* Size increases */
156562  u32 *aSzDel, /* Size decreases */
156563  int nChng /* Change in the number of documents */
156564 ){
156565  char *pBlob; /* Storage for BLOB written into %_stat */
156566  int nBlob; /* Size of BLOB written into %_stat */
156567  u32 *a; /* Array of integers that becomes the BLOB */
156568  sqlite3_stmt *pStmt; /* Statement for reading and writing */
156569  int i; /* Loop counter */
156570  int rc; /* Result code from subfunctions */
156571 
156572  const int nStat = p->nColumn+2;
156573 
156574  if( *pRC ) return;
156575  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
156576  if( a==0 ){
156577  *pRC = SQLITE_NOMEM;
156578  return;
156579  }
156580  pBlob = (char*)&a[nStat];
156581  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
156582  if( rc ){
156583  sqlite3_free(a);
156584  *pRC = rc;
156585  return;
156586  }
156587  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
156588  if( sqlite3_step(pStmt)==SQLITE_ROW ){
156589  fts3DecodeIntArray(nStat, a,
156590  sqlite3_column_blob(pStmt, 0),
156591  sqlite3_column_bytes(pStmt, 0));
156592  }else{
156593  memset(a, 0, sizeof(u32)*(nStat) );
156594  }
156595  rc = sqlite3_reset(pStmt);
156596  if( rc!=SQLITE_OK ){
156597  sqlite3_free(a);
156598  *pRC = rc;
156599  return;
156600  }
156601  if( nChng<0 && a[0]<(u32)(-nChng) ){
156602  a[0] = 0;
156603  }else{
156604  a[0] += nChng;
156605  }
156606  for(i=0; i<p->nColumn+1; i++){
156607  u32 x = a[i+1];
156608  if( x+aSzIns[i] < aSzDel[i] ){
156609  x = 0;
156610  }else{
156611  x = x + aSzIns[i] - aSzDel[i];
156612  }
156613  a[i+1] = x;
156614  }
156615  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
156616  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
156617  if( rc ){
156618  sqlite3_free(a);
156619  *pRC = rc;
156620  return;
156621  }
156622  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
156623  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
156624  sqlite3_step(pStmt);
156625  *pRC = sqlite3_reset(pStmt);
156626  sqlite3_free(a);
156627 }
156628 
156629 /*
156630 ** Merge the entire database so that there is one segment for each
156631 ** iIndex/iLangid combination.
156632 */
156633 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
156634  int bSeenDone = 0;
156635  int rc;
156636  sqlite3_stmt *pAllLangid = 0;
156637 
156638  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
156639  if( rc==SQLITE_OK ){
156640  int rc2;
156641  sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
156642  sqlite3_bind_int(pAllLangid, 2, p->nIndex);
156643  while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
156644  int i;
156645  int iLangid = sqlite3_column_int(pAllLangid, 0);
156646  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
156647  rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
156648  if( rc==SQLITE_DONE ){
156649  bSeenDone = 1;
156650  rc = SQLITE_OK;
156651  }
156652  }
156653  }
156654  rc2 = sqlite3_reset(pAllLangid);
156655  if( rc==SQLITE_OK ) rc = rc2;
156656  }
156657 
156658  sqlite3Fts3SegmentsClose(p);
156659  sqlite3Fts3PendingTermsClear(p);
156660 
156661  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
156662 }
156663 
156664 /*
156665 ** This function is called when the user executes the following statement:
156666 **
156667 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
156668 **
156669 ** The entire FTS index is discarded and rebuilt. If the table is one
156670 ** created using the content=xxx option, then the new index is based on
156671 ** the current contents of the xxx table. Otherwise, it is rebuilt based
156672 ** on the contents of the %_content table.
156673 */
156674 static int fts3DoRebuild(Fts3Table *p){
156675  int rc; /* Return Code */
156676 
156677  rc = fts3DeleteAll(p, 0);
156678  if( rc==SQLITE_OK ){
156679  u32 *aSz = 0;
156680  u32 *aSzIns = 0;
156681  u32 *aSzDel = 0;
156682  sqlite3_stmt *pStmt = 0;
156683  int nEntry = 0;
156684 
156685  /* Compose and prepare an SQL statement to loop through the content table */
156686  char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
156687  if( !zSql ){
156688  rc = SQLITE_NOMEM;
156689  }else{
156690  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
156691  sqlite3_free(zSql);
156692  }
156693 
156694  if( rc==SQLITE_OK ){
156695  int nByte = sizeof(u32) * (p->nColumn+1)*3;
156696  aSz = (u32 *)sqlite3_malloc(nByte);
156697  if( aSz==0 ){
156698  rc = SQLITE_NOMEM;
156699  }else{
156700  memset(aSz, 0, nByte);
156701  aSzIns = &aSz[p->nColumn+1];
156702  aSzDel = &aSzIns[p->nColumn+1];
156703  }
156704  }
156705 
156706  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
156707  int iCol;
156708  int iLangid = langidFromSelect(p, pStmt);
156709  rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
156710  memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
156711  for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
156712  if( p->abNotindexed[iCol]==0 ){
156713  const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
156714  rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
156715  aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
156716  }
156717  }
156718  if( p->bHasDocsize ){
156719  fts3InsertDocsize(&rc, p, aSz);
156720  }
156721  if( rc!=SQLITE_OK ){
156722  sqlite3_finalize(pStmt);
156723  pStmt = 0;
156724  }else{
156725  nEntry++;
156726  for(iCol=0; iCol<=p->nColumn; iCol++){
156727  aSzIns[iCol] += aSz[iCol];
156728  }
156729  }
156730  }
156731  if( p->bFts4 ){
156732  fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
156733  }
156734  sqlite3_free(aSz);
156735 
156736  if( pStmt ){
156737  int rc2 = sqlite3_finalize(pStmt);
156738  if( rc==SQLITE_OK ){
156739  rc = rc2;
156740  }
156741  }
156742  }
156743 
156744  return rc;
156745 }
156746 
156747 
156748 /*
156749 ** This function opens a cursor used to read the input data for an
156750 ** incremental merge operation. Specifically, it opens a cursor to scan
156751 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
156752 ** level iAbsLevel.
156753 */
156754 static int fts3IncrmergeCsr(
156755  Fts3Table *p, /* FTS3 table handle */
156756  sqlite3_int64 iAbsLevel, /* Absolute level to open */
156757  int nSeg, /* Number of segments to merge */
156758  Fts3MultiSegReader *pCsr /* Cursor object to populate */
156759 ){
156760  int rc; /* Return Code */
156761  sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
156762  int nByte; /* Bytes allocated at pCsr->apSegment[] */
156763 
156764  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
156765  memset(pCsr, 0, sizeof(*pCsr));
156766  nByte = sizeof(Fts3SegReader *) * nSeg;
156767  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
156768 
156769  if( pCsr->apSegment==0 ){
156770  rc = SQLITE_NOMEM;
156771  }else{
156772  memset(pCsr->apSegment, 0, nByte);
156773  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
156774  }
156775  if( rc==SQLITE_OK ){
156776  int i;
156777  int rc2;
156778  sqlite3_bind_int64(pStmt, 1, iAbsLevel);
156779  assert( pCsr->nSegment==0 );
156780  for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
156781  rc = sqlite3Fts3SegReaderNew(i, 0,
156782  sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
156783  sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
156784  sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
156785  sqlite3_column_blob(pStmt, 4), /* segdir.root */
156786  sqlite3_column_bytes(pStmt, 4), /* segdir.root */
156787  &pCsr->apSegment[i]
156788  );
156789  pCsr->nSegment++;
156790  }
156791  rc2 = sqlite3_reset(pStmt);
156792  if( rc==SQLITE_OK ) rc = rc2;
156793  }
156794 
156795  return rc;
156796 }
156797 
156798 typedef struct IncrmergeWriter IncrmergeWriter;
156799 typedef struct NodeWriter NodeWriter;
156800 typedef struct Blob Blob;
156801 typedef struct NodeReader NodeReader;
156802 
156803 /*
156804 ** An instance of the following structure is used as a dynamic buffer
156805 ** to build up nodes or other blobs of data in.
156806 **
156807 ** The function blobGrowBuffer() is used to extend the allocation.
156808 */
156809 struct Blob {
156810  char *a; /* Pointer to allocation */
156811  int n; /* Number of valid bytes of data in a[] */
156812  int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
156813 };
156814 
156815 /*
156816 ** This structure is used to build up buffers containing segment b-tree
156817 ** nodes (blocks).
156818 */
156819 struct NodeWriter {
156820  sqlite3_int64 iBlock; /* Current block id */
156821  Blob key; /* Last key written to the current block */
156822  Blob block; /* Current block image */
156823 };
156824 
156825 /*
156826 ** An object of this type contains the state required to create or append
156827 ** to an appendable b-tree segment.
156828 */
156829 struct IncrmergeWriter {
156830  int nLeafEst; /* Space allocated for leaf blocks */
156831  int nWork; /* Number of leaf pages flushed */
156832  sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
156833  int iIdx; /* Index of *output* segment in iAbsLevel+1 */
156834  sqlite3_int64 iStart; /* Block number of first allocated block */
156835  sqlite3_int64 iEnd; /* Block number of last allocated block */
156836  sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
156837  u8 bNoLeafData; /* If true, store 0 for segment size */
156838  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
156839 };
156840 
156841 /*
156842 ** An object of the following type is used to read data from a single
156843 ** FTS segment node. See the following functions:
156844 **
156845 ** nodeReaderInit()
156846 ** nodeReaderNext()
156847 ** nodeReaderRelease()
156848 */
156849 struct NodeReader {
156850  const char *aNode;
156851  int nNode;
156852  int iOff; /* Current offset within aNode[] */
156853 
156854  /* Output variables. Containing the current node entry. */
156855  sqlite3_int64 iChild; /* Pointer to child node */
156856  Blob term; /* Current term */
156857  const char *aDoclist; /* Pointer to doclist */
156858  int nDoclist; /* Size of doclist in bytes */
156859 };
156860 
156861 /*
156862 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
156863 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
156864 ** bytes in size, extend (realloc) it to be so.
156865 **
156866 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
156867 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
156868 ** to reflect the new size of the pBlob->a[] buffer.
156869 */
156870 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
156871  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
156872  int nAlloc = nMin;
156873  char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
156874  if( a ){
156875  pBlob->nAlloc = nAlloc;
156876  pBlob->a = a;
156877  }else{
156878  *pRc = SQLITE_NOMEM;
156879  }
156880  }
156881 }
156882 
156883 /*
156884 ** Attempt to advance the node-reader object passed as the first argument to
156885 ** the next entry on the node.
156886 **
156887 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
156888 ** Otherwise return SQLITE_OK. If there is no next entry on the node
156889 ** (e.g. because the current entry is the last) set NodeReader->aNode to
156890 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
156891 ** variables for the new entry.
156892 */
156893 static int nodeReaderNext(NodeReader *p){
156894  int bFirst = (p->term.n==0); /* True for first term on the node */
156895  int nPrefix = 0; /* Bytes to copy from previous term */
156896  int nSuffix = 0; /* Bytes to append to the prefix */
156897  int rc = SQLITE_OK; /* Return code */
156898 
156899  assert( p->aNode );
156900  if( p->iChild && bFirst==0 ) p->iChild++;
156901  if( p->iOff>=p->nNode ){
156902  /* EOF */
156903  p->aNode = 0;
156904  }else{
156905  if( bFirst==0 ){
156906  p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
156907  }
156908  p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
156909 
156910  blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
156911  if( rc==SQLITE_OK ){
156912  memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
156913  p->term.n = nPrefix+nSuffix;
156914  p->iOff += nSuffix;
156915  if( p->iChild==0 ){
156916  p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
156917  p->aDoclist = &p->aNode[p->iOff];
156918  p->iOff += p->nDoclist;
156919  }
156920  }
156921  }
156922 
156923  assert( p->iOff<=p->nNode );
156924 
156925  return rc;
156926 }
156927 
156928 /*
156929 ** Release all dynamic resources held by node-reader object *p.
156930 */
156931 static void nodeReaderRelease(NodeReader *p){
156932  sqlite3_free(p->term.a);
156933 }
156934 
156935 /*
156936 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
156937 **
156938 ** If successful, SQLITE_OK is returned and the NodeReader object set to
156939 ** point to the first entry on the node (if any). Otherwise, an SQLite
156940 ** error code is returned.
156941 */
156942 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
156943  memset(p, 0, sizeof(NodeReader));
156944  p->aNode = aNode;
156945  p->nNode = nNode;
156946 
156947  /* Figure out if this is a leaf or an internal node. */
156948  if( p->aNode[0] ){
156949  /* An internal node. */
156950  p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
156951  }else{
156952  p->iOff = 1;
156953  }
156954 
156955  return nodeReaderNext(p);
156956 }
156957 
156958 /*
156959 ** This function is called while writing an FTS segment each time a leaf o
156960 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
156961 ** to be greater than the largest key on the node just written, but smaller
156962 ** than or equal to the first key that will be written to the next leaf
156963 ** node.
156964 **
156965 ** The block id of the leaf node just written to disk may be found in
156966 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
156967 */
156968 static int fts3IncrmergePush(
156969  Fts3Table *p, /* Fts3 table handle */
156970  IncrmergeWriter *pWriter, /* Writer object */
156971  const char *zTerm, /* Term to write to internal node */
156972  int nTerm /* Bytes at zTerm */
156973 ){
156974  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
156975  int iLayer;
156976 
156977  assert( nTerm>0 );
156978  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
156979  sqlite3_int64 iNextPtr = 0;
156980  NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
156981  int rc = SQLITE_OK;
156982  int nPrefix;
156983  int nSuffix;
156984  int nSpace;
156985 
156986  /* Figure out how much space the key will consume if it is written to
156987  ** the current node of layer iLayer. Due to the prefix compression,
156988  ** the space required changes depending on which node the key is to
156989  ** be added to. */
156990  nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
156991  nSuffix = nTerm - nPrefix;
156992  nSpace = sqlite3Fts3VarintLen(nPrefix);
156993  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
156994 
156995  if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
156996  /* If the current node of layer iLayer contains zero keys, or if adding
156997  ** the key to it will not cause it to grow to larger than nNodeSize
156998  ** bytes in size, write the key here. */
156999 
157000  Blob *pBlk = &pNode->block;
157001  if( pBlk->n==0 ){
157002  blobGrowBuffer(pBlk, p->nNodeSize, &rc);
157003  if( rc==SQLITE_OK ){
157004  pBlk->a[0] = (char)iLayer;
157005  pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
157006  }
157007  }
157008  blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
157009  blobGrowBuffer(&pNode->key, nTerm, &rc);
157010 
157011  if( rc==SQLITE_OK ){
157012  if( pNode->key.n ){
157013  pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
157014  }
157015  pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
157016  memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
157017  pBlk->n += nSuffix;
157018 
157019  memcpy(pNode->key.a, zTerm, nTerm);
157020  pNode->key.n = nTerm;
157021  }
157022  }else{
157023  /* Otherwise, flush the current node of layer iLayer to disk.
157024  ** Then allocate a new, empty sibling node. The key will be written
157025  ** into the parent of this node. */
157026  rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
157027 
157028  assert( pNode->block.nAlloc>=p->nNodeSize );
157029  pNode->block.a[0] = (char)iLayer;
157030  pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
157031 
157032  iNextPtr = pNode->iBlock;
157033  pNode->iBlock++;
157034  pNode->key.n = 0;
157035  }
157036 
157037  if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
157038  iPtr = iNextPtr;
157039  }
157040 
157041  assert( 0 );
157042  return 0;
157043 }
157044 
157045 /*
157046 ** Append a term and (optionally) doclist to the FTS segment node currently
157047 ** stored in blob *pNode. The node need not contain any terms, but the
157048 ** header must be written before this function is called.
157049 **
157050 ** A node header is a single 0x00 byte for a leaf node, or a height varint
157051 ** followed by the left-hand-child varint for an internal node.
157052 **
157053 ** The term to be appended is passed via arguments zTerm/nTerm. For a
157054 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
157055 ** node, both aDoclist and nDoclist must be passed 0.
157056 **
157057 ** If the size of the value in blob pPrev is zero, then this is the first
157058 ** term written to the node. Otherwise, pPrev contains a copy of the
157059 ** previous term. Before this function returns, it is updated to contain a
157060 ** copy of zTerm/nTerm.
157061 **
157062 ** It is assumed that the buffer associated with pNode is already large
157063 ** enough to accommodate the new entry. The buffer associated with pPrev
157064 ** is extended by this function if requrired.
157065 **
157066 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
157067 ** returned. Otherwise, SQLITE_OK.
157068 */
157069 static int fts3AppendToNode(
157070  Blob *pNode, /* Current node image to append to */
157071  Blob *pPrev, /* Buffer containing previous term written */
157072  const char *zTerm, /* New term to write */
157073  int nTerm, /* Size of zTerm in bytes */
157074  const char *aDoclist, /* Doclist (or NULL) to write */
157075  int nDoclist /* Size of aDoclist in bytes */
157076 ){
157077  int rc = SQLITE_OK; /* Return code */
157078  int bFirst = (pPrev->n==0); /* True if this is the first term written */
157079  int nPrefix; /* Size of term prefix in bytes */
157080  int nSuffix; /* Size of term suffix in bytes */
157081 
157082  /* Node must have already been started. There must be a doclist for a
157083  ** leaf node, and there must not be a doclist for an internal node. */
157084  assert( pNode->n>0 );
157085  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
157086 
157087  blobGrowBuffer(pPrev, nTerm, &rc);
157088  if( rc!=SQLITE_OK ) return rc;
157089 
157090  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
157091  nSuffix = nTerm - nPrefix;
157092  memcpy(pPrev->a, zTerm, nTerm);
157093  pPrev->n = nTerm;
157094 
157095  if( bFirst==0 ){
157096  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
157097  }
157098  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
157099  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
157100  pNode->n += nSuffix;
157101 
157102  if( aDoclist ){
157103  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
157104  memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
157105  pNode->n += nDoclist;
157106  }
157107 
157108  assert( pNode->n<=pNode->nAlloc );
157109 
157110  return SQLITE_OK;
157111 }
157112 
157113 /*
157114 ** Append the current term and doclist pointed to by cursor pCsr to the
157115 ** appendable b-tree segment opened for writing by pWriter.
157116 **
157117 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
157118 */
157119 static int fts3IncrmergeAppend(
157120  Fts3Table *p, /* Fts3 table handle */
157121  IncrmergeWriter *pWriter, /* Writer object */
157122  Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
157123 ){
157124  const char *zTerm = pCsr->zTerm;
157125  int nTerm = pCsr->nTerm;
157126  const char *aDoclist = pCsr->aDoclist;
157127  int nDoclist = pCsr->nDoclist;
157128  int rc = SQLITE_OK; /* Return code */
157129  int nSpace; /* Total space in bytes required on leaf */
157130  int nPrefix; /* Size of prefix shared with previous term */
157131  int nSuffix; /* Size of suffix (nTerm - nPrefix) */
157132  NodeWriter *pLeaf; /* Object used to write leaf nodes */
157133 
157134  pLeaf = &pWriter->aNodeWriter[0];
157135  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
157136  nSuffix = nTerm - nPrefix;
157137 
157138  nSpace = sqlite3Fts3VarintLen(nPrefix);
157139  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
157140  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
157141 
157142  /* If the current block is not empty, and if adding this term/doclist
157143  ** to the current block would make it larger than Fts3Table.nNodeSize
157144  ** bytes, write this block out to the database. */
157145  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
157146  rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
157147  pWriter->nWork++;
157148 
157149  /* Add the current term to the parent node. The term added to the
157150  ** parent must:
157151  **
157152  ** a) be greater than the largest term on the leaf node just written
157153  ** to the database (still available in pLeaf->key), and
157154  **
157155  ** b) be less than or equal to the term about to be added to the new
157156  ** leaf node (zTerm/nTerm).
157157  **
157158  ** In other words, it must be the prefix of zTerm 1 byte longer than
157159  ** the common prefix (if any) of zTerm and pWriter->zTerm.
157160  */
157161  if( rc==SQLITE_OK ){
157162  rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
157163  }
157164 
157165  /* Advance to the next output block */
157166  pLeaf->iBlock++;
157167  pLeaf->key.n = 0;
157168  pLeaf->block.n = 0;
157169 
157170  nSuffix = nTerm;
157171  nSpace = 1;
157172  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
157173  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
157174  }
157175 
157176  pWriter->nLeafData += nSpace;
157177  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
157178  if( rc==SQLITE_OK ){
157179  if( pLeaf->block.n==0 ){
157180  pLeaf->block.n = 1;
157181  pLeaf->block.a[0] = '\0';
157182  }
157183  rc = fts3AppendToNode(
157184  &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
157185  );
157186  }
157187 
157188  return rc;
157189 }
157190 
157191 /*
157192 ** This function is called to release all dynamic resources held by the
157193 ** merge-writer object pWriter, and if no error has occurred, to flush
157194 ** all outstanding node buffers held by pWriter to disk.
157195 **
157196 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
157197 ** is made to write any data to disk. Instead, this function serves only
157198 ** to release outstanding resources.
157199 **
157200 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
157201 ** flushing buffers to disk, *pRc is set to an SQLite error code before
157202 ** returning.
157203 */
157204 static void fts3IncrmergeRelease(
157205  Fts3Table *p, /* FTS3 table handle */
157206  IncrmergeWriter *pWriter, /* Merge-writer object */
157207  int *pRc /* IN/OUT: Error code */
157208 ){
157209  int i; /* Used to iterate through non-root layers */
157210  int iRoot; /* Index of root in pWriter->aNodeWriter */
157211  NodeWriter *pRoot; /* NodeWriter for root node */
157212  int rc = *pRc; /* Error code */
157213 
157214  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
157215  ** root node. If the segment fits entirely on a single leaf node, iRoot
157216  ** will be set to 0. If the root node is the parent of the leaves, iRoot
157217  ** will be 1. And so on. */
157218  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
157219  NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
157220  if( pNode->block.n>0 ) break;
157221  assert( *pRc || pNode->block.nAlloc==0 );
157222  assert( *pRc || pNode->key.nAlloc==0 );
157223  sqlite3_free(pNode->block.a);
157224  sqlite3_free(pNode->key.a);
157225  }
157226 
157227  /* Empty output segment. This is a no-op. */
157228  if( iRoot<0 ) return;
157229 
157230  /* The entire output segment fits on a single node. Normally, this means
157231  ** the node would be stored as a blob in the "root" column of the %_segdir
157232  ** table. However, this is not permitted in this case. The problem is that
157233  ** space has already been reserved in the %_segments table, and so the
157234  ** start_block and end_block fields of the %_segdir table must be populated.
157235  ** And, by design or by accident, released versions of FTS cannot handle
157236  ** segments that fit entirely on the root node with start_block!=0.
157237  **
157238  ** Instead, create a synthetic root node that contains nothing but a
157239  ** pointer to the single content node. So that the segment consists of a
157240  ** single leaf and a single interior (root) node.
157241  **
157242  ** Todo: Better might be to defer allocating space in the %_segments
157243  ** table until we are sure it is needed.
157244  */
157245  if( iRoot==0 ){
157246  Blob *pBlock = &pWriter->aNodeWriter[1].block;
157247  blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
157248  if( rc==SQLITE_OK ){
157249  pBlock->a[0] = 0x01;
157250  pBlock->n = 1 + sqlite3Fts3PutVarint(
157251  &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
157252  );
157253  }
157254  iRoot = 1;
157255  }
157256  pRoot = &pWriter->aNodeWriter[iRoot];
157257 
157258  /* Flush all currently outstanding nodes to disk. */
157259  for(i=0; i<iRoot; i++){
157260  NodeWriter *pNode = &pWriter->aNodeWriter[i];
157261  if( pNode->block.n>0 && rc==SQLITE_OK ){
157262  rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
157263  }
157264  sqlite3_free(pNode->block.a);
157265  sqlite3_free(pNode->key.a);
157266  }
157267 
157268  /* Write the %_segdir record. */
157269  if( rc==SQLITE_OK ){
157270  rc = fts3WriteSegdir(p,
157271  pWriter->iAbsLevel+1, /* level */
157272  pWriter->iIdx, /* idx */
157273  pWriter->iStart, /* start_block */
157274  pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
157275  pWriter->iEnd, /* end_block */
157276  (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
157277  pRoot->block.a, pRoot->block.n /* root */
157278  );
157279  }
157280  sqlite3_free(pRoot->block.a);
157281  sqlite3_free(pRoot->key.a);
157282 
157283  *pRc = rc;
157284 }
157285 
157286 /*
157287 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
157288 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
157289 ** the other, it is considered to be smaller than the other.
157290 **
157291 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
157292 ** if it is greater.
157293 */
157294 static int fts3TermCmp(
157295  const char *zLhs, int nLhs, /* LHS of comparison */
157296  const char *zRhs, int nRhs /* RHS of comparison */
157297 ){
157298  int nCmp = MIN(nLhs, nRhs);
157299  int res;
157300 
157301  res = memcmp(zLhs, zRhs, nCmp);
157302  if( res==0 ) res = nLhs - nRhs;
157303 
157304  return res;
157305 }
157306 
157307 
157308 /*
157309 ** Query to see if the entry in the %_segments table with blockid iEnd is
157310 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
157311 ** returning. Otherwise, set *pbRes to 0.
157312 **
157313 ** Or, if an error occurs while querying the database, return an SQLite
157314 ** error code. The final value of *pbRes is undefined in this case.
157315 **
157316 ** This is used to test if a segment is an "appendable" segment. If it
157317 ** is, then a NULL entry has been inserted into the %_segments table
157318 ** with blockid %_segdir.end_block.
157319 */
157320 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
157321  int bRes = 0; /* Result to set *pbRes to */
157322  sqlite3_stmt *pCheck = 0; /* Statement to query database with */
157323  int rc; /* Return code */
157324 
157325  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
157326  if( rc==SQLITE_OK ){
157327  sqlite3_bind_int64(pCheck, 1, iEnd);
157328  if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
157329  rc = sqlite3_reset(pCheck);
157330  }
157331 
157332  *pbRes = bRes;
157333  return rc;
157334 }
157335 
157336 /*
157337 ** This function is called when initializing an incremental-merge operation.
157338 ** It checks if the existing segment with index value iIdx at absolute level
157339 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
157340 ** merge-writer object *pWriter is initialized to write to it.
157341 **
157342 ** An existing segment can be appended to by an incremental merge if:
157343 **
157344 ** * It was initially created as an appendable segment (with all required
157345 ** space pre-allocated), and
157346 **
157347 ** * The first key read from the input (arguments zKey and nKey) is
157348 ** greater than the largest key currently stored in the potential
157349 ** output segment.
157350 */
157351 static int fts3IncrmergeLoad(
157352  Fts3Table *p, /* Fts3 table handle */
157353  sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
157354  int iIdx, /* Index of candidate output segment */
157355  const char *zKey, /* First key to write */
157356  int nKey, /* Number of bytes in nKey */
157357  IncrmergeWriter *pWriter /* Populate this object */
157358 ){
157359  int rc; /* Return code */
157360  sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
157361 
157362  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
157363  if( rc==SQLITE_OK ){
157364  sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
157365  sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
157366  sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
157367  const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
157368  int nRoot = 0; /* Size of aRoot[] in bytes */
157369  int rc2; /* Return code from sqlite3_reset() */
157370  int bAppendable = 0; /* Set to true if segment is appendable */
157371 
157372  /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
157373  sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
157374  sqlite3_bind_int(pSelect, 2, iIdx);
157375  if( sqlite3_step(pSelect)==SQLITE_ROW ){
157376  iStart = sqlite3_column_int64(pSelect, 1);
157377  iLeafEnd = sqlite3_column_int64(pSelect, 2);
157378  fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
157379  if( pWriter->nLeafData<0 ){
157380  pWriter->nLeafData = pWriter->nLeafData * -1;
157381  }
157382  pWriter->bNoLeafData = (pWriter->nLeafData==0);
157383  nRoot = sqlite3_column_bytes(pSelect, 4);
157384  aRoot = sqlite3_column_blob(pSelect, 4);
157385  }else{
157386  return sqlite3_reset(pSelect);
157387  }
157388 
157389  /* Check for the zero-length marker in the %_segments table */
157390  rc = fts3IsAppendable(p, iEnd, &bAppendable);
157391 
157392  /* Check that zKey/nKey is larger than the largest key the candidate */
157393  if( rc==SQLITE_OK && bAppendable ){
157394  char *aLeaf = 0;
157395  int nLeaf = 0;
157396 
157397  rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
157398  if( rc==SQLITE_OK ){
157399  NodeReader reader;
157400  for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
157401  rc==SQLITE_OK && reader.aNode;
157402  rc = nodeReaderNext(&reader)
157403  ){
157404  assert( reader.aNode );
157405  }
157406  if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
157407  bAppendable = 0;
157408  }
157409  nodeReaderRelease(&reader);
157410  }
157411  sqlite3_free(aLeaf);
157412  }
157413 
157414  if( rc==SQLITE_OK && bAppendable ){
157415  /* It is possible to append to this segment. Set up the IncrmergeWriter
157416  ** object to do so. */
157417  int i;
157418  int nHeight = (int)aRoot[0];
157419  NodeWriter *pNode;
157420 
157421  pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
157422  pWriter->iStart = iStart;
157423  pWriter->iEnd = iEnd;
157424  pWriter->iAbsLevel = iAbsLevel;
157425  pWriter->iIdx = iIdx;
157426 
157427  for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
157428  pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
157429  }
157430 
157431  pNode = &pWriter->aNodeWriter[nHeight];
157432  pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
157433  blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
157434  if( rc==SQLITE_OK ){
157435  memcpy(pNode->block.a, aRoot, nRoot);
157436  pNode->block.n = nRoot;
157437  }
157438 
157439  for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
157440  NodeReader reader;
157441  pNode = &pWriter->aNodeWriter[i];
157442 
157443  rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
157444  while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
157445  blobGrowBuffer(&pNode->key, reader.term.n, &rc);
157446  if( rc==SQLITE_OK ){
157447  memcpy(pNode->key.a, reader.term.a, reader.term.n);
157448  pNode->key.n = reader.term.n;
157449  if( i>0 ){
157450  char *aBlock = 0;
157451  int nBlock = 0;
157452  pNode = &pWriter->aNodeWriter[i-1];
157453  pNode->iBlock = reader.iChild;
157454  rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
157455  blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
157456  if( rc==SQLITE_OK ){
157457  memcpy(pNode->block.a, aBlock, nBlock);
157458  pNode->block.n = nBlock;
157459  }
157460  sqlite3_free(aBlock);
157461  }
157462  }
157463  nodeReaderRelease(&reader);
157464  }
157465  }
157466 
157467  rc2 = sqlite3_reset(pSelect);
157468  if( rc==SQLITE_OK ) rc = rc2;
157469  }
157470 
157471  return rc;
157472 }
157473 
157474 /*
157475 ** Determine the largest segment index value that exists within absolute
157476 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
157477 ** one before returning SQLITE_OK. Or, if there are no segments at all
157478 ** within level iAbsLevel, set *piIdx to zero.
157479 **
157480 ** If an error occurs, return an SQLite error code. The final value of
157481 ** *piIdx is undefined in this case.
157482 */
157483 static int fts3IncrmergeOutputIdx(
157484  Fts3Table *p, /* FTS Table handle */
157485  sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
157486  int *piIdx /* OUT: Next free index at iAbsLevel+1 */
157487 ){
157488  int rc;
157489  sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
157490 
157491  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
157492  if( rc==SQLITE_OK ){
157493  sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
157494  sqlite3_step(pOutputIdx);
157495  *piIdx = sqlite3_column_int(pOutputIdx, 0);
157496  rc = sqlite3_reset(pOutputIdx);
157497  }
157498 
157499  return rc;
157500 }
157501 
157502 /*
157503 ** Allocate an appendable output segment on absolute level iAbsLevel+1
157504 ** with idx value iIdx.
157505 **
157506 ** In the %_segdir table, a segment is defined by the values in three
157507 ** columns:
157508 **
157509 ** start_block
157510 ** leaves_end_block
157511 ** end_block
157512 **
157513 ** When an appendable segment is allocated, it is estimated that the
157514 ** maximum number of leaf blocks that may be required is the sum of the
157515 ** number of leaf blocks consumed by the input segments, plus the number
157516 ** of input segments, multiplied by two. This value is stored in stack
157517 ** variable nLeafEst.
157518 **
157519 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
157520 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
157521 ** array of leaf nodes starts at the first block allocated. The array
157522 ** of interior nodes that are parents of the leaf nodes start at block
157523 ** (start_block + (1 + end_block - start_block) / 16). And so on.
157524 **
157525 ** In the actual code below, the value "16" is replaced with the
157526 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
157527 */
157528 static int fts3IncrmergeWriter(
157529  Fts3Table *p, /* Fts3 table handle */
157530  sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
157531  int iIdx, /* Index of new output segment */
157532  Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
157533  IncrmergeWriter *pWriter /* Populate this object */
157534 ){
157535  int rc; /* Return Code */
157536  int i; /* Iterator variable */
157537  int nLeafEst = 0; /* Blocks allocated for leaf nodes */
157538  sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
157539  sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
157540 
157541  /* Calculate nLeafEst. */
157542  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
157543  if( rc==SQLITE_OK ){
157544  sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
157545  sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
157546  if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
157547  nLeafEst = sqlite3_column_int(pLeafEst, 0);
157548  }
157549  rc = sqlite3_reset(pLeafEst);
157550  }
157551  if( rc!=SQLITE_OK ) return rc;
157552 
157553  /* Calculate the first block to use in the output segment */
157554  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
157555  if( rc==SQLITE_OK ){
157556  if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
157557  pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
157558  pWriter->iEnd = pWriter->iStart - 1;
157559  pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
157560  }
157561  rc = sqlite3_reset(pFirstBlock);
157562  }
157563  if( rc!=SQLITE_OK ) return rc;
157564 
157565  /* Insert the marker in the %_segments table to make sure nobody tries
157566  ** to steal the space just allocated. This is also used to identify
157567  ** appendable segments. */
157568  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
157569  if( rc!=SQLITE_OK ) return rc;
157570 
157571  pWriter->iAbsLevel = iAbsLevel;
157572  pWriter->nLeafEst = nLeafEst;
157573  pWriter->iIdx = iIdx;
157574 
157575  /* Set up the array of NodeWriter objects */
157576  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
157577  pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
157578  }
157579  return SQLITE_OK;
157580 }
157581 
157582 /*
157583 ** Remove an entry from the %_segdir table. This involves running the
157584 ** following two statements:
157585 **
157586 ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
157587 ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
157588 **
157589 ** The DELETE statement removes the specific %_segdir level. The UPDATE
157590 ** statement ensures that the remaining segments have contiguously allocated
157591 ** idx values.
157592 */
157593 static int fts3RemoveSegdirEntry(
157594  Fts3Table *p, /* FTS3 table handle */
157595  sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
157596  int iIdx /* Index of %_segdir entry to delete */
157597 ){
157598  int rc; /* Return code */
157599  sqlite3_stmt *pDelete = 0; /* DELETE statement */
157600 
157601  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
157602  if( rc==SQLITE_OK ){
157603  sqlite3_bind_int64(pDelete, 1, iAbsLevel);
157604  sqlite3_bind_int(pDelete, 2, iIdx);
157605  sqlite3_step(pDelete);
157606  rc = sqlite3_reset(pDelete);
157607  }
157608 
157609  return rc;
157610 }
157611 
157612 /*
157613 ** One or more segments have just been removed from absolute level iAbsLevel.
157614 ** Update the 'idx' values of the remaining segments in the level so that
157615 ** the idx values are a contiguous sequence starting from 0.
157616 */
157617 static int fts3RepackSegdirLevel(
157618  Fts3Table *p, /* FTS3 table handle */
157619  sqlite3_int64 iAbsLevel /* Absolute level to repack */
157620 ){
157621  int rc; /* Return code */
157622  int *aIdx = 0; /* Array of remaining idx values */
157623  int nIdx = 0; /* Valid entries in aIdx[] */
157624  int nAlloc = 0; /* Allocated size of aIdx[] */
157625  int i; /* Iterator variable */
157626  sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
157627  sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
157628 
157629  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
157630  if( rc==SQLITE_OK ){
157631  int rc2;
157632  sqlite3_bind_int64(pSelect, 1, iAbsLevel);
157633  while( SQLITE_ROW==sqlite3_step(pSelect) ){
157634  if( nIdx>=nAlloc ){
157635  int *aNew;
157636  nAlloc += 16;
157637  aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
157638  if( !aNew ){
157639  rc = SQLITE_NOMEM;
157640  break;
157641  }
157642  aIdx = aNew;
157643  }
157644  aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
157645  }
157646  rc2 = sqlite3_reset(pSelect);
157647  if( rc==SQLITE_OK ) rc = rc2;
157648  }
157649 
157650  if( rc==SQLITE_OK ){
157651  rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
157652  }
157653  if( rc==SQLITE_OK ){
157654  sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
157655  }
157656 
157657  assert( p->bIgnoreSavepoint==0 );
157658  p->bIgnoreSavepoint = 1;
157659  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
157660  if( aIdx[i]!=i ){
157661  sqlite3_bind_int(pUpdate, 3, aIdx[i]);
157662  sqlite3_bind_int(pUpdate, 1, i);
157663  sqlite3_step(pUpdate);
157664  rc = sqlite3_reset(pUpdate);
157665  }
157666  }
157667  p->bIgnoreSavepoint = 0;
157668 
157669  sqlite3_free(aIdx);
157670  return rc;
157671 }
157672 
157673 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
157674  pNode->a[0] = (char)iHeight;
157675  if( iChild ){
157676  assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
157677  pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
157678  }else{
157679  assert( pNode->nAlloc>=1 );
157680  pNode->n = 1;
157681  }
157682 }
157683 
157684 /*
157685 ** The first two arguments are a pointer to and the size of a segment b-tree
157686 ** node. The node may be a leaf or an internal node.
157687 **
157688 ** This function creates a new node image in blob object *pNew by copying
157689 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
157690 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
157691 */
157692 static int fts3TruncateNode(
157693  const char *aNode, /* Current node image */
157694  int nNode, /* Size of aNode in bytes */
157695  Blob *pNew, /* OUT: Write new node image here */
157696  const char *zTerm, /* Omit all terms smaller than this */
157697  int nTerm, /* Size of zTerm in bytes */
157698  sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
157699 ){
157700  NodeReader reader; /* Reader object */
157701  Blob prev = {0, 0, 0}; /* Previous term written to new node */
157702  int rc = SQLITE_OK; /* Return code */
157703  int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
157704 
157705  /* Allocate required output space */
157706  blobGrowBuffer(pNew, nNode, &rc);
157707  if( rc!=SQLITE_OK ) return rc;
157708  pNew->n = 0;
157709 
157710  /* Populate new node buffer */
157711  for(rc = nodeReaderInit(&reader, aNode, nNode);
157712  rc==SQLITE_OK && reader.aNode;
157713  rc = nodeReaderNext(&reader)
157714  ){
157715  if( pNew->n==0 ){
157716  int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
157717  if( res<0 || (bLeaf==0 && res==0) ) continue;
157718  fts3StartNode(pNew, (int)aNode[0], reader.iChild);
157719  *piBlock = reader.iChild;
157720  }
157721  rc = fts3AppendToNode(
157722  pNew, &prev, reader.term.a, reader.term.n,
157723  reader.aDoclist, reader.nDoclist
157724  );
157725  if( rc!=SQLITE_OK ) break;
157726  }
157727  if( pNew->n==0 ){
157728  fts3StartNode(pNew, (int)aNode[0], reader.iChild);
157729  *piBlock = reader.iChild;
157730  }
157731  assert( pNew->n<=pNew->nAlloc );
157732 
157733  nodeReaderRelease(&reader);
157734  sqlite3_free(prev.a);
157735  return rc;
157736 }
157737 
157738 /*
157739 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
157740 ** level iAbsLevel. This may involve deleting entries from the %_segments
157741 ** table, and modifying existing entries in both the %_segments and %_segdir
157742 ** tables.
157743 **
157744 ** SQLITE_OK is returned if the segment is updated successfully. Or an
157745 ** SQLite error code otherwise.
157746 */
157747 static int fts3TruncateSegment(
157748  Fts3Table *p, /* FTS3 table handle */
157749  sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
157750  int iIdx, /* Index within level of segment to modify */
157751  const char *zTerm, /* Remove terms smaller than this */
157752  int nTerm /* Number of bytes in buffer zTerm */
157753 ){
157754  int rc = SQLITE_OK; /* Return code */
157755  Blob root = {0,0,0}; /* New root page image */
157756  Blob block = {0,0,0}; /* Buffer used for any other block */
157757  sqlite3_int64 iBlock = 0; /* Block id */
157758  sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
157759  sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
157760  sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
157761 
157762  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
157763  if( rc==SQLITE_OK ){
157764  int rc2; /* sqlite3_reset() return code */
157765  sqlite3_bind_int64(pFetch, 1, iAbsLevel);
157766  sqlite3_bind_int(pFetch, 2, iIdx);
157767  if( SQLITE_ROW==sqlite3_step(pFetch) ){
157768  const char *aRoot = sqlite3_column_blob(pFetch, 4);
157769  int nRoot = sqlite3_column_bytes(pFetch, 4);
157770  iOldStart = sqlite3_column_int64(pFetch, 1);
157771  rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
157772  }
157773  rc2 = sqlite3_reset(pFetch);
157774  if( rc==SQLITE_OK ) rc = rc2;
157775  }
157776 
157777  while( rc==SQLITE_OK && iBlock ){
157778  char *aBlock = 0;
157779  int nBlock = 0;
157780  iNewStart = iBlock;
157781 
157782  rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
157783  if( rc==SQLITE_OK ){
157784  rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
157785  }
157786  if( rc==SQLITE_OK ){
157787  rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
157788  }
157789  sqlite3_free(aBlock);
157790  }
157791 
157792  /* Variable iNewStart now contains the first valid leaf node. */
157793  if( rc==SQLITE_OK && iNewStart ){
157794  sqlite3_stmt *pDel = 0;
157795  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
157796  if( rc==SQLITE_OK ){
157797  sqlite3_bind_int64(pDel, 1, iOldStart);
157798  sqlite3_bind_int64(pDel, 2, iNewStart-1);
157799  sqlite3_step(pDel);
157800  rc = sqlite3_reset(pDel);
157801  }
157802  }
157803 
157804  if( rc==SQLITE_OK ){
157805  sqlite3_stmt *pChomp = 0;
157806  rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
157807  if( rc==SQLITE_OK ){
157808  sqlite3_bind_int64(pChomp, 1, iNewStart);
157809  sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
157810  sqlite3_bind_int64(pChomp, 3, iAbsLevel);
157811  sqlite3_bind_int(pChomp, 4, iIdx);
157812  sqlite3_step(pChomp);
157813  rc = sqlite3_reset(pChomp);
157814  }
157815  }
157816 
157817  sqlite3_free(root.a);
157818  sqlite3_free(block.a);
157819  return rc;
157820 }
157821 
157822 /*
157823 ** This function is called after an incrmental-merge operation has run to
157824 ** merge (or partially merge) two or more segments from absolute level
157825 ** iAbsLevel.
157826 **
157827 ** Each input segment is either removed from the db completely (if all of
157828 ** its data was copied to the output segment by the incrmerge operation)
157829 ** or modified in place so that it no longer contains those entries that
157830 ** have been duplicated in the output segment.
157831 */
157832 static int fts3IncrmergeChomp(
157833  Fts3Table *p, /* FTS table handle */
157834  sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
157835  Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
157836  int *pnRem /* Number of segments not deleted */
157837 ){
157838  int i;
157839  int nRem = 0;
157840  int rc = SQLITE_OK;
157841 
157842  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
157843  Fts3SegReader *pSeg = 0;
157844  int j;
157845 
157846  /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
157847  ** somewhere in the pCsr->apSegment[] array. */
157848  for(j=0; ALWAYS(j<pCsr->nSegment); j++){
157849  pSeg = pCsr->apSegment[j];
157850  if( pSeg->iIdx==i ) break;
157851  }
157852  assert( j<pCsr->nSegment && pSeg->iIdx==i );
157853 
157854  if( pSeg->aNode==0 ){
157855  /* Seg-reader is at EOF. Remove the entire input segment. */
157856  rc = fts3DeleteSegment(p, pSeg);
157857  if( rc==SQLITE_OK ){
157858  rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
157859  }
157860  *pnRem = 0;
157861  }else{
157862  /* The incremental merge did not copy all the data from this
157863  ** segment to the upper level. The segment is modified in place
157864  ** so that it contains no keys smaller than zTerm/nTerm. */
157865  const char *zTerm = pSeg->zTerm;
157866  int nTerm = pSeg->nTerm;
157867  rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
157868  nRem++;
157869  }
157870  }
157871 
157872  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
157873  rc = fts3RepackSegdirLevel(p, iAbsLevel);
157874  }
157875 
157876  *pnRem = nRem;
157877  return rc;
157878 }
157879 
157880 /*
157881 ** Store an incr-merge hint in the database.
157882 */
157883 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
157884  sqlite3_stmt *pReplace = 0;
157885  int rc; /* Return code */
157886 
157887  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
157888  if( rc==SQLITE_OK ){
157889  sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
157890  sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
157891  sqlite3_step(pReplace);
157892  rc = sqlite3_reset(pReplace);
157893  }
157894 
157895  return rc;
157896 }
157897 
157898 /*
157899 ** Load an incr-merge hint from the database. The incr-merge hint, if one
157900 ** exists, is stored in the rowid==1 row of the %_stat table.
157901 **
157902 ** If successful, populate blob *pHint with the value read from the %_stat
157903 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
157904 ** SQLite error code.
157905 */
157906 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
157907  sqlite3_stmt *pSelect = 0;
157908  int rc;
157909 
157910  pHint->n = 0;
157911  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
157912  if( rc==SQLITE_OK ){
157913  int rc2;
157914  sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
157915  if( SQLITE_ROW==sqlite3_step(pSelect) ){
157916  const char *aHint = sqlite3_column_blob(pSelect, 0);
157917  int nHint = sqlite3_column_bytes(pSelect, 0);
157918  if( aHint ){
157919  blobGrowBuffer(pHint, nHint, &rc);
157920  if( rc==SQLITE_OK ){
157921  memcpy(pHint->a, aHint, nHint);
157922  pHint->n = nHint;
157923  }
157924  }
157925  }
157926  rc2 = sqlite3_reset(pSelect);
157927  if( rc==SQLITE_OK ) rc = rc2;
157928  }
157929 
157930  return rc;
157931 }
157932 
157933 /*
157934 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
157935 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
157936 ** consists of two varints, the absolute level number of the input segments
157937 ** and the number of input segments.
157938 **
157939 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
157940 ** set *pRc to an SQLite error code before returning.
157941 */
157942 static void fts3IncrmergeHintPush(
157943  Blob *pHint, /* Hint blob to append to */
157944  i64 iAbsLevel, /* First varint to store in hint */
157945  int nInput, /* Second varint to store in hint */
157946  int *pRc /* IN/OUT: Error code */
157947 ){
157948  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
157949  if( *pRc==SQLITE_OK ){
157950  pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
157951  pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
157952  }
157953 }
157954 
157955 /*
157956 ** Read the last entry (most recently pushed) from the hint blob *pHint
157957 ** and then remove the entry. Write the two values read to *piAbsLevel and
157958 ** *pnInput before returning.
157959 **
157960 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
157961 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
157962 */
157963 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
157964  const int nHint = pHint->n;
157965  int i;
157966 
157967  i = pHint->n-2;
157968  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
157969  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
157970 
157971  pHint->n = i;
157972  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
157973  i += fts3GetVarint32(&pHint->a[i], pnInput);
157974  if( i!=nHint ) return FTS_CORRUPT_VTAB;
157975 
157976  return SQLITE_OK;
157977 }
157978 
157979 
157980 /*
157981 ** Attempt an incremental merge that writes nMerge leaf blocks.
157982 **
157983 ** Incremental merges happen nMin segments at a time. The segments
157984 ** to be merged are the nMin oldest segments (the ones with the smallest
157985 ** values for the _segdir.idx field) in the highest level that contains
157986 ** at least nMin segments. Multiple merges might occur in an attempt to
157987 ** write the quota of nMerge leaf blocks.
157988 */
157989 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
157990  int rc; /* Return code */
157991  int nRem = nMerge; /* Number of leaf pages yet to be written */
157992  Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
157993  Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
157994  IncrmergeWriter *pWriter; /* Writer object */
157995  int nSeg = 0; /* Number of input segments */
157996  sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
157997  Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
157998  int bDirtyHint = 0; /* True if blob 'hint' has been modified */
157999 
158000  /* Allocate space for the cursor, filter and writer objects */
158001  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
158002  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
158003  if( !pWriter ) return SQLITE_NOMEM;
158004  pFilter = (Fts3SegFilter *)&pWriter[1];
158005  pCsr = (Fts3MultiSegReader *)&pFilter[1];
158006 
158007  rc = fts3IncrmergeHintLoad(p, &hint);
158008  while( rc==SQLITE_OK && nRem>0 ){
158009  const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
158010  sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
158011  int bUseHint = 0; /* True if attempting to append */
158012  int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
158013 
158014  /* Search the %_segdir table for the absolute level with the smallest
158015  ** relative level number that contains at least nMin segments, if any.
158016  ** If one is found, set iAbsLevel to the absolute level number and
158017  ** nSeg to nMin. If no level with at least nMin segments can be found,
158018  ** set nSeg to -1.
158019  */
158020  rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
158021  sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
158022  if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
158023  iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
158024  nSeg = sqlite3_column_int(pFindLevel, 1);
158025  assert( nSeg>=2 );
158026  }else{
158027  nSeg = -1;
158028  }
158029  rc = sqlite3_reset(pFindLevel);
158030 
158031  /* If the hint read from the %_stat table is not empty, check if the
158032  ** last entry in it specifies a relative level smaller than or equal
158033  ** to the level identified by the block above (if any). If so, this
158034  ** iteration of the loop will work on merging at the hinted level.
158035  */
158036  if( rc==SQLITE_OK && hint.n ){
158037  int nHint = hint.n;
158038  sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
158039  int nHintSeg = 0; /* Hint number of segments */
158040 
158041  rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
158042  if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
158043  iAbsLevel = iHintAbsLevel;
158044  nSeg = nHintSeg;
158045  bUseHint = 1;
158046  bDirtyHint = 1;
158047  }else{
158048  /* This undoes the effect of the HintPop() above - so that no entry
158049  ** is removed from the hint blob. */
158050  hint.n = nHint;
158051  }
158052  }
158053 
158054  /* If nSeg is less that zero, then there is no level with at least
158055  ** nMin segments and no hint in the %_stat table. No work to do.
158056  ** Exit early in this case. */
158057  if( nSeg<0 ) break;
158058 
158059  /* Open a cursor to iterate through the contents of the oldest nSeg
158060  ** indexes of absolute level iAbsLevel. If this cursor is opened using
158061  ** the 'hint' parameters, it is possible that there are less than nSeg
158062  ** segments available in level iAbsLevel. In this case, no work is
158063  ** done on iAbsLevel - fall through to the next iteration of the loop
158064  ** to start work on some other level. */
158065  memset(pWriter, 0, nAlloc);
158066  pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
158067 
158068  if( rc==SQLITE_OK ){
158069  rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
158070  assert( bUseHint==1 || bUseHint==0 );
158071  if( iIdx==0 || (bUseHint && iIdx==1) ){
158072  int bIgnore = 0;
158073  rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
158074  if( bIgnore ){
158075  pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
158076  }
158077  }
158078  }
158079 
158080  if( rc==SQLITE_OK ){
158081  rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
158082  }
158083  if( SQLITE_OK==rc && pCsr->nSegment==nSeg
158084  && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
158085  && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
158086  ){
158087  if( bUseHint && iIdx>0 ){
158088  const char *zKey = pCsr->zTerm;
158089  int nKey = pCsr->nTerm;
158090  rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
158091  }else{
158092  rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
158093  }
158094 
158095  if( rc==SQLITE_OK && pWriter->nLeafEst ){
158096  fts3LogMerge(nSeg, iAbsLevel);
158097  do {
158098  rc = fts3IncrmergeAppend(p, pWriter, pCsr);
158099  if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
158100  if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
158101  }while( rc==SQLITE_ROW );
158102 
158103  /* Update or delete the input segments */
158104  if( rc==SQLITE_OK ){
158105  nRem -= (1 + pWriter->nWork);
158106  rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
158107  if( nSeg!=0 ){
158108  bDirtyHint = 1;
158109  fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
158110  }
158111  }
158112  }
158113 
158114  if( nSeg!=0 ){
158115  pWriter->nLeafData = pWriter->nLeafData * -1;
158116  }
158117  fts3IncrmergeRelease(p, pWriter, &rc);
158118  if( nSeg==0 && pWriter->bNoLeafData==0 ){
158119  fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
158120  }
158121  }
158122 
158123  sqlite3Fts3SegReaderFinish(pCsr);
158124  }
158125 
158126  /* Write the hint values into the %_stat table for the next incr-merger */
158127  if( bDirtyHint && rc==SQLITE_OK ){
158128  rc = fts3IncrmergeHintStore(p, &hint);
158129  }
158130 
158131  sqlite3_free(pWriter);
158132  sqlite3_free(hint.a);
158133  return rc;
158134 }
158135 
158136 /*
158137 ** Convert the text beginning at *pz into an integer and return
158138 ** its value. Advance *pz to point to the first character past
158139 ** the integer.
158140 */
158141 static int fts3Getint(const char **pz){
158142  const char *z = *pz;
158143  int i = 0;
158144  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
158145  *pz = z;
158146  return i;
158147 }
158148 
158149 /*
158150 ** Process statements of the form:
158151 **
158152 ** INSERT INTO table(table) VALUES('merge=A,B');
158153 **
158154 ** A and B are integers that decode to be the number of leaf pages
158155 ** written for the merge, and the minimum number of segments on a level
158156 ** before it will be selected for a merge, respectively.
158157 */
158158 static int fts3DoIncrmerge(
158159  Fts3Table *p, /* FTS3 table handle */
158160  const char *zParam /* Nul-terminated string containing "A,B" */
158161 ){
158162  int rc;
158163  int nMin = (FTS3_MERGE_COUNT / 2);
158164  int nMerge = 0;
158165  const char *z = zParam;
158166 
158167  /* Read the first integer value */
158168  nMerge = fts3Getint(&z);
158169 
158170  /* If the first integer value is followed by a ',', read the second
158171  ** integer value. */
158172  if( z[0]==',' && z[1]!='\0' ){
158173  z++;
158174  nMin = fts3Getint(&z);
158175  }
158176 
158177  if( z[0]!='\0' || nMin<2 ){
158178  rc = SQLITE_ERROR;
158179  }else{
158180  rc = SQLITE_OK;
158181  if( !p->bHasStat ){
158182  assert( p->bFts4==0 );
158183  sqlite3Fts3CreateStatTable(&rc, p);
158184  }
158185  if( rc==SQLITE_OK ){
158186  rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
158187  }
158188  sqlite3Fts3SegmentsClose(p);
158189  }
158190  return rc;
158191 }
158192 
158193 /*
158194 ** Process statements of the form:
158195 **
158196 ** INSERT INTO table(table) VALUES('automerge=X');
158197 **
158198 ** where X is an integer. X==0 means to turn automerge off. X!=0 means
158199 ** turn it on. The setting is persistent.
158200 */
158201 static int fts3DoAutoincrmerge(
158202  Fts3Table *p, /* FTS3 table handle */
158203  const char *zParam /* Nul-terminated string containing boolean */
158204 ){
158205  int rc = SQLITE_OK;
158206  sqlite3_stmt *pStmt = 0;
158207  p->nAutoincrmerge = fts3Getint(&zParam);
158208  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
158209  p->nAutoincrmerge = 8;
158210  }
158211  if( !p->bHasStat ){
158212  assert( p->bFts4==0 );
158213  sqlite3Fts3CreateStatTable(&rc, p);
158214  if( rc ) return rc;
158215  }
158216  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
158217  if( rc ) return rc;
158218  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
158219  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
158220  sqlite3_step(pStmt);
158221  rc = sqlite3_reset(pStmt);
158222  return rc;
158223 }
158224 
158225 /*
158226 ** Return a 64-bit checksum for the FTS index entry specified by the
158227 ** arguments to this function.
158228 */
158229 static u64 fts3ChecksumEntry(
158230  const char *zTerm, /* Pointer to buffer containing term */
158231  int nTerm, /* Size of zTerm in bytes */
158232  int iLangid, /* Language id for current row */
158233  int iIndex, /* Index (0..Fts3Table.nIndex-1) */
158234  i64 iDocid, /* Docid for current row. */
158235  int iCol, /* Column number */
158236  int iPos /* Position */
158237 ){
158238  int i;
158239  u64 ret = (u64)iDocid;
158240 
158241  ret += (ret<<3) + iLangid;
158242  ret += (ret<<3) + iIndex;
158243  ret += (ret<<3) + iCol;
158244  ret += (ret<<3) + iPos;
158245  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
158246 
158247  return ret;
158248 }
158249 
158250 /*
158251 ** Return a checksum of all entries in the FTS index that correspond to
158252 ** language id iLangid. The checksum is calculated by XORing the checksums
158253 ** of each individual entry (see fts3ChecksumEntry()) together.
158254 **
158255 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
158256 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
158257 ** return value is undefined in this case.
158258 */
158259 static u64 fts3ChecksumIndex(
158260  Fts3Table *p, /* FTS3 table handle */
158261  int iLangid, /* Language id to return cksum for */
158262  int iIndex, /* Index to cksum (0..p->nIndex-1) */
158263  int *pRc /* OUT: Return code */
158264 ){
158265  Fts3SegFilter filter;
158266  Fts3MultiSegReader csr;
158267  int rc;
158268  u64 cksum = 0;
158269 
158270  assert( *pRc==SQLITE_OK );
158271 
158272  memset(&filter, 0, sizeof(filter));
158273  memset(&csr, 0, sizeof(csr));
158274  filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
158275  filter.flags |= FTS3_SEGMENT_SCAN;
158276 
158277  rc = sqlite3Fts3SegReaderCursor(
158278  p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
158279  );
158280  if( rc==SQLITE_OK ){
158281  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
158282  }
158283 
158284  if( rc==SQLITE_OK ){
158285  while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
158286  char *pCsr = csr.aDoclist;
158287  char *pEnd = &pCsr[csr.nDoclist];
158288 
158289  i64 iDocid = 0;
158290  i64 iCol = 0;
158291  i64 iPos = 0;
158292 
158293  pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
158294  while( pCsr<pEnd ){
158295  i64 iVal = 0;
158296  pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
158297  if( pCsr<pEnd ){
158298  if( iVal==0 || iVal==1 ){
158299  iCol = 0;
158300  iPos = 0;
158301  if( iVal ){
158302  pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
158303  }else{
158304  pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
158305  iDocid += iVal;
158306  }
158307  }else{
158308  iPos += (iVal - 2);
158309  cksum = cksum ^ fts3ChecksumEntry(
158310  csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
158311  (int)iCol, (int)iPos
158312  );
158313  }
158314  }
158315  }
158316  }
158317  }
158318  sqlite3Fts3SegReaderFinish(&csr);
158319 
158320  *pRc = rc;
158321  return cksum;
158322 }
158323 
158324 /*
158325 ** Check if the contents of the FTS index match the current contents of the
158326 ** content table. If no error occurs and the contents do match, set *pbOk
158327 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
158328 ** to false before returning.
158329 **
158330 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
158331 ** code. The final value of *pbOk is undefined in this case.
158332 */
158333 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
158334  int rc = SQLITE_OK; /* Return code */
158335  u64 cksum1 = 0; /* Checksum based on FTS index contents */
158336  u64 cksum2 = 0; /* Checksum based on %_content contents */
158337  sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
158338 
158339  /* This block calculates the checksum according to the FTS index. */
158340  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
158341  if( rc==SQLITE_OK ){
158342  int rc2;
158343  sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
158344  sqlite3_bind_int(pAllLangid, 2, p->nIndex);
158345  while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
158346  int iLangid = sqlite3_column_int(pAllLangid, 0);
158347  int i;
158348  for(i=0; i<p->nIndex; i++){
158349  cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
158350  }
158351  }
158352  rc2 = sqlite3_reset(pAllLangid);
158353  if( rc==SQLITE_OK ) rc = rc2;
158354  }
158355 
158356  /* This block calculates the checksum according to the %_content table */
158357  if( rc==SQLITE_OK ){
158358  sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
158359  sqlite3_stmt *pStmt = 0;
158360  char *zSql;
158361 
158362  zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
158363  if( !zSql ){
158364  rc = SQLITE_NOMEM;
158365  }else{
158366  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
158367  sqlite3_free(zSql);
158368  }
158369 
158370  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
158371  i64 iDocid = sqlite3_column_int64(pStmt, 0);
158372  int iLang = langidFromSelect(p, pStmt);
158373  int iCol;
158374 
158375  for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
158376  if( p->abNotindexed[iCol]==0 ){
158377  const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
158378  int nText = sqlite3_column_bytes(pStmt, iCol+1);
158379  sqlite3_tokenizer_cursor *pT = 0;
158380 
158381  rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
158382  while( rc==SQLITE_OK ){
158383  char const *zToken; /* Buffer containing token */
158384  int nToken = 0; /* Number of bytes in token */
158385  int iDum1 = 0, iDum2 = 0; /* Dummy variables */
158386  int iPos = 0; /* Position of token in zText */
158387 
158388  rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
158389  if( rc==SQLITE_OK ){
158390  int i;
158391  cksum2 = cksum2 ^ fts3ChecksumEntry(
158392  zToken, nToken, iLang, 0, iDocid, iCol, iPos
158393  );
158394  for(i=1; i<p->nIndex; i++){
158395  if( p->aIndex[i].nPrefix<=nToken ){
158396  cksum2 = cksum2 ^ fts3ChecksumEntry(
158397  zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
158398  );
158399  }
158400  }
158401  }
158402  }
158403  if( pT ) pModule->xClose(pT);
158404  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
158405  }
158406  }
158407  }
158408 
158409  sqlite3_finalize(pStmt);
158410  }
158411 
158412  *pbOk = (cksum1==cksum2);
158413  return rc;
158414 }
158415 
158416 /*
158417 ** Run the integrity-check. If no error occurs and the current contents of
158418 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
158419 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
158420 **
158421 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
158422 ** error code.
158423 **
158424 ** The integrity-check works as follows. For each token and indexed token
158425 ** prefix in the document set, a 64-bit checksum is calculated (by code
158426 ** in fts3ChecksumEntry()) based on the following:
158427 **
158428 ** + The index number (0 for the main index, 1 for the first prefix
158429 ** index etc.),
158430 ** + The token (or token prefix) text itself,
158431 ** + The language-id of the row it appears in,
158432 ** + The docid of the row it appears in,
158433 ** + The column it appears in, and
158434 ** + The tokens position within that column.
158435 **
158436 ** The checksums for all entries in the index are XORed together to create
158437 ** a single checksum for the entire index.
158438 **
158439 ** The integrity-check code calculates the same checksum in two ways:
158440 **
158441 ** 1. By scanning the contents of the FTS index, and
158442 ** 2. By scanning and tokenizing the content table.
158443 **
158444 ** If the two checksums are identical, the integrity-check is deemed to have
158445 ** passed.
158446 */
158447 static int fts3DoIntegrityCheck(
158448  Fts3Table *p /* FTS3 table handle */
158449 ){
158450  int rc;
158451  int bOk = 0;
158452  rc = fts3IntegrityCheck(p, &bOk);
158453  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
158454  return rc;
158455 }
158456 
158457 /*
158458 ** Handle a 'special' INSERT of the form:
158459 **
158460 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
158461 **
158462 ** Argument pVal contains the result of <expr>. Currently the only
158463 ** meaningful value to insert is the text 'optimize'.
158464 */
158465 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
158466  int rc; /* Return Code */
158467  const char *zVal = (const char *)sqlite3_value_text(pVal);
158468  int nVal = sqlite3_value_bytes(pVal);
158469 
158470  if( !zVal ){
158471  return SQLITE_NOMEM;
158472  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
158473  rc = fts3DoOptimize(p, 0);
158474  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
158475  rc = fts3DoRebuild(p);
158476  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
158477  rc = fts3DoIntegrityCheck(p);
158478  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
158479  rc = fts3DoIncrmerge(p, &zVal[6]);
158480  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
158481  rc = fts3DoAutoincrmerge(p, &zVal[10]);
158482 #ifdef SQLITE_TEST
158483  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
158484  p->nNodeSize = atoi(&zVal[9]);
158485  rc = SQLITE_OK;
158486  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
158487  p->nMaxPendingData = atoi(&zVal[11]);
158488  rc = SQLITE_OK;
158489  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
158490  p->bNoIncrDoclist = atoi(&zVal[21]);
158491  rc = SQLITE_OK;
158492 #endif
158493  }else{
158494  rc = SQLITE_ERROR;
158495  }
158496 
158497  return rc;
158498 }
158499 
158500 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
158501 /*
158502 ** Delete all cached deferred doclists. Deferred doclists are cached
158503 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
158504 */
158505 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
158506  Fts3DeferredToken *pDef;
158507  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
158508  fts3PendingListDelete(pDef->pList);
158509  pDef->pList = 0;
158510  }
158511 }
158512 
158513 /*
158514 ** Free all entries in the pCsr->pDeffered list. Entries are added to
158515 ** this list using sqlite3Fts3DeferToken().
158516 */
158517 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
158518  Fts3DeferredToken *pDef;
158519  Fts3DeferredToken *pNext;
158520  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
158521  pNext = pDef->pNext;
158522  fts3PendingListDelete(pDef->pList);
158523  sqlite3_free(pDef);
158524  }
158525  pCsr->pDeferred = 0;
158526 }
158527 
158528 /*
158529 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
158530 ** based on the row that pCsr currently points to.
158531 **
158532 ** A deferred-doclist is like any other doclist with position information
158533 ** included, except that it only contains entries for a single row of the
158534 ** table, not for all rows.
158535 */
158536 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
158537  int rc = SQLITE_OK; /* Return code */
158538  if( pCsr->pDeferred ){
158539  int i; /* Used to iterate through table columns */
158540  sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
158541  Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
158542 
158543  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
158544  sqlite3_tokenizer *pT = p->pTokenizer;
158545  sqlite3_tokenizer_module const *pModule = pT->pModule;
158546 
158547  assert( pCsr->isRequireSeek==0 );
158548  iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
158549 
158550  for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
158551  if( p->abNotindexed[i]==0 ){
158552  const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
158553  sqlite3_tokenizer_cursor *pTC = 0;
158554 
158555  rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
158556  while( rc==SQLITE_OK ){
158557  char const *zToken; /* Buffer containing token */
158558  int nToken = 0; /* Number of bytes in token */
158559  int iDum1 = 0, iDum2 = 0; /* Dummy variables */
158560  int iPos = 0; /* Position of token in zText */
158561 
158562  rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
158563  for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
158564  Fts3PhraseToken *pPT = pDef->pToken;
158565  if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
158566  && (pPT->bFirst==0 || iPos==0)
158567  && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
158568  && (0==memcmp(zToken, pPT->z, pPT->n))
158569  ){
158570  fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
158571  }
158572  }
158573  }
158574  if( pTC ) pModule->xClose(pTC);
158575  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
158576  }
158577  }
158578 
158579  for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
158580  if( pDef->pList ){
158581  rc = fts3PendingListAppendVarint(&pDef->pList, 0);
158582  }
158583  }
158584  }
158585 
158586  return rc;
158587 }
158588 
158589 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
158590  Fts3DeferredToken *p,
158591  char **ppData,
158592  int *pnData
158593 ){
158594  char *pRet;
158595  int nSkip;
158596  sqlite3_int64 dummy;
158597 
158598  *ppData = 0;
158599  *pnData = 0;
158600 
158601  if( p->pList==0 ){
158602  return SQLITE_OK;
158603  }
158604 
158605  pRet = (char *)sqlite3_malloc(p->pList->nData);
158606  if( !pRet ) return SQLITE_NOMEM;
158607 
158608  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
158609  *pnData = p->pList->nData - nSkip;
158610  *ppData = pRet;
158611 
158612  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
158613  return SQLITE_OK;
158614 }
158615 
158616 /*
158617 ** Add an entry for token pToken to the pCsr->pDeferred list.
158618 */
158619 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
158620  Fts3Cursor *pCsr, /* Fts3 table cursor */
158621  Fts3PhraseToken *pToken, /* Token to defer */
158622  int iCol /* Column that token must appear in (or -1) */
158623 ){
158624  Fts3DeferredToken *pDeferred;
158625  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
158626  if( !pDeferred ){
158627  return SQLITE_NOMEM;
158628  }
158629  memset(pDeferred, 0, sizeof(*pDeferred));
158630  pDeferred->pToken = pToken;
158631  pDeferred->pNext = pCsr->pDeferred;
158632  pDeferred->iCol = iCol;
158633  pCsr->pDeferred = pDeferred;
158634 
158635  assert( pToken->pDeferred==0 );
158636  pToken->pDeferred = pDeferred;
158637 
158638  return SQLITE_OK;
158639 }
158640 #endif
158641 
158642 /*
158643 ** SQLite value pRowid contains the rowid of a row that may or may not be
158644 ** present in the FTS3 table. If it is, delete it and adjust the contents
158645 ** of subsiduary data structures accordingly.
158646 */
158647 static int fts3DeleteByRowid(
158648  Fts3Table *p,
158649  sqlite3_value *pRowid,
158650  int *pnChng, /* IN/OUT: Decrement if row is deleted */
158651  u32 *aSzDel
158652 ){
158653  int rc = SQLITE_OK; /* Return code */
158654  int bFound = 0; /* True if *pRowid really is in the table */
158655 
158656  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
158657  if( bFound && rc==SQLITE_OK ){
158658  int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
158659  rc = fts3IsEmpty(p, pRowid, &isEmpty);
158660  if( rc==SQLITE_OK ){
158661  if( isEmpty ){
158662  /* Deleting this row means the whole table is empty. In this case
158663  ** delete the contents of all three tables and throw away any
158664  ** data in the pendingTerms hash table. */
158665  rc = fts3DeleteAll(p, 1);
158666  *pnChng = 0;
158667  memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
158668  }else{
158669  *pnChng = *pnChng - 1;
158670  if( p->zContentTbl==0 ){
158671  fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
158672  }
158673  if( p->bHasDocsize ){
158674  fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
158675  }
158676  }
158677  }
158678  }
158679 
158680  return rc;
158681 }
158682 
158683 /*
158684 ** This function does the work for the xUpdate method of FTS3 virtual
158685 ** tables. The schema of the virtual table being:
158686 **
158687 ** CREATE TABLE <table name>(
158688 ** <user columns>,
158689 ** <table name> HIDDEN,
158690 ** docid HIDDEN,
158691 ** <langid> HIDDEN
158692 ** );
158693 **
158694 **
158695 */
158696 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
158697  sqlite3_vtab *pVtab, /* FTS3 vtab object */
158698  int nArg, /* Size of argument array */
158699  sqlite3_value **apVal, /* Array of arguments */
158700  sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
158701 ){
158702  Fts3Table *p = (Fts3Table *)pVtab;
158703  int rc = SQLITE_OK; /* Return Code */
158704  int isRemove = 0; /* True for an UPDATE or DELETE */
158705  u32 *aSzIns = 0; /* Sizes of inserted documents */
158706  u32 *aSzDel = 0; /* Sizes of deleted documents */
158707  int nChng = 0; /* Net change in number of documents */
158708  int bInsertDone = 0;
158709 
158710  /* At this point it must be known if the %_stat table exists or not.
158711  ** So bHasStat may not be 2. */
158712  assert( p->bHasStat==0 || p->bHasStat==1 );
158713 
158714  assert( p->pSegments==0 );
158715  assert(
158716  nArg==1 /* DELETE operations */
158717  || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
158718  );
158719 
158720  /* Check for a "special" INSERT operation. One of the form:
158721  **
158722  ** INSERT INTO xyz(xyz) VALUES('command');
158723  */
158724  if( nArg>1
158725  && sqlite3_value_type(apVal[0])==SQLITE_NULL
158726  && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
158727  ){
158728  rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
158729  goto update_out;
158730  }
158731 
158732  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
158733  rc = SQLITE_CONSTRAINT;
158734  goto update_out;
158735  }
158736 
158737  /* Allocate space to hold the change in document sizes */
158738  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
158739  if( aSzDel==0 ){
158740  rc = SQLITE_NOMEM;
158741  goto update_out;
158742  }
158743  aSzIns = &aSzDel[p->nColumn+1];
158744  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
158745 
158746  rc = fts3Writelock(p);
158747  if( rc!=SQLITE_OK ) goto update_out;
158748 
158749  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
158750  ** value, then this operation requires constraint handling.
158751  **
158752  ** If the on-conflict mode is REPLACE, this means that the existing row
158753  ** should be deleted from the database before inserting the new row. Or,
158754  ** if the on-conflict mode is other than REPLACE, then this method must
158755  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
158756  ** modify the database file.
158757  */
158758  if( nArg>1 && p->zContentTbl==0 ){
158759  /* Find the value object that holds the new rowid value. */
158760  sqlite3_value *pNewRowid = apVal[3+p->nColumn];
158761  if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
158762  pNewRowid = apVal[1];
158763  }
158764 
158765  if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
158766  sqlite3_value_type(apVal[0])==SQLITE_NULL
158767  || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
158768  )){
158769  /* The new rowid is not NULL (in this case the rowid will be
158770  ** automatically assigned and there is no chance of a conflict), and
158771  ** the statement is either an INSERT or an UPDATE that modifies the
158772  ** rowid column. So if the conflict mode is REPLACE, then delete any
158773  ** existing row with rowid=pNewRowid.
158774  **
158775  ** Or, if the conflict mode is not REPLACE, insert the new record into
158776  ** the %_content table. If we hit the duplicate rowid constraint (or any
158777  ** other error) while doing so, return immediately.
158778  **
158779  ** This branch may also run if pNewRowid contains a value that cannot
158780  ** be losslessly converted to an integer. In this case, the eventual
158781  ** call to fts3InsertData() (either just below or further on in this
158782  ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
158783  ** invoked, it will delete zero rows (since no row will have
158784  ** docid=$pNewRowid if $pNewRowid is not an integer value).
158785  */
158786  if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
158787  rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
158788  }else{
158789  rc = fts3InsertData(p, apVal, pRowid);
158790  bInsertDone = 1;
158791  }
158792  }
158793  }
158794  if( rc!=SQLITE_OK ){
158795  goto update_out;
158796  }
158797 
158798  /* If this is a DELETE or UPDATE operation, remove the old record. */
158799  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
158800  assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
158801  rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
158802  isRemove = 1;
158803  }
158804 
158805  /* If this is an INSERT or UPDATE operation, insert the new record. */
158806  if( nArg>1 && rc==SQLITE_OK ){
158807  int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
158808  if( bInsertDone==0 ){
158809  rc = fts3InsertData(p, apVal, pRowid);
158810  if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
158811  rc = FTS_CORRUPT_VTAB;
158812  }
158813  }
158814  if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
158815  rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
158816  }
158817  if( rc==SQLITE_OK ){
158818  assert( p->iPrevDocid==*pRowid );
158819  rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
158820  }
158821  if( p->bHasDocsize ){
158822  fts3InsertDocsize(&rc, p, aSzIns);
158823  }
158824  nChng++;
158825  }
158826 
158827  if( p->bFts4 ){
158828  fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
158829  }
158830 
158831  update_out:
158832  sqlite3_free(aSzDel);
158833  sqlite3Fts3SegmentsClose(p);
158834  return rc;
158835 }
158836 
158837 /*
158838 ** Flush any data in the pending-terms hash table to disk. If successful,
158839 ** merge all segments in the database (including the new segment, if
158840 ** there was any data to flush) into a single segment.
158841 */
158842 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
158843  int rc;
158844  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
158845  if( rc==SQLITE_OK ){
158846  rc = fts3DoOptimize(p, 1);
158847  if( rc==SQLITE_OK || rc==SQLITE_DONE ){
158848  int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
158849  if( rc2!=SQLITE_OK ) rc = rc2;
158850  }else{
158851  sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
158852  sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
158853  }
158854  }
158855  sqlite3Fts3SegmentsClose(p);
158856  return rc;
158857 }
158858 
158859 #endif
158860 
158861 /************** End of fts3_write.c ******************************************/
158862 /************** Begin file fts3_snippet.c ************************************/
158863 /*
158864 ** 2009 Oct 23
158865 **
158866 ** The author disclaims copyright to this source code. In place of
158867 ** a legal notice, here is a blessing:
158868 **
158869 ** May you do good and not evil.
158870 ** May you find forgiveness for yourself and forgive others.
158871 ** May you share freely, never taking more than you give.
158872 **
158873 ******************************************************************************
158874 */
158875 
158876 /* #include "fts3Int.h" */
158877 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
158878 
158879 /* #include <string.h> */
158880 /* #include <assert.h> */
158881 
158882 /*
158883 ** Characters that may appear in the second argument to matchinfo().
158884 */
158885 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
158886 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
158887 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
158888 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
158889 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
158890 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
158891 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
158892 #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
158893 #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
158894 
158895 /*
158896 ** The default value for the second argument to matchinfo().
158897 */
158898 #define FTS3_MATCHINFO_DEFAULT "pcx"
158899 
158900 
158901 /*
158902 ** Used as an fts3ExprIterate() context when loading phrase doclists to
158903 ** Fts3Expr.aDoclist[]/nDoclist.
158904 */
158905 typedef struct LoadDoclistCtx LoadDoclistCtx;
158906 struct LoadDoclistCtx {
158907  Fts3Cursor *pCsr; /* FTS3 Cursor */
158908  int nPhrase; /* Number of phrases seen so far */
158909  int nToken; /* Number of tokens seen so far */
158910 };
158911 
158912 /*
158913 ** The following types are used as part of the implementation of the
158914 ** fts3BestSnippet() routine.
158915 */
158916 typedef struct SnippetIter SnippetIter;
158917 typedef struct SnippetPhrase SnippetPhrase;
158918 typedef struct SnippetFragment SnippetFragment;
158919 
158920 struct SnippetIter {
158921  Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
158922  int iCol; /* Extract snippet from this column */
158923  int nSnippet; /* Requested snippet length (in tokens) */
158924  int nPhrase; /* Number of phrases in query */
158925  SnippetPhrase *aPhrase; /* Array of size nPhrase */
158926  int iCurrent; /* First token of current snippet */
158927 };
158928 
158929 struct SnippetPhrase {
158930  int nToken; /* Number of tokens in phrase */
158931  char *pList; /* Pointer to start of phrase position list */
158932  int iHead; /* Next value in position list */
158933  char *pHead; /* Position list data following iHead */
158934  int iTail; /* Next value in trailing position list */
158935  char *pTail; /* Position list data following iTail */
158936 };
158937 
158938 struct SnippetFragment {
158939  int iCol; /* Column snippet is extracted from */
158940  int iPos; /* Index of first token in snippet */
158941  u64 covered; /* Mask of query phrases covered */
158942  u64 hlmask; /* Mask of snippet terms to highlight */
158943 };
158944 
158945 /*
158946 ** This type is used as an fts3ExprIterate() context object while
158947 ** accumulating the data returned by the matchinfo() function.
158948 */
158949 typedef struct MatchInfo MatchInfo;
158950 struct MatchInfo {
158951  Fts3Cursor *pCursor; /* FTS3 Cursor */
158952  int nCol; /* Number of columns in table */
158953  int nPhrase; /* Number of matchable phrases in query */
158954  sqlite3_int64 nDoc; /* Number of docs in database */
158955  char flag;
158956  u32 *aMatchinfo; /* Pre-allocated buffer */
158957 };
158958 
158959 /*
158960 ** An instance of this structure is used to manage a pair of buffers, each
158961 ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
158962 ** for details.
158963 */
158964 struct MatchinfoBuffer {
158965  u8 aRef[3];
158966  int nElem;
158967  int bGlobal; /* Set if global data is loaded */
158968  char *zMatchinfo;
158969  u32 aMatchinfo[1];
158970 };
158971 
158972 
158973 /*
158974 ** The snippet() and offsets() functions both return text values. An instance
158975 ** of the following structure is used to accumulate those values while the
158976 ** functions are running. See fts3StringAppend() for details.
158977 */
158978 typedef struct StrBuffer StrBuffer;
158979 struct StrBuffer {
158980  char *z; /* Pointer to buffer containing string */
158981  int n; /* Length of z in bytes (excl. nul-term) */
158982  int nAlloc; /* Allocated size of buffer z in bytes */
158983 };
158984 
158985 
158986 /*************************************************************************
158987 ** Start of MatchinfoBuffer code.
158988 */
158989 
158990 /*
158991 ** Allocate a two-slot MatchinfoBuffer object.
158992 */
158993 static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
158994  MatchinfoBuffer *pRet;
158995  int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
158996  int nStr = (int)strlen(zMatchinfo);
158997 
158998  pRet = sqlite3_malloc(nByte + nStr+1);
158999  if( pRet ){
159000  memset(pRet, 0, nByte);
159001  pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
159002  pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
159003  pRet->nElem = nElem;
159004  pRet->zMatchinfo = ((char*)pRet) + nByte;
159005  memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
159006  pRet->aRef[0] = 1;
159007  }
159008 
159009  return pRet;
159010 }
159011 
159012 static void fts3MIBufferFree(void *p){
159013  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
159014 
159015  assert( (u32*)p==&pBuf->aMatchinfo[1]
159016  || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
159017  );
159018  if( (u32*)p==&pBuf->aMatchinfo[1] ){
159019  pBuf->aRef[1] = 0;
159020  }else{
159021  pBuf->aRef[2] = 0;
159022  }
159023 
159024  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
159025  sqlite3_free(pBuf);
159026  }
159027 }
159028 
159029 static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
159030  void (*xRet)(void*) = 0;
159031  u32 *aOut = 0;
159032 
159033  if( p->aRef[1]==0 ){
159034  p->aRef[1] = 1;
159035  aOut = &p->aMatchinfo[1];
159036  xRet = fts3MIBufferFree;
159037  }
159038  else if( p->aRef[2]==0 ){
159039  p->aRef[2] = 1;
159040  aOut = &p->aMatchinfo[p->nElem+2];
159041  xRet = fts3MIBufferFree;
159042  }else{
159043  aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
159044  if( aOut ){
159045  xRet = sqlite3_free;
159046  if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
159047  }
159048  }
159049 
159050  *paOut = aOut;
159051  return xRet;
159052 }
159053 
159054 static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
159055  p->bGlobal = 1;
159056  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
159057 }
159058 
159059 /*
159060 ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
159061 */
159062 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
159063  if( p ){
159064  assert( p->aRef[0]==1 );
159065  p->aRef[0] = 0;
159066  if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
159067  sqlite3_free(p);
159068  }
159069  }
159070 }
159071 
159072 /*
159073 ** End of MatchinfoBuffer code.
159074 *************************************************************************/
159075 
159076 
159077 /*
159078 ** This function is used to help iterate through a position-list. A position
159079 ** list is a list of unique integers, sorted from smallest to largest. Each
159080 ** element of the list is represented by an FTS3 varint that takes the value
159081 ** of the difference between the current element and the previous one plus
159082 ** two. For example, to store the position-list:
159083 **
159084 ** 4 9 113
159085 **
159086 ** the three varints:
159087 **
159088 ** 6 7 106
159089 **
159090 ** are encoded.
159091 **
159092 ** When this function is called, *pp points to the start of an element of
159093 ** the list. *piPos contains the value of the previous entry in the list.
159094 ** After it returns, *piPos contains the value of the next element of the
159095 ** list and *pp is advanced to the following varint.
159096 */
159097 static void fts3GetDeltaPosition(char **pp, int *piPos){
159098  int iVal;
159099  *pp += fts3GetVarint32(*pp, &iVal);
159100  *piPos += (iVal-2);
159101 }
159102 
159103 /*
159104 ** Helper function for fts3ExprIterate() (see below).
159105 */
159106 static int fts3ExprIterate2(
159107  Fts3Expr *pExpr, /* Expression to iterate phrases of */
159108  int *piPhrase, /* Pointer to phrase counter */
159109  int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
159110  void *pCtx /* Second argument to pass to callback */
159111 ){
159112  int rc; /* Return code */
159113  int eType = pExpr->eType; /* Type of expression node pExpr */
159114 
159115  if( eType!=FTSQUERY_PHRASE ){
159116  assert( pExpr->pLeft && pExpr->pRight );
159117  rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
159118  if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
159119  rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
159120  }
159121  }else{
159122  rc = x(pExpr, *piPhrase, pCtx);
159123  (*piPhrase)++;
159124  }
159125  return rc;
159126 }
159127 
159128 /*
159129 ** Iterate through all phrase nodes in an FTS3 query, except those that
159130 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
159131 ** For each phrase node found, the supplied callback function is invoked.
159132 **
159133 ** If the callback function returns anything other than SQLITE_OK,
159134 ** the iteration is abandoned and the error code returned immediately.
159135 ** Otherwise, SQLITE_OK is returned after a callback has been made for
159136 ** all eligible phrase nodes.
159137 */
159138 static int fts3ExprIterate(
159139  Fts3Expr *pExpr, /* Expression to iterate phrases of */
159140  int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
159141  void *pCtx /* Second argument to pass to callback */
159142 ){
159143  int iPhrase = 0; /* Variable used as the phrase counter */
159144  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
159145 }
159146 
159147 
159148 /*
159149 ** This is an fts3ExprIterate() callback used while loading the doclists
159150 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
159151 ** fts3ExprLoadDoclists().
159152 */
159153 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
159154  int rc = SQLITE_OK;
159155  Fts3Phrase *pPhrase = pExpr->pPhrase;
159156  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
159157 
159158  UNUSED_PARAMETER(iPhrase);
159159 
159160  p->nPhrase++;
159161  p->nToken += pPhrase->nToken;
159162 
159163  return rc;
159164 }
159165 
159166 /*
159167 ** Load the doclists for each phrase in the query associated with FTS3 cursor
159168 ** pCsr.
159169 **
159170 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
159171 ** phrases in the expression (all phrases except those directly or
159172 ** indirectly descended from the right-hand-side of a NOT operator). If
159173 ** pnToken is not NULL, then it is set to the number of tokens in all
159174 ** matchable phrases of the expression.
159175 */
159176 static int fts3ExprLoadDoclists(
159177  Fts3Cursor *pCsr, /* Fts3 cursor for current query */
159178  int *pnPhrase, /* OUT: Number of phrases in query */
159179  int *pnToken /* OUT: Number of tokens in query */
159180 ){
159181  int rc; /* Return Code */
159182  LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
159183  sCtx.pCsr = pCsr;
159184  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
159185  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
159186  if( pnToken ) *pnToken = sCtx.nToken;
159187  return rc;
159188 }
159189 
159190 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
159191  (*(int *)ctx)++;
159192  pExpr->iPhrase = iPhrase;
159193  return SQLITE_OK;
159194 }
159195 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
159196  int nPhrase = 0;
159197  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
159198  return nPhrase;
159199 }
159200 
159201 /*
159202 ** Advance the position list iterator specified by the first two
159203 ** arguments so that it points to the first element with a value greater
159204 ** than or equal to parameter iNext.
159205 */
159206 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
159207  char *pIter = *ppIter;
159208  if( pIter ){
159209  int iIter = *piIter;
159210 
159211  while( iIter<iNext ){
159212  if( 0==(*pIter & 0xFE) ){
159213  iIter = -1;
159214  pIter = 0;
159215  break;
159216  }
159217  fts3GetDeltaPosition(&pIter, &iIter);
159218  }
159219 
159220  *piIter = iIter;
159221  *ppIter = pIter;
159222  }
159223 }
159224 
159225 /*
159226 ** Advance the snippet iterator to the next candidate snippet.
159227 */
159228 static int fts3SnippetNextCandidate(SnippetIter *pIter){
159229  int i; /* Loop counter */
159230 
159231  if( pIter->iCurrent<0 ){
159232  /* The SnippetIter object has just been initialized. The first snippet
159233  ** candidate always starts at offset 0 (even if this candidate has a
159234  ** score of 0.0).
159235  */
159236  pIter->iCurrent = 0;
159237 
159238  /* Advance the 'head' iterator of each phrase to the first offset that
159239  ** is greater than or equal to (iNext+nSnippet).
159240  */
159241  for(i=0; i<pIter->nPhrase; i++){
159242  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
159243  fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
159244  }
159245  }else{
159246  int iStart;
159247  int iEnd = 0x7FFFFFFF;
159248 
159249  for(i=0; i<pIter->nPhrase; i++){
159250  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
159251  if( pPhrase->pHead && pPhrase->iHead<iEnd ){
159252  iEnd = pPhrase->iHead;
159253  }
159254  }
159255  if( iEnd==0x7FFFFFFF ){
159256  return 1;
159257  }
159258 
159259  pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
159260  for(i=0; i<pIter->nPhrase; i++){
159261  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
159262  fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
159263  fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
159264  }
159265  }
159266 
159267  return 0;
159268 }
159269 
159270 /*
159271 ** Retrieve information about the current candidate snippet of snippet
159272 ** iterator pIter.
159273 */
159274 static void fts3SnippetDetails(
159275  SnippetIter *pIter, /* Snippet iterator */
159276  u64 mCovered, /* Bitmask of phrases already covered */
159277  int *piToken, /* OUT: First token of proposed snippet */
159278  int *piScore, /* OUT: "Score" for this snippet */
159279  u64 *pmCover, /* OUT: Bitmask of phrases covered */
159280  u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
159281 ){
159282  int iStart = pIter->iCurrent; /* First token of snippet */
159283  int iScore = 0; /* Score of this snippet */
159284  int i; /* Loop counter */
159285  u64 mCover = 0; /* Mask of phrases covered by this snippet */
159286  u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
159287 
159288  for(i=0; i<pIter->nPhrase; i++){
159289  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
159290  if( pPhrase->pTail ){
159291  char *pCsr = pPhrase->pTail;
159292  int iCsr = pPhrase->iTail;
159293 
159294  while( iCsr<(iStart+pIter->nSnippet) ){
159295  int j;
159296  u64 mPhrase = (u64)1 << i;
159297  u64 mPos = (u64)1 << (iCsr - iStart);
159298  assert( iCsr>=iStart );
159299  if( (mCover|mCovered)&mPhrase ){
159300  iScore++;
159301  }else{
159302  iScore += 1000;
159303  }
159304  mCover |= mPhrase;
159305 
159306  for(j=0; j<pPhrase->nToken; j++){
159307  mHighlight |= (mPos>>j);
159308  }
159309 
159310  if( 0==(*pCsr & 0x0FE) ) break;
159311  fts3GetDeltaPosition(&pCsr, &iCsr);
159312  }
159313  }
159314  }
159315 
159316  /* Set the output variables before returning. */
159317  *piToken = iStart;
159318  *piScore = iScore;
159319  *pmCover = mCover;
159320  *pmHighlight = mHighlight;
159321 }
159322 
159323 /*
159324 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
159325 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
159326 */
159327 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
159328  SnippetIter *p = (SnippetIter *)ctx;
159329  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
159330  char *pCsr;
159331  int rc;
159332 
159333  pPhrase->nToken = pExpr->pPhrase->nToken;
159334  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
159335  assert( rc==SQLITE_OK || pCsr==0 );
159336  if( pCsr ){
159337  int iFirst = 0;
159338  pPhrase->pList = pCsr;
159339  fts3GetDeltaPosition(&pCsr, &iFirst);
159340  assert( iFirst>=0 );
159341  pPhrase->pHead = pCsr;
159342  pPhrase->pTail = pCsr;
159343  pPhrase->iHead = iFirst;
159344  pPhrase->iTail = iFirst;
159345  }else{
159346  assert( rc!=SQLITE_OK || (
159347  pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
159348  ));
159349  }
159350 
159351  return rc;
159352 }
159353 
159354 /*
159355 ** Select the fragment of text consisting of nFragment contiguous tokens
159356 ** from column iCol that represent the "best" snippet. The best snippet
159357 ** is the snippet with the highest score, where scores are calculated
159358 ** by adding:
159359 **
159360 ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
159361 **
159362 ** (b) +1000 points for the first occurrence of each matchable phrase in
159363 ** the snippet for which the corresponding mCovered bit is not set.
159364 **
159365 ** The selected snippet parameters are stored in structure *pFragment before
159366 ** returning. The score of the selected snippet is stored in *piScore
159367 ** before returning.
159368 */
159369 static int fts3BestSnippet(
159370  int nSnippet, /* Desired snippet length */
159371  Fts3Cursor *pCsr, /* Cursor to create snippet for */
159372  int iCol, /* Index of column to create snippet from */
159373  u64 mCovered, /* Mask of phrases already covered */
159374  u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
159375  SnippetFragment *pFragment, /* OUT: Best snippet found */
159376  int *piScore /* OUT: Score of snippet pFragment */
159377 ){
159378  int rc; /* Return Code */
159379  int nList; /* Number of phrases in expression */
159380  SnippetIter sIter; /* Iterates through snippet candidates */
159381  int nByte; /* Number of bytes of space to allocate */
159382  int iBestScore = -1; /* Best snippet score found so far */
159383  int i; /* Loop counter */
159384 
159385  memset(&sIter, 0, sizeof(sIter));
159386 
159387  /* Iterate through the phrases in the expression to count them. The same
159388  ** callback makes sure the doclists are loaded for each phrase.
159389  */
159390  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
159391  if( rc!=SQLITE_OK ){
159392  return rc;
159393  }
159394 
159395  /* Now that it is known how many phrases there are, allocate and zero
159396  ** the required space using malloc().
159397  */
159398  nByte = sizeof(SnippetPhrase) * nList;
159399  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
159400  if( !sIter.aPhrase ){
159401  return SQLITE_NOMEM;
159402  }
159403  memset(sIter.aPhrase, 0, nByte);
159404 
159405  /* Initialize the contents of the SnippetIter object. Then iterate through
159406  ** the set of phrases in the expression to populate the aPhrase[] array.
159407  */
159408  sIter.pCsr = pCsr;
159409  sIter.iCol = iCol;
159410  sIter.nSnippet = nSnippet;
159411  sIter.nPhrase = nList;
159412  sIter.iCurrent = -1;
159413  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
159414  if( rc==SQLITE_OK ){
159415 
159416  /* Set the *pmSeen output variable. */
159417  for(i=0; i<nList; i++){
159418  if( sIter.aPhrase[i].pHead ){
159419  *pmSeen |= (u64)1 << i;
159420  }
159421  }
159422 
159423  /* Loop through all candidate snippets. Store the best snippet in
159424  ** *pFragment. Store its associated 'score' in iBestScore.
159425  */
159426  pFragment->iCol = iCol;
159427  while( !fts3SnippetNextCandidate(&sIter) ){
159428  int iPos;
159429  int iScore;
159430  u64 mCover;
159431  u64 mHighlite;
159432  fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
159433  assert( iScore>=0 );
159434  if( iScore>iBestScore ){
159435  pFragment->iPos = iPos;
159436  pFragment->hlmask = mHighlite;
159437  pFragment->covered = mCover;
159438  iBestScore = iScore;
159439  }
159440  }
159441 
159442  *piScore = iBestScore;
159443  }
159444  sqlite3_free(sIter.aPhrase);
159445  return rc;
159446 }
159447 
159448 
159449 /*
159450 ** Append a string to the string-buffer passed as the first argument.
159451 **
159452 ** If nAppend is negative, then the length of the string zAppend is
159453 ** determined using strlen().
159454 */
159455 static int fts3StringAppend(
159456  StrBuffer *pStr, /* Buffer to append to */
159457  const char *zAppend, /* Pointer to data to append to buffer */
159458  int nAppend /* Size of zAppend in bytes (or -1) */
159459 ){
159460  if( nAppend<0 ){
159461  nAppend = (int)strlen(zAppend);
159462  }
159463 
159464  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
159465  ** to grow the buffer until so that it is big enough to accomadate the
159466  ** appended data.
159467  */
159468  if( pStr->n+nAppend+1>=pStr->nAlloc ){
159469  int nAlloc = pStr->nAlloc+nAppend+100;
159470  char *zNew = sqlite3_realloc(pStr->z, nAlloc);
159471  if( !zNew ){
159472  return SQLITE_NOMEM;
159473  }
159474  pStr->z = zNew;
159475  pStr->nAlloc = nAlloc;
159476  }
159477  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
159478 
159479  /* Append the data to the string buffer. */
159480  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
159481  pStr->n += nAppend;
159482  pStr->z[pStr->n] = '\0';
159483 
159484  return SQLITE_OK;
159485 }
159486 
159487 /*
159488 ** The fts3BestSnippet() function often selects snippets that end with a
159489 ** query term. That is, the final term of the snippet is always a term
159490 ** that requires highlighting. For example, if 'X' is a highlighted term
159491 ** and '.' is a non-highlighted term, BestSnippet() may select:
159492 **
159493 ** ........X.....X
159494 **
159495 ** This function "shifts" the beginning of the snippet forward in the
159496 ** document so that there are approximately the same number of
159497 ** non-highlighted terms to the right of the final highlighted term as there
159498 ** are to the left of the first highlighted term. For example, to this:
159499 **
159500 ** ....X.....X....
159501 **
159502 ** This is done as part of extracting the snippet text, not when selecting
159503 ** the snippet. Snippet selection is done based on doclists only, so there
159504 ** is no way for fts3BestSnippet() to know whether or not the document
159505 ** actually contains terms that follow the final highlighted term.
159506 */
159507 static int fts3SnippetShift(
159508  Fts3Table *pTab, /* FTS3 table snippet comes from */
159509  int iLangid, /* Language id to use in tokenizing */
159510  int nSnippet, /* Number of tokens desired for snippet */
159511  const char *zDoc, /* Document text to extract snippet from */
159512  int nDoc, /* Size of buffer zDoc in bytes */
159513  int *piPos, /* IN/OUT: First token of snippet */
159514  u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
159515 ){
159516  u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
159517 
159518  if( hlmask ){
159519  int nLeft; /* Tokens to the left of first highlight */
159520  int nRight; /* Tokens to the right of last highlight */
159521  int nDesired; /* Ideal number of tokens to shift forward */
159522 
159523  for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
159524  for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
159525  nDesired = (nLeft-nRight)/2;
159526 
159527  /* Ideally, the start of the snippet should be pushed forward in the
159528  ** document nDesired tokens. This block checks if there are actually
159529  ** nDesired tokens to the right of the snippet. If so, *piPos and
159530  ** *pHlMask are updated to shift the snippet nDesired tokens to the
159531  ** right. Otherwise, the snippet is shifted by the number of tokens
159532  ** available.
159533  */
159534  if( nDesired>0 ){
159535  int nShift; /* Number of tokens to shift snippet by */
159536  int iCurrent = 0; /* Token counter */
159537  int rc; /* Return Code */
159538  sqlite3_tokenizer_module *pMod;
159539  sqlite3_tokenizer_cursor *pC;
159540  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
159541 
159542  /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
159543  ** or more tokens in zDoc/nDoc.
159544  */
159545  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
159546  if( rc!=SQLITE_OK ){
159547  return rc;
159548  }
159549  while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
159550  const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
159551  rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
159552  }
159553  pMod->xClose(pC);
159554  if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
159555 
159556  nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
159557  assert( nShift<=nDesired );
159558  if( nShift>0 ){
159559  *piPos += nShift;
159560  *pHlmask = hlmask >> nShift;
159561  }
159562  }
159563  }
159564  return SQLITE_OK;
159565 }
159566 
159567 /*
159568 ** Extract the snippet text for fragment pFragment from cursor pCsr and
159569 ** append it to string buffer pOut.
159570 */
159571 static int fts3SnippetText(
159572  Fts3Cursor *pCsr, /* FTS3 Cursor */
159573  SnippetFragment *pFragment, /* Snippet to extract */
159574  int iFragment, /* Fragment number */
159575  int isLast, /* True for final fragment in snippet */
159576  int nSnippet, /* Number of tokens in extracted snippet */
159577  const char *zOpen, /* String inserted before highlighted term */
159578  const char *zClose, /* String inserted after highlighted term */
159579  const char *zEllipsis, /* String inserted between snippets */
159580  StrBuffer *pOut /* Write output here */
159581 ){
159582  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
159583  int rc; /* Return code */
159584  const char *zDoc; /* Document text to extract snippet from */
159585  int nDoc; /* Size of zDoc in bytes */
159586  int iCurrent = 0; /* Current token number of document */
159587  int iEnd = 0; /* Byte offset of end of current token */
159588  int isShiftDone = 0; /* True after snippet is shifted */
159589  int iPos = pFragment->iPos; /* First token of snippet */
159590  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
159591  int iCol = pFragment->iCol+1; /* Query column to extract text from */
159592  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
159593  sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
159594 
159595  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
159596  if( zDoc==0 ){
159597  if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
159598  return SQLITE_NOMEM;
159599  }
159600  return SQLITE_OK;
159601  }
159602  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
159603 
159604  /* Open a token cursor on the document. */
159605  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
159606  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
159607  if( rc!=SQLITE_OK ){
159608  return rc;
159609  }
159610 
159611  while( rc==SQLITE_OK ){
159612  const char *ZDUMMY; /* Dummy argument used with tokenizer */
159613  int DUMMY1 = -1; /* Dummy argument used with tokenizer */
159614  int iBegin = 0; /* Offset in zDoc of start of token */
159615  int iFin = 0; /* Offset in zDoc of end of token */
159616  int isHighlight = 0; /* True for highlighted terms */
159617 
159618  /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
159619  ** in the FTS code the variable that the third argument to xNext points to
159620  ** is initialized to zero before the first (*but not necessarily
159621  ** subsequent*) call to xNext(). This is done for a particular application
159622  ** that needs to know whether or not the tokenizer is being used for
159623  ** snippet generation or for some other purpose.
159624  **
159625  ** Extreme care is required when writing code to depend on this
159626  ** initialization. It is not a documented part of the tokenizer interface.
159627  ** If a tokenizer is used directly by any code outside of FTS, this
159628  ** convention might not be respected. */
159629  rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
159630  if( rc!=SQLITE_OK ){
159631  if( rc==SQLITE_DONE ){
159632  /* Special case - the last token of the snippet is also the last token
159633  ** of the column. Append any punctuation that occurred between the end
159634  ** of the previous token and the end of the document to the output.
159635  ** Then break out of the loop. */
159636  rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
159637  }
159638  break;
159639  }
159640  if( iCurrent<iPos ){ continue; }
159641 
159642  if( !isShiftDone ){
159643  int n = nDoc - iBegin;
159644  rc = fts3SnippetShift(
159645  pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
159646  );
159647  isShiftDone = 1;
159648 
159649  /* Now that the shift has been done, check if the initial "..." are
159650  ** required. They are required if (a) this is not the first fragment,
159651  ** or (b) this fragment does not begin at position 0 of its column.
159652  */
159653  if( rc==SQLITE_OK ){
159654  if( iPos>0 || iFragment>0 ){
159655  rc = fts3StringAppend(pOut, zEllipsis, -1);
159656  }else if( iBegin ){
159657  rc = fts3StringAppend(pOut, zDoc, iBegin);
159658  }
159659  }
159660  if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
159661  }
159662 
159663  if( iCurrent>=(iPos+nSnippet) ){
159664  if( isLast ){
159665  rc = fts3StringAppend(pOut, zEllipsis, -1);
159666  }
159667  break;
159668  }
159669 
159670  /* Set isHighlight to true if this term should be highlighted. */
159671  isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
159672 
159673  if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
159674  if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
159675  if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
159676  if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
159677 
159678  iEnd = iFin;
159679  }
159680 
159681  pMod->xClose(pC);
159682  return rc;
159683 }
159684 
159685 
159686 /*
159687 ** This function is used to count the entries in a column-list (a
159688 ** delta-encoded list of term offsets within a single column of a single
159689 ** row). When this function is called, *ppCollist should point to the
159690 ** beginning of the first varint in the column-list (the varint that
159691 ** contains the position of the first matching term in the column data).
159692 ** Before returning, *ppCollist is set to point to the first byte after
159693 ** the last varint in the column-list (either the 0x00 signifying the end
159694 ** of the position-list, or the 0x01 that precedes the column number of
159695 ** the next column in the position-list).
159696 **
159697 ** The number of elements in the column-list is returned.
159698 */
159699 static int fts3ColumnlistCount(char **ppCollist){
159700  char *pEnd = *ppCollist;
159701  char c = 0;
159702  int nEntry = 0;
159703 
159704  /* A column-list is terminated by either a 0x01 or 0x00. */
159705  while( 0xFE & (*pEnd | c) ){
159706  c = *pEnd++ & 0x80;
159707  if( !c ) nEntry++;
159708  }
159709 
159710  *ppCollist = pEnd;
159711  return nEntry;
159712 }
159713 
159714 /*
159715 ** This function gathers 'y' or 'b' data for a single phrase.
159716 */
159717 static void fts3ExprLHits(
159718  Fts3Expr *pExpr, /* Phrase expression node */
159719  MatchInfo *p /* Matchinfo context */
159720 ){
159721  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
159722  int iStart;
159723  Fts3Phrase *pPhrase = pExpr->pPhrase;
159724  char *pIter = pPhrase->doclist.pList;
159725  int iCol = 0;
159726 
159727  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
159728  if( p->flag==FTS3_MATCHINFO_LHITS ){
159729  iStart = pExpr->iPhrase * p->nCol;
159730  }else{
159731  iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
159732  }
159733 
159734  while( 1 ){
159735  int nHit = fts3ColumnlistCount(&pIter);
159736  if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
159737  if( p->flag==FTS3_MATCHINFO_LHITS ){
159738  p->aMatchinfo[iStart + iCol] = (u32)nHit;
159739  }else if( nHit ){
159740  p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
159741  }
159742  }
159743  assert( *pIter==0x00 || *pIter==0x01 );
159744  if( *pIter!=0x01 ) break;
159745  pIter++;
159746  pIter += fts3GetVarint32(pIter, &iCol);
159747  }
159748 }
159749 
159750 /*
159751 ** Gather the results for matchinfo directives 'y' and 'b'.
159752 */
159753 static void fts3ExprLHitGather(
159754  Fts3Expr *pExpr,
159755  MatchInfo *p
159756 ){
159757  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
159758  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
159759  if( pExpr->pLeft ){
159760  fts3ExprLHitGather(pExpr->pLeft, p);
159761  fts3ExprLHitGather(pExpr->pRight, p);
159762  }else{
159763  fts3ExprLHits(pExpr, p);
159764  }
159765  }
159766 }
159767 
159768 /*
159769 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
159770 ** for a single query.
159771 **
159772 ** fts3ExprIterate() callback to load the 'global' elements of a
159773 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
159774 ** of the matchinfo array that are constant for all rows returned by the
159775 ** current query.
159776 **
159777 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
159778 ** function populates Matchinfo.aMatchinfo[] as follows:
159779 **
159780 ** for(iCol=0; iCol<nCol; iCol++){
159781 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
159782 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
159783 ** }
159784 **
159785 ** where X is the number of matches for phrase iPhrase is column iCol of all
159786 ** rows of the table. Y is the number of rows for which column iCol contains
159787 ** at least one instance of phrase iPhrase.
159788 **
159789 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
159790 ** Y values are set to nDoc, where nDoc is the number of documents in the
159791 ** file system. This is done because the full-text index doclist is required
159792 ** to calculate these values properly, and the full-text index doclist is
159793 ** not available for deferred tokens.
159794 */
159795 static int fts3ExprGlobalHitsCb(
159796  Fts3Expr *pExpr, /* Phrase expression node */
159797  int iPhrase, /* Phrase number (numbered from zero) */
159798  void *pCtx /* Pointer to MatchInfo structure */
159799 ){
159800  MatchInfo *p = (MatchInfo *)pCtx;
159801  return sqlite3Fts3EvalPhraseStats(
159802  p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
159803  );
159804 }
159805 
159806 /*
159807 ** fts3ExprIterate() callback used to collect the "local" part of the
159808 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
159809 ** array that are different for each row returned by the query.
159810 */
159811 static int fts3ExprLocalHitsCb(
159812  Fts3Expr *pExpr, /* Phrase expression node */
159813  int iPhrase, /* Phrase number */
159814  void *pCtx /* Pointer to MatchInfo structure */
159815 ){
159816  int rc = SQLITE_OK;
159817  MatchInfo *p = (MatchInfo *)pCtx;
159818  int iStart = iPhrase * p->nCol * 3;
159819  int i;
159820 
159821  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
159822  char *pCsr;
159823  rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
159824  if( pCsr ){
159825  p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
159826  }else{
159827  p->aMatchinfo[iStart+i*3] = 0;
159828  }
159829  }
159830 
159831  return rc;
159832 }
159833 
159834 static int fts3MatchinfoCheck(
159835  Fts3Table *pTab,
159836  char cArg,
159837  char **pzErr
159838 ){
159839  if( (cArg==FTS3_MATCHINFO_NPHRASE)
159840  || (cArg==FTS3_MATCHINFO_NCOL)
159841  || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
159842  || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
159843  || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
159844  || (cArg==FTS3_MATCHINFO_LCS)
159845  || (cArg==FTS3_MATCHINFO_HITS)
159846  || (cArg==FTS3_MATCHINFO_LHITS)
159847  || (cArg==FTS3_MATCHINFO_LHITS_BM)
159848  ){
159849  return SQLITE_OK;
159850  }
159851  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
159852  return SQLITE_ERROR;
159853 }
159854 
159855 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
159856  int nVal; /* Number of integers output by cArg */
159857 
159858  switch( cArg ){
159859  case FTS3_MATCHINFO_NDOC:
159860  case FTS3_MATCHINFO_NPHRASE:
159861  case FTS3_MATCHINFO_NCOL:
159862  nVal = 1;
159863  break;
159864 
159865  case FTS3_MATCHINFO_AVGLENGTH:
159866  case FTS3_MATCHINFO_LENGTH:
159867  case FTS3_MATCHINFO_LCS:
159868  nVal = pInfo->nCol;
159869  break;
159870 
159871  case FTS3_MATCHINFO_LHITS:
159872  nVal = pInfo->nCol * pInfo->nPhrase;
159873  break;
159874 
159875  case FTS3_MATCHINFO_LHITS_BM:
159876  nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
159877  break;
159878 
159879  default:
159880  assert( cArg==FTS3_MATCHINFO_HITS );
159881  nVal = pInfo->nCol * pInfo->nPhrase * 3;
159882  break;
159883  }
159884 
159885  return nVal;
159886 }
159887 
159888 static int fts3MatchinfoSelectDoctotal(
159889  Fts3Table *pTab,
159890  sqlite3_stmt **ppStmt,
159891  sqlite3_int64 *pnDoc,
159892  const char **paLen
159893 ){
159894  sqlite3_stmt *pStmt;
159895  const char *a;
159896  sqlite3_int64 nDoc;
159897 
159898  if( !*ppStmt ){
159899  int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
159900  if( rc!=SQLITE_OK ) return rc;
159901  }
159902  pStmt = *ppStmt;
159903  assert( sqlite3_data_count(pStmt)==1 );
159904 
159905  a = sqlite3_column_blob(pStmt, 0);
159906  a += sqlite3Fts3GetVarint(a, &nDoc);
159907  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
159908  *pnDoc = (u32)nDoc;
159909 
159910  if( paLen ) *paLen = a;
159911  return SQLITE_OK;
159912 }
159913 
159914 /*
159915 ** An instance of the following structure is used to store state while
159916 ** iterating through a multi-column position-list corresponding to the
159917 ** hits for a single phrase on a single row in order to calculate the
159918 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
159919 */
159920 typedef struct LcsIterator LcsIterator;
159921 struct LcsIterator {
159922  Fts3Expr *pExpr; /* Pointer to phrase expression */
159923  int iPosOffset; /* Tokens count up to end of this phrase */
159924  char *pRead; /* Cursor used to iterate through aDoclist */
159925  int iPos; /* Current position */
159926 };
159927 
159928 /*
159929 ** If LcsIterator.iCol is set to the following value, the iterator has
159930 ** finished iterating through all offsets for all columns.
159931 */
159932 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
159933 
159934 static int fts3MatchinfoLcsCb(
159935  Fts3Expr *pExpr, /* Phrase expression node */
159936  int iPhrase, /* Phrase number (numbered from zero) */
159937  void *pCtx /* Pointer to MatchInfo structure */
159938 ){
159939  LcsIterator *aIter = (LcsIterator *)pCtx;
159940  aIter[iPhrase].pExpr = pExpr;
159941  return SQLITE_OK;
159942 }
159943 
159944 /*
159945 ** Advance the iterator passed as an argument to the next position. Return
159946 ** 1 if the iterator is at EOF or if it now points to the start of the
159947 ** position list for the next column.
159948 */
159949 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
159950  char *pRead = pIter->pRead;
159951  sqlite3_int64 iRead;
159952  int rc = 0;
159953 
159954  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
159955  if( iRead==0 || iRead==1 ){
159956  pRead = 0;
159957  rc = 1;
159958  }else{
159959  pIter->iPos += (int)(iRead-2);
159960  }
159961 
159962  pIter->pRead = pRead;
159963  return rc;
159964 }
159965 
159966 /*
159967 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
159968 **
159969 ** If the call is successful, the longest-common-substring lengths for each
159970 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
159971 ** array before returning. SQLITE_OK is returned in this case.
159972 **
159973 ** Otherwise, if an error occurs, an SQLite error code is returned and the
159974 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
159975 ** undefined.
159976 */
159977 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
159978  LcsIterator *aIter;
159979  int i;
159980  int iCol;
159981  int nToken = 0;
159982 
159983  /* Allocate and populate the array of LcsIterator objects. The array
159984  ** contains one element for each matchable phrase in the query.
159985  **/
159986  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
159987  if( !aIter ) return SQLITE_NOMEM;
159988  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
159989  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
159990 
159991  for(i=0; i<pInfo->nPhrase; i++){
159992  LcsIterator *pIter = &aIter[i];
159993  nToken -= pIter->pExpr->pPhrase->nToken;
159994  pIter->iPosOffset = nToken;
159995  }
159996 
159997  for(iCol=0; iCol<pInfo->nCol; iCol++){
159998  int nLcs = 0; /* LCS value for this column */
159999  int nLive = 0; /* Number of iterators in aIter not at EOF */
160000 
160001  for(i=0; i<pInfo->nPhrase; i++){
160002  int rc;
160003  LcsIterator *pIt = &aIter[i];
160004  rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
160005  if( rc!=SQLITE_OK ) return rc;
160006  if( pIt->pRead ){
160007  pIt->iPos = pIt->iPosOffset;
160008  fts3LcsIteratorAdvance(&aIter[i]);
160009  nLive++;
160010  }
160011  }
160012 
160013  while( nLive>0 ){
160014  LcsIterator *pAdv = 0; /* The iterator to advance by one position */
160015  int nThisLcs = 0; /* LCS for the current iterator positions */
160016 
160017  for(i=0; i<pInfo->nPhrase; i++){
160018  LcsIterator *pIter = &aIter[i];
160019  if( pIter->pRead==0 ){
160020  /* This iterator is already at EOF for this column. */
160021  nThisLcs = 0;
160022  }else{
160023  if( pAdv==0 || pIter->iPos<pAdv->iPos ){
160024  pAdv = pIter;
160025  }
160026  if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
160027  nThisLcs++;
160028  }else{
160029  nThisLcs = 1;
160030  }
160031  if( nThisLcs>nLcs ) nLcs = nThisLcs;
160032  }
160033  }
160034  if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
160035  }
160036 
160037  pInfo->aMatchinfo[iCol] = nLcs;
160038  }
160039 
160040  sqlite3_free(aIter);
160041  return SQLITE_OK;
160042 }
160043 
160044 /*
160045 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
160046 ** be returned by the matchinfo() function. Argument zArg contains the
160047 ** format string passed as the second argument to matchinfo (or the
160048 ** default value "pcx" if no second argument was specified). The format
160049 ** string has already been validated and the pInfo->aMatchinfo[] array
160050 ** is guaranteed to be large enough for the output.
160051 **
160052 ** If bGlobal is true, then populate all fields of the matchinfo() output.
160053 ** If it is false, then assume that those fields that do not change between
160054 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
160055 ** have already been populated.
160056 **
160057 ** Return SQLITE_OK if successful, or an SQLite error code if an error
160058 ** occurs. If a value other than SQLITE_OK is returned, the state the
160059 ** pInfo->aMatchinfo[] buffer is left in is undefined.
160060 */
160061 static int fts3MatchinfoValues(
160062  Fts3Cursor *pCsr, /* FTS3 cursor object */
160063  int bGlobal, /* True to grab the global stats */
160064  MatchInfo *pInfo, /* Matchinfo context object */
160065  const char *zArg /* Matchinfo format string */
160066 ){
160067  int rc = SQLITE_OK;
160068  int i;
160069  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160070  sqlite3_stmt *pSelect = 0;
160071 
160072  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
160073  pInfo->flag = zArg[i];
160074  switch( zArg[i] ){
160075  case FTS3_MATCHINFO_NPHRASE:
160076  if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
160077  break;
160078 
160079  case FTS3_MATCHINFO_NCOL:
160080  if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
160081  break;
160082 
160083  case FTS3_MATCHINFO_NDOC:
160084  if( bGlobal ){
160085  sqlite3_int64 nDoc = 0;
160086  rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
160087  pInfo->aMatchinfo[0] = (u32)nDoc;
160088  }
160089  break;
160090 
160091  case FTS3_MATCHINFO_AVGLENGTH:
160092  if( bGlobal ){
160093  sqlite3_int64 nDoc; /* Number of rows in table */
160094  const char *a; /* Aggregate column length array */
160095 
160096  rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
160097  if( rc==SQLITE_OK ){
160098  int iCol;
160099  for(iCol=0; iCol<pInfo->nCol; iCol++){
160100  u32 iVal;
160101  sqlite3_int64 nToken;
160102  a += sqlite3Fts3GetVarint(a, &nToken);
160103  iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
160104  pInfo->aMatchinfo[iCol] = iVal;
160105  }
160106  }
160107  }
160108  break;
160109 
160110  case FTS3_MATCHINFO_LENGTH: {
160111  sqlite3_stmt *pSelectDocsize = 0;
160112  rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
160113  if( rc==SQLITE_OK ){
160114  int iCol;
160115  const char *a = sqlite3_column_blob(pSelectDocsize, 0);
160116  for(iCol=0; iCol<pInfo->nCol; iCol++){
160117  sqlite3_int64 nToken;
160118  a += sqlite3Fts3GetVarint(a, &nToken);
160119  pInfo->aMatchinfo[iCol] = (u32)nToken;
160120  }
160121  }
160122  sqlite3_reset(pSelectDocsize);
160123  break;
160124  }
160125 
160126  case FTS3_MATCHINFO_LCS:
160127  rc = fts3ExprLoadDoclists(pCsr, 0, 0);
160128  if( rc==SQLITE_OK ){
160129  rc = fts3MatchinfoLcs(pCsr, pInfo);
160130  }
160131  break;
160132 
160133  case FTS3_MATCHINFO_LHITS_BM:
160134  case FTS3_MATCHINFO_LHITS: {
160135  int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
160136  memset(pInfo->aMatchinfo, 0, nZero);
160137  fts3ExprLHitGather(pCsr->pExpr, pInfo);
160138  break;
160139  }
160140 
160141  default: {
160142  Fts3Expr *pExpr;
160143  assert( zArg[i]==FTS3_MATCHINFO_HITS );
160144  pExpr = pCsr->pExpr;
160145  rc = fts3ExprLoadDoclists(pCsr, 0, 0);
160146  if( rc!=SQLITE_OK ) break;
160147  if( bGlobal ){
160148  if( pCsr->pDeferred ){
160149  rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
160150  if( rc!=SQLITE_OK ) break;
160151  }
160152  rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
160153  sqlite3Fts3EvalTestDeferred(pCsr, &rc);
160154  if( rc!=SQLITE_OK ) break;
160155  }
160156  (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
160157  break;
160158  }
160159  }
160160 
160161  pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
160162  }
160163 
160164  sqlite3_reset(pSelect);
160165  return rc;
160166 }
160167 
160168 
160169 /*
160170 ** Populate pCsr->aMatchinfo[] with data for the current row. The
160171 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
160172 */
160173 static void fts3GetMatchinfo(
160174  sqlite3_context *pCtx, /* Return results here */
160175  Fts3Cursor *pCsr, /* FTS3 Cursor object */
160176  const char *zArg /* Second argument to matchinfo() function */
160177 ){
160178  MatchInfo sInfo;
160179  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160180  int rc = SQLITE_OK;
160181  int bGlobal = 0; /* Collect 'global' stats as well as local */
160182 
160183  u32 *aOut = 0;
160184  void (*xDestroyOut)(void*) = 0;
160185 
160186  memset(&sInfo, 0, sizeof(MatchInfo));
160187  sInfo.pCursor = pCsr;
160188  sInfo.nCol = pTab->nColumn;
160189 
160190  /* If there is cached matchinfo() data, but the format string for the
160191  ** cache does not match the format string for this request, discard
160192  ** the cached data. */
160193  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
160194  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
160195  pCsr->pMIBuffer = 0;
160196  }
160197 
160198  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
160199  ** matchinfo function has been called for this query. In this case
160200  ** allocate the array used to accumulate the matchinfo data and
160201  ** initialize those elements that are constant for every row.
160202  */
160203  if( pCsr->pMIBuffer==0 ){
160204  int nMatchinfo = 0; /* Number of u32 elements in match-info */
160205  int i; /* Used to iterate through zArg */
160206 
160207  /* Determine the number of phrases in the query */
160208  pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
160209  sInfo.nPhrase = pCsr->nPhrase;
160210 
160211  /* Determine the number of integers in the buffer returned by this call. */
160212  for(i=0; zArg[i]; i++){
160213  char *zErr = 0;
160214  if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
160215  sqlite3_result_error(pCtx, zErr, -1);
160216  sqlite3_free(zErr);
160217  return;
160218  }
160219  nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
160220  }
160221 
160222  /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
160223  pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
160224  if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
160225 
160226  pCsr->isMatchinfoNeeded = 1;
160227  bGlobal = 1;
160228  }
160229 
160230  if( rc==SQLITE_OK ){
160231  xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
160232  if( xDestroyOut==0 ){
160233  rc = SQLITE_NOMEM;
160234  }
160235  }
160236 
160237  if( rc==SQLITE_OK ){
160238  sInfo.aMatchinfo = aOut;
160239  sInfo.nPhrase = pCsr->nPhrase;
160240  rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
160241  if( bGlobal ){
160242  fts3MIBufferSetGlobal(pCsr->pMIBuffer);
160243  }
160244  }
160245 
160246  if( rc!=SQLITE_OK ){
160247  sqlite3_result_error_code(pCtx, rc);
160248  if( xDestroyOut ) xDestroyOut(aOut);
160249  }else{
160250  int n = pCsr->pMIBuffer->nElem * sizeof(u32);
160251  sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
160252  }
160253 }
160254 
160255 /*
160256 ** Implementation of snippet() function.
160257 */
160258 SQLITE_PRIVATE void sqlite3Fts3Snippet(
160259  sqlite3_context *pCtx, /* SQLite function call context */
160260  Fts3Cursor *pCsr, /* Cursor object */
160261  const char *zStart, /* Snippet start text - "<b>" */
160262  const char *zEnd, /* Snippet end text - "</b>" */
160263  const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
160264  int iCol, /* Extract snippet from this column */
160265  int nToken /* Approximate number of tokens in snippet */
160266 ){
160267  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160268  int rc = SQLITE_OK;
160269  int i;
160270  StrBuffer res = {0, 0, 0};
160271 
160272  /* The returned text includes up to four fragments of text extracted from
160273  ** the data in the current row. The first iteration of the for(...) loop
160274  ** below attempts to locate a single fragment of text nToken tokens in
160275  ** size that contains at least one instance of all phrases in the query
160276  ** expression that appear in the current row. If such a fragment of text
160277  ** cannot be found, the second iteration of the loop attempts to locate
160278  ** a pair of fragments, and so on.
160279  */
160280  int nSnippet = 0; /* Number of fragments in this snippet */
160281  SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
160282  int nFToken = -1; /* Number of tokens in each fragment */
160283 
160284  if( !pCsr->pExpr ){
160285  sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
160286  return;
160287  }
160288 
160289  for(nSnippet=1; 1; nSnippet++){
160290 
160291  int iSnip; /* Loop counter 0..nSnippet-1 */
160292  u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
160293  u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
160294 
160295  if( nToken>=0 ){
160296  nFToken = (nToken+nSnippet-1) / nSnippet;
160297  }else{
160298  nFToken = -1 * nToken;
160299  }
160300 
160301  for(iSnip=0; iSnip<nSnippet; iSnip++){
160302  int iBestScore = -1; /* Best score of columns checked so far */
160303  int iRead; /* Used to iterate through columns */
160304  SnippetFragment *pFragment = &aSnippet[iSnip];
160305 
160306  memset(pFragment, 0, sizeof(*pFragment));
160307 
160308  /* Loop through all columns of the table being considered for snippets.
160309  ** If the iCol argument to this function was negative, this means all
160310  ** columns of the FTS3 table. Otherwise, only column iCol is considered.
160311  */
160312  for(iRead=0; iRead<pTab->nColumn; iRead++){
160313  SnippetFragment sF = {0, 0, 0, 0};
160314  int iS = 0;
160315  if( iCol>=0 && iRead!=iCol ) continue;
160316 
160317  /* Find the best snippet of nFToken tokens in column iRead. */
160318  rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
160319  if( rc!=SQLITE_OK ){
160320  goto snippet_out;
160321  }
160322  if( iS>iBestScore ){
160323  *pFragment = sF;
160324  iBestScore = iS;
160325  }
160326  }
160327 
160328  mCovered |= pFragment->covered;
160329  }
160330 
160331  /* If all query phrases seen by fts3BestSnippet() are present in at least
160332  ** one of the nSnippet snippet fragments, break out of the loop.
160333  */
160334  assert( (mCovered&mSeen)==mCovered );
160335  if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
160336  }
160337 
160338  assert( nFToken>0 );
160339 
160340  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
160341  rc = fts3SnippetText(pCsr, &aSnippet[i],
160342  i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
160343  );
160344  }
160345 
160346  snippet_out:
160347  sqlite3Fts3SegmentsClose(pTab);
160348  if( rc!=SQLITE_OK ){
160349  sqlite3_result_error_code(pCtx, rc);
160350  sqlite3_free(res.z);
160351  }else{
160352  sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
160353  }
160354 }
160355 
160356 
160357 typedef struct TermOffset TermOffset;
160358 typedef struct TermOffsetCtx TermOffsetCtx;
160359 
160360 struct TermOffset {
160361  char *pList; /* Position-list */
160362  int iPos; /* Position just read from pList */
160363  int iOff; /* Offset of this term from read positions */
160364 };
160365 
160366 struct TermOffsetCtx {
160367  Fts3Cursor *pCsr;
160368  int iCol; /* Column of table to populate aTerm for */
160369  int iTerm;
160370  sqlite3_int64 iDocid;
160371  TermOffset *aTerm;
160372 };
160373 
160374 /*
160375 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
160376 */
160377 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
160378  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
160379  int nTerm; /* Number of tokens in phrase */
160380  int iTerm; /* For looping through nTerm phrase terms */
160381  char *pList; /* Pointer to position list for phrase */
160382  int iPos = 0; /* First position in position-list */
160383  int rc;
160384 
160385  UNUSED_PARAMETER(iPhrase);
160386  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
160387  nTerm = pExpr->pPhrase->nToken;
160388  if( pList ){
160389  fts3GetDeltaPosition(&pList, &iPos);
160390  assert( iPos>=0 );
160391  }
160392 
160393  for(iTerm=0; iTerm<nTerm; iTerm++){
160394  TermOffset *pT = &p->aTerm[p->iTerm++];
160395  pT->iOff = nTerm-iTerm-1;
160396  pT->pList = pList;
160397  pT->iPos = iPos;
160398  }
160399 
160400  return rc;
160401 }
160402 
160403 /*
160404 ** Implementation of offsets() function.
160405 */
160406 SQLITE_PRIVATE void sqlite3Fts3Offsets(
160407  sqlite3_context *pCtx, /* SQLite function call context */
160408  Fts3Cursor *pCsr /* Cursor object */
160409 ){
160410  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160411  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
160412  int rc; /* Return Code */
160413  int nToken; /* Number of tokens in query */
160414  int iCol; /* Column currently being processed */
160415  StrBuffer res = {0, 0, 0}; /* Result string */
160416  TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
160417 
160418  if( !pCsr->pExpr ){
160419  sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
160420  return;
160421  }
160422 
160423  memset(&sCtx, 0, sizeof(sCtx));
160424  assert( pCsr->isRequireSeek==0 );
160425 
160426  /* Count the number of terms in the query */
160427  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
160428  if( rc!=SQLITE_OK ) goto offsets_out;
160429 
160430  /* Allocate the array of TermOffset iterators. */
160431  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
160432  if( 0==sCtx.aTerm ){
160433  rc = SQLITE_NOMEM;
160434  goto offsets_out;
160435  }
160436  sCtx.iDocid = pCsr->iPrevId;
160437  sCtx.pCsr = pCsr;
160438 
160439  /* Loop through the table columns, appending offset information to
160440  ** string-buffer res for each column.
160441  */
160442  for(iCol=0; iCol<pTab->nColumn; iCol++){
160443  sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
160444  const char *ZDUMMY; /* Dummy argument used with xNext() */
160445  int NDUMMY = 0; /* Dummy argument used with xNext() */
160446  int iStart = 0;
160447  int iEnd = 0;
160448  int iCurrent = 0;
160449  const char *zDoc;
160450  int nDoc;
160451 
160452  /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
160453  ** no way that this operation can fail, so the return code from
160454  ** fts3ExprIterate() can be discarded.
160455  */
160456  sCtx.iCol = iCol;
160457  sCtx.iTerm = 0;
160458  (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
160459 
160460  /* Retreive the text stored in column iCol. If an SQL NULL is stored
160461  ** in column iCol, jump immediately to the next iteration of the loop.
160462  ** If an OOM occurs while retrieving the data (this can happen if SQLite
160463  ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
160464  ** to the caller.
160465  */
160466  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
160467  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
160468  if( zDoc==0 ){
160469  if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
160470  continue;
160471  }
160472  rc = SQLITE_NOMEM;
160473  goto offsets_out;
160474  }
160475 
160476  /* Initialize a tokenizer iterator to iterate through column iCol. */
160477  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
160478  zDoc, nDoc, &pC
160479  );
160480  if( rc!=SQLITE_OK ) goto offsets_out;
160481 
160482  rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
160483  while( rc==SQLITE_OK ){
160484  int i; /* Used to loop through terms */
160485  int iMinPos = 0x7FFFFFFF; /* Position of next token */
160486  TermOffset *pTerm = 0; /* TermOffset associated with next token */
160487 
160488  for(i=0; i<nToken; i++){
160489  TermOffset *pT = &sCtx.aTerm[i];
160490  if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
160491  iMinPos = pT->iPos-pT->iOff;
160492  pTerm = pT;
160493  }
160494  }
160495 
160496  if( !pTerm ){
160497  /* All offsets for this column have been gathered. */
160498  rc = SQLITE_DONE;
160499  }else{
160500  assert( iCurrent<=iMinPos );
160501  if( 0==(0xFE&*pTerm->pList) ){
160502  pTerm->pList = 0;
160503  }else{
160504  fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
160505  }
160506  while( rc==SQLITE_OK && iCurrent<iMinPos ){
160507  rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
160508  }
160509  if( rc==SQLITE_OK ){
160510  char aBuffer[64];
160511  sqlite3_snprintf(sizeof(aBuffer), aBuffer,
160512  "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
160513  );
160514  rc = fts3StringAppend(&res, aBuffer, -1);
160515  }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
160516  rc = FTS_CORRUPT_VTAB;
160517  }
160518  }
160519  }
160520  if( rc==SQLITE_DONE ){
160521  rc = SQLITE_OK;
160522  }
160523 
160524  pMod->xClose(pC);
160525  if( rc!=SQLITE_OK ) goto offsets_out;
160526  }
160527 
160528  offsets_out:
160529  sqlite3_free(sCtx.aTerm);
160530  assert( rc!=SQLITE_DONE );
160531  sqlite3Fts3SegmentsClose(pTab);
160532  if( rc!=SQLITE_OK ){
160533  sqlite3_result_error_code(pCtx, rc);
160534  sqlite3_free(res.z);
160535  }else{
160536  sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
160537  }
160538  return;
160539 }
160540 
160541 /*
160542 ** Implementation of matchinfo() function.
160543 */
160544 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
160545  sqlite3_context *pContext, /* Function call context */
160546  Fts3Cursor *pCsr, /* FTS3 table cursor */
160547  const char *zArg /* Second arg to matchinfo() function */
160548 ){
160549  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160550  const char *zFormat;
160551 
160552  if( zArg ){
160553  zFormat = zArg;
160554  }else{
160555  zFormat = FTS3_MATCHINFO_DEFAULT;
160556  }
160557 
160558  if( !pCsr->pExpr ){
160559  sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
160560  return;
160561  }else{
160562  /* Retrieve matchinfo() data. */
160563  fts3GetMatchinfo(pContext, pCsr, zFormat);
160564  sqlite3Fts3SegmentsClose(pTab);
160565  }
160566 }
160567 
160568 #endif
160569 
160570 /************** End of fts3_snippet.c ****************************************/
160571 /************** Begin file fts3_unicode.c ************************************/
160572 /*
160573 ** 2012 May 24
160574 **
160575 ** The author disclaims copyright to this source code. In place of
160576 ** a legal notice, here is a blessing:
160577 **
160578 ** May you do good and not evil.
160579 ** May you find forgiveness for yourself and forgive others.
160580 ** May you share freely, never taking more than you give.
160581 **
160582 ******************************************************************************
160583 **
160584 ** Implementation of the "unicode" full-text-search tokenizer.
160585 */
160586 
160587 #ifndef SQLITE_DISABLE_FTS3_UNICODE
160588 
160589 /* #include "fts3Int.h" */
160590 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
160591 
160592 /* #include <assert.h> */
160593 /* #include <stdlib.h> */
160594 /* #include <stdio.h> */
160595 /* #include <string.h> */
160596 
160597 /* #include "fts3_tokenizer.h" */
160598 
160599 /*
160600 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
160601 ** from the sqlite3 source file utf.c. If this file is compiled as part
160602 ** of the amalgamation, they are not required.
160603 */
160604 #ifndef SQLITE_AMALGAMATION
160605 
160606 static const unsigned char sqlite3Utf8Trans1[] = {
160607  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
160608  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
160609  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
160610  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
160611  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
160612  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
160613  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
160614  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
160615 };
160616 
160617 #define READ_UTF8(zIn, zTerm, c) \
160618  c = *(zIn++); \
160619  if( c>=0xc0 ){ \
160620  c = sqlite3Utf8Trans1[c-0xc0]; \
160621  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
160622  c = (c<<6) + (0x3f & *(zIn++)); \
160623  } \
160624  if( c<0x80 \
160625  || (c&0xFFFFF800)==0xD800 \
160626  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
160627  }
160628 
160629 #define WRITE_UTF8(zOut, c) { \
160630  if( c<0x00080 ){ \
160631  *zOut++ = (u8)(c&0xFF); \
160632  } \
160633  else if( c<0x00800 ){ \
160634  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
160635  *zOut++ = 0x80 + (u8)(c & 0x3F); \
160636  } \
160637  else if( c<0x10000 ){ \
160638  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
160639  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
160640  *zOut++ = 0x80 + (u8)(c & 0x3F); \
160641  }else{ \
160642  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
160643  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
160644  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
160645  *zOut++ = 0x80 + (u8)(c & 0x3F); \
160646  } \
160647 }
160648 
160649 #endif /* ifndef SQLITE_AMALGAMATION */
160650 
160651 typedef struct unicode_tokenizer unicode_tokenizer;
160652 typedef struct unicode_cursor unicode_cursor;
160653 
160654 struct unicode_tokenizer {
160655  sqlite3_tokenizer base;
160656  int bRemoveDiacritic;
160657  int nException;
160658  int *aiException;
160659 };
160660 
160661 struct unicode_cursor {
160662  sqlite3_tokenizer_cursor base;
160663  const unsigned char *aInput; /* Input text being tokenized */
160664  int nInput; /* Size of aInput[] in bytes */
160665  int iOff; /* Current offset within aInput[] */
160666  int iToken; /* Index of next token to be returned */
160667  char *zToken; /* storage for current token */
160668  int nAlloc; /* space allocated at zToken */
160669 };
160670 
160671 
160672 /*
160673 ** Destroy a tokenizer allocated by unicodeCreate().
160674 */
160675 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
160676  if( pTokenizer ){
160677  unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
160678  sqlite3_free(p->aiException);
160679  sqlite3_free(p);
160680  }
160681  return SQLITE_OK;
160682 }
160683 
160684 /*
160685 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
160686 ** statement has specified that the tokenizer for this table shall consider
160687 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
160688 ** token characters (if bAlnum==1).
160689 **
160690 ** For each codepoint in the zIn/nIn string, this function checks if the
160691 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
160692 ** If so, no action is taken. Otherwise, the codepoint is added to the
160693 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
160694 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
160695 ** codepoints in the aiException[] array.
160696 **
160697 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
160698 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
160699 ** It is not possible to change the behavior of the tokenizer with respect
160700 ** to these codepoints.
160701 */
160702 static int unicodeAddExceptions(
160703  unicode_tokenizer *p, /* Tokenizer to add exceptions to */
160704  int bAlnum, /* Replace Isalnum() return value with this */
160705  const char *zIn, /* Array of characters to make exceptions */
160706  int nIn /* Length of z in bytes */
160707 ){
160708  const unsigned char *z = (const unsigned char *)zIn;
160709  const unsigned char *zTerm = &z[nIn];
160710  int iCode;
160711  int nEntry = 0;
160712 
160713  assert( bAlnum==0 || bAlnum==1 );
160714 
160715  while( z<zTerm ){
160716  READ_UTF8(z, zTerm, iCode);
160717  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
160718  if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
160719  && sqlite3FtsUnicodeIsdiacritic(iCode)==0
160720  ){
160721  nEntry++;
160722  }
160723  }
160724 
160725  if( nEntry ){
160726  int *aNew; /* New aiException[] array */
160727  int nNew; /* Number of valid entries in array aNew[] */
160728 
160729  aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
160730  if( aNew==0 ) return SQLITE_NOMEM;
160731  nNew = p->nException;
160732 
160733  z = (const unsigned char *)zIn;
160734  while( z<zTerm ){
160735  READ_UTF8(z, zTerm, iCode);
160736  if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
160737  && sqlite3FtsUnicodeIsdiacritic(iCode)==0
160738  ){
160739  int i, j;
160740  for(i=0; i<nNew && aNew[i]<iCode; i++);
160741  for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
160742  aNew[i] = iCode;
160743  nNew++;
160744  }
160745  }
160746  p->aiException = aNew;
160747  p->nException = nNew;
160748  }
160749 
160750  return SQLITE_OK;
160751 }
160752 
160753 /*
160754 ** Return true if the p->aiException[] array contains the value iCode.
160755 */
160756 static int unicodeIsException(unicode_tokenizer *p, int iCode){
160757  if( p->nException>0 ){
160758  int *a = p->aiException;
160759  int iLo = 0;
160760  int iHi = p->nException-1;
160761 
160762  while( iHi>=iLo ){
160763  int iTest = (iHi + iLo) / 2;
160764  if( iCode==a[iTest] ){
160765  return 1;
160766  }else if( iCode>a[iTest] ){
160767  iLo = iTest+1;
160768  }else{
160769  iHi = iTest-1;
160770  }
160771  }
160772  }
160773 
160774  return 0;
160775 }
160776 
160777 /*
160778 ** Return true if, for the purposes of tokenization, codepoint iCode is
160779 ** considered a token character (not a separator).
160780 */
160781 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
160782  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
160783  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
160784 }
160785 
160786 /*
160787 ** Create a new tokenizer instance.
160788 */
160789 static int unicodeCreate(
160790  int nArg, /* Size of array argv[] */
160791  const char * const *azArg, /* Tokenizer creation arguments */
160792  sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
160793 ){
160794  unicode_tokenizer *pNew; /* New tokenizer object */
160795  int i;
160796  int rc = SQLITE_OK;
160797 
160798  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
160799  if( pNew==NULL ) return SQLITE_NOMEM;
160800  memset(pNew, 0, sizeof(unicode_tokenizer));
160801  pNew->bRemoveDiacritic = 1;
160802 
160803  for(i=0; rc==SQLITE_OK && i<nArg; i++){
160804  const char *z = azArg[i];
160805  int n = (int)strlen(z);
160806 
160807  if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
160808  pNew->bRemoveDiacritic = 1;
160809  }
160810  else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
160811  pNew->bRemoveDiacritic = 0;
160812  }
160813  else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
160814  rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
160815  }
160816  else if( n>=11 && memcmp("separators=", z, 11)==0 ){
160817  rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
160818  }
160819  else{
160820  /* Unrecognized argument */
160821  rc = SQLITE_ERROR;
160822  }
160823  }
160824 
160825  if( rc!=SQLITE_OK ){
160826  unicodeDestroy((sqlite3_tokenizer *)pNew);
160827  pNew = 0;
160828  }
160829  *pp = (sqlite3_tokenizer *)pNew;
160830  return rc;
160831 }
160832 
160833 /*
160834 ** Prepare to begin tokenizing a particular string. The input
160835 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
160836 ** used to incrementally tokenize this string is returned in
160837 ** *ppCursor.
160838 */
160839 static int unicodeOpen(
160840  sqlite3_tokenizer *p, /* The tokenizer */
160841  const char *aInput, /* Input string */
160842  int nInput, /* Size of string aInput in bytes */
160843  sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
160844 ){
160845  unicode_cursor *pCsr;
160846 
160847  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
160848  if( pCsr==0 ){
160849  return SQLITE_NOMEM;
160850  }
160851  memset(pCsr, 0, sizeof(unicode_cursor));
160852 
160853  pCsr->aInput = (const unsigned char *)aInput;
160854  if( aInput==0 ){
160855  pCsr->nInput = 0;
160856  }else if( nInput<0 ){
160857  pCsr->nInput = (int)strlen(aInput);
160858  }else{
160859  pCsr->nInput = nInput;
160860  }
160861 
160862  *pp = &pCsr->base;
160863  UNUSED_PARAMETER(p);
160864  return SQLITE_OK;
160865 }
160866 
160867 /*
160868 ** Close a tokenization cursor previously opened by a call to
160869 ** simpleOpen() above.
160870 */
160871 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
160872  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
160873  sqlite3_free(pCsr->zToken);
160874  sqlite3_free(pCsr);
160875  return SQLITE_OK;
160876 }
160877 
160878 /*
160879 ** Extract the next token from a tokenization cursor. The cursor must
160880 ** have been opened by a prior call to simpleOpen().
160881 */
160882 static int unicodeNext(
160883  sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
160884  const char **paToken, /* OUT: Token text */
160885  int *pnToken, /* OUT: Number of bytes at *paToken */
160886  int *piStart, /* OUT: Starting offset of token */
160887  int *piEnd, /* OUT: Ending offset of token */
160888  int *piPos /* OUT: Position integer of token */
160889 ){
160890  unicode_cursor *pCsr = (unicode_cursor *)pC;
160891  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
160892  int iCode = 0;
160893  char *zOut;
160894  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
160895  const unsigned char *zStart = z;
160896  const unsigned char *zEnd;
160897  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
160898 
160899  /* Scan past any delimiter characters before the start of the next token.
160900  ** Return SQLITE_DONE early if this takes us all the way to the end of
160901  ** the input. */
160902  while( z<zTerm ){
160903  READ_UTF8(z, zTerm, iCode);
160904  if( unicodeIsAlnum(p, iCode) ) break;
160905  zStart = z;
160906  }
160907  if( zStart>=zTerm ) return SQLITE_DONE;
160908 
160909  zOut = pCsr->zToken;
160910  do {
160911  int iOut;
160912 
160913  /* Grow the output buffer if required. */
160914  if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
160915  char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
160916  if( !zNew ) return SQLITE_NOMEM;
160917  zOut = &zNew[zOut - pCsr->zToken];
160918  pCsr->zToken = zNew;
160919  pCsr->nAlloc += 64;
160920  }
160921 
160922  /* Write the folded case of the last character read to the output */
160923  zEnd = z;
160924  iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
160925  if( iOut ){
160926  WRITE_UTF8(zOut, iOut);
160927  }
160928 
160929  /* If the cursor is not at EOF, read the next character */
160930  if( z>=zTerm ) break;
160931  READ_UTF8(z, zTerm, iCode);
160932  }while( unicodeIsAlnum(p, iCode)
160933  || sqlite3FtsUnicodeIsdiacritic(iCode)
160934  );
160935 
160936  /* Set the output variables and return. */
160937  pCsr->iOff = (int)(z - pCsr->aInput);
160938  *paToken = pCsr->zToken;
160939  *pnToken = (int)(zOut - pCsr->zToken);
160940  *piStart = (int)(zStart - pCsr->aInput);
160941  *piEnd = (int)(zEnd - pCsr->aInput);
160942  *piPos = pCsr->iToken++;
160943  return SQLITE_OK;
160944 }
160945 
160946 /*
160947 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
160948 ** structure for the unicode tokenizer.
160949 */
160950 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
160951  static const sqlite3_tokenizer_module module = {
160952  0,
160953  unicodeCreate,
160954  unicodeDestroy,
160955  unicodeOpen,
160956  unicodeClose,
160957  unicodeNext,
160958  0,
160959  };
160960  *ppModule = &module;
160961 }
160962 
160963 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
160964 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
160965 
160966 /************** End of fts3_unicode.c ****************************************/
160967 /************** Begin file fts3_unicode2.c ***********************************/
160968 /*
160969 ** 2012 May 25
160970 **
160971 ** The author disclaims copyright to this source code. In place of
160972 ** a legal notice, here is a blessing:
160973 **
160974 ** May you do good and not evil.
160975 ** May you find forgiveness for yourself and forgive others.
160976 ** May you share freely, never taking more than you give.
160977 **
160978 ******************************************************************************
160979 */
160980 
160981 /*
160982 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
160983 */
160984 
160985 #ifndef SQLITE_DISABLE_FTS3_UNICODE
160986 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
160987 
160988 /* #include <assert.h> */
160989 
160990 /*
160991 ** Return true if the argument corresponds to a unicode codepoint
160992 ** classified as either a letter or a number. Otherwise false.
160993 **
160994 ** The results are undefined if the value passed to this function
160995 ** is less than zero.
160996 */
160997 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
160998  /* Each unsigned integer in the following array corresponds to a contiguous
160999  ** range of unicode codepoints that are not either letters or numbers (i.e.
161000  ** codepoints for which this function should return 0).
161001  **
161002  ** The most significant 22 bits in each 32-bit value contain the first
161003  ** codepoint in the range. The least significant 10 bits are used to store
161004  ** the size of the range (always at least 1). In other words, the value
161005  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
161006  ** C. It is not possible to represent a range larger than 1023 codepoints
161007  ** using this format.
161008  */
161009  static const unsigned int aEntry[] = {
161010  0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
161011  0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
161012  0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
161013  0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
161014  0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
161015  0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
161016  0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
161017  0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
161018  0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
161019  0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
161020  0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
161021  0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
161022  0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
161023  0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
161024  0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
161025  0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
161026  0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
161027  0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
161028  0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
161029  0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
161030  0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
161031  0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
161032  0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
161033  0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
161034  0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
161035  0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
161036  0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
161037  0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
161038  0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
161039  0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
161040  0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
161041  0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
161042  0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
161043  0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
161044  0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
161045  0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
161046  0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
161047  0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
161048  0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
161049  0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
161050  0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
161051  0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
161052  0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
161053  0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
161054  0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
161055  0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
161056  0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
161057  0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
161058  0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
161059  0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
161060  0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
161061  0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
161062  0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
161063  0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
161064  0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
161065  0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
161066  0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
161067  0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
161068  0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
161069  0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
161070  0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
161071  0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
161072  0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
161073  0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
161074  0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
161075  0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
161076  0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
161077  0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
161078  0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
161079  0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
161080  0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
161081  0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
161082  0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
161083  0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
161084  0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
161085  0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
161086  0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
161087  0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
161088  0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
161089  0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
161090  0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
161091  0x380400F0,
161092  };
161093  static const unsigned int aAscii[4] = {
161094  0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
161095  };
161096 
161097  if( c<128 ){
161098  return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
161099  }else if( c<(1<<22) ){
161100  unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
161101  int iRes = 0;
161102  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
161103  int iLo = 0;
161104  while( iHi>=iLo ){
161105  int iTest = (iHi + iLo) / 2;
161106  if( key >= aEntry[iTest] ){
161107  iRes = iTest;
161108  iLo = iTest+1;
161109  }else{
161110  iHi = iTest-1;
161111  }
161112  }
161113  assert( aEntry[0]<key );
161114  assert( key>=aEntry[iRes] );
161115  return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
161116  }
161117  return 1;
161118 }
161119 
161120 
161121 /*
161122 ** If the argument is a codepoint corresponding to a lowercase letter
161123 ** in the ASCII range with a diacritic added, return the codepoint
161124 ** of the ASCII letter only. For example, if passed 235 - "LATIN
161125 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
161126 ** E"). The resuls of passing a codepoint that corresponds to an
161127 ** uppercase letter are undefined.
161128 */
161129 static int remove_diacritic(int c){
161130  unsigned short aDia[] = {
161131  0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
161132  2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
161133  2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
161134  2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
161135  3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
161136  3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
161137  4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
161138  6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
161139  61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
161140  61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
161141  62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
161142  62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
161143  62924, 63050, 63082, 63274, 63390,
161144  };
161145  char aChar[] = {
161146  '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
161147  'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
161148  's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
161149  'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
161150  'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
161151  '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
161152  'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
161153  'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
161154  'e', 'i', 'o', 'u', 'y',
161155  };
161156 
161157  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
161158  int iRes = 0;
161159  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
161160  int iLo = 0;
161161  while( iHi>=iLo ){
161162  int iTest = (iHi + iLo) / 2;
161163  if( key >= aDia[iTest] ){
161164  iRes = iTest;
161165  iLo = iTest+1;
161166  }else{
161167  iHi = iTest-1;
161168  }
161169  }
161170  assert( key>=aDia[iRes] );
161171  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
161172 }
161173 
161174 
161175 /*
161176 ** Return true if the argument interpreted as a unicode codepoint
161177 ** is a diacritical modifier character.
161178 */
161179 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
161180  unsigned int mask0 = 0x08029FDF;
161181  unsigned int mask1 = 0x000361F8;
161182  if( c<768 || c>817 ) return 0;
161183  return (c < 768+32) ?
161184  (mask0 & (1 << (c-768))) :
161185  (mask1 & (1 << (c-768-32)));
161186 }
161187 
161188 
161189 /*
161190 ** Interpret the argument as a unicode codepoint. If the codepoint
161191 ** is an upper case character that has a lower case equivalent,
161192 ** return the codepoint corresponding to the lower case version.
161193 ** Otherwise, return a copy of the argument.
161194 **
161195 ** The results are undefined if the value passed to this function
161196 ** is less than zero.
161197 */
161198 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
161199  /* Each entry in the following array defines a rule for folding a range
161200  ** of codepoints to lower case. The rule applies to a range of nRange
161201  ** codepoints starting at codepoint iCode.
161202  **
161203  ** If the least significant bit in flags is clear, then the rule applies
161204  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
161205  ** need to be folded). Or, if it is set, then the rule only applies to
161206  ** every second codepoint in the range, starting with codepoint C.
161207  **
161208  ** The 7 most significant bits in flags are an index into the aiOff[]
161209  ** array. If a specific codepoint C does require folding, then its lower
161210  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
161211  **
161212  ** The contents of this array are generated by parsing the CaseFolding.txt
161213  ** file distributed as part of the "Unicode Character Database". See
161214  ** http://www.unicode.org for details.
161215  */
161216  static const struct TableEntry {
161217  unsigned short iCode;
161218  unsigned char flags;
161219  unsigned char nRange;
161220  } aEntry[] = {
161221  {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
161222  {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
161223  {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
161224  {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
161225  {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
161226  {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
161227  {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
161228  {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
161229  {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
161230  {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
161231  {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
161232  {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
161233  {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
161234  {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
161235  {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
161236  {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
161237  {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
161238  {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
161239  {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
161240  {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
161241  {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
161242  {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
161243  {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
161244  {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
161245  {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
161246  {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
161247  {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
161248  {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
161249  {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
161250  {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
161251  {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
161252  {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
161253  {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
161254  {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
161255  {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
161256  {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
161257  {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
161258  {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
161259  {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
161260  {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
161261  {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
161262  {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
161263  {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
161264  {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
161265  {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
161266  {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
161267  {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
161268  {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
161269  {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
161270  {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
161271  {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
161272  {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
161273  {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
161274  {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
161275  {65313, 14, 26},
161276  };
161277  static const unsigned short aiOff[] = {
161278  1, 2, 8, 15, 16, 26, 28, 32,
161279  37, 38, 40, 48, 63, 64, 69, 71,
161280  79, 80, 116, 202, 203, 205, 206, 207,
161281  209, 210, 211, 213, 214, 217, 218, 219,
161282  775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
161283  54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
161284  57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
161285  65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
161286  65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
161287  65514, 65521, 65527, 65528, 65529,
161288  };
161289 
161290  int ret = c;
161291 
161292  assert( c>=0 );
161293  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
161294 
161295  if( c<128 ){
161296  if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
161297  }else if( c<65536 ){
161298  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
161299  int iLo = 0;
161300  int iRes = -1;
161301 
161302  while( iHi>=iLo ){
161303  int iTest = (iHi + iLo) / 2;
161304  int cmp = (c - aEntry[iTest].iCode);
161305  if( cmp>=0 ){
161306  iRes = iTest;
161307  iLo = iTest+1;
161308  }else{
161309  iHi = iTest-1;
161310  }
161311  }
161312  assert( iRes<0 || c>=aEntry[iRes].iCode );
161313 
161314  if( iRes>=0 ){
161315  const struct TableEntry *p = &aEntry[iRes];
161316  if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
161317  ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
161318  assert( ret>0 );
161319  }
161320  }
161321 
161322  if( bRemoveDiacritic ) ret = remove_diacritic(ret);
161323  }
161324 
161325  else if( c>=66560 && c<66600 ){
161326  ret = c + 40;
161327  }
161328 
161329  return ret;
161330 }
161331 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
161332 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
161333 
161334 /************** End of fts3_unicode2.c ***************************************/
161335 /************** Begin file rtree.c *******************************************/
161336 /*
161337 ** 2001 September 15
161338 **
161339 ** The author disclaims copyright to this source code. In place of
161340 ** a legal notice, here is a blessing:
161341 **
161342 ** May you do good and not evil.
161343 ** May you find forgiveness for yourself and forgive others.
161344 ** May you share freely, never taking more than you give.
161345 **
161346 *************************************************************************
161347 ** This file contains code for implementations of the r-tree and r*-tree
161348 ** algorithms packaged as an SQLite virtual table module.
161349 */
161350 
161351 /*
161352 ** Database Format of R-Tree Tables
161353 ** --------------------------------
161354 **
161355 ** The data structure for a single virtual r-tree table is stored in three
161356 ** native SQLite tables declared as follows. In each case, the '%' character
161357 ** in the table name is replaced with the user-supplied name of the r-tree
161358 ** table.
161359 **
161360 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
161361 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
161362 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
161363 **
161364 ** The data for each node of the r-tree structure is stored in the %_node
161365 ** table. For each node that is not the root node of the r-tree, there is
161366 ** an entry in the %_parent table associating the node with its parent.
161367 ** And for each row of data in the table, there is an entry in the %_rowid
161368 ** table that maps from the entries rowid to the id of the node that it
161369 ** is stored on.
161370 **
161371 ** The root node of an r-tree always exists, even if the r-tree table is
161372 ** empty. The nodeno of the root node is always 1. All other nodes in the
161373 ** table must be the same size as the root node. The content of each node
161374 ** is formatted as follows:
161375 **
161376 ** 1. If the node is the root node (node 1), then the first 2 bytes
161377 ** of the node contain the tree depth as a big-endian integer.
161378 ** For non-root nodes, the first 2 bytes are left unused.
161379 **
161380 ** 2. The next 2 bytes contain the number of entries currently
161381 ** stored in the node.
161382 **
161383 ** 3. The remainder of the node contains the node entries. Each entry
161384 ** consists of a single 8-byte integer followed by an even number
161385 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
161386 ** of a record. For internal nodes it is the node number of a
161387 ** child page.
161388 */
161389 
161390 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
161391 
161392 #ifndef SQLITE_CORE
161393 /* #include "sqlite3ext.h" */
161394  SQLITE_EXTENSION_INIT1
161395 #else
161396 /* #include "sqlite3.h" */
161397 #endif
161398 
161399 /* #include <string.h> */
161400 /* #include <assert.h> */
161401 /* #include <stdio.h> */
161402 
161403 #ifndef SQLITE_AMALGAMATION
161404 #include "sqlite3rtree.h"
161405 typedef sqlite3_int64 i64;
161406 typedef unsigned char u8;
161407 typedef unsigned short u16;
161408 typedef unsigned int u32;
161409 #endif
161410 
161411 /* The following macro is used to suppress compiler warnings.
161412 */
161413 #ifndef UNUSED_PARAMETER
161414 # define UNUSED_PARAMETER(x) (void)(x)
161415 #endif
161416 
161417 typedef struct Rtree Rtree;
161418 typedef struct RtreeCursor RtreeCursor;
161419 typedef struct RtreeNode RtreeNode;
161420 typedef struct RtreeCell RtreeCell;
161421 typedef struct RtreeConstraint RtreeConstraint;
161422 typedef struct RtreeMatchArg RtreeMatchArg;
161423 typedef struct RtreeGeomCallback RtreeGeomCallback;
161424 typedef union RtreeCoord RtreeCoord;
161425 typedef struct RtreeSearchPoint RtreeSearchPoint;
161426 
161427 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
161428 #define RTREE_MAX_DIMENSIONS 5
161429 
161430 /* Size of hash table Rtree.aHash. This hash table is not expected to
161431 ** ever contain very many entries, so a fixed number of buckets is
161432 ** used.
161433 */
161434 #define HASHSIZE 97
161435 
161436 /* The xBestIndex method of this virtual table requires an estimate of
161437 ** the number of rows in the virtual table to calculate the costs of
161438 ** various strategies. If possible, this estimate is loaded from the
161439 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
161440 ** Otherwise, if no sqlite_stat1 entry is available, use
161441 ** RTREE_DEFAULT_ROWEST.
161442 */
161443 #define RTREE_DEFAULT_ROWEST 1048576
161444 #define RTREE_MIN_ROWEST 100
161445 
161446 /*
161447 ** An rtree virtual-table object.
161448 */
161449 struct Rtree {
161450  sqlite3_vtab base; /* Base class. Must be first */
161451  sqlite3 *db; /* Host database connection */
161452  int iNodeSize; /* Size in bytes of each node in the node table */
161453  u8 nDim; /* Number of dimensions */
161454  u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
161455  u8 nBytesPerCell; /* Bytes consumed per cell */
161456  int iDepth; /* Current depth of the r-tree structure */
161457  char *zDb; /* Name of database containing r-tree table */
161458  char *zName; /* Name of r-tree table */
161459  int nBusy; /* Current number of users of this structure */
161460  i64 nRowEst; /* Estimated number of rows in this table */
161461 
161462  /* List of nodes removed during a CondenseTree operation. List is
161463  ** linked together via the pointer normally used for hash chains -
161464  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
161465  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
161466  */
161467  RtreeNode *pDeleted;
161468  int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
161469 
161470  /* Statements to read/write/delete a record from xxx_node */
161471  sqlite3_stmt *pReadNode;
161472  sqlite3_stmt *pWriteNode;
161473  sqlite3_stmt *pDeleteNode;
161474 
161475  /* Statements to read/write/delete a record from xxx_rowid */
161476  sqlite3_stmt *pReadRowid;
161477  sqlite3_stmt *pWriteRowid;
161478  sqlite3_stmt *pDeleteRowid;
161479 
161480  /* Statements to read/write/delete a record from xxx_parent */
161481  sqlite3_stmt *pReadParent;
161482  sqlite3_stmt *pWriteParent;
161483  sqlite3_stmt *pDeleteParent;
161484 
161485  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
161486 };
161487 
161488 /* Possible values for Rtree.eCoordType: */
161489 #define RTREE_COORD_REAL32 0
161490 #define RTREE_COORD_INT32 1
161491 
161492 /*
161493 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
161494 ** only deal with integer coordinates. No floating point operations
161495 ** will be done.
161496 */
161497 #ifdef SQLITE_RTREE_INT_ONLY
161498  typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
161499  typedef int RtreeValue; /* Low accuracy coordinate */
161500 # define RTREE_ZERO 0
161501 #else
161502  typedef double RtreeDValue; /* High accuracy coordinate */
161503  typedef float RtreeValue; /* Low accuracy coordinate */
161504 # define RTREE_ZERO 0.0
161505 #endif
161506 
161507 /*
161508 ** When doing a search of an r-tree, instances of the following structure
161509 ** record intermediate results from the tree walk.
161510 **
161511 ** The id is always a node-id. For iLevel>=1 the id is the node-id of
161512 ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
161513 ** the id is of the parent node and the cell that RtreeSearchPoint
161514 ** represents is the iCell-th entry in the parent node.
161515 */
161516 struct RtreeSearchPoint {
161517  RtreeDValue rScore; /* The score for this node. Smallest goes first. */
161518  sqlite3_int64 id; /* Node ID */
161519  u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
161520  u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
161521  u8 iCell; /* Cell index within the node */
161522 };
161523 
161524 /*
161525 ** The minimum number of cells allowed for a node is a third of the
161526 ** maximum. In Gutman's notation:
161527 **
161528 ** m = M/3
161529 **
161530 ** If an R*-tree "Reinsert" operation is required, the same number of
161531 ** cells are removed from the overfull node and reinserted into the tree.
161532 */
161533 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
161534 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
161535 #define RTREE_MAXCELLS 51
161536 
161537 /*
161538 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
161539 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
161540 ** Therefore all non-root nodes must contain at least 3 entries. Since
161541 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
161542 ** 40 or less.
161543 */
161544 #define RTREE_MAX_DEPTH 40
161545 
161546 
161547 /*
161548 ** Number of entries in the cursor RtreeNode cache. The first entry is
161549 ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
161550 ** entries cache the RtreeNode for the first elements of the priority queue.
161551 */
161552 #define RTREE_CACHE_SZ 5
161553 
161554 /*
161555 ** An rtree cursor object.
161556 */
161557 struct RtreeCursor {
161558  sqlite3_vtab_cursor base; /* Base class. Must be first */
161559  u8 atEOF; /* True if at end of search */
161560  u8 bPoint; /* True if sPoint is valid */
161561  int iStrategy; /* Copy of idxNum search parameter */
161562  int nConstraint; /* Number of entries in aConstraint */
161563  RtreeConstraint *aConstraint; /* Search constraints. */
161564  int nPointAlloc; /* Number of slots allocated for aPoint[] */
161565  int nPoint; /* Number of slots used in aPoint[] */
161566  int mxLevel; /* iLevel value for root of the tree */
161567  RtreeSearchPoint *aPoint; /* Priority queue for search points */
161568  RtreeSearchPoint sPoint; /* Cached next search point */
161569  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
161570  u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
161571 };
161572 
161573 /* Return the Rtree of a RtreeCursor */
161574 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
161575 
161576 /*
161577 ** A coordinate can be either a floating point number or a integer. All
161578 ** coordinates within a single R-Tree are always of the same time.
161579 */
161580 union RtreeCoord {
161581  RtreeValue f; /* Floating point value */
161582  int i; /* Integer value */
161583  u32 u; /* Unsigned for byte-order conversions */
161584 };
161585 
161586 /*
161587 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
161588 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
161589 ** variable pRtree points to the Rtree structure associated with the
161590 ** RtreeCoord.
161591 */
161592 #ifdef SQLITE_RTREE_INT_ONLY
161593 # define DCOORD(coord) ((RtreeDValue)coord.i)
161594 #else
161595 # define DCOORD(coord) ( \
161596  (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
161597  ((double)coord.f) : \
161598  ((double)coord.i) \
161599  )
161600 #endif
161601 
161602 /*
161603 ** A search constraint.
161604 */
161605 struct RtreeConstraint {
161606  int iCoord; /* Index of constrained coordinate */
161607  int op; /* Constraining operation */
161608  union {
161609  RtreeDValue rValue; /* Constraint value. */
161610  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
161611  int (*xQueryFunc)(sqlite3_rtree_query_info*);
161612  } u;
161613  sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
161614 };
161615 
161616 /* Possible values for RtreeConstraint.op */
161617 #define RTREE_EQ 0x41 /* A */
161618 #define RTREE_LE 0x42 /* B */
161619 #define RTREE_LT 0x43 /* C */
161620 #define RTREE_GE 0x44 /* D */
161621 #define RTREE_GT 0x45 /* E */
161622 #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
161623 #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
161624 
161625 
161626 /*
161627 ** An rtree structure node.
161628 */
161629 struct RtreeNode {
161630  RtreeNode *pParent; /* Parent node */
161631  i64 iNode; /* The node number */
161632  int nRef; /* Number of references to this node */
161633  int isDirty; /* True if the node needs to be written to disk */
161634  u8 *zData; /* Content of the node, as should be on disk */
161635  RtreeNode *pNext; /* Next node in this hash collision chain */
161636 };
161637 
161638 /* Return the number of cells in a node */
161639 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
161640 
161641 /*
161642 ** A single cell from a node, deserialized
161643 */
161644 struct RtreeCell {
161645  i64 iRowid; /* Node or entry ID */
161646  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
161647 };
161648 
161649 
161650 /*
161651 ** This object becomes the sqlite3_user_data() for the SQL functions
161652 ** that are created by sqlite3_rtree_geometry_callback() and
161653 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
161654 ** operators in order to constrain a search.
161655 **
161656 ** xGeom and xQueryFunc are the callback functions. Exactly one of
161657 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
161658 ** SQL function was created using sqlite3_rtree_geometry_callback() or
161659 ** sqlite3_rtree_query_callback().
161660 **
161661 ** This object is deleted automatically by the destructor mechanism in
161662 ** sqlite3_create_function_v2().
161663 */
161664 struct RtreeGeomCallback {
161665  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
161666  int (*xQueryFunc)(sqlite3_rtree_query_info*);
161667  void (*xDestructor)(void*);
161668  void *pContext;
161669 };
161670 
161671 
161672 /*
161673 ** Value for the first field of every RtreeMatchArg object. The MATCH
161674 ** operator tests that the first field of a blob operand matches this
161675 ** value to avoid operating on invalid blobs (which could cause a segfault).
161676 */
161677 #define RTREE_GEOMETRY_MAGIC 0x891245AB
161678 
161679 /*
161680 ** An instance of this structure (in the form of a BLOB) is returned by
161681 ** the SQL functions that sqlite3_rtree_geometry_callback() and
161682 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
161683 ** operand to the MATCH operator of an R-Tree.
161684 */
161685 struct RtreeMatchArg {
161686  u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
161687  RtreeGeomCallback cb; /* Info about the callback functions */
161688  int nParam; /* Number of parameters to the SQL function */
161689  sqlite3_value **apSqlParam; /* Original SQL parameter values */
161690  RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
161691 };
161692 
161693 #ifndef MAX
161694 # define MAX(x,y) ((x) < (y) ? (y) : (x))
161695 #endif
161696 #ifndef MIN
161697 # define MIN(x,y) ((x) > (y) ? (y) : (x))
161698 #endif
161699 
161700 /*
161701 ** Functions to deserialize a 16 bit integer, 32 bit real number and
161702 ** 64 bit integer. The deserialized value is returned.
161703 */
161704 static int readInt16(u8 *p){
161705  return (p[0]<<8) + p[1];
161706 }
161707 static void readCoord(u8 *p, RtreeCoord *pCoord){
161708  pCoord->u = (
161709  (((u32)p[0]) << 24) +
161710  (((u32)p[1]) << 16) +
161711  (((u32)p[2]) << 8) +
161712  (((u32)p[3]) << 0)
161713  );
161714 }
161715 static i64 readInt64(u8 *p){
161716  return (
161717  (((i64)p[0]) << 56) +
161718  (((i64)p[1]) << 48) +
161719  (((i64)p[2]) << 40) +
161720  (((i64)p[3]) << 32) +
161721  (((i64)p[4]) << 24) +
161722  (((i64)p[5]) << 16) +
161723  (((i64)p[6]) << 8) +
161724  (((i64)p[7]) << 0)
161725  );
161726 }
161727 
161728 /*
161729 ** Functions to serialize a 16 bit integer, 32 bit real number and
161730 ** 64 bit integer. The value returned is the number of bytes written
161731 ** to the argument buffer (always 2, 4 and 8 respectively).
161732 */
161733 static int writeInt16(u8 *p, int i){
161734  p[0] = (i>> 8)&0xFF;
161735  p[1] = (i>> 0)&0xFF;
161736  return 2;
161737 }
161738 static int writeCoord(u8 *p, RtreeCoord *pCoord){
161739  u32 i;
161740  assert( sizeof(RtreeCoord)==4 );
161741  assert( sizeof(u32)==4 );
161742  i = pCoord->u;
161743  p[0] = (i>>24)&0xFF;
161744  p[1] = (i>>16)&0xFF;
161745  p[2] = (i>> 8)&0xFF;
161746  p[3] = (i>> 0)&0xFF;
161747  return 4;
161748 }
161749 static int writeInt64(u8 *p, i64 i){
161750  p[0] = (i>>56)&0xFF;
161751  p[1] = (i>>48)&0xFF;
161752  p[2] = (i>>40)&0xFF;
161753  p[3] = (i>>32)&0xFF;
161754  p[4] = (i>>24)&0xFF;
161755  p[5] = (i>>16)&0xFF;
161756  p[6] = (i>> 8)&0xFF;
161757  p[7] = (i>> 0)&0xFF;
161758  return 8;
161759 }
161760 
161761 /*
161762 ** Increment the reference count of node p.
161763 */
161764 static void nodeReference(RtreeNode *p){
161765  if( p ){
161766  p->nRef++;
161767  }
161768 }
161769 
161770 /*
161771 ** Clear the content of node p (set all bytes to 0x00).
161772 */
161773 static void nodeZero(Rtree *pRtree, RtreeNode *p){
161774  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
161775  p->isDirty = 1;
161776 }
161777 
161778 /*
161779 ** Given a node number iNode, return the corresponding key to use
161780 ** in the Rtree.aHash table.
161781 */
161782 static int nodeHash(i64 iNode){
161783  return iNode % HASHSIZE;
161784 }
161785 
161786 /*
161787 ** Search the node hash table for node iNode. If found, return a pointer
161788 ** to it. Otherwise, return 0.
161789 */
161790 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
161791  RtreeNode *p;
161792  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
161793  return p;
161794 }
161795 
161796 /*
161797 ** Add node pNode to the node hash table.
161798 */
161799 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
161800  int iHash;
161801  assert( pNode->pNext==0 );
161802  iHash = nodeHash(pNode->iNode);
161803  pNode->pNext = pRtree->aHash[iHash];
161804  pRtree->aHash[iHash] = pNode;
161805 }
161806 
161807 /*
161808 ** Remove node pNode from the node hash table.
161809 */
161810 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
161811  RtreeNode **pp;
161812  if( pNode->iNode!=0 ){
161813  pp = &pRtree->aHash[nodeHash(pNode->iNode)];
161814  for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
161815  *pp = pNode->pNext;
161816  pNode->pNext = 0;
161817  }
161818 }
161819 
161820 /*
161821 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
161822 ** indicating that node has not yet been assigned a node number. It is
161823 ** assigned a node number when nodeWrite() is called to write the
161824 ** node contents out to the database.
161825 */
161826 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
161827  RtreeNode *pNode;
161828  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
161829  if( pNode ){
161830  memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
161831  pNode->zData = (u8 *)&pNode[1];
161832  pNode->nRef = 1;
161833  pNode->pParent = pParent;
161834  pNode->isDirty = 1;
161835  nodeReference(pParent);
161836  }
161837  return pNode;
161838 }
161839 
161840 /*
161841 ** Obtain a reference to an r-tree node.
161842 */
161843 static int nodeAcquire(
161844  Rtree *pRtree, /* R-tree structure */
161845  i64 iNode, /* Node number to load */
161846  RtreeNode *pParent, /* Either the parent node or NULL */
161847  RtreeNode **ppNode /* OUT: Acquired node */
161848 ){
161849  int rc;
161850  int rc2 = SQLITE_OK;
161851  RtreeNode *pNode;
161852 
161853  /* Check if the requested node is already in the hash table. If so,
161854  ** increase its reference count and return it.
161855  */
161856  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
161857  assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
161858  if( pParent && !pNode->pParent ){
161859  nodeReference(pParent);
161860  pNode->pParent = pParent;
161861  }
161862  pNode->nRef++;
161863  *ppNode = pNode;
161864  return SQLITE_OK;
161865  }
161866 
161867  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
161868  rc = sqlite3_step(pRtree->pReadNode);
161869  if( rc==SQLITE_ROW ){
161870  const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
161871  if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
161872  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
161873  if( !pNode ){
161874  rc2 = SQLITE_NOMEM;
161875  }else{
161876  pNode->pParent = pParent;
161877  pNode->zData = (u8 *)&pNode[1];
161878  pNode->nRef = 1;
161879  pNode->iNode = iNode;
161880  pNode->isDirty = 0;
161881  pNode->pNext = 0;
161882  memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
161883  nodeReference(pParent);
161884  }
161885  }
161886  }
161887  rc = sqlite3_reset(pRtree->pReadNode);
161888  if( rc==SQLITE_OK ) rc = rc2;
161889 
161890  /* If the root node was just loaded, set pRtree->iDepth to the height
161891  ** of the r-tree structure. A height of zero means all data is stored on
161892  ** the root node. A height of one means the children of the root node
161893  ** are the leaves, and so on. If the depth as specified on the root node
161894  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
161895  */
161896  if( pNode && iNode==1 ){
161897  pRtree->iDepth = readInt16(pNode->zData);
161898  if( pRtree->iDepth>RTREE_MAX_DEPTH ){
161899  rc = SQLITE_CORRUPT_VTAB;
161900  }
161901  }
161902 
161903  /* If no error has occurred so far, check if the "number of entries"
161904  ** field on the node is too large. If so, set the return code to
161905  ** SQLITE_CORRUPT_VTAB.
161906  */
161907  if( pNode && rc==SQLITE_OK ){
161908  if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
161909  rc = SQLITE_CORRUPT_VTAB;
161910  }
161911  }
161912 
161913  if( rc==SQLITE_OK ){
161914  if( pNode!=0 ){
161915  nodeHashInsert(pRtree, pNode);
161916  }else{
161917  rc = SQLITE_CORRUPT_VTAB;
161918  }
161919  *ppNode = pNode;
161920  }else{
161921  sqlite3_free(pNode);
161922  *ppNode = 0;
161923  }
161924 
161925  return rc;
161926 }
161927 
161928 /*
161929 ** Overwrite cell iCell of node pNode with the contents of pCell.
161930 */
161931 static void nodeOverwriteCell(
161932  Rtree *pRtree, /* The overall R-Tree */
161933  RtreeNode *pNode, /* The node into which the cell is to be written */
161934  RtreeCell *pCell, /* The cell to write */
161935  int iCell /* Index into pNode into which pCell is written */
161936 ){
161937  int ii;
161938  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
161939  p += writeInt64(p, pCell->iRowid);
161940  for(ii=0; ii<(pRtree->nDim*2); ii++){
161941  p += writeCoord(p, &pCell->aCoord[ii]);
161942  }
161943  pNode->isDirty = 1;
161944 }
161945 
161946 /*
161947 ** Remove the cell with index iCell from node pNode.
161948 */
161949 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
161950  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
161951  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
161952  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
161953  memmove(pDst, pSrc, nByte);
161954  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
161955  pNode->isDirty = 1;
161956 }
161957 
161958 /*
161959 ** Insert the contents of cell pCell into node pNode. If the insert
161960 ** is successful, return SQLITE_OK.
161961 **
161962 ** If there is not enough free space in pNode, return SQLITE_FULL.
161963 */
161964 static int nodeInsertCell(
161965  Rtree *pRtree, /* The overall R-Tree */
161966  RtreeNode *pNode, /* Write new cell into this node */
161967  RtreeCell *pCell /* The cell to be inserted */
161968 ){
161969  int nCell; /* Current number of cells in pNode */
161970  int nMaxCell; /* Maximum number of cells for pNode */
161971 
161972  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
161973  nCell = NCELL(pNode);
161974 
161975  assert( nCell<=nMaxCell );
161976  if( nCell<nMaxCell ){
161977  nodeOverwriteCell(pRtree, pNode, pCell, nCell);
161978  writeInt16(&pNode->zData[2], nCell+1);
161979  pNode->isDirty = 1;
161980  }
161981 
161982  return (nCell==nMaxCell);
161983 }
161984 
161985 /*
161986 ** If the node is dirty, write it out to the database.
161987 */
161988 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
161989  int rc = SQLITE_OK;
161990  if( pNode->isDirty ){
161991  sqlite3_stmt *p = pRtree->pWriteNode;
161992  if( pNode->iNode ){
161993  sqlite3_bind_int64(p, 1, pNode->iNode);
161994  }else{
161995  sqlite3_bind_null(p, 1);
161996  }
161997  sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
161998  sqlite3_step(p);
161999  pNode->isDirty = 0;
162000  rc = sqlite3_reset(p);
162001  if( pNode->iNode==0 && rc==SQLITE_OK ){
162002  pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
162003  nodeHashInsert(pRtree, pNode);
162004  }
162005  }
162006  return rc;
162007 }
162008 
162009 /*
162010 ** Release a reference to a node. If the node is dirty and the reference
162011 ** count drops to zero, the node data is written to the database.
162012 */
162013 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
162014  int rc = SQLITE_OK;
162015  if( pNode ){
162016  assert( pNode->nRef>0 );
162017  pNode->nRef--;
162018  if( pNode->nRef==0 ){
162019  if( pNode->iNode==1 ){
162020  pRtree->iDepth = -1;
162021  }
162022  if( pNode->pParent ){
162023  rc = nodeRelease(pRtree, pNode->pParent);
162024  }
162025  if( rc==SQLITE_OK ){
162026  rc = nodeWrite(pRtree, pNode);
162027  }
162028  nodeHashDelete(pRtree, pNode);
162029  sqlite3_free(pNode);
162030  }
162031  }
162032  return rc;
162033 }
162034 
162035 /*
162036 ** Return the 64-bit integer value associated with cell iCell of
162037 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
162038 ** an internal node, then the 64-bit integer is a child page number.
162039 */
162040 static i64 nodeGetRowid(
162041  Rtree *pRtree, /* The overall R-Tree */
162042  RtreeNode *pNode, /* The node from which to extract the ID */
162043  int iCell /* The cell index from which to extract the ID */
162044 ){
162045  assert( iCell<NCELL(pNode) );
162046  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
162047 }
162048 
162049 /*
162050 ** Return coordinate iCoord from cell iCell in node pNode.
162051 */
162052 static void nodeGetCoord(
162053  Rtree *pRtree, /* The overall R-Tree */
162054  RtreeNode *pNode, /* The node from which to extract a coordinate */
162055  int iCell, /* The index of the cell within the node */
162056  int iCoord, /* Which coordinate to extract */
162057  RtreeCoord *pCoord /* OUT: Space to write result to */
162058 ){
162059  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
162060 }
162061 
162062 /*
162063 ** Deserialize cell iCell of node pNode. Populate the structure pointed
162064 ** to by pCell with the results.
162065 */
162066 static void nodeGetCell(
162067  Rtree *pRtree, /* The overall R-Tree */
162068  RtreeNode *pNode, /* The node containing the cell to be read */
162069  int iCell, /* Index of the cell within the node */
162070  RtreeCell *pCell /* OUT: Write the cell contents here */
162071 ){
162072  u8 *pData;
162073  RtreeCoord *pCoord;
162074  int ii;
162075  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
162076  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
162077  pCoord = pCell->aCoord;
162078  for(ii=0; ii<pRtree->nDim*2; ii++){
162079  readCoord(&pData[ii*4], &pCoord[ii]);
162080  }
162081 }
162082 
162083 
162084 /* Forward declaration for the function that does the work of
162085 ** the virtual table module xCreate() and xConnect() methods.
162086 */
162087 static int rtreeInit(
162088  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
162089 );
162090 
162091 /*
162092 ** Rtree virtual table module xCreate method.
162093 */
162094 static int rtreeCreate(
162095  sqlite3 *db,
162096  void *pAux,
162097  int argc, const char *const*argv,
162098  sqlite3_vtab **ppVtab,
162099  char **pzErr
162100 ){
162101  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
162102 }
162103 
162104 /*
162105 ** Rtree virtual table module xConnect method.
162106 */
162107 static int rtreeConnect(
162108  sqlite3 *db,
162109  void *pAux,
162110  int argc, const char *const*argv,
162111  sqlite3_vtab **ppVtab,
162112  char **pzErr
162113 ){
162114  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
162115 }
162116 
162117 /*
162118 ** Increment the r-tree reference count.
162119 */
162120 static void rtreeReference(Rtree *pRtree){
162121  pRtree->nBusy++;
162122 }
162123 
162124 /*
162125 ** Decrement the r-tree reference count. When the reference count reaches
162126 ** zero the structure is deleted.
162127 */
162128 static void rtreeRelease(Rtree *pRtree){
162129  pRtree->nBusy--;
162130  if( pRtree->nBusy==0 ){
162131  sqlite3_finalize(pRtree->pReadNode);
162132  sqlite3_finalize(pRtree->pWriteNode);
162133  sqlite3_finalize(pRtree->pDeleteNode);
162134  sqlite3_finalize(pRtree->pReadRowid);
162135  sqlite3_finalize(pRtree->pWriteRowid);
162136  sqlite3_finalize(pRtree->pDeleteRowid);
162137  sqlite3_finalize(pRtree->pReadParent);
162138  sqlite3_finalize(pRtree->pWriteParent);
162139  sqlite3_finalize(pRtree->pDeleteParent);
162140  sqlite3_free(pRtree);
162141  }
162142 }
162143 
162144 /*
162145 ** Rtree virtual table module xDisconnect method.
162146 */
162147 static int rtreeDisconnect(sqlite3_vtab *pVtab){
162148  rtreeRelease((Rtree *)pVtab);
162149  return SQLITE_OK;
162150 }
162151 
162152 /*
162153 ** Rtree virtual table module xDestroy method.
162154 */
162155 static int rtreeDestroy(sqlite3_vtab *pVtab){
162156  Rtree *pRtree = (Rtree *)pVtab;
162157  int rc;
162158  char *zCreate = sqlite3_mprintf(
162159  "DROP TABLE '%q'.'%q_node';"
162160  "DROP TABLE '%q'.'%q_rowid';"
162161  "DROP TABLE '%q'.'%q_parent';",
162162  pRtree->zDb, pRtree->zName,
162163  pRtree->zDb, pRtree->zName,
162164  pRtree->zDb, pRtree->zName
162165  );
162166  if( !zCreate ){
162167  rc = SQLITE_NOMEM;
162168  }else{
162169  rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
162170  sqlite3_free(zCreate);
162171  }
162172  if( rc==SQLITE_OK ){
162173  rtreeRelease(pRtree);
162174  }
162175 
162176  return rc;
162177 }
162178 
162179 /*
162180 ** Rtree virtual table module xOpen method.
162181 */
162182 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
162183  int rc = SQLITE_NOMEM;
162184  RtreeCursor *pCsr;
162185 
162186  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
162187  if( pCsr ){
162188  memset(pCsr, 0, sizeof(RtreeCursor));
162189  pCsr->base.pVtab = pVTab;
162190  rc = SQLITE_OK;
162191  }
162192  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
162193 
162194  return rc;
162195 }
162196 
162197 
162198 /*
162199 ** Free the RtreeCursor.aConstraint[] array and its contents.
162200 */
162201 static void freeCursorConstraints(RtreeCursor *pCsr){
162202  if( pCsr->aConstraint ){
162203  int i; /* Used to iterate through constraint array */
162204  for(i=0; i<pCsr->nConstraint; i++){
162205  sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
162206  if( pInfo ){
162207  if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
162208  sqlite3_free(pInfo);
162209  }
162210  }
162211  sqlite3_free(pCsr->aConstraint);
162212  pCsr->aConstraint = 0;
162213  }
162214 }
162215 
162216 /*
162217 ** Rtree virtual table module xClose method.
162218 */
162219 static int rtreeClose(sqlite3_vtab_cursor *cur){
162220  Rtree *pRtree = (Rtree *)(cur->pVtab);
162221  int ii;
162222  RtreeCursor *pCsr = (RtreeCursor *)cur;
162223  freeCursorConstraints(pCsr);
162224  sqlite3_free(pCsr->aPoint);
162225  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
162226  sqlite3_free(pCsr);
162227  return SQLITE_OK;
162228 }
162229 
162230 /*
162231 ** Rtree virtual table module xEof method.
162232 **
162233 ** Return non-zero if the cursor does not currently point to a valid
162234 ** record (i.e if the scan has finished), or zero otherwise.
162235 */
162236 static int rtreeEof(sqlite3_vtab_cursor *cur){
162237  RtreeCursor *pCsr = (RtreeCursor *)cur;
162238  return pCsr->atEOF;
162239 }
162240 
162241 /*
162242 ** Convert raw bits from the on-disk RTree record into a coordinate value.
162243 ** The on-disk format is big-endian and needs to be converted for little-
162244 ** endian platforms. The on-disk record stores integer coordinates if
162245 ** eInt is true and it stores 32-bit floating point records if eInt is
162246 ** false. a[] is the four bytes of the on-disk record to be decoded.
162247 ** Store the results in "r".
162248 **
162249 ** There are three versions of this macro, one each for little-endian and
162250 ** big-endian processors and a third generic implementation. The endian-
162251 ** specific implementations are much faster and are preferred if the
162252 ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
162253 ** macro is part of sqliteInt.h and hence the endian-specific
162254 ** implementation will only be used if this module is compiled as part
162255 ** of the amalgamation.
162256 */
162257 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
162258 #define RTREE_DECODE_COORD(eInt, a, r) { \
162259  RtreeCoord c; /* Coordinate decoded */ \
162260  memcpy(&c.u,a,4); \
162261  c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
162262  ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
162263  r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
162264 }
162265 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
162266 #define RTREE_DECODE_COORD(eInt, a, r) { \
162267  RtreeCoord c; /* Coordinate decoded */ \
162268  memcpy(&c.u,a,4); \
162269  r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
162270 }
162271 #else
162272 #define RTREE_DECODE_COORD(eInt, a, r) { \
162273  RtreeCoord c; /* Coordinate decoded */ \
162274  c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
162275  +((u32)a[2]<<8) + a[3]; \
162276  r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
162277 }
162278 #endif
162279 
162280 /*
162281 ** Check the RTree node or entry given by pCellData and p against the MATCH
162282 ** constraint pConstraint.
162283 */
162284 static int rtreeCallbackConstraint(
162285  RtreeConstraint *pConstraint, /* The constraint to test */
162286  int eInt, /* True if RTree holding integer coordinates */
162287  u8 *pCellData, /* Raw cell content */
162288  RtreeSearchPoint *pSearch, /* Container of this cell */
162289  sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
162290  int *peWithin /* OUT: visibility of the cell */
162291 ){
162292  int i; /* Loop counter */
162293  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
162294  int nCoord = pInfo->nCoord; /* No. of coordinates */
162295  int rc; /* Callback return code */
162296  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
162297 
162298  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
162299  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
162300 
162301  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
162302  pInfo->iRowid = readInt64(pCellData);
162303  }
162304  pCellData += 8;
162305  for(i=0; i<nCoord; i++, pCellData += 4){
162306  RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
162307  }
162308  if( pConstraint->op==RTREE_MATCH ){
162309  rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
162310  nCoord, aCoord, &i);
162311  if( i==0 ) *peWithin = NOT_WITHIN;
162312  *prScore = RTREE_ZERO;
162313  }else{
162314  pInfo->aCoord = aCoord;
162315  pInfo->iLevel = pSearch->iLevel - 1;
162316  pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
162317  pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
162318  rc = pConstraint->u.xQueryFunc(pInfo);
162319  if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
162320  if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
162321  *prScore = pInfo->rScore;
162322  }
162323  }
162324  return rc;
162325 }
162326 
162327 /*
162328 ** Check the internal RTree node given by pCellData against constraint p.
162329 ** If this constraint cannot be satisfied by any child within the node,
162330 ** set *peWithin to NOT_WITHIN.
162331 */
162332 static void rtreeNonleafConstraint(
162333  RtreeConstraint *p, /* The constraint to test */
162334  int eInt, /* True if RTree holds integer coordinates */
162335  u8 *pCellData, /* Raw cell content as appears on disk */
162336  int *peWithin /* Adjust downward, as appropriate */
162337 ){
162338  sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
162339 
162340  /* p->iCoord might point to either a lower or upper bound coordinate
162341  ** in a coordinate pair. But make pCellData point to the lower bound.
162342  */
162343  pCellData += 8 + 4*(p->iCoord&0xfe);
162344 
162345  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
162346  || p->op==RTREE_GT || p->op==RTREE_EQ );
162347  switch( p->op ){
162348  case RTREE_LE:
162349  case RTREE_LT:
162350  case RTREE_EQ:
162351  RTREE_DECODE_COORD(eInt, pCellData, val);
162352  /* val now holds the lower bound of the coordinate pair */
162353  if( p->u.rValue>=val ) return;
162354  if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
162355  /* Fall through for the RTREE_EQ case */
162356 
162357  default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
162358  pCellData += 4;
162359  RTREE_DECODE_COORD(eInt, pCellData, val);
162360  /* val now holds the upper bound of the coordinate pair */
162361  if( p->u.rValue<=val ) return;
162362  }
162363  *peWithin = NOT_WITHIN;
162364 }
162365 
162366 /*
162367 ** Check the leaf RTree cell given by pCellData against constraint p.
162368 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
162369 ** If the constraint is satisfied, leave *peWithin unchanged.
162370 **
162371 ** The constraint is of the form: xN op $val
162372 **
162373 ** The op is given by p->op. The xN is p->iCoord-th coordinate in
162374 ** pCellData. $val is given by p->u.rValue.
162375 */
162376 static void rtreeLeafConstraint(
162377  RtreeConstraint *p, /* The constraint to test */
162378  int eInt, /* True if RTree holds integer coordinates */
162379  u8 *pCellData, /* Raw cell content as appears on disk */
162380  int *peWithin /* Adjust downward, as appropriate */
162381 ){
162382  RtreeDValue xN; /* Coordinate value converted to a double */
162383 
162384  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
162385  || p->op==RTREE_GT || p->op==RTREE_EQ );
162386  pCellData += 8 + p->iCoord*4;
162387  RTREE_DECODE_COORD(eInt, pCellData, xN);
162388  switch( p->op ){
162389  case RTREE_LE: if( xN <= p->u.rValue ) return; break;
162390  case RTREE_LT: if( xN < p->u.rValue ) return; break;
162391  case RTREE_GE: if( xN >= p->u.rValue ) return; break;
162392  case RTREE_GT: if( xN > p->u.rValue ) return; break;
162393  default: if( xN == p->u.rValue ) return; break;
162394  }
162395  *peWithin = NOT_WITHIN;
162396 }
162397 
162398 /*
162399 ** One of the cells in node pNode is guaranteed to have a 64-bit
162400 ** integer value equal to iRowid. Return the index of this cell.
162401 */
162402 static int nodeRowidIndex(
162403  Rtree *pRtree,
162404  RtreeNode *pNode,
162405  i64 iRowid,
162406  int *piIndex
162407 ){
162408  int ii;
162409  int nCell = NCELL(pNode);
162410  assert( nCell<200 );
162411  for(ii=0; ii<nCell; ii++){
162412  if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
162413  *piIndex = ii;
162414  return SQLITE_OK;
162415  }
162416  }
162417  return SQLITE_CORRUPT_VTAB;
162418 }
162419 
162420 /*
162421 ** Return the index of the cell containing a pointer to node pNode
162422 ** in its parent. If pNode is the root node, return -1.
162423 */
162424 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
162425  RtreeNode *pParent = pNode->pParent;
162426  if( pParent ){
162427  return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
162428  }
162429  *piIndex = -1;
162430  return SQLITE_OK;
162431 }
162432 
162433 /*
162434 ** Compare two search points. Return negative, zero, or positive if the first
162435 ** is less than, equal to, or greater than the second.
162436 **
162437 ** The rScore is the primary key. Smaller rScore values come first.
162438 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
162439 ** iLevel values coming first. In this way, if rScore is the same for all
162440 ** SearchPoints, then iLevel becomes the deciding factor and the result
162441 ** is a depth-first search, which is the desired default behavior.
162442 */
162443 static int rtreeSearchPointCompare(
162444  const RtreeSearchPoint *pA,
162445  const RtreeSearchPoint *pB
162446 ){
162447  if( pA->rScore<pB->rScore ) return -1;
162448  if( pA->rScore>pB->rScore ) return +1;
162449  if( pA->iLevel<pB->iLevel ) return -1;
162450  if( pA->iLevel>pB->iLevel ) return +1;
162451  return 0;
162452 }
162453 
162454 /*
162455 ** Interchange to search points in a cursor.
162456 */
162457 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
162458  RtreeSearchPoint t = p->aPoint[i];
162459  assert( i<j );
162460  p->aPoint[i] = p->aPoint[j];
162461  p->aPoint[j] = t;
162462  i++; j++;
162463  if( i<RTREE_CACHE_SZ ){
162464  if( j>=RTREE_CACHE_SZ ){
162465  nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
162466  p->aNode[i] = 0;
162467  }else{
162468  RtreeNode *pTemp = p->aNode[i];
162469  p->aNode[i] = p->aNode[j];
162470  p->aNode[j] = pTemp;
162471  }
162472  }
162473 }
162474 
162475 /*
162476 ** Return the search point with the lowest current score.
162477 */
162478 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
162479  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
162480 }
162481 
162482 /*
162483 ** Get the RtreeNode for the search point with the lowest score.
162484 */
162485 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
162486  sqlite3_int64 id;
162487  int ii = 1 - pCur->bPoint;
162488  assert( ii==0 || ii==1 );
162489  assert( pCur->bPoint || pCur->nPoint );
162490  if( pCur->aNode[ii]==0 ){
162491  assert( pRC!=0 );
162492  id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
162493  *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
162494  }
162495  return pCur->aNode[ii];
162496 }
162497 
162498 /*
162499 ** Push a new element onto the priority queue
162500 */
162501 static RtreeSearchPoint *rtreeEnqueue(
162502  RtreeCursor *pCur, /* The cursor */
162503  RtreeDValue rScore, /* Score for the new search point */
162504  u8 iLevel /* Level for the new search point */
162505 ){
162506  int i, j;
162507  RtreeSearchPoint *pNew;
162508  if( pCur->nPoint>=pCur->nPointAlloc ){
162509  int nNew = pCur->nPointAlloc*2 + 8;
162510  pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
162511  if( pNew==0 ) return 0;
162512  pCur->aPoint = pNew;
162513  pCur->nPointAlloc = nNew;
162514  }
162515  i = pCur->nPoint++;
162516  pNew = pCur->aPoint + i;
162517  pNew->rScore = rScore;
162518  pNew->iLevel = iLevel;
162519  assert( iLevel<=RTREE_MAX_DEPTH );
162520  while( i>0 ){
162521  RtreeSearchPoint *pParent;
162522  j = (i-1)/2;
162523  pParent = pCur->aPoint + j;
162524  if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
162525  rtreeSearchPointSwap(pCur, j, i);
162526  i = j;
162527  pNew = pParent;
162528  }
162529  return pNew;
162530 }
162531 
162532 /*
162533 ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
162534 ** NULL if malloc fails.
162535 */
162536 static RtreeSearchPoint *rtreeSearchPointNew(
162537  RtreeCursor *pCur, /* The cursor */
162538  RtreeDValue rScore, /* Score for the new search point */
162539  u8 iLevel /* Level for the new search point */
162540 ){
162541  RtreeSearchPoint *pNew, *pFirst;
162542  pFirst = rtreeSearchPointFirst(pCur);
162543  pCur->anQueue[iLevel]++;
162544  if( pFirst==0
162545  || pFirst->rScore>rScore
162546  || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
162547  ){
162548  if( pCur->bPoint ){
162549  int ii;
162550  pNew = rtreeEnqueue(pCur, rScore, iLevel);
162551  if( pNew==0 ) return 0;
162552  ii = (int)(pNew - pCur->aPoint) + 1;
162553  if( ii<RTREE_CACHE_SZ ){
162554  assert( pCur->aNode[ii]==0 );
162555  pCur->aNode[ii] = pCur->aNode[0];
162556  }else{
162557  nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
162558  }
162559  pCur->aNode[0] = 0;
162560  *pNew = pCur->sPoint;
162561  }
162562  pCur->sPoint.rScore = rScore;
162563  pCur->sPoint.iLevel = iLevel;
162564  pCur->bPoint = 1;
162565  return &pCur->sPoint;
162566  }else{
162567  return rtreeEnqueue(pCur, rScore, iLevel);
162568  }
162569 }
162570 
162571 #if 0
162572 /* Tracing routines for the RtreeSearchPoint queue */
162573 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
162574  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
162575  printf(" %d.%05lld.%02d %g %d",
162576  p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
162577  );
162578  idx++;
162579  if( idx<RTREE_CACHE_SZ ){
162580  printf(" %p\n", pCur->aNode[idx]);
162581  }else{
162582  printf("\n");
162583  }
162584 }
162585 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
162586  int ii;
162587  printf("=== %9s ", zPrefix);
162588  if( pCur->bPoint ){
162589  tracePoint(&pCur->sPoint, -1, pCur);
162590  }
162591  for(ii=0; ii<pCur->nPoint; ii++){
162592  if( ii>0 || pCur->bPoint ) printf(" ");
162593  tracePoint(&pCur->aPoint[ii], ii, pCur);
162594  }
162595 }
162596 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
162597 #else
162598 # define RTREE_QUEUE_TRACE(A,B) /* no-op */
162599 #endif
162600 
162601 /* Remove the search point with the lowest current score.
162602 */
162603 static void rtreeSearchPointPop(RtreeCursor *p){
162604  int i, j, k, n;
162605  i = 1 - p->bPoint;
162606  assert( i==0 || i==1 );
162607  if( p->aNode[i] ){
162608  nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
162609  p->aNode[i] = 0;
162610  }
162611  if( p->bPoint ){
162612  p->anQueue[p->sPoint.iLevel]--;
162613  p->bPoint = 0;
162614  }else if( p->nPoint ){
162615  p->anQueue[p->aPoint[0].iLevel]--;
162616  n = --p->nPoint;
162617  p->aPoint[0] = p->aPoint[n];
162618  if( n<RTREE_CACHE_SZ-1 ){
162619  p->aNode[1] = p->aNode[n+1];
162620  p->aNode[n+1] = 0;
162621  }
162622  i = 0;
162623  while( (j = i*2+1)<n ){
162624  k = j+1;
162625  if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
162626  if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
162627  rtreeSearchPointSwap(p, i, k);
162628  i = k;
162629  }else{
162630  break;
162631  }
162632  }else{
162633  if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
162634  rtreeSearchPointSwap(p, i, j);
162635  i = j;
162636  }else{
162637  break;
162638  }
162639  }
162640  }
162641  }
162642 }
162643 
162644 
162645 /*
162646 ** Continue the search on cursor pCur until the front of the queue
162647 ** contains an entry suitable for returning as a result-set row,
162648 ** or until the RtreeSearchPoint queue is empty, indicating that the
162649 ** query has completed.
162650 */
162651 static int rtreeStepToLeaf(RtreeCursor *pCur){
162652  RtreeSearchPoint *p;
162653  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
162654  RtreeNode *pNode;
162655  int eWithin;
162656  int rc = SQLITE_OK;
162657  int nCell;
162658  int nConstraint = pCur->nConstraint;
162659  int ii;
162660  int eInt;
162661  RtreeSearchPoint x;
162662 
162663  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
162664  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
162665  pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
162666  if( rc ) return rc;
162667  nCell = NCELL(pNode);
162668  assert( nCell<200 );
162669  while( p->iCell<nCell ){
162670  sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
162671  u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
162672  eWithin = FULLY_WITHIN;
162673  for(ii=0; ii<nConstraint; ii++){
162674  RtreeConstraint *pConstraint = pCur->aConstraint + ii;
162675  if( pConstraint->op>=RTREE_MATCH ){
162676  rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
162677  &rScore, &eWithin);
162678  if( rc ) return rc;
162679  }else if( p->iLevel==1 ){
162680  rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
162681  }else{
162682  rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
162683  }
162684  if( eWithin==NOT_WITHIN ) break;
162685  }
162686  p->iCell++;
162687  if( eWithin==NOT_WITHIN ) continue;
162688  x.iLevel = p->iLevel - 1;
162689  if( x.iLevel ){
162690  x.id = readInt64(pCellData);
162691  x.iCell = 0;
162692  }else{
162693  x.id = p->id;
162694  x.iCell = p->iCell - 1;
162695  }
162696  if( p->iCell>=nCell ){
162697  RTREE_QUEUE_TRACE(pCur, "POP-S:");
162698  rtreeSearchPointPop(pCur);
162699  }
162700  if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
162701  p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
162702  if( p==0 ) return SQLITE_NOMEM;
162703  p->eWithin = eWithin;
162704  p->id = x.id;
162705  p->iCell = x.iCell;
162706  RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
162707  break;
162708  }
162709  if( p->iCell>=nCell ){
162710  RTREE_QUEUE_TRACE(pCur, "POP-Se:");
162711  rtreeSearchPointPop(pCur);
162712  }
162713  }
162714  pCur->atEOF = p==0;
162715  return SQLITE_OK;
162716 }
162717 
162718 /*
162719 ** Rtree virtual table module xNext method.
162720 */
162721 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
162722  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
162723  int rc = SQLITE_OK;
162724 
162725  /* Move to the next entry that matches the configured constraints. */
162726  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
162727  rtreeSearchPointPop(pCsr);
162728  rc = rtreeStepToLeaf(pCsr);
162729  return rc;
162730 }
162731 
162732 /*
162733 ** Rtree virtual table module xRowid method.
162734 */
162735 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
162736  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
162737  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
162738  int rc = SQLITE_OK;
162739  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
162740  if( rc==SQLITE_OK && p ){
162741  *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
162742  }
162743  return rc;
162744 }
162745 
162746 /*
162747 ** Rtree virtual table module xColumn method.
162748 */
162749 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
162750  Rtree *pRtree = (Rtree *)cur->pVtab;
162751  RtreeCursor *pCsr = (RtreeCursor *)cur;
162752  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
162753  RtreeCoord c;
162754  int rc = SQLITE_OK;
162755  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
162756 
162757  if( rc ) return rc;
162758  if( p==0 ) return SQLITE_OK;
162759  if( i==0 ){
162760  sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
162761  }else{
162762  if( rc ) return rc;
162763  nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
162764 #ifndef SQLITE_RTREE_INT_ONLY
162765  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
162766  sqlite3_result_double(ctx, c.f);
162767  }else
162768 #endif
162769  {
162770  assert( pRtree->eCoordType==RTREE_COORD_INT32 );
162771  sqlite3_result_int(ctx, c.i);
162772  }
162773  }
162774  return SQLITE_OK;
162775 }
162776 
162777 /*
162778 ** Use nodeAcquire() to obtain the leaf node containing the record with
162779 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
162780 ** return SQLITE_OK. If there is no such record in the table, set
162781 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
162782 ** to zero and return an SQLite error code.
162783 */
162784 static int findLeafNode(
162785  Rtree *pRtree, /* RTree to search */
162786  i64 iRowid, /* The rowid searching for */
162787  RtreeNode **ppLeaf, /* Write the node here */
162788  sqlite3_int64 *piNode /* Write the node-id here */
162789 ){
162790  int rc;
162791  *ppLeaf = 0;
162792  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
162793  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
162794  i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
162795  if( piNode ) *piNode = iNode;
162796  rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
162797  sqlite3_reset(pRtree->pReadRowid);
162798  }else{
162799  rc = sqlite3_reset(pRtree->pReadRowid);
162800  }
162801  return rc;
162802 }
162803 
162804 /*
162805 ** This function is called to configure the RtreeConstraint object passed
162806 ** as the second argument for a MATCH constraint. The value passed as the
162807 ** first argument to this function is the right-hand operand to the MATCH
162808 ** operator.
162809 */
162810 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
162811  RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
162812  sqlite3_rtree_query_info *pInfo; /* Callback information */
162813  int nBlob; /* Size of the geometry function blob */
162814  int nExpected; /* Expected size of the BLOB */
162815 
162816  /* Check that value is actually a blob. */
162817  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
162818 
162819  /* Check that the blob is roughly the right size. */
162820  nBlob = sqlite3_value_bytes(pValue);
162821  if( nBlob<(int)sizeof(RtreeMatchArg) ){
162822  return SQLITE_ERROR;
162823  }
162824 
162825  pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
162826  if( !pInfo ) return SQLITE_NOMEM;
162827  memset(pInfo, 0, sizeof(*pInfo));
162828  pBlob = (RtreeMatchArg*)&pInfo[1];
162829 
162830  memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
162831  nExpected = (int)(sizeof(RtreeMatchArg) +
162832  pBlob->nParam*sizeof(sqlite3_value*) +
162833  (pBlob->nParam-1)*sizeof(RtreeDValue));
162834  if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
162835  sqlite3_free(pInfo);
162836  return SQLITE_ERROR;
162837  }
162838  pInfo->pContext = pBlob->cb.pContext;
162839  pInfo->nParam = pBlob->nParam;
162840  pInfo->aParam = pBlob->aParam;
162841  pInfo->apSqlParam = pBlob->apSqlParam;
162842 
162843  if( pBlob->cb.xGeom ){
162844  pCons->u.xGeom = pBlob->cb.xGeom;
162845  }else{
162846  pCons->op = RTREE_QUERY;
162847  pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
162848  }
162849  pCons->pInfo = pInfo;
162850  return SQLITE_OK;
162851 }
162852 
162853 /*
162854 ** Rtree virtual table module xFilter method.
162855 */
162856 static int rtreeFilter(
162857  sqlite3_vtab_cursor *pVtabCursor,
162858  int idxNum, const char *idxStr,
162859  int argc, sqlite3_value **argv
162860 ){
162861  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
162862  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
162863  RtreeNode *pRoot = 0;
162864  int ii;
162865  int rc = SQLITE_OK;
162866  int iCell = 0;
162867 
162868  rtreeReference(pRtree);
162869 
162870  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
162871  freeCursorConstraints(pCsr);
162872  sqlite3_free(pCsr->aPoint);
162873  memset(pCsr, 0, sizeof(RtreeCursor));
162874  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
162875 
162876  pCsr->iStrategy = idxNum;
162877  if( idxNum==1 ){
162878  /* Special case - lookup by rowid. */
162879  RtreeNode *pLeaf; /* Leaf on which the required cell resides */
162880  RtreeSearchPoint *p; /* Search point for the leaf */
162881  i64 iRowid = sqlite3_value_int64(argv[0]);
162882  i64 iNode = 0;
162883  rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
162884  if( rc==SQLITE_OK && pLeaf!=0 ){
162885  p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
162886  assert( p!=0 ); /* Always returns pCsr->sPoint */
162887  pCsr->aNode[0] = pLeaf;
162888  p->id = iNode;
162889  p->eWithin = PARTLY_WITHIN;
162890  rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
162891  p->iCell = iCell;
162892  RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
162893  }else{
162894  pCsr->atEOF = 1;
162895  }
162896  }else{
162897  /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
162898  ** with the configured constraints.
162899  */
162900  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
162901  if( rc==SQLITE_OK && argc>0 ){
162902  pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
162903  pCsr->nConstraint = argc;
162904  if( !pCsr->aConstraint ){
162905  rc = SQLITE_NOMEM;
162906  }else{
162907  memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
162908  memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
162909  assert( (idxStr==0 && argc==0)
162910  || (idxStr && (int)strlen(idxStr)==argc*2) );
162911  for(ii=0; ii<argc; ii++){
162912  RtreeConstraint *p = &pCsr->aConstraint[ii];
162913  p->op = idxStr[ii*2];
162914  p->iCoord = idxStr[ii*2+1]-'0';
162915  if( p->op>=RTREE_MATCH ){
162916  /* A MATCH operator. The right-hand-side must be a blob that
162917  ** can be cast into an RtreeMatchArg object. One created using
162918  ** an sqlite3_rtree_geometry_callback() SQL user function.
162919  */
162920  rc = deserializeGeometry(argv[ii], p);
162921  if( rc!=SQLITE_OK ){
162922  break;
162923  }
162924  p->pInfo->nCoord = pRtree->nDim*2;
162925  p->pInfo->anQueue = pCsr->anQueue;
162926  p->pInfo->mxLevel = pRtree->iDepth + 1;
162927  }else{
162928 #ifdef SQLITE_RTREE_INT_ONLY
162929  p->u.rValue = sqlite3_value_int64(argv[ii]);
162930 #else
162931  p->u.rValue = sqlite3_value_double(argv[ii]);
162932 #endif
162933  }
162934  }
162935  }
162936  }
162937  if( rc==SQLITE_OK ){
162938  RtreeSearchPoint *pNew;
162939  pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
162940  if( pNew==0 ) return SQLITE_NOMEM;
162941  pNew->id = 1;
162942  pNew->iCell = 0;
162943  pNew->eWithin = PARTLY_WITHIN;
162944  assert( pCsr->bPoint==1 );
162945  pCsr->aNode[0] = pRoot;
162946  pRoot = 0;
162947  RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
162948  rc = rtreeStepToLeaf(pCsr);
162949  }
162950  }
162951 
162952  nodeRelease(pRtree, pRoot);
162953  rtreeRelease(pRtree);
162954  return rc;
162955 }
162956 
162957 /*
162958 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
162959 ** extension is currently being used by a version of SQLite too old to
162960 ** support estimatedRows. In that case this function is a no-op.
162961 */
162962 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
162963 #if SQLITE_VERSION_NUMBER>=3008002
162964  if( sqlite3_libversion_number()>=3008002 ){
162965  pIdxInfo->estimatedRows = nRow;
162966  }
162967 #endif
162968 }
162969 
162970 /*
162971 ** Rtree virtual table module xBestIndex method. There are three
162972 ** table scan strategies to choose from (in order from most to
162973 ** least desirable):
162974 **
162975 ** idxNum idxStr Strategy
162976 ** ------------------------------------------------
162977 ** 1 Unused Direct lookup by rowid.
162978 ** 2 See below R-tree query or full-table scan.
162979 ** ------------------------------------------------
162980 **
162981 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
162982 ** 2 is used, idxStr is formatted to contain 2 bytes for each
162983 ** constraint used. The first two bytes of idxStr correspond to
162984 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
162985 ** (argvIndex==1) etc.
162986 **
162987 ** The first of each pair of bytes in idxStr identifies the constraint
162988 ** operator as follows:
162989 **
162990 ** Operator Byte Value
162991 ** ----------------------
162992 ** = 0x41 ('A')
162993 ** <= 0x42 ('B')
162994 ** < 0x43 ('C')
162995 ** >= 0x44 ('D')
162996 ** > 0x45 ('E')
162997 ** MATCH 0x46 ('F')
162998 ** ----------------------
162999 **
163000 ** The second of each pair of bytes identifies the coordinate column
163001 ** to which the constraint applies. The leftmost coordinate column
163002 ** is 'a', the second from the left 'b' etc.
163003 */
163004 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
163005  Rtree *pRtree = (Rtree*)tab;
163006  int rc = SQLITE_OK;
163007  int ii;
163008  int bMatch = 0; /* True if there exists a MATCH constraint */
163009  i64 nRow; /* Estimated rows returned by this scan */
163010 
163011  int iIdx = 0;
163012  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
163013  memset(zIdxStr, 0, sizeof(zIdxStr));
163014 
163015  /* Check if there exists a MATCH constraint - even an unusable one. If there
163016  ** is, do not consider the lookup-by-rowid plan as using such a plan would
163017  ** require the VDBE to evaluate the MATCH constraint, which is not currently
163018  ** possible. */
163019  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
163020  if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
163021  bMatch = 1;
163022  }
163023  }
163024 
163025  assert( pIdxInfo->idxStr==0 );
163026  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
163027  struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
163028 
163029  if( bMatch==0 && p->usable
163030  && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
163031  ){
163032  /* We have an equality constraint on the rowid. Use strategy 1. */
163033  int jj;
163034  for(jj=0; jj<ii; jj++){
163035  pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
163036  pIdxInfo->aConstraintUsage[jj].omit = 0;
163037  }
163038  pIdxInfo->idxNum = 1;
163039  pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
163040  pIdxInfo->aConstraintUsage[jj].omit = 1;
163041 
163042  /* This strategy involves a two rowid lookups on an B-Tree structures
163043  ** and then a linear search of an R-Tree node. This should be
163044  ** considered almost as quick as a direct rowid lookup (for which
163045  ** sqlite uses an internal cost of 0.0). It is expected to return
163046  ** a single row.
163047  */
163048  pIdxInfo->estimatedCost = 30.0;
163049  setEstimatedRows(pIdxInfo, 1);
163050  return SQLITE_OK;
163051  }
163052 
163053  if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
163054  u8 op;
163055  switch( p->op ){
163056  case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
163057  case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
163058  case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
163059  case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
163060  case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
163061  default:
163062  assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
163063  op = RTREE_MATCH;
163064  break;
163065  }
163066  zIdxStr[iIdx++] = op;
163067  zIdxStr[iIdx++] = p->iColumn - 1 + '0';
163068  pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
163069  pIdxInfo->aConstraintUsage[ii].omit = 1;
163070  }
163071  }
163072 
163073  pIdxInfo->idxNum = 2;
163074  pIdxInfo->needToFreeIdxStr = 1;
163075  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
163076  return SQLITE_NOMEM;
163077  }
163078 
163079  nRow = pRtree->nRowEst >> (iIdx/2);
163080  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
163081  setEstimatedRows(pIdxInfo, nRow);
163082 
163083  return rc;
163084 }
163085 
163086 /*
163087 ** Return the N-dimensional volumn of the cell stored in *p.
163088 */
163089 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
163090  RtreeDValue area = (RtreeDValue)1;
163091  int ii;
163092  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163093  area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
163094  }
163095  return area;
163096 }
163097 
163098 /*
163099 ** Return the margin length of cell p. The margin length is the sum
163100 ** of the objects size in each dimension.
163101 */
163102 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
163103  RtreeDValue margin = (RtreeDValue)0;
163104  int ii;
163105  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163106  margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
163107  }
163108  return margin;
163109 }
163110 
163111 /*
163112 ** Store the union of cells p1 and p2 in p1.
163113 */
163114 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
163115  int ii;
163116  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
163117  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163118  p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
163119  p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
163120  }
163121  }else{
163122  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163123  p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
163124  p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
163125  }
163126  }
163127 }
163128 
163129 /*
163130 ** Return true if the area covered by p2 is a subset of the area covered
163131 ** by p1. False otherwise.
163132 */
163133 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
163134  int ii;
163135  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
163136  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163137  RtreeCoord *a1 = &p1->aCoord[ii];
163138  RtreeCoord *a2 = &p2->aCoord[ii];
163139  if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
163140  || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
163141  ){
163142  return 0;
163143  }
163144  }
163145  return 1;
163146 }
163147 
163148 /*
163149 ** Return the amount cell p would grow by if it were unioned with pCell.
163150 */
163151 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
163152  RtreeDValue area;
163153  RtreeCell cell;
163154  memcpy(&cell, p, sizeof(RtreeCell));
163155  area = cellArea(pRtree, &cell);
163156  cellUnion(pRtree, &cell, pCell);
163157  return (cellArea(pRtree, &cell)-area);
163158 }
163159 
163160 static RtreeDValue cellOverlap(
163161  Rtree *pRtree,
163162  RtreeCell *p,
163163  RtreeCell *aCell,
163164  int nCell
163165 ){
163166  int ii;
163167  RtreeDValue overlap = RTREE_ZERO;
163168  for(ii=0; ii<nCell; ii++){
163169  int jj;
163170  RtreeDValue o = (RtreeDValue)1;
163171  for(jj=0; jj<(pRtree->nDim*2); jj+=2){
163172  RtreeDValue x1, x2;
163173  x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
163174  x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
163175  if( x2<x1 ){
163176  o = (RtreeDValue)0;
163177  break;
163178  }else{
163179  o = o * (x2-x1);
163180  }
163181  }
163182  overlap += o;
163183  }
163184  return overlap;
163185 }
163186 
163187 
163188 /*
163189 ** This function implements the ChooseLeaf algorithm from Gutman[84].
163190 ** ChooseSubTree in r*tree terminology.
163191 */
163192 static int ChooseLeaf(
163193  Rtree *pRtree, /* Rtree table */
163194  RtreeCell *pCell, /* Cell to insert into rtree */
163195  int iHeight, /* Height of sub-tree rooted at pCell */
163196  RtreeNode **ppLeaf /* OUT: Selected leaf page */
163197 ){
163198  int rc;
163199  int ii;
163200  RtreeNode *pNode;
163201  rc = nodeAcquire(pRtree, 1, 0, &pNode);
163202 
163203  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
163204  int iCell;
163205  sqlite3_int64 iBest = 0;
163206 
163207  RtreeDValue fMinGrowth = RTREE_ZERO;
163208  RtreeDValue fMinArea = RTREE_ZERO;
163209 
163210  int nCell = NCELL(pNode);
163211  RtreeCell cell;
163212  RtreeNode *pChild;
163213 
163214  RtreeCell *aCell = 0;
163215 
163216  /* Select the child node which will be enlarged the least if pCell
163217  ** is inserted into it. Resolve ties by choosing the entry with
163218  ** the smallest area.
163219  */
163220  for(iCell=0; iCell<nCell; iCell++){
163221  int bBest = 0;
163222  RtreeDValue growth;
163223  RtreeDValue area;
163224  nodeGetCell(pRtree, pNode, iCell, &cell);
163225  growth = cellGrowth(pRtree, &cell, pCell);
163226  area = cellArea(pRtree, &cell);
163227  if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
163228  bBest = 1;
163229  }
163230  if( bBest ){
163231  fMinGrowth = growth;
163232  fMinArea = area;
163233  iBest = cell.iRowid;
163234  }
163235  }
163236 
163237  sqlite3_free(aCell);
163238  rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
163239  nodeRelease(pRtree, pNode);
163240  pNode = pChild;
163241  }
163242 
163243  *ppLeaf = pNode;
163244  return rc;
163245 }
163246 
163247 /*
163248 ** A cell with the same content as pCell has just been inserted into
163249 ** the node pNode. This function updates the bounding box cells in
163250 ** all ancestor elements.
163251 */
163252 static int AdjustTree(
163253  Rtree *pRtree, /* Rtree table */
163254  RtreeNode *pNode, /* Adjust ancestry of this node. */
163255  RtreeCell *pCell /* This cell was just inserted */
163256 ){
163257  RtreeNode *p = pNode;
163258  while( p->pParent ){
163259  RtreeNode *pParent = p->pParent;
163260  RtreeCell cell;
163261  int iCell;
163262 
163263  if( nodeParentIndex(pRtree, p, &iCell) ){
163264  return SQLITE_CORRUPT_VTAB;
163265  }
163266 
163267  nodeGetCell(pRtree, pParent, iCell, &cell);
163268  if( !cellContains(pRtree, &cell, pCell) ){
163269  cellUnion(pRtree, &cell, pCell);
163270  nodeOverwriteCell(pRtree, pParent, &cell, iCell);
163271  }
163272 
163273  p = pParent;
163274  }
163275  return SQLITE_OK;
163276 }
163277 
163278 /*
163279 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
163280 */
163281 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
163282  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
163283  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
163284  sqlite3_step(pRtree->pWriteRowid);
163285  return sqlite3_reset(pRtree->pWriteRowid);
163286 }
163287 
163288 /*
163289 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
163290 */
163291 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
163292  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
163293  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
163294  sqlite3_step(pRtree->pWriteParent);
163295  return sqlite3_reset(pRtree->pWriteParent);
163296 }
163297 
163298 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
163299 
163300 
163301 /*
163302 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
163303 ** nIdx. The aIdx array contains the set of integers from 0 to
163304 ** (nIdx-1) in no particular order. This function sorts the values
163305 ** in aIdx according to the indexed values in aDistance. For
163306 ** example, assuming the inputs:
163307 **
163308 ** aIdx = { 0, 1, 2, 3 }
163309 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
163310 **
163311 ** this function sets the aIdx array to contain:
163312 **
163313 ** aIdx = { 0, 1, 2, 3 }
163314 **
163315 ** The aSpare array is used as temporary working space by the
163316 ** sorting algorithm.
163317 */
163318 static void SortByDistance(
163319  int *aIdx,
163320  int nIdx,
163321  RtreeDValue *aDistance,
163322  int *aSpare
163323 ){
163324  if( nIdx>1 ){
163325  int iLeft = 0;
163326  int iRight = 0;
163327 
163328  int nLeft = nIdx/2;
163329  int nRight = nIdx-nLeft;
163330  int *aLeft = aIdx;
163331  int *aRight = &aIdx[nLeft];
163332 
163333  SortByDistance(aLeft, nLeft, aDistance, aSpare);
163334  SortByDistance(aRight, nRight, aDistance, aSpare);
163335 
163336  memcpy(aSpare, aLeft, sizeof(int)*nLeft);
163337  aLeft = aSpare;
163338 
163339  while( iLeft<nLeft || iRight<nRight ){
163340  if( iLeft==nLeft ){
163341  aIdx[iLeft+iRight] = aRight[iRight];
163342  iRight++;
163343  }else if( iRight==nRight ){
163344  aIdx[iLeft+iRight] = aLeft[iLeft];
163345  iLeft++;
163346  }else{
163347  RtreeDValue fLeft = aDistance[aLeft[iLeft]];
163348  RtreeDValue fRight = aDistance[aRight[iRight]];
163349  if( fLeft<fRight ){
163350  aIdx[iLeft+iRight] = aLeft[iLeft];
163351  iLeft++;
163352  }else{
163353  aIdx[iLeft+iRight] = aRight[iRight];
163354  iRight++;
163355  }
163356  }
163357  }
163358 
163359 #if 0
163360  /* Check that the sort worked */
163361  {
163362  int jj;
163363  for(jj=1; jj<nIdx; jj++){
163364  RtreeDValue left = aDistance[aIdx[jj-1]];
163365  RtreeDValue right = aDistance[aIdx[jj]];
163366  assert( left<=right );
163367  }
163368  }
163369 #endif
163370  }
163371 }
163372 
163373 /*
163374 ** Arguments aIdx, aCell and aSpare all point to arrays of size
163375 ** nIdx. The aIdx array contains the set of integers from 0 to
163376 ** (nIdx-1) in no particular order. This function sorts the values
163377 ** in aIdx according to dimension iDim of the cells in aCell. The
163378 ** minimum value of dimension iDim is considered first, the
163379 ** maximum used to break ties.
163380 **
163381 ** The aSpare array is used as temporary working space by the
163382 ** sorting algorithm.
163383 */
163384 static void SortByDimension(
163385  Rtree *pRtree,
163386  int *aIdx,
163387  int nIdx,
163388  int iDim,
163389  RtreeCell *aCell,
163390  int *aSpare
163391 ){
163392  if( nIdx>1 ){
163393 
163394  int iLeft = 0;
163395  int iRight = 0;
163396 
163397  int nLeft = nIdx/2;
163398  int nRight = nIdx-nLeft;
163399  int *aLeft = aIdx;
163400  int *aRight = &aIdx[nLeft];
163401 
163402  SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
163403  SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
163404 
163405  memcpy(aSpare, aLeft, sizeof(int)*nLeft);
163406  aLeft = aSpare;
163407  while( iLeft<nLeft || iRight<nRight ){
163408  RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
163409  RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
163410  RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
163411  RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
163412  if( (iLeft!=nLeft) && ((iRight==nRight)
163413  || (xleft1<xright1)
163414  || (xleft1==xright1 && xleft2<xright2)
163415  )){
163416  aIdx[iLeft+iRight] = aLeft[iLeft];
163417  iLeft++;
163418  }else{
163419  aIdx[iLeft+iRight] = aRight[iRight];
163420  iRight++;
163421  }
163422  }
163423 
163424 #if 0
163425  /* Check that the sort worked */
163426  {
163427  int jj;
163428  for(jj=1; jj<nIdx; jj++){
163429  RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
163430  RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
163431  RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
163432  RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
163433  assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
163434  }
163435  }
163436 #endif
163437  }
163438 }
163439 
163440 /*
163441 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
163442 */
163443 static int splitNodeStartree(
163444  Rtree *pRtree,
163445  RtreeCell *aCell,
163446  int nCell,
163447  RtreeNode *pLeft,
163448  RtreeNode *pRight,
163449  RtreeCell *pBboxLeft,
163450  RtreeCell *pBboxRight
163451 ){
163452  int **aaSorted;
163453  int *aSpare;
163454  int ii;
163455 
163456  int iBestDim = 0;
163457  int iBestSplit = 0;
163458  RtreeDValue fBestMargin = RTREE_ZERO;
163459 
163460  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
163461 
163462  aaSorted = (int **)sqlite3_malloc(nByte);
163463  if( !aaSorted ){
163464  return SQLITE_NOMEM;
163465  }
163466 
163467  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
163468  memset(aaSorted, 0, nByte);
163469  for(ii=0; ii<pRtree->nDim; ii++){
163470  int jj;
163471  aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
163472  for(jj=0; jj<nCell; jj++){
163473  aaSorted[ii][jj] = jj;
163474  }
163475  SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
163476  }
163477 
163478  for(ii=0; ii<pRtree->nDim; ii++){
163479  RtreeDValue margin = RTREE_ZERO;
163480  RtreeDValue fBestOverlap = RTREE_ZERO;
163481  RtreeDValue fBestArea = RTREE_ZERO;
163482  int iBestLeft = 0;
163483  int nLeft;
163484 
163485  for(
163486  nLeft=RTREE_MINCELLS(pRtree);
163487  nLeft<=(nCell-RTREE_MINCELLS(pRtree));
163488  nLeft++
163489  ){
163490  RtreeCell left;
163491  RtreeCell right;
163492  int kk;
163493  RtreeDValue overlap;
163494  RtreeDValue area;
163495 
163496  memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
163497  memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
163498  for(kk=1; kk<(nCell-1); kk++){
163499  if( kk<nLeft ){
163500  cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
163501  }else{
163502  cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
163503  }
163504  }
163505  margin += cellMargin(pRtree, &left);
163506  margin += cellMargin(pRtree, &right);
163507  overlap = cellOverlap(pRtree, &left, &right, 1);
163508  area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
163509  if( (nLeft==RTREE_MINCELLS(pRtree))
163510  || (overlap<fBestOverlap)
163511  || (overlap==fBestOverlap && area<fBestArea)
163512  ){
163513  iBestLeft = nLeft;
163514  fBestOverlap = overlap;
163515  fBestArea = area;
163516  }
163517  }
163518 
163519  if( ii==0 || margin<fBestMargin ){
163520  iBestDim = ii;
163521  fBestMargin = margin;
163522  iBestSplit = iBestLeft;
163523  }
163524  }
163525 
163526  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
163527  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
163528  for(ii=0; ii<nCell; ii++){
163529  RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
163530  RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
163531  RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
163532  nodeInsertCell(pRtree, pTarget, pCell);
163533  cellUnion(pRtree, pBbox, pCell);
163534  }
163535 
163536  sqlite3_free(aaSorted);
163537  return SQLITE_OK;
163538 }
163539 
163540 
163541 static int updateMapping(
163542  Rtree *pRtree,
163543  i64 iRowid,
163544  RtreeNode *pNode,
163545  int iHeight
163546 ){
163547  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
163548  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
163549  if( iHeight>0 ){
163550  RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
163551  if( pChild ){
163552  nodeRelease(pRtree, pChild->pParent);
163553  nodeReference(pNode);
163554  pChild->pParent = pNode;
163555  }
163556  }
163557  return xSetMapping(pRtree, iRowid, pNode->iNode);
163558 }
163559 
163560 static int SplitNode(
163561  Rtree *pRtree,
163562  RtreeNode *pNode,
163563  RtreeCell *pCell,
163564  int iHeight
163565 ){
163566  int i;
163567  int newCellIsRight = 0;
163568 
163569  int rc = SQLITE_OK;
163570  int nCell = NCELL(pNode);
163571  RtreeCell *aCell;
163572  int *aiUsed;
163573 
163574  RtreeNode *pLeft = 0;
163575  RtreeNode *pRight = 0;
163576 
163577  RtreeCell leftbbox;
163578  RtreeCell rightbbox;
163579 
163580  /* Allocate an array and populate it with a copy of pCell and
163581  ** all cells from node pLeft. Then zero the original node.
163582  */
163583  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
163584  if( !aCell ){
163585  rc = SQLITE_NOMEM;
163586  goto splitnode_out;
163587  }
163588  aiUsed = (int *)&aCell[nCell+1];
163589  memset(aiUsed, 0, sizeof(int)*(nCell+1));
163590  for(i=0; i<nCell; i++){
163591  nodeGetCell(pRtree, pNode, i, &aCell[i]);
163592  }
163593  nodeZero(pRtree, pNode);
163594  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
163595  nCell++;
163596 
163597  if( pNode->iNode==1 ){
163598  pRight = nodeNew(pRtree, pNode);
163599  pLeft = nodeNew(pRtree, pNode);
163600  pRtree->iDepth++;
163601  pNode->isDirty = 1;
163602  writeInt16(pNode->zData, pRtree->iDepth);
163603  }else{
163604  pLeft = pNode;
163605  pRight = nodeNew(pRtree, pLeft->pParent);
163606  nodeReference(pLeft);
163607  }
163608 
163609  if( !pLeft || !pRight ){
163610  rc = SQLITE_NOMEM;
163611  goto splitnode_out;
163612  }
163613 
163614  memset(pLeft->zData, 0, pRtree->iNodeSize);
163615  memset(pRight->zData, 0, pRtree->iNodeSize);
163616 
163617  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
163618  &leftbbox, &rightbbox);
163619  if( rc!=SQLITE_OK ){
163620  goto splitnode_out;
163621  }
163622 
163623  /* Ensure both child nodes have node numbers assigned to them by calling
163624  ** nodeWrite(). Node pRight always needs a node number, as it was created
163625  ** by nodeNew() above. But node pLeft sometimes already has a node number.
163626  ** In this case avoid the all to nodeWrite().
163627  */
163628  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
163629  || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
163630  ){
163631  goto splitnode_out;
163632  }
163633 
163634  rightbbox.iRowid = pRight->iNode;
163635  leftbbox.iRowid = pLeft->iNode;
163636 
163637  if( pNode->iNode==1 ){
163638  rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
163639  if( rc!=SQLITE_OK ){
163640  goto splitnode_out;
163641  }
163642  }else{
163643  RtreeNode *pParent = pLeft->pParent;
163644  int iCell;
163645  rc = nodeParentIndex(pRtree, pLeft, &iCell);
163646  if( rc==SQLITE_OK ){
163647  nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
163648  rc = AdjustTree(pRtree, pParent, &leftbbox);
163649  }
163650  if( rc!=SQLITE_OK ){
163651  goto splitnode_out;
163652  }
163653  }
163654  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
163655  goto splitnode_out;
163656  }
163657 
163658  for(i=0; i<NCELL(pRight); i++){
163659  i64 iRowid = nodeGetRowid(pRtree, pRight, i);
163660  rc = updateMapping(pRtree, iRowid, pRight, iHeight);
163661  if( iRowid==pCell->iRowid ){
163662  newCellIsRight = 1;
163663  }
163664  if( rc!=SQLITE_OK ){
163665  goto splitnode_out;
163666  }
163667  }
163668  if( pNode->iNode==1 ){
163669  for(i=0; i<NCELL(pLeft); i++){
163670  i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
163671  rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
163672  if( rc!=SQLITE_OK ){
163673  goto splitnode_out;
163674  }
163675  }
163676  }else if( newCellIsRight==0 ){
163677  rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
163678  }
163679 
163680  if( rc==SQLITE_OK ){
163681  rc = nodeRelease(pRtree, pRight);
163682  pRight = 0;
163683  }
163684  if( rc==SQLITE_OK ){
163685  rc = nodeRelease(pRtree, pLeft);
163686  pLeft = 0;
163687  }
163688 
163689 splitnode_out:
163690  nodeRelease(pRtree, pRight);
163691  nodeRelease(pRtree, pLeft);
163692  sqlite3_free(aCell);
163693  return rc;
163694 }
163695 
163696 /*
163697 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
163698 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
163699 ** the pLeaf->pParent chain all the way up to the root node.
163700 **
163701 ** This operation is required when a row is deleted (or updated - an update
163702 ** is implemented as a delete followed by an insert). SQLite provides the
163703 ** rowid of the row to delete, which can be used to find the leaf on which
163704 ** the entry resides (argument pLeaf). Once the leaf is located, this
163705 ** function is called to determine its ancestry.
163706 */
163707 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
163708  int rc = SQLITE_OK;
163709  RtreeNode *pChild = pLeaf;
163710  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
163711  int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
163712  sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
163713  rc = sqlite3_step(pRtree->pReadParent);
163714  if( rc==SQLITE_ROW ){
163715  RtreeNode *pTest; /* Used to test for reference loops */
163716  i64 iNode; /* Node number of parent node */
163717 
163718  /* Before setting pChild->pParent, test that we are not creating a
163719  ** loop of references (as we would if, say, pChild==pParent). We don't
163720  ** want to do this as it leads to a memory leak when trying to delete
163721  ** the referenced counted node structures.
163722  */
163723  iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
163724  for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
163725  if( !pTest ){
163726  rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
163727  }
163728  }
163729  rc = sqlite3_reset(pRtree->pReadParent);
163730  if( rc==SQLITE_OK ) rc = rc2;
163731  if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
163732  pChild = pChild->pParent;
163733  }
163734  return rc;
163735 }
163736 
163737 static int deleteCell(Rtree *, RtreeNode *, int, int);
163738 
163739 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
163740  int rc;
163741  int rc2;
163742  RtreeNode *pParent = 0;
163743  int iCell;
163744 
163745  assert( pNode->nRef==1 );
163746 
163747  /* Remove the entry in the parent cell. */
163748  rc = nodeParentIndex(pRtree, pNode, &iCell);
163749  if( rc==SQLITE_OK ){
163750  pParent = pNode->pParent;
163751  pNode->pParent = 0;
163752  rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
163753  }
163754  rc2 = nodeRelease(pRtree, pParent);
163755  if( rc==SQLITE_OK ){
163756  rc = rc2;
163757  }
163758  if( rc!=SQLITE_OK ){
163759  return rc;
163760  }
163761 
163762  /* Remove the xxx_node entry. */
163763  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
163764  sqlite3_step(pRtree->pDeleteNode);
163765  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
163766  return rc;
163767  }
163768 
163769  /* Remove the xxx_parent entry. */
163770  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
163771  sqlite3_step(pRtree->pDeleteParent);
163772  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
163773  return rc;
163774  }
163775 
163776  /* Remove the node from the in-memory hash table and link it into
163777  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
163778  */
163779  nodeHashDelete(pRtree, pNode);
163780  pNode->iNode = iHeight;
163781  pNode->pNext = pRtree->pDeleted;
163782  pNode->nRef++;
163783  pRtree->pDeleted = pNode;
163784 
163785  return SQLITE_OK;
163786 }
163787 
163788 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
163789  RtreeNode *pParent = pNode->pParent;
163790  int rc = SQLITE_OK;
163791  if( pParent ){
163792  int ii;
163793  int nCell = NCELL(pNode);
163794  RtreeCell box; /* Bounding box for pNode */
163795  nodeGetCell(pRtree, pNode, 0, &box);
163796  for(ii=1; ii<nCell; ii++){
163797  RtreeCell cell;
163798  nodeGetCell(pRtree, pNode, ii, &cell);
163799  cellUnion(pRtree, &box, &cell);
163800  }
163801  box.iRowid = pNode->iNode;
163802  rc = nodeParentIndex(pRtree, pNode, &ii);
163803  if( rc==SQLITE_OK ){
163804  nodeOverwriteCell(pRtree, pParent, &box, ii);
163805  rc = fixBoundingBox(pRtree, pParent);
163806  }
163807  }
163808  return rc;
163809 }
163810 
163811 /*
163812 ** Delete the cell at index iCell of node pNode. After removing the
163813 ** cell, adjust the r-tree data structure if required.
163814 */
163815 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
163816  RtreeNode *pParent;
163817  int rc;
163818 
163819  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
163820  return rc;
163821  }
163822 
163823  /* Remove the cell from the node. This call just moves bytes around
163824  ** the in-memory node image, so it cannot fail.
163825  */
163826  nodeDeleteCell(pRtree, pNode, iCell);
163827 
163828  /* If the node is not the tree root and now has less than the minimum
163829  ** number of cells, remove it from the tree. Otherwise, update the
163830  ** cell in the parent node so that it tightly contains the updated
163831  ** node.
163832  */
163833  pParent = pNode->pParent;
163834  assert( pParent || pNode->iNode==1 );
163835  if( pParent ){
163836  if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
163837  rc = removeNode(pRtree, pNode, iHeight);
163838  }else{
163839  rc = fixBoundingBox(pRtree, pNode);
163840  }
163841  }
163842 
163843  return rc;
163844 }
163845 
163846 static int Reinsert(
163847  Rtree *pRtree,
163848  RtreeNode *pNode,
163849  RtreeCell *pCell,
163850  int iHeight
163851 ){
163852  int *aOrder;
163853  int *aSpare;
163854  RtreeCell *aCell;
163855  RtreeDValue *aDistance;
163856  int nCell;
163857  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
163858  int iDim;
163859  int ii;
163860  int rc = SQLITE_OK;
163861  int n;
163862 
163863  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
163864 
163865  nCell = NCELL(pNode)+1;
163866  n = (nCell+1)&(~1);
163867 
163868  /* Allocate the buffers used by this operation. The allocation is
163869  ** relinquished before this function returns.
163870  */
163871  aCell = (RtreeCell *)sqlite3_malloc(n * (
163872  sizeof(RtreeCell) + /* aCell array */
163873  sizeof(int) + /* aOrder array */
163874  sizeof(int) + /* aSpare array */
163875  sizeof(RtreeDValue) /* aDistance array */
163876  ));
163877  if( !aCell ){
163878  return SQLITE_NOMEM;
163879  }
163880  aOrder = (int *)&aCell[n];
163881  aSpare = (int *)&aOrder[n];
163882  aDistance = (RtreeDValue *)&aSpare[n];
163883 
163884  for(ii=0; ii<nCell; ii++){
163885  if( ii==(nCell-1) ){
163886  memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
163887  }else{
163888  nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
163889  }
163890  aOrder[ii] = ii;
163891  for(iDim=0; iDim<pRtree->nDim; iDim++){
163892  aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
163893  aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
163894  }
163895  }
163896  for(iDim=0; iDim<pRtree->nDim; iDim++){
163897  aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
163898  }
163899 
163900  for(ii=0; ii<nCell; ii++){
163901  aDistance[ii] = RTREE_ZERO;
163902  for(iDim=0; iDim<pRtree->nDim; iDim++){
163903  RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
163904  DCOORD(aCell[ii].aCoord[iDim*2]));
163905  aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
163906  }
163907  }
163908 
163909  SortByDistance(aOrder, nCell, aDistance, aSpare);
163910  nodeZero(pRtree, pNode);
163911 
163912  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
163913  RtreeCell *p = &aCell[aOrder[ii]];
163914  nodeInsertCell(pRtree, pNode, p);
163915  if( p->iRowid==pCell->iRowid ){
163916  if( iHeight==0 ){
163917  rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
163918  }else{
163919  rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
163920  }
163921  }
163922  }
163923  if( rc==SQLITE_OK ){
163924  rc = fixBoundingBox(pRtree, pNode);
163925  }
163926  for(; rc==SQLITE_OK && ii<nCell; ii++){
163927  /* Find a node to store this cell in. pNode->iNode currently contains
163928  ** the height of the sub-tree headed by the cell.
163929  */
163930  RtreeNode *pInsert;
163931  RtreeCell *p = &aCell[aOrder[ii]];
163932  rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
163933  if( rc==SQLITE_OK ){
163934  int rc2;
163935  rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
163936  rc2 = nodeRelease(pRtree, pInsert);
163937  if( rc==SQLITE_OK ){
163938  rc = rc2;
163939  }
163940  }
163941  }
163942 
163943  sqlite3_free(aCell);
163944  return rc;
163945 }
163946 
163947 /*
163948 ** Insert cell pCell into node pNode. Node pNode is the head of a
163949 ** subtree iHeight high (leaf nodes have iHeight==0).
163950 */
163951 static int rtreeInsertCell(
163952  Rtree *pRtree,
163953  RtreeNode *pNode,
163954  RtreeCell *pCell,
163955  int iHeight
163956 ){
163957  int rc = SQLITE_OK;
163958  if( iHeight>0 ){
163959  RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
163960  if( pChild ){
163961  nodeRelease(pRtree, pChild->pParent);
163962  nodeReference(pNode);
163963  pChild->pParent = pNode;
163964  }
163965  }
163966  if( nodeInsertCell(pRtree, pNode, pCell) ){
163967  if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
163968  rc = SplitNode(pRtree, pNode, pCell, iHeight);
163969  }else{
163970  pRtree->iReinsertHeight = iHeight;
163971  rc = Reinsert(pRtree, pNode, pCell, iHeight);
163972  }
163973  }else{
163974  rc = AdjustTree(pRtree, pNode, pCell);
163975  if( rc==SQLITE_OK ){
163976  if( iHeight==0 ){
163977  rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
163978  }else{
163979  rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
163980  }
163981  }
163982  }
163983  return rc;
163984 }
163985 
163986 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
163987  int ii;
163988  int rc = SQLITE_OK;
163989  int nCell = NCELL(pNode);
163990 
163991  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
163992  RtreeNode *pInsert;
163993  RtreeCell cell;
163994  nodeGetCell(pRtree, pNode, ii, &cell);
163995 
163996  /* Find a node to store this cell in. pNode->iNode currently contains
163997  ** the height of the sub-tree headed by the cell.
163998  */
163999  rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
164000  if( rc==SQLITE_OK ){
164001  int rc2;
164002  rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
164003  rc2 = nodeRelease(pRtree, pInsert);
164004  if( rc==SQLITE_OK ){
164005  rc = rc2;
164006  }
164007  }
164008  }
164009  return rc;
164010 }
164011 
164012 /*
164013 ** Select a currently unused rowid for a new r-tree record.
164014 */
164015 static int newRowid(Rtree *pRtree, i64 *piRowid){
164016  int rc;
164017  sqlite3_bind_null(pRtree->pWriteRowid, 1);
164018  sqlite3_bind_null(pRtree->pWriteRowid, 2);
164019  sqlite3_step(pRtree->pWriteRowid);
164020  rc = sqlite3_reset(pRtree->pWriteRowid);
164021  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
164022  return rc;
164023 }
164024 
164025 /*
164026 ** Remove the entry with rowid=iDelete from the r-tree structure.
164027 */
164028 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
164029  int rc; /* Return code */
164030  RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
164031  int iCell; /* Index of iDelete cell in pLeaf */
164032  RtreeNode *pRoot; /* Root node of rtree structure */
164033 
164034 
164035  /* Obtain a reference to the root node to initialize Rtree.iDepth */
164036  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
164037 
164038  /* Obtain a reference to the leaf node that contains the entry
164039  ** about to be deleted.
164040  */
164041  if( rc==SQLITE_OK ){
164042  rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
164043  }
164044 
164045  /* Delete the cell in question from the leaf node. */
164046  if( rc==SQLITE_OK ){
164047  int rc2;
164048  rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
164049  if( rc==SQLITE_OK ){
164050  rc = deleteCell(pRtree, pLeaf, iCell, 0);
164051  }
164052  rc2 = nodeRelease(pRtree, pLeaf);
164053  if( rc==SQLITE_OK ){
164054  rc = rc2;
164055  }
164056  }
164057 
164058  /* Delete the corresponding entry in the <rtree>_rowid table. */
164059  if( rc==SQLITE_OK ){
164060  sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
164061  sqlite3_step(pRtree->pDeleteRowid);
164062  rc = sqlite3_reset(pRtree->pDeleteRowid);
164063  }
164064 
164065  /* Check if the root node now has exactly one child. If so, remove
164066  ** it, schedule the contents of the child for reinsertion and
164067  ** reduce the tree height by one.
164068  **
164069  ** This is equivalent to copying the contents of the child into
164070  ** the root node (the operation that Gutman's paper says to perform
164071  ** in this scenario).
164072  */
164073  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
164074  int rc2;
164075  RtreeNode *pChild;
164076  i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
164077  rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
164078  if( rc==SQLITE_OK ){
164079  rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
164080  }
164081  rc2 = nodeRelease(pRtree, pChild);
164082  if( rc==SQLITE_OK ) rc = rc2;
164083  if( rc==SQLITE_OK ){
164084  pRtree->iDepth--;
164085  writeInt16(pRoot->zData, pRtree->iDepth);
164086  pRoot->isDirty = 1;
164087  }
164088  }
164089 
164090  /* Re-insert the contents of any underfull nodes removed from the tree. */
164091  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
164092  if( rc==SQLITE_OK ){
164093  rc = reinsertNodeContent(pRtree, pLeaf);
164094  }
164095  pRtree->pDeleted = pLeaf->pNext;
164096  sqlite3_free(pLeaf);
164097  }
164098 
164099  /* Release the reference to the root node. */
164100  if( rc==SQLITE_OK ){
164101  rc = nodeRelease(pRtree, pRoot);
164102  }else{
164103  nodeRelease(pRtree, pRoot);
164104  }
164105 
164106  return rc;
164107 }
164108 
164109 /*
164110 ** Rounding constants for float->double conversion.
164111 */
164112 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
164113 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
164114 
164115 #if !defined(SQLITE_RTREE_INT_ONLY)
164116 /*
164117 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
164118 ** while taking care to round toward negative or positive, respectively.
164119 */
164120 static RtreeValue rtreeValueDown(sqlite3_value *v){
164121  double d = sqlite3_value_double(v);
164122  float f = (float)d;
164123  if( f>d ){
164124  f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
164125  }
164126  return f;
164127 }
164128 static RtreeValue rtreeValueUp(sqlite3_value *v){
164129  double d = sqlite3_value_double(v);
164130  float f = (float)d;
164131  if( f<d ){
164132  f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
164133  }
164134  return f;
164135 }
164136 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
164137 
164138 /*
164139 ** A constraint has failed while inserting a row into an rtree table.
164140 ** Assuming no OOM error occurs, this function sets the error message
164141 ** (at pRtree->base.zErrMsg) to an appropriate value and returns
164142 ** SQLITE_CONSTRAINT.
164143 **
164144 ** Parameter iCol is the index of the leftmost column involved in the
164145 ** constraint failure. If it is 0, then the constraint that failed is
164146 ** the unique constraint on the id column. Otherwise, it is the rtree
164147 ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
164148 **
164149 ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
164150 */
164151 static int rtreeConstraintError(Rtree *pRtree, int iCol){
164152  sqlite3_stmt *pStmt = 0;
164153  char *zSql;
164154  int rc;
164155 
164156  assert( iCol==0 || iCol%2 );
164157  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
164158  if( zSql ){
164159  rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
164160  }else{
164161  rc = SQLITE_NOMEM;
164162  }
164163  sqlite3_free(zSql);
164164 
164165  if( rc==SQLITE_OK ){
164166  if( iCol==0 ){
164167  const char *zCol = sqlite3_column_name(pStmt, 0);
164168  pRtree->base.zErrMsg = sqlite3_mprintf(
164169  "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
164170  );
164171  }else{
164172  const char *zCol1 = sqlite3_column_name(pStmt, iCol);
164173  const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
164174  pRtree->base.zErrMsg = sqlite3_mprintf(
164175  "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
164176  );
164177  }
164178  }
164179 
164180  sqlite3_finalize(pStmt);
164181  return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
164182 }
164183 
164184 
164185 
164186 /*
164187 ** The xUpdate method for rtree module virtual tables.
164188 */
164189 static int rtreeUpdate(
164190  sqlite3_vtab *pVtab,
164191  int nData,
164192  sqlite3_value **azData,
164193  sqlite_int64 *pRowid
164194 ){
164195  Rtree *pRtree = (Rtree *)pVtab;
164196  int rc = SQLITE_OK;
164197  RtreeCell cell; /* New cell to insert if nData>1 */
164198  int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
164199 
164200  rtreeReference(pRtree);
164201  assert(nData>=1);
164202 
164203  cell.iRowid = 0; /* Used only to suppress a compiler warning */
164204 
164205  /* Constraint handling. A write operation on an r-tree table may return
164206  ** SQLITE_CONSTRAINT for two reasons:
164207  **
164208  ** 1. A duplicate rowid value, or
164209  ** 2. The supplied data violates the "x2>=x1" constraint.
164210  **
164211  ** In the first case, if the conflict-handling mode is REPLACE, then
164212  ** the conflicting row can be removed before proceeding. In the second
164213  ** case, SQLITE_CONSTRAINT must be returned regardless of the
164214  ** conflict-handling mode specified by the user.
164215  */
164216  if( nData>1 ){
164217  int ii;
164218 
164219  /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
164220  **
164221  ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
164222  ** with "column" that are interpreted as table constraints.
164223  ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
164224  ** This problem was discovered after years of use, so we silently ignore
164225  ** these kinds of misdeclared tables to avoid breaking any legacy.
164226  */
164227  assert( nData<=(pRtree->nDim*2 + 3) );
164228 
164229 #ifndef SQLITE_RTREE_INT_ONLY
164230  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
164231  for(ii=0; ii<nData-4; ii+=2){
164232  cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
164233  cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
164234  if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
164235  rc = rtreeConstraintError(pRtree, ii+1);
164236  goto constraint;
164237  }
164238  }
164239  }else
164240 #endif
164241  {
164242  for(ii=0; ii<nData-4; ii+=2){
164243  cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
164244  cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
164245  if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
164246  rc = rtreeConstraintError(pRtree, ii+1);
164247  goto constraint;
164248  }
164249  }
164250  }
164251 
164252  /* If a rowid value was supplied, check if it is already present in
164253  ** the table. If so, the constraint has failed. */
164254  if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
164255  cell.iRowid = sqlite3_value_int64(azData[2]);
164256  if( sqlite3_value_type(azData[0])==SQLITE_NULL
164257  || sqlite3_value_int64(azData[0])!=cell.iRowid
164258  ){
164259  int steprc;
164260  sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
164261  steprc = sqlite3_step(pRtree->pReadRowid);
164262  rc = sqlite3_reset(pRtree->pReadRowid);
164263  if( SQLITE_ROW==steprc ){
164264  if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
164265  rc = rtreeDeleteRowid(pRtree, cell.iRowid);
164266  }else{
164267  rc = rtreeConstraintError(pRtree, 0);
164268  goto constraint;
164269  }
164270  }
164271  }
164272  bHaveRowid = 1;
164273  }
164274  }
164275 
164276  /* If azData[0] is not an SQL NULL value, it is the rowid of a
164277  ** record to delete from the r-tree table. The following block does
164278  ** just that.
164279  */
164280  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
164281  rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
164282  }
164283 
164284  /* If the azData[] array contains more than one element, elements
164285  ** (azData[2]..azData[argc-1]) contain a new record to insert into
164286  ** the r-tree structure.
164287  */
164288  if( rc==SQLITE_OK && nData>1 ){
164289  /* Insert the new record into the r-tree */
164290  RtreeNode *pLeaf = 0;
164291 
164292  /* Figure out the rowid of the new row. */
164293  if( bHaveRowid==0 ){
164294  rc = newRowid(pRtree, &cell.iRowid);
164295  }
164296  *pRowid = cell.iRowid;
164297 
164298  if( rc==SQLITE_OK ){
164299  rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
164300  }
164301  if( rc==SQLITE_OK ){
164302  int rc2;
164303  pRtree->iReinsertHeight = -1;
164304  rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
164305  rc2 = nodeRelease(pRtree, pLeaf);
164306  if( rc==SQLITE_OK ){
164307  rc = rc2;
164308  }
164309  }
164310  }
164311 
164312 constraint:
164313  rtreeRelease(pRtree);
164314  return rc;
164315 }
164316 
164317 /*
164318 ** The xRename method for rtree module virtual tables.
164319 */
164320 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
164321  Rtree *pRtree = (Rtree *)pVtab;
164322  int rc = SQLITE_NOMEM;
164323  char *zSql = sqlite3_mprintf(
164324  "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
164325  "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
164326  "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
164327  , pRtree->zDb, pRtree->zName, zNewName
164328  , pRtree->zDb, pRtree->zName, zNewName
164329  , pRtree->zDb, pRtree->zName, zNewName
164330  );
164331  if( zSql ){
164332  rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
164333  sqlite3_free(zSql);
164334  }
164335  return rc;
164336 }
164337 
164338 /*
164339 ** This function populates the pRtree->nRowEst variable with an estimate
164340 ** of the number of rows in the virtual table. If possible, this is based
164341 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
164342 */
164343 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
164344  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
164345  char *zSql;
164346  sqlite3_stmt *p;
164347  int rc;
164348  i64 nRow = 0;
164349 
164350  rc = sqlite3_table_column_metadata(
164351  db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
164352  );
164353  if( rc!=SQLITE_OK ){
164354  pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
164355  return rc==SQLITE_ERROR ? SQLITE_OK : rc;
164356  }
164357  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
164358  if( zSql==0 ){
164359  rc = SQLITE_NOMEM;
164360  }else{
164361  rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
164362  if( rc==SQLITE_OK ){
164363  if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
164364  rc = sqlite3_finalize(p);
164365  }else if( rc!=SQLITE_NOMEM ){
164366  rc = SQLITE_OK;
164367  }
164368 
164369  if( rc==SQLITE_OK ){
164370  if( nRow==0 ){
164371  pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
164372  }else{
164373  pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
164374  }
164375  }
164376  sqlite3_free(zSql);
164377  }
164378 
164379  return rc;
164380 }
164381 
164382 static sqlite3_module rtreeModule = {
164383  0, /* iVersion */
164384  rtreeCreate, /* xCreate - create a table */
164385  rtreeConnect, /* xConnect - connect to an existing table */
164386  rtreeBestIndex, /* xBestIndex - Determine search strategy */
164387  rtreeDisconnect, /* xDisconnect - Disconnect from a table */
164388  rtreeDestroy, /* xDestroy - Drop a table */
164389  rtreeOpen, /* xOpen - open a cursor */
164390  rtreeClose, /* xClose - close a cursor */
164391  rtreeFilter, /* xFilter - configure scan constraints */
164392  rtreeNext, /* xNext - advance a cursor */
164393  rtreeEof, /* xEof */
164394  rtreeColumn, /* xColumn - read data */
164395  rtreeRowid, /* xRowid - read data */
164396  rtreeUpdate, /* xUpdate - write data */
164397  0, /* xBegin - begin transaction */
164398  0, /* xSync - sync transaction */
164399  0, /* xCommit - commit transaction */
164400  0, /* xRollback - rollback transaction */
164401  0, /* xFindFunction - function overloading */
164402  rtreeRename, /* xRename - rename the table */
164403  0, /* xSavepoint */
164404  0, /* xRelease */
164405  0 /* xRollbackTo */
164406 };
164407 
164408 static int rtreeSqlInit(
164409  Rtree *pRtree,
164410  sqlite3 *db,
164411  const char *zDb,
164412  const char *zPrefix,
164413  int isCreate
164414 ){
164415  int rc = SQLITE_OK;
164416 
164417  #define N_STATEMENT 9
164418  static const char *azSql[N_STATEMENT] = {
164419  /* Read and write the xxx_node table */
164420  "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
164421  "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
164422  "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
164423 
164424  /* Read and write the xxx_rowid table */
164425  "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
164426  "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
164427  "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
164428 
164429  /* Read and write the xxx_parent table */
164430  "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
164431  "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
164432  "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
164433  };
164434  sqlite3_stmt **appStmt[N_STATEMENT];
164435  int i;
164436 
164437  pRtree->db = db;
164438 
164439  if( isCreate ){
164440  char *zCreate = sqlite3_mprintf(
164441 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
164442 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
164443 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
164444  " parentnode INTEGER);"
164445 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
164446  zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
164447  );
164448  if( !zCreate ){
164449  return SQLITE_NOMEM;
164450  }
164451  rc = sqlite3_exec(db, zCreate, 0, 0, 0);
164452  sqlite3_free(zCreate);
164453  if( rc!=SQLITE_OK ){
164454  return rc;
164455  }
164456  }
164457 
164458  appStmt[0] = &pRtree->pReadNode;
164459  appStmt[1] = &pRtree->pWriteNode;
164460  appStmt[2] = &pRtree->pDeleteNode;
164461  appStmt[3] = &pRtree->pReadRowid;
164462  appStmt[4] = &pRtree->pWriteRowid;
164463  appStmt[5] = &pRtree->pDeleteRowid;
164464  appStmt[6] = &pRtree->pReadParent;
164465  appStmt[7] = &pRtree->pWriteParent;
164466  appStmt[8] = &pRtree->pDeleteParent;
164467 
164468  rc = rtreeQueryStat1(db, pRtree);
164469  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
164470  char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
164471  if( zSql ){
164472  rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
164473  }else{
164474  rc = SQLITE_NOMEM;
164475  }
164476  sqlite3_free(zSql);
164477  }
164478 
164479  return rc;
164480 }
164481 
164482 /*
164483 ** The second argument to this function contains the text of an SQL statement
164484 ** that returns a single integer value. The statement is compiled and executed
164485 ** using database connection db. If successful, the integer value returned
164486 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
164487 ** code is returned and the value of *piVal after returning is not defined.
164488 */
164489 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
164490  int rc = SQLITE_NOMEM;
164491  if( zSql ){
164492  sqlite3_stmt *pStmt = 0;
164493  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
164494  if( rc==SQLITE_OK ){
164495  if( SQLITE_ROW==sqlite3_step(pStmt) ){
164496  *piVal = sqlite3_column_int(pStmt, 0);
164497  }
164498  rc = sqlite3_finalize(pStmt);
164499  }
164500  }
164501  return rc;
164502 }
164503 
164504 /*
164505 ** This function is called from within the xConnect() or xCreate() method to
164506 ** determine the node-size used by the rtree table being created or connected
164507 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
164508 ** Otherwise, an SQLite error code is returned.
164509 **
164510 ** If this function is being called as part of an xConnect(), then the rtree
164511 ** table already exists. In this case the node-size is determined by inspecting
164512 ** the root node of the tree.
164513 **
164514 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
164515 ** This ensures that each node is stored on a single database page. If the
164516 ** database page-size is so large that more than RTREE_MAXCELLS entries
164517 ** would fit in a single node, use a smaller node-size.
164518 */
164519 static int getNodeSize(
164520  sqlite3 *db, /* Database handle */
164521  Rtree *pRtree, /* Rtree handle */
164522  int isCreate, /* True for xCreate, false for xConnect */
164523  char **pzErr /* OUT: Error message, if any */
164524 ){
164525  int rc;
164526  char *zSql;
164527  if( isCreate ){
164528  int iPageSize = 0;
164529  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
164530  rc = getIntFromStmt(db, zSql, &iPageSize);
164531  if( rc==SQLITE_OK ){
164532  pRtree->iNodeSize = iPageSize-64;
164533  if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
164534  pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
164535  }
164536  }else{
164537  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164538  }
164539  }else{
164540  zSql = sqlite3_mprintf(
164541  "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
164542  pRtree->zDb, pRtree->zName
164543  );
164544  rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
164545  if( rc!=SQLITE_OK ){
164546  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164547  }
164548  }
164549 
164550  sqlite3_free(zSql);
164551  return rc;
164552 }
164553 
164554 /*
164555 ** This function is the implementation of both the xConnect and xCreate
164556 ** methods of the r-tree virtual table.
164557 **
164558 ** argv[0] -> module name
164559 ** argv[1] -> database name
164560 ** argv[2] -> table name
164561 ** argv[...] -> column names...
164562 */
164563 static int rtreeInit(
164564  sqlite3 *db, /* Database connection */
164565  void *pAux, /* One of the RTREE_COORD_* constants */
164566  int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
164567  sqlite3_vtab **ppVtab, /* OUT: New virtual table */
164568  char **pzErr, /* OUT: Error message, if any */
164569  int isCreate /* True for xCreate, false for xConnect */
164570 ){
164571  int rc = SQLITE_OK;
164572  Rtree *pRtree;
164573  int nDb; /* Length of string argv[1] */
164574  int nName; /* Length of string argv[2] */
164575  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
164576 
164577  const char *aErrMsg[] = {
164578  0, /* 0 */
164579  "Wrong number of columns for an rtree table", /* 1 */
164580  "Too few columns for an rtree table", /* 2 */
164581  "Too many columns for an rtree table" /* 3 */
164582  };
164583 
164584  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
164585  if( aErrMsg[iErr] ){
164586  *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
164587  return SQLITE_ERROR;
164588  }
164589 
164590  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
164591 
164592  /* Allocate the sqlite3_vtab structure */
164593  nDb = (int)strlen(argv[1]);
164594  nName = (int)strlen(argv[2]);
164595  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
164596  if( !pRtree ){
164597  return SQLITE_NOMEM;
164598  }
164599  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
164600  pRtree->nBusy = 1;
164601  pRtree->base.pModule = &rtreeModule;
164602  pRtree->zDb = (char *)&pRtree[1];
164603  pRtree->zName = &pRtree->zDb[nDb+1];
164604  pRtree->nDim = (argc-4)/2;
164605  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
164606  pRtree->eCoordType = eCoordType;
164607  memcpy(pRtree->zDb, argv[1], nDb);
164608  memcpy(pRtree->zName, argv[2], nName);
164609 
164610  /* Figure out the node size to use. */
164611  rc = getNodeSize(db, pRtree, isCreate, pzErr);
164612 
164613  /* Create/Connect to the underlying relational database schema. If
164614  ** that is successful, call sqlite3_declare_vtab() to configure
164615  ** the r-tree table schema.
164616  */
164617  if( rc==SQLITE_OK ){
164618  if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
164619  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164620  }else{
164621  char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
164622  char *zTmp;
164623  int ii;
164624  for(ii=4; zSql && ii<argc; ii++){
164625  zTmp = zSql;
164626  zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
164627  sqlite3_free(zTmp);
164628  }
164629  if( zSql ){
164630  zTmp = zSql;
164631  zSql = sqlite3_mprintf("%s);", zTmp);
164632  sqlite3_free(zTmp);
164633  }
164634  if( !zSql ){
164635  rc = SQLITE_NOMEM;
164636  }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
164637  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164638  }
164639  sqlite3_free(zSql);
164640  }
164641  }
164642 
164643  if( rc==SQLITE_OK ){
164644  *ppVtab = (sqlite3_vtab *)pRtree;
164645  }else{
164646  assert( *ppVtab==0 );
164647  assert( pRtree->nBusy==1 );
164648  rtreeRelease(pRtree);
164649  }
164650  return rc;
164651 }
164652 
164653 
164654 /*
164655 ** Implementation of a scalar function that decodes r-tree nodes to
164656 ** human readable strings. This can be used for debugging and analysis.
164657 **
164658 ** The scalar function takes two arguments: (1) the number of dimensions
164659 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
164660 ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
164661 ** deserialize all nodes, a statement like:
164662 **
164663 ** SELECT rtreenode(2, data) FROM rt_node;
164664 **
164665 ** The human readable string takes the form of a Tcl list with one
164666 ** entry for each cell in the r-tree node. Each entry is itself a
164667 ** list, containing the 8-byte rowid/pageno followed by the
164668 ** <num-dimension>*2 coordinates.
164669 */
164670 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
164671  char *zText = 0;
164672  RtreeNode node;
164673  Rtree tree;
164674  int ii;
164675 
164676  UNUSED_PARAMETER(nArg);
164677  memset(&node, 0, sizeof(RtreeNode));
164678  memset(&tree, 0, sizeof(Rtree));
164679  tree.nDim = sqlite3_value_int(apArg[0]);
164680  tree.nBytesPerCell = 8 + 8 * tree.nDim;
164681  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
164682 
164683  for(ii=0; ii<NCELL(&node); ii++){
164684  char zCell[512];
164685  int nCell = 0;
164686  RtreeCell cell;
164687  int jj;
164688 
164689  nodeGetCell(&tree, &node, ii, &cell);
164690  sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
164691  nCell = (int)strlen(zCell);
164692  for(jj=0; jj<tree.nDim*2; jj++){
164693 #ifndef SQLITE_RTREE_INT_ONLY
164694  sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
164695  (double)cell.aCoord[jj].f);
164696 #else
164697  sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
164698  cell.aCoord[jj].i);
164699 #endif
164700  nCell = (int)strlen(zCell);
164701  }
164702 
164703  if( zText ){
164704  char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
164705  sqlite3_free(zText);
164706  zText = zTextNew;
164707  }else{
164708  zText = sqlite3_mprintf("{%s}", zCell);
164709  }
164710  }
164711 
164712  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
164713 }
164714 
164715 /* This routine implements an SQL function that returns the "depth" parameter
164716 ** from the front of a blob that is an r-tree node. For example:
164717 **
164718 ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
164719 **
164720 ** The depth value is 0 for all nodes other than the root node, and the root
164721 ** node always has nodeno=1, so the example above is the primary use for this
164722 ** routine. This routine is intended for testing and analysis only.
164723 */
164724 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
164725  UNUSED_PARAMETER(nArg);
164726  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
164727  || sqlite3_value_bytes(apArg[0])<2
164728  ){
164729  sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
164730  }else{
164731  u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
164732  sqlite3_result_int(ctx, readInt16(zBlob));
164733  }
164734 }
164735 
164736 /*
164737 ** Register the r-tree module with database handle db. This creates the
164738 ** virtual table module "rtree" and the debugging/analysis scalar
164739 ** function "rtreenode".
164740 */
164741 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
164742  const int utf8 = SQLITE_UTF8;
164743  int rc;
164744 
164745  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
164746  if( rc==SQLITE_OK ){
164747  rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
164748  }
164749  if( rc==SQLITE_OK ){
164750 #ifdef SQLITE_RTREE_INT_ONLY
164751  void *c = (void *)RTREE_COORD_INT32;
164752 #else
164753  void *c = (void *)RTREE_COORD_REAL32;
164754 #endif
164755  rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
164756  }
164757  if( rc==SQLITE_OK ){
164758  void *c = (void *)RTREE_COORD_INT32;
164759  rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
164760  }
164761 
164762  return rc;
164763 }
164764 
164765 /*
164766 ** This routine deletes the RtreeGeomCallback object that was attached
164767 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
164768 ** or sqlite3_rtree_query_callback(). In other words, this routine is the
164769 ** destructor for an RtreeGeomCallback objecct. This routine is called when
164770 ** the corresponding SQL function is deleted.
164771 */
164772 static void rtreeFreeCallback(void *p){
164773  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
164774  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
164775  sqlite3_free(p);
164776 }
164777 
164778 /*
164779 ** This routine frees the BLOB that is returned by geomCallback().
164780 */
164781 static void rtreeMatchArgFree(void *pArg){
164782  int i;
164783  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
164784  for(i=0; i<p->nParam; i++){
164785  sqlite3_value_free(p->apSqlParam[i]);
164786  }
164787  sqlite3_free(p);
164788 }
164789 
164790 /*
164791 ** Each call to sqlite3_rtree_geometry_callback() or
164792 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
164793 ** scalar function that is implemented by this routine.
164794 **
164795 ** All this function does is construct an RtreeMatchArg object that
164796 ** contains the geometry-checking callback routines and a list of
164797 ** parameters to this function, then return that RtreeMatchArg object
164798 ** as a BLOB.
164799 **
164800 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
164801 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
164802 ** out which elements of the R-Tree should be returned by the query.
164803 */
164804 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
164805  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
164806  RtreeMatchArg *pBlob;
164807  int nBlob;
164808  int memErr = 0;
164809 
164810  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
164811  + nArg*sizeof(sqlite3_value*);
164812  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
164813  if( !pBlob ){
164814  sqlite3_result_error_nomem(ctx);
164815  }else{
164816  int i;
164817  pBlob->magic = RTREE_GEOMETRY_MAGIC;
164818  pBlob->cb = pGeomCtx[0];
164819  pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
164820  pBlob->nParam = nArg;
164821  for(i=0; i<nArg; i++){
164822  pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
164823  if( pBlob->apSqlParam[i]==0 ) memErr = 1;
164824 #ifdef SQLITE_RTREE_INT_ONLY
164825  pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
164826 #else
164827  pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
164828 #endif
164829  }
164830  if( memErr ){
164831  sqlite3_result_error_nomem(ctx);
164832  rtreeMatchArgFree(pBlob);
164833  }else{
164834  sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
164835  }
164836  }
164837 }
164838 
164839 /*
164840 ** Register a new geometry function for use with the r-tree MATCH operator.
164841 */
164842 SQLITE_API int sqlite3_rtree_geometry_callback(
164843  sqlite3 *db, /* Register SQL function on this connection */
164844  const char *zGeom, /* Name of the new SQL function */
164845  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
164846  void *pContext /* Extra data associated with the callback */
164847 ){
164848  RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
164849 
164850  /* Allocate and populate the context object. */
164851  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
164852  if( !pGeomCtx ) return SQLITE_NOMEM;
164853  pGeomCtx->xGeom = xGeom;
164854  pGeomCtx->xQueryFunc = 0;
164855  pGeomCtx->xDestructor = 0;
164856  pGeomCtx->pContext = pContext;
164857  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
164858  (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
164859  );
164860 }
164861 
164862 /*
164863 ** Register a new 2nd-generation geometry function for use with the
164864 ** r-tree MATCH operator.
164865 */
164866 SQLITE_API int sqlite3_rtree_query_callback(
164867  sqlite3 *db, /* Register SQL function on this connection */
164868  const char *zQueryFunc, /* Name of new SQL function */
164869  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
164870  void *pContext, /* Extra data passed into the callback */
164871  void (*xDestructor)(void*) /* Destructor for the extra data */
164872 ){
164873  RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
164874 
164875  /* Allocate and populate the context object. */
164876  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
164877  if( !pGeomCtx ) return SQLITE_NOMEM;
164878  pGeomCtx->xGeom = 0;
164879  pGeomCtx->xQueryFunc = xQueryFunc;
164880  pGeomCtx->xDestructor = xDestructor;
164881  pGeomCtx->pContext = pContext;
164882  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
164883  (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
164884  );
164885 }
164886 
164887 #if !SQLITE_CORE
164888 #ifdef _WIN32
164889 __declspec(dllexport)
164890 #endif
164891 SQLITE_API int sqlite3_rtree_init(
164892  sqlite3 *db,
164893  char **pzErrMsg,
164894  const sqlite3_api_routines *pApi
164895 ){
164896  SQLITE_EXTENSION_INIT2(pApi)
164897  return sqlite3RtreeInit(db);
164898 }
164899 #endif
164900 
164901 #endif
164902 
164903 /************** End of rtree.c ***********************************************/
164904 /************** Begin file icu.c *********************************************/
164905 /*
164906 ** 2007 May 6
164907 **
164908 ** The author disclaims copyright to this source code. In place of
164909 ** a legal notice, here is a blessing:
164910 **
164911 ** May you do good and not evil.
164912 ** May you find forgiveness for yourself and forgive others.
164913 ** May you share freely, never taking more than you give.
164914 **
164915 *************************************************************************
164916 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
164917 **
164918 ** This file implements an integration between the ICU library
164919 ** ("International Components for Unicode", an open-source library
164920 ** for handling unicode data) and SQLite. The integration uses
164921 ** ICU to provide the following to SQLite:
164922 **
164923 ** * An implementation of the SQL regexp() function (and hence REGEXP
164924 ** operator) using the ICU uregex_XX() APIs.
164925 **
164926 ** * Implementations of the SQL scalar upper() and lower() functions
164927 ** for case mapping.
164928 **
164929 ** * Integration of ICU and SQLite collation sequences.
164930 **
164931 ** * An implementation of the LIKE operator that uses ICU to
164932 ** provide case-independent matching.
164933 */
164934 
164935 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
164936 
164937 /* Include ICU headers */
164938 #include <unicode/utypes.h>
164939 #include <unicode/uregex.h>
164940 #include <unicode/ustring.h>
164941 #include <unicode/ucol.h>
164942 
164943 /* #include <assert.h> */
164944 
164945 #ifndef SQLITE_CORE
164946 /* #include "sqlite3ext.h" */
164947  SQLITE_EXTENSION_INIT1
164948 #else
164949 /* #include "sqlite3.h" */
164950 #endif
164951 
164952 /*
164953 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
164954 ** operator.
164955 */
164956 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
164957 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
164958 #endif
164959 
164960 /*
164961 ** Version of sqlite3_free() that is always a function, never a macro.
164962 */
164963 static void xFree(void *p){
164964  sqlite3_free(p);
164965 }
164966 
164967 /*
164968 ** This lookup table is used to help decode the first byte of
164969 ** a multi-byte UTF8 character. It is copied here from SQLite source
164970 ** code file utf8.c.
164971 */
164972 static const unsigned char icuUtf8Trans1[] = {
164973  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164974  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164975  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
164976  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
164977  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164978  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164979  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164980  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
164981 };
164982 
164983 #define SQLITE_ICU_READ_UTF8(zIn, c) \
164984  c = *(zIn++); \
164985  if( c>=0xc0 ){ \
164986  c = icuUtf8Trans1[c-0xc0]; \
164987  while( (*zIn & 0xc0)==0x80 ){ \
164988  c = (c<<6) + (0x3f & *(zIn++)); \
164989  } \
164990  }
164991 
164992 #define SQLITE_ICU_SKIP_UTF8(zIn) \
164993  assert( *zIn ); \
164994  if( *(zIn++)>=0xc0 ){ \
164995  while( (*zIn & 0xc0)==0x80 ){zIn++;} \
164996  }
164997 
164998 
164999 /*
165000 ** Compare two UTF-8 strings for equality where the first string is
165001 ** a "LIKE" expression. Return true (1) if they are the same and
165002 ** false (0) if they are different.
165003 */
165004 static int icuLikeCompare(
165005  const uint8_t *zPattern, /* LIKE pattern */
165006  const uint8_t *zString, /* The UTF-8 string to compare against */
165007  const UChar32 uEsc /* The escape character */
165008 ){
165009  static const int MATCH_ONE = (UChar32)'_';
165010  static const int MATCH_ALL = (UChar32)'%';
165011 
165012  int prevEscape = 0; /* True if the previous character was uEsc */
165013 
165014  while( 1 ){
165015 
165016  /* Read (and consume) the next character from the input pattern. */
165017  UChar32 uPattern;
165018  SQLITE_ICU_READ_UTF8(zPattern, uPattern);
165019  if( uPattern==0 ) break;
165020 
165021  /* There are now 4 possibilities:
165022  **
165023  ** 1. uPattern is an unescaped match-all character "%",
165024  ** 2. uPattern is an unescaped match-one character "_",
165025  ** 3. uPattern is an unescaped escape character, or
165026  ** 4. uPattern is to be handled as an ordinary character
165027  */
165028  if( !prevEscape && uPattern==MATCH_ALL ){
165029  /* Case 1. */
165030  uint8_t c;
165031 
165032  /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
165033  ** MATCH_ALL. For each MATCH_ONE, skip one character in the
165034  ** test string.
165035  */
165036  while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
165037  if( c==MATCH_ONE ){
165038  if( *zString==0 ) return 0;
165039  SQLITE_ICU_SKIP_UTF8(zString);
165040  }
165041  zPattern++;
165042  }
165043 
165044  if( *zPattern==0 ) return 1;
165045 
165046  while( *zString ){
165047  if( icuLikeCompare(zPattern, zString, uEsc) ){
165048  return 1;
165049  }
165050  SQLITE_ICU_SKIP_UTF8(zString);
165051  }
165052  return 0;
165053 
165054  }else if( !prevEscape && uPattern==MATCH_ONE ){
165055  /* Case 2. */
165056  if( *zString==0 ) return 0;
165057  SQLITE_ICU_SKIP_UTF8(zString);
165058 
165059  }else if( !prevEscape && uPattern==uEsc){
165060  /* Case 3. */
165061  prevEscape = 1;
165062 
165063  }else{
165064  /* Case 4. */
165065  UChar32 uString;
165066  SQLITE_ICU_READ_UTF8(zString, uString);
165067  uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
165068  uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
165069  if( uString!=uPattern ){
165070  return 0;
165071  }
165072  prevEscape = 0;
165073  }
165074  }
165075 
165076  return *zString==0;
165077 }
165078 
165079 /*
165080 ** Implementation of the like() SQL function. This function implements
165081 ** the build-in LIKE operator. The first argument to the function is the
165082 ** pattern and the second argument is the string. So, the SQL statements:
165083 **
165084 ** A LIKE B
165085 **
165086 ** is implemented as like(B, A). If there is an escape character E,
165087 **
165088 ** A LIKE B ESCAPE E
165089 **
165090 ** is mapped to like(B, A, E).
165091 */
165092 static void icuLikeFunc(
165093  sqlite3_context *context,
165094  int argc,
165095  sqlite3_value **argv
165096 ){
165097  const unsigned char *zA = sqlite3_value_text(argv[0]);
165098  const unsigned char *zB = sqlite3_value_text(argv[1]);
165099  UChar32 uEsc = 0;
165100 
165101  /* Limit the length of the LIKE or GLOB pattern to avoid problems
165102  ** of deep recursion and N*N behavior in patternCompare().
165103  */
165104  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
165105  sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
165106  return;
165107  }
165108 
165109 
165110  if( argc==3 ){
165111  /* The escape character string must consist of a single UTF-8 character.
165112  ** Otherwise, return an error.
165113  */
165114  int nE= sqlite3_value_bytes(argv[2]);
165115  const unsigned char *zE = sqlite3_value_text(argv[2]);
165116  int i = 0;
165117  if( zE==0 ) return;
165118  U8_NEXT(zE, i, nE, uEsc);
165119  if( i!=nE){
165120  sqlite3_result_error(context,
165121  "ESCAPE expression must be a single character", -1);
165122  return;
165123  }
165124  }
165125 
165126  if( zA && zB ){
165127  sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
165128  }
165129 }
165130 
165131 /*
165132 ** This function is called when an ICU function called from within
165133 ** the implementation of an SQL scalar function returns an error.
165134 **
165135 ** The scalar function context passed as the first argument is
165136 ** loaded with an error message based on the following two args.
165137 */
165138 static void icuFunctionError(
165139  sqlite3_context *pCtx, /* SQLite scalar function context */
165140  const char *zName, /* Name of ICU function that failed */
165141  UErrorCode e /* Error code returned by ICU function */
165142 ){
165143  char zBuf[128];
165144  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
165145  zBuf[127] = '\0';
165146  sqlite3_result_error(pCtx, zBuf, -1);
165147 }
165148 
165149 /*
165150 ** Function to delete compiled regexp objects. Registered as
165151 ** a destructor function with sqlite3_set_auxdata().
165152 */
165153 static void icuRegexpDelete(void *p){
165154  URegularExpression *pExpr = (URegularExpression *)p;
165155  uregex_close(pExpr);
165156 }
165157 
165158 /*
165159 ** Implementation of SQLite REGEXP operator. This scalar function takes
165160 ** two arguments. The first is a regular expression pattern to compile
165161 ** the second is a string to match against that pattern. If either
165162 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
165163 ** is 1 if the string matches the pattern, or 0 otherwise.
165164 **
165165 ** SQLite maps the regexp() function to the regexp() operator such
165166 ** that the following two are equivalent:
165167 **
165168 ** zString REGEXP zPattern
165169 ** regexp(zPattern, zString)
165170 **
165171 ** Uses the following ICU regexp APIs:
165172 **
165173 ** uregex_open()
165174 ** uregex_matches()
165175 ** uregex_close()
165176 */
165177 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
165178  UErrorCode status = U_ZERO_ERROR;
165179  URegularExpression *pExpr;
165180  UBool res;
165181  const UChar *zString = sqlite3_value_text16(apArg[1]);
165182 
165183  (void)nArg; /* Unused parameter */
165184 
165185  /* If the left hand side of the regexp operator is NULL,
165186  ** then the result is also NULL.
165187  */
165188  if( !zString ){
165189  return;
165190  }
165191 
165192  pExpr = sqlite3_get_auxdata(p, 0);
165193  if( !pExpr ){
165194  const UChar *zPattern = sqlite3_value_text16(apArg[0]);
165195  if( !zPattern ){
165196  return;
165197  }
165198  pExpr = uregex_open(zPattern, -1, 0, 0, &status);
165199 
165200  if( U_SUCCESS(status) ){
165201  sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
165202  }else{
165203  assert(!pExpr);
165204  icuFunctionError(p, "uregex_open", status);
165205  return;
165206  }
165207  }
165208 
165209  /* Configure the text that the regular expression operates on. */
165210  uregex_setText(pExpr, zString, -1, &status);
165211  if( !U_SUCCESS(status) ){
165212  icuFunctionError(p, "uregex_setText", status);
165213  return;
165214  }
165215 
165216  /* Attempt the match */
165217  res = uregex_matches(pExpr, 0, &status);
165218  if( !U_SUCCESS(status) ){
165219  icuFunctionError(p, "uregex_matches", status);
165220  return;
165221  }
165222 
165223  /* Set the text that the regular expression operates on to a NULL
165224  ** pointer. This is not really necessary, but it is tidier than
165225  ** leaving the regular expression object configured with an invalid
165226  ** pointer after this function returns.
165227  */
165228  uregex_setText(pExpr, 0, 0, &status);
165229 
165230  /* Return 1 or 0. */
165231  sqlite3_result_int(p, res ? 1 : 0);
165232 }
165233 
165234 /*
165235 ** Implementations of scalar functions for case mapping - upper() and
165236 ** lower(). Function upper() converts its input to upper-case (ABC).
165237 ** Function lower() converts to lower-case (abc).
165238 **
165239 ** ICU provides two types of case mapping, "general" case mapping and
165240 ** "language specific". Refer to ICU documentation for the differences
165241 ** between the two.
165242 **
165243 ** To utilise "general" case mapping, the upper() or lower() scalar
165244 ** functions are invoked with one argument:
165245 **
165246 ** upper('ABC') -> 'abc'
165247 ** lower('abc') -> 'ABC'
165248 **
165249 ** To access ICU "language specific" case mapping, upper() or lower()
165250 ** should be invoked with two arguments. The second argument is the name
165251 ** of the locale to use. Passing an empty string ("") or SQL NULL value
165252 ** as the second argument is the same as invoking the 1 argument version
165253 ** of upper() or lower().
165254 **
165255 ** lower('I', 'en_us') -> 'i'
165256 ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
165257 **
165258 ** http://www.icu-project.org/userguide/posix.html#case_mappings
165259 */
165260 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
165261  const UChar *zInput; /* Pointer to input string */
165262  UChar *zOutput = 0; /* Pointer to output buffer */
165263  int nInput; /* Size of utf-16 input string in bytes */
165264  int nOut; /* Size of output buffer in bytes */
165265  int cnt;
165266  int bToUpper; /* True for toupper(), false for tolower() */
165267  UErrorCode status;
165268  const char *zLocale = 0;
165269 
165270  assert(nArg==1 || nArg==2);
165271  bToUpper = (sqlite3_user_data(p)!=0);
165272  if( nArg==2 ){
165273  zLocale = (const char *)sqlite3_value_text(apArg[1]);
165274  }
165275 
165276  zInput = sqlite3_value_text16(apArg[0]);
165277  if( !zInput ){
165278  return;
165279  }
165280  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
165281  if( nOut==0 ){
165282  sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
165283  return;
165284  }
165285 
165286  for(cnt=0; cnt<2; cnt++){
165287  UChar *zNew = sqlite3_realloc(zOutput, nOut);
165288  if( zNew==0 ){
165289  sqlite3_free(zOutput);
165290  sqlite3_result_error_nomem(p);
165291  return;
165292  }
165293  zOutput = zNew;
165294  status = U_ZERO_ERROR;
165295  if( bToUpper ){
165296  nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
165297  }else{
165298  nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
165299  }
165300 
165301  if( U_SUCCESS(status) ){
165302  sqlite3_result_text16(p, zOutput, nOut, xFree);
165303  }else if( status==U_BUFFER_OVERFLOW_ERROR ){
165304  assert( cnt==0 );
165305  continue;
165306  }else{
165307  icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
165308  }
165309  return;
165310  }
165311  assert( 0 ); /* Unreachable */
165312 }
165313 
165314 /*
165315 ** Collation sequence destructor function. The pCtx argument points to
165316 ** a UCollator structure previously allocated using ucol_open().
165317 */
165318 static void icuCollationDel(void *pCtx){
165319  UCollator *p = (UCollator *)pCtx;
165320  ucol_close(p);
165321 }
165322 
165323 /*
165324 ** Collation sequence comparison function. The pCtx argument points to
165325 ** a UCollator structure previously allocated using ucol_open().
165326 */
165327 static int icuCollationColl(
165328  void *pCtx,
165329  int nLeft,
165330  const void *zLeft,
165331  int nRight,
165332  const void *zRight
165333 ){
165334  UCollationResult res;
165335  UCollator *p = (UCollator *)pCtx;
165336  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
165337  switch( res ){
165338  case UCOL_LESS: return -1;
165339  case UCOL_GREATER: return +1;
165340  case UCOL_EQUAL: return 0;
165341  }
165342  assert(!"Unexpected return value from ucol_strcoll()");
165343  return 0;
165344 }
165345 
165346 /*
165347 ** Implementation of the scalar function icu_load_collation().
165348 **
165349 ** This scalar function is used to add ICU collation based collation
165350 ** types to an SQLite database connection. It is intended to be called
165351 ** as follows:
165352 **
165353 ** SELECT icu_load_collation(<locale>, <collation-name>);
165354 **
165355 ** Where <locale> is a string containing an ICU locale identifier (i.e.
165356 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
165357 ** collation sequence to create.
165358 */
165359 static void icuLoadCollation(
165360  sqlite3_context *p,
165361  int nArg,
165362  sqlite3_value **apArg
165363 ){
165364  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
165365  UErrorCode status = U_ZERO_ERROR;
165366  const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
165367  const char *zName; /* SQL Collation sequence name (eg. "japanese") */
165368  UCollator *pUCollator; /* ICU library collation object */
165369  int rc; /* Return code from sqlite3_create_collation_x() */
165370 
165371  assert(nArg==2);
165372  (void)nArg; /* Unused parameter */
165373  zLocale = (const char *)sqlite3_value_text(apArg[0]);
165374  zName = (const char *)sqlite3_value_text(apArg[1]);
165375 
165376  if( !zLocale || !zName ){
165377  return;
165378  }
165379 
165380  pUCollator = ucol_open(zLocale, &status);
165381  if( !U_SUCCESS(status) ){
165382  icuFunctionError(p, "ucol_open", status);
165383  return;
165384  }
165385  assert(p);
165386 
165387  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
165388  icuCollationColl, icuCollationDel
165389  );
165390  if( rc!=SQLITE_OK ){
165391  ucol_close(pUCollator);
165392  sqlite3_result_error(p, "Error registering collation function", -1);
165393  }
165394 }
165395 
165396 /*
165397 ** Register the ICU extension functions with database db.
165398 */
165399 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
165400  struct IcuScalar {
165401  const char *zName; /* Function name */
165402  int nArg; /* Number of arguments */
165403  int enc; /* Optimal text encoding */
165404  void *pContext; /* sqlite3_user_data() context */
165405  void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
165406  } scalars[] = {
165407  {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
165408 
165409  {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
165410  {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
165411  {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
165412  {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
165413 
165414  {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
165415  {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
165416  {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
165417  {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
165418 
165419  {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
165420  {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
165421 
165422  {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
165423  };
165424 
165425  int rc = SQLITE_OK;
165426  int i;
165427 
165428  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
165429  struct IcuScalar *p = &scalars[i];
165430  rc = sqlite3_create_function(
165431  db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
165432  );
165433  }
165434 
165435  return rc;
165436 }
165437 
165438 #if !SQLITE_CORE
165439 #ifdef _WIN32
165440 __declspec(dllexport)
165441 #endif
165442 SQLITE_API int sqlite3_icu_init(
165443  sqlite3 *db,
165444  char **pzErrMsg,
165445  const sqlite3_api_routines *pApi
165446 ){
165447  SQLITE_EXTENSION_INIT2(pApi)
165448  return sqlite3IcuInit(db);
165449 }
165450 #endif
165451 
165452 #endif
165453 
165454 /************** End of icu.c *************************************************/
165455 /************** Begin file fts3_icu.c ****************************************/
165456 /*
165457 ** 2007 June 22
165458 **
165459 ** The author disclaims copyright to this source code. In place of
165460 ** a legal notice, here is a blessing:
165461 **
165462 ** May you do good and not evil.
165463 ** May you find forgiveness for yourself and forgive others.
165464 ** May you share freely, never taking more than you give.
165465 **
165466 *************************************************************************
165467 ** This file implements a tokenizer for fts3 based on the ICU library.
165468 */
165469 /* #include "fts3Int.h" */
165470 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
165471 #ifdef SQLITE_ENABLE_ICU
165472 
165473 /* #include <assert.h> */
165474 /* #include <string.h> */
165475 /* #include "fts3_tokenizer.h" */
165476 
165477 #include <unicode/ubrk.h>
165478 /* #include <unicode/ucol.h> */
165479 /* #include <unicode/ustring.h> */
165480 #include <unicode/utf16.h>
165481 
165482 typedef struct IcuTokenizer IcuTokenizer;
165483 typedef struct IcuCursor IcuCursor;
165484 
165485 struct IcuTokenizer {
165486  sqlite3_tokenizer base;
165487  char *zLocale;
165488 };
165489 
165490 struct IcuCursor {
165491  sqlite3_tokenizer_cursor base;
165492 
165493  UBreakIterator *pIter; /* ICU break-iterator object */
165494  int nChar; /* Number of UChar elements in pInput */
165495  UChar *aChar; /* Copy of input using utf-16 encoding */
165496  int *aOffset; /* Offsets of each character in utf-8 input */
165497 
165498  int nBuffer;
165499  char *zBuffer;
165500 
165501  int iToken;
165502 };
165503 
165504 /*
165505 ** Create a new tokenizer instance.
165506 */
165507 static int icuCreate(
165508  int argc, /* Number of entries in argv[] */
165509  const char * const *argv, /* Tokenizer creation arguments */
165510  sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
165511 ){
165512  IcuTokenizer *p;
165513  int n = 0;
165514 
165515  if( argc>0 ){
165516  n = strlen(argv[0])+1;
165517  }
165518  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
165519  if( !p ){
165520  return SQLITE_NOMEM;
165521  }
165522  memset(p, 0, sizeof(IcuTokenizer));
165523 
165524  if( n ){
165525  p->zLocale = (char *)&p[1];
165526  memcpy(p->zLocale, argv[0], n);
165527  }
165528 
165529  *ppTokenizer = (sqlite3_tokenizer *)p;
165530 
165531  return SQLITE_OK;
165532 }
165533 
165534 /*
165535 ** Destroy a tokenizer
165536 */
165537 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
165538  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
165539  sqlite3_free(p);
165540  return SQLITE_OK;
165541 }
165542 
165543 /*
165544 ** Prepare to begin tokenizing a particular string. The input
165545 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
165546 ** used to incrementally tokenize this string is returned in
165547 ** *ppCursor.
165548 */
165549 static int icuOpen(
165550  sqlite3_tokenizer *pTokenizer, /* The tokenizer */
165551  const char *zInput, /* Input string */
165552  int nInput, /* Length of zInput in bytes */
165553  sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
165554 ){
165555  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
165556  IcuCursor *pCsr;
165557 
165558  const int32_t opt = U_FOLD_CASE_DEFAULT;
165559  UErrorCode status = U_ZERO_ERROR;
165560  int nChar;
165561 
165562  UChar32 c;
165563  int iInput = 0;
165564  int iOut = 0;
165565 
165566  *ppCursor = 0;
165567 
165568  if( zInput==0 ){
165569  nInput = 0;
165570  zInput = "";
165571  }else if( nInput<0 ){
165572  nInput = strlen(zInput);
165573  }
165574  nChar = nInput+1;
165575  pCsr = (IcuCursor *)sqlite3_malloc(
165576  sizeof(IcuCursor) + /* IcuCursor */
165577  ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
165578  (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
165579  );
165580  if( !pCsr ){
165581  return SQLITE_NOMEM;
165582  }
165583  memset(pCsr, 0, sizeof(IcuCursor));
165584  pCsr->aChar = (UChar *)&pCsr[1];
165585  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
165586 
165587  pCsr->aOffset[iOut] = iInput;
165588  U8_NEXT(zInput, iInput, nInput, c);
165589  while( c>0 ){
165590  int isError = 0;
165591  c = u_foldCase(c, opt);
165592  U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
165593  if( isError ){
165594  sqlite3_free(pCsr);
165595  return SQLITE_ERROR;
165596  }
165597  pCsr->aOffset[iOut] = iInput;
165598 
165599  if( iInput<nInput ){
165600  U8_NEXT(zInput, iInput, nInput, c);
165601  }else{
165602  c = 0;
165603  }
165604  }
165605 
165606  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
165607  if( !U_SUCCESS(status) ){
165608  sqlite3_free(pCsr);
165609  return SQLITE_ERROR;
165610  }
165611  pCsr->nChar = iOut;
165612 
165613  ubrk_first(pCsr->pIter);
165614  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
165615  return SQLITE_OK;
165616 }
165617 
165618 /*
165619 ** Close a tokenization cursor previously opened by a call to icuOpen().
165620 */
165621 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
165622  IcuCursor *pCsr = (IcuCursor *)pCursor;
165623  ubrk_close(pCsr->pIter);
165624  sqlite3_free(pCsr->zBuffer);
165625  sqlite3_free(pCsr);
165626  return SQLITE_OK;
165627 }
165628 
165629 /*
165630 ** Extract the next token from a tokenization cursor.
165631 */
165632 static int icuNext(
165633  sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
165634  const char **ppToken, /* OUT: *ppToken is the token text */
165635  int *pnBytes, /* OUT: Number of bytes in token */
165636  int *piStartOffset, /* OUT: Starting offset of token */
165637  int *piEndOffset, /* OUT: Ending offset of token */
165638  int *piPosition /* OUT: Position integer of token */
165639 ){
165640  IcuCursor *pCsr = (IcuCursor *)pCursor;
165641 
165642  int iStart = 0;
165643  int iEnd = 0;
165644  int nByte = 0;
165645 
165646  while( iStart==iEnd ){
165647  UChar32 c;
165648 
165649  iStart = ubrk_current(pCsr->pIter);
165650  iEnd = ubrk_next(pCsr->pIter);
165651  if( iEnd==UBRK_DONE ){
165652  return SQLITE_DONE;
165653  }
165654 
165655  while( iStart<iEnd ){
165656  int iWhite = iStart;
165657  U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
165658  if( u_isspace(c) ){
165659  iStart = iWhite;
165660  }else{
165661  break;
165662  }
165663  }
165664  assert(iStart<=iEnd);
165665  }
165666 
165667  do {
165668  UErrorCode status = U_ZERO_ERROR;
165669  if( nByte ){
165670  char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
165671  if( !zNew ){
165672  return SQLITE_NOMEM;
165673  }
165674  pCsr->zBuffer = zNew;
165675  pCsr->nBuffer = nByte;
165676  }
165677 
165678  u_strToUTF8(
165679  pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
165680  &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
165681  &status /* Output success/failure */
165682  );
165683  } while( nByte>pCsr->nBuffer );
165684 
165685  *ppToken = pCsr->zBuffer;
165686  *pnBytes = nByte;
165687  *piStartOffset = pCsr->aOffset[iStart];
165688  *piEndOffset = pCsr->aOffset[iEnd];
165689  *piPosition = pCsr->iToken++;
165690 
165691  return SQLITE_OK;
165692 }
165693 
165694 /*
165695 ** The set of routines that implement the simple tokenizer
165696 */
165697 static const sqlite3_tokenizer_module icuTokenizerModule = {
165698  0, /* iVersion */
165699  icuCreate, /* xCreate */
165700  icuDestroy, /* xCreate */
165701  icuOpen, /* xOpen */
165702  icuClose, /* xClose */
165703  icuNext, /* xNext */
165704  0, /* xLanguageid */
165705 };
165706 
165707 /*
165708 ** Set *ppModule to point at the implementation of the ICU tokenizer.
165709 */
165710 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
165711  sqlite3_tokenizer_module const**ppModule
165712 ){
165713  *ppModule = &icuTokenizerModule;
165714 }
165715 
165716 #endif /* defined(SQLITE_ENABLE_ICU) */
165717 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
165718 
165719 /************** End of fts3_icu.c ********************************************/
165720 /************** Begin file sqlite3rbu.c **************************************/
165721 /*
165722 ** 2014 August 30
165723 **
165724 ** The author disclaims copyright to this source code. In place of
165725 ** a legal notice, here is a blessing:
165726 **
165727 ** May you do good and not evil.
165728 ** May you find forgiveness for yourself and forgive others.
165729 ** May you share freely, never taking more than you give.
165730 **
165731 *************************************************************************
165732 **
165733 **
165734 ** OVERVIEW
165735 **
165736 ** The RBU extension requires that the RBU update be packaged as an
165737 ** SQLite database. The tables it expects to find are described in
165738 ** sqlite3rbu.h. Essentially, for each table xyz in the target database
165739 ** that the user wishes to write to, a corresponding data_xyz table is
165740 ** created in the RBU database and populated with one row for each row to
165741 ** update, insert or delete from the target table.
165742 **
165743 ** The update proceeds in three stages:
165744 **
165745 ** 1) The database is updated. The modified database pages are written
165746 ** to a *-oal file. A *-oal file is just like a *-wal file, except
165747 ** that it is named "<database>-oal" instead of "<database>-wal".
165748 ** Because regular SQLite clients do not look for file named
165749 ** "<database>-oal", they go on using the original database in
165750 ** rollback mode while the *-oal file is being generated.
165751 **
165752 ** During this stage RBU does not update the database by writing
165753 ** directly to the target tables. Instead it creates "imposter"
165754 ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
165755 ** to update each b-tree individually. All updates required by each
165756 ** b-tree are completed before moving on to the next, and all
165757 ** updates are done in sorted key order.
165758 **
165759 ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
165760 ** location using a call to rename(2). Before doing this the RBU
165761 ** module takes an EXCLUSIVE lock on the database file, ensuring
165762 ** that there are no other active readers.
165763 **
165764 ** Once the EXCLUSIVE lock is released, any other database readers
165765 ** detect the new *-wal file and read the database in wal mode. At
165766 ** this point they see the new version of the database - including
165767 ** the updates made as part of the RBU update.
165768 **
165769 ** 3) The new *-wal file is checkpointed. This proceeds in the same way
165770 ** as a regular database checkpoint, except that a single frame is
165771 ** checkpointed each time sqlite3rbu_step() is called. If the RBU
165772 ** handle is closed before the entire *-wal file is checkpointed,
165773 ** the checkpoint progress is saved in the RBU database and the
165774 ** checkpoint can be resumed by another RBU client at some point in
165775 ** the future.
165776 **
165777 ** POTENTIAL PROBLEMS
165778 **
165779 ** The rename() call might not be portable. And RBU is not currently
165780 ** syncing the directory after renaming the file.
165781 **
165782 ** When state is saved, any commit to the *-oal file and the commit to
165783 ** the RBU update database are not atomic. So if the power fails at the
165784 ** wrong moment they might get out of sync. As the main database will be
165785 ** committed before the RBU update database this will likely either just
165786 ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
165787 ** constraint violations).
165788 **
165789 ** If some client does modify the target database mid RBU update, or some
165790 ** other error occurs, the RBU extension will keep throwing errors. It's
165791 ** not really clear how to get out of this state. The system could just
165792 ** by delete the RBU update database and *-oal file and have the device
165793 ** download the update again and start over.
165794 **
165795 ** At present, for an UPDATE, both the new.* and old.* records are
165796 ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
165797 ** fields are collected. This means we're probably writing a lot more
165798 ** data to disk when saving the state of an ongoing update to the RBU
165799 ** update database than is strictly necessary.
165800 **
165801 */
165802 
165803 /* #include <assert.h> */
165804 /* #include <string.h> */
165805 /* #include <stdio.h> */
165806 
165807 /* #include "sqlite3.h" */
165808 
165809 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
165810 /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
165811 /************** Begin file sqlite3rbu.h **************************************/
165812 /*
165813 ** 2014 August 30
165814 **
165815 ** The author disclaims copyright to this source code. In place of
165816 ** a legal notice, here is a blessing:
165817 **
165818 ** May you do good and not evil.
165819 ** May you find forgiveness for yourself and forgive others.
165820 ** May you share freely, never taking more than you give.
165821 **
165822 *************************************************************************
165823 **
165824 ** This file contains the public interface for the RBU extension.
165825 */
165826 
165827 /*
165828 ** SUMMARY
165829 **
165830 ** Writing a transaction containing a large number of operations on
165831 ** b-tree indexes that are collectively larger than the available cache
165832 ** memory can be very inefficient.
165833 **
165834 ** The problem is that in order to update a b-tree, the leaf page (at least)
165835 ** containing the entry being inserted or deleted must be modified. If the
165836 ** working set of leaves is larger than the available cache memory, then a
165837 ** single leaf that is modified more than once as part of the transaction
165838 ** may be loaded from or written to the persistent media multiple times.
165839 ** Additionally, because the index updates are likely to be applied in
165840 ** random order, access to pages within the database is also likely to be in
165841 ** random order, which is itself quite inefficient.
165842 **
165843 ** One way to improve the situation is to sort the operations on each index
165844 ** by index key before applying them to the b-tree. This leads to an IO
165845 ** pattern that resembles a single linear scan through the index b-tree,
165846 ** and all but guarantees each modified leaf page is loaded and stored
165847 ** exactly once. SQLite uses this trick to improve the performance of
165848 ** CREATE INDEX commands. This extension allows it to be used to improve
165849 ** the performance of large transactions on existing databases.
165850 **
165851 ** Additionally, this extension allows the work involved in writing the
165852 ** large transaction to be broken down into sub-transactions performed
165853 ** sequentially by separate processes. This is useful if the system cannot
165854 ** guarantee that a single update process will run for long enough to apply
165855 ** the entire update, for example because the update is being applied on a
165856 ** mobile device that is frequently rebooted. Even after the writer process
165857 ** has committed one or more sub-transactions, other database clients continue
165858 ** to read from the original database snapshot. In other words, partially
165859 ** applied transactions are not visible to other clients.
165860 **
165861 ** "RBU" stands for "Resumable Bulk Update". As in a large database update
165862 ** transmitted via a wireless network to a mobile device. A transaction
165863 ** applied using this extension is hence refered to as an "RBU update".
165864 **
165865 **
165866 ** LIMITATIONS
165867 **
165868 ** An "RBU update" transaction is subject to the following limitations:
165869 **
165870 ** * The transaction must consist of INSERT, UPDATE and DELETE operations
165871 ** only.
165872 **
165873 ** * INSERT statements may not use any default values.
165874 **
165875 ** * UPDATE and DELETE statements must identify their target rows by
165876 ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
165877 ** KEY fields may not be updated or deleted. If the table being written
165878 ** has no PRIMARY KEY, affected rows must be identified by rowid.
165879 **
165880 ** * UPDATE statements may not modify PRIMARY KEY columns.
165881 **
165882 ** * No triggers will be fired.
165883 **
165884 ** * No foreign key violations are detected or reported.
165885 **
165886 ** * CHECK constraints are not enforced.
165887 **
165888 ** * No constraint handling mode except for "OR ROLLBACK" is supported.
165889 **
165890 **
165891 ** PREPARATION
165892 **
165893 ** An "RBU update" is stored as a separate SQLite database. A database
165894 ** containing an RBU update is an "RBU database". For each table in the
165895 ** target database to be updated, the RBU database should contain a table
165896 ** named "data_<target name>" containing the same set of columns as the
165897 ** target table, and one more - "rbu_control". The data_% table should
165898 ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
165899 ** the same type as the corresponding column in the target database.
165900 ** The "rbu_control" column should have no type at all. For example, if
165901 ** the target database contains:
165902 **
165903 ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
165904 **
165905 ** Then the RBU database should contain:
165906 **
165907 ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
165908 **
165909 ** The order of the columns in the data_% table does not matter.
165910 **
165911 ** Instead of a regular table, the RBU database may also contain virtual
165912 ** tables or view named using the data_<target> naming scheme.
165913 **
165914 ** Instead of the plain data_<target> naming scheme, RBU database tables
165915 ** may also be named data<integer>_<target>, where <integer> is any sequence
165916 ** of zero or more numeric characters (0-9). This can be significant because
165917 ** tables within the RBU database are always processed in order sorted by
165918 ** name. By judicious selection of the <integer> portion of the names
165919 ** of the RBU tables the user can therefore control the order in which they
165920 ** are processed. This can be useful, for example, to ensure that "external
165921 ** content" FTS4 tables are updated before their underlying content tables.
165922 **
165923 ** If the target database table is a virtual table or a table that has no
165924 ** PRIMARY KEY declaration, the data_% table must also contain a column
165925 ** named "rbu_rowid". This column is mapped to the tables implicit primary
165926 ** key column - "rowid". Virtual tables for which the "rowid" column does
165927 ** not function like a primary key value cannot be updated using RBU. For
165928 ** example, if the target db contains either of the following:
165929 **
165930 ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
165931 ** CREATE TABLE x1(a, b)
165932 **
165933 ** then the RBU database should contain:
165934 **
165935 ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
165936 **
165937 ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
165938 ** target table must be present in the input table. For virtual tables,
165939 ** hidden columns are optional - they are updated by RBU if present in
165940 ** the input table, or not otherwise. For example, to write to an fts4
165941 ** table with a hidden languageid column such as:
165942 **
165943 ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
165944 **
165945 ** Either of the following input table schemas may be used:
165946 **
165947 ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
165948 ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
165949 **
165950 ** For each row to INSERT into the target database as part of the RBU
165951 ** update, the corresponding data_% table should contain a single record
165952 ** with the "rbu_control" column set to contain integer value 0. The
165953 ** other columns should be set to the values that make up the new record
165954 ** to insert.
165955 **
165956 ** If the target database table has an INTEGER PRIMARY KEY, it is not
165957 ** possible to insert a NULL value into the IPK column. Attempting to
165958 ** do so results in an SQLITE_MISMATCH error.
165959 **
165960 ** For each row to DELETE from the target database as part of the RBU
165961 ** update, the corresponding data_% table should contain a single record
165962 ** with the "rbu_control" column set to contain integer value 1. The
165963 ** real primary key values of the row to delete should be stored in the
165964 ** corresponding columns of the data_% table. The values stored in the
165965 ** other columns are not used.
165966 **
165967 ** For each row to UPDATE from the target database as part of the RBU
165968 ** update, the corresponding data_% table should contain a single record
165969 ** with the "rbu_control" column set to contain a value of type text.
165970 ** The real primary key values identifying the row to update should be
165971 ** stored in the corresponding columns of the data_% table row, as should
165972 ** the new values of all columns being update. The text value in the
165973 ** "rbu_control" column must contain the same number of characters as
165974 ** there are columns in the target database table, and must consist entirely
165975 ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
165976 ** each column that is being updated, the corresponding character is set to
165977 ** 'x'. For those that remain as they are, the corresponding character of the
165978 ** rbu_control value should be set to '.'. For example, given the tables
165979 ** above, the update statement:
165980 **
165981 ** UPDATE t1 SET c = 'usa' WHERE a = 4;
165982 **
165983 ** is represented by the data_t1 row created by:
165984 **
165985 ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
165986 **
165987 ** Instead of an 'x' character, characters of the rbu_control value specified
165988 ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
165989 ** target table with the value stored in the corresponding data_% column, the
165990 ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
165991 ** the target table column. rbu_delta() is invoked with two arguments - the
165992 ** original value currently stored in the target table column and the
165993 ** value specified in the data_xxx table.
165994 **
165995 ** For example, this row:
165996 **
165997 ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
165998 **
165999 ** is similar to an UPDATE statement such as:
166000 **
166001 ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
166002 **
166003 ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
166004 ** ota_control string, the contents of the data_xxx table column is assumed
166005 ** to be a "fossil delta" - a patch to be applied to a blob value in the
166006 ** format used by the fossil source-code management system. In this case
166007 ** the existing value within the target database table must be of type BLOB.
166008 ** It is replaced by the result of applying the specified fossil delta to
166009 ** itself.
166010 **
166011 ** If the target database table is a virtual table or a table with no PRIMARY
166012 ** KEY, the rbu_control value should not include a character corresponding
166013 ** to the rbu_rowid value. For example, this:
166014 **
166015 ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
166016 ** VALUES(NULL, 'usa', 12, '.x');
166017 **
166018 ** causes a result similar to:
166019 **
166020 ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
166021 **
166022 ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
166023 ** However, RBU is more efficient if reading the rows in from each data_xxx
166024 ** table in "rowid" order is roughly the same as reading them sorted by
166025 ** the PRIMARY KEY of the corresponding target database table. In other
166026 ** words, rows should be sorted using the destination table PRIMARY KEY
166027 ** fields before they are inserted into the data_xxx tables.
166028 **
166029 ** USAGE
166030 **
166031 ** The API declared below allows an application to apply an RBU update
166032 ** stored on disk to an existing target database. Essentially, the
166033 ** application:
166034 **
166035 ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
166036 **
166037 ** 2) Registers any required virtual table modules with the database
166038 ** handle returned by sqlite3rbu_db(). Also, if required, register
166039 ** the rbu_delta() implementation.
166040 **
166041 ** 3) Calls the sqlite3rbu_step() function one or more times on
166042 ** the new handle. Each call to sqlite3rbu_step() performs a single
166043 ** b-tree operation, so thousands of calls may be required to apply
166044 ** a complete update.
166045 **
166046 ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
166047 ** sqlite3rbu_step() has been called enough times to completely
166048 ** apply the update to the target database, then the RBU database
166049 ** is marked as fully applied. Otherwise, the state of the RBU
166050 ** update application is saved in the RBU database for later
166051 ** resumption.
166052 **
166053 ** See comments below for more detail on APIs.
166054 **
166055 ** If an update is only partially applied to the target database by the
166056 ** time sqlite3rbu_close() is called, various state information is saved
166057 ** within the RBU database. This allows subsequent processes to automatically
166058 ** resume the RBU update from where it left off.
166059 **
166060 ** To remove all RBU extension state information, returning an RBU database
166061 ** to its original contents, it is sufficient to drop all tables that begin
166062 ** with the prefix "rbu_"
166063 **
166064 ** DATABASE LOCKING
166065 **
166066 ** An RBU update may not be applied to a database in WAL mode. Attempting
166067 ** to do so is an error (SQLITE_ERROR).
166068 **
166069 ** While an RBU handle is open, a SHARED lock may be held on the target
166070 ** database file. This means it is possible for other clients to read the
166071 ** database, but not to write it.
166072 **
166073 ** If an RBU update is started and then suspended before it is completed,
166074 ** then an external client writes to the database, then attempting to resume
166075 ** the suspended RBU update is also an error (SQLITE_BUSY).
166076 */
166077 
166078 #ifndef _SQLITE3RBU_H
166079 #define _SQLITE3RBU_H
166080 
166081 /* #include "sqlite3.h" ** Required for error code definitions ** */
166082 
166083 #if 0
166084 extern "C" {
166085 #endif
166086 
166087 typedef struct sqlite3rbu sqlite3rbu;
166088 
166089 /*
166090 ** Open an RBU handle.
166091 **
166092 ** Argument zTarget is the path to the target database. Argument zRbu is
166093 ** the path to the RBU database. Each call to this function must be matched
166094 ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
166095 ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
166096 ** or zRbu begin with "file:", it will be interpreted as an SQLite
166097 ** database URI, not a regular file name.
166098 **
166099 ** If the zState argument is passed a NULL value, the RBU extension stores
166100 ** the current state of the update (how many rows have been updated, which
166101 ** indexes are yet to be updated etc.) within the RBU database itself. This
166102 ** can be convenient, as it means that the RBU application does not need to
166103 ** organize removing a separate state file after the update is concluded.
166104 ** Or, if zState is non-NULL, it must be a path to a database file in which
166105 ** the RBU extension can store the state of the update.
166106 **
166107 ** When resuming an RBU update, the zState argument must be passed the same
166108 ** value as when the RBU update was started.
166109 **
166110 ** Once the RBU update is finished, the RBU extension does not
166111 ** automatically remove any zState database file, even if it created it.
166112 **
166113 ** By default, RBU uses the default VFS to access the files on disk. To
166114 ** use a VFS other than the default, an SQLite "file:" URI containing a
166115 ** "vfs=..." option may be passed as the zTarget option.
166116 **
166117 ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
166118 ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
166119 ** not work out of the box with zipvfs. Refer to the comment describing
166120 ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
166121 */
166122 SQLITE_API sqlite3rbu *sqlite3rbu_open(
166123  const char *zTarget,
166124  const char *zRbu,
166125  const char *zState
166126 );
166127 
166128 /*
166129 ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
166130 ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
166131 ** that it can be suspended and resumed like an RBU update.
166132 **
166133 ** The second argument to this function identifies a database in which
166134 ** to store the state of the RBU vacuum operation if it is suspended. The
166135 ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
166136 ** operation, the state database should either not exist or be empty
166137 ** (contain no tables). If an RBU vacuum is suspended by calling
166138 ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
166139 ** returned SQLITE_DONE, the vacuum state is stored in the state database.
166140 ** The vacuum can be resumed by calling this function to open a new RBU
166141 ** handle specifying the same target and state databases.
166142 **
166143 ** If the second argument passed to this function is NULL, then the
166144 ** name of the state database is "<database>-vacuum", where <database>
166145 ** is the name of the target database file. In this case, on UNIX, if the
166146 ** state database is not already present in the file-system, it is created
166147 ** with the same permissions as the target db is made.
166148 **
166149 ** This function does not delete the state database after an RBU vacuum
166150 ** is completed, even if it created it. However, if the call to
166151 ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
166152 ** of the state tables within the state database are zeroed. This way,
166153 ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
166154 ** new RBU vacuum operation.
166155 **
166156 ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
166157 ** describing the sqlite3rbu_create_vfs() API function below for
166158 ** a description of the complications associated with using RBU with
166159 ** zipvfs databases.
166160 */
166161 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
166162  const char *zTarget,
166163  const char *zState
166164 );
166165 
166166 /*
166167 ** Internally, each RBU connection uses a separate SQLite database
166168 ** connection to access the target and rbu update databases. This
166169 ** API allows the application direct access to these database handles.
166170 **
166171 ** The first argument passed to this function must be a valid, open, RBU
166172 ** handle. The second argument should be passed zero to access the target
166173 ** database handle, or non-zero to access the rbu update database handle.
166174 ** Accessing the underlying database handles may be useful in the
166175 ** following scenarios:
166176 **
166177 ** * If any target tables are virtual tables, it may be necessary to
166178 ** call sqlite3_create_module() on the target database handle to
166179 ** register the required virtual table implementations.
166180 **
166181 ** * If the data_xxx tables in the RBU source database are virtual
166182 ** tables, the application may need to call sqlite3_create_module() on
166183 ** the rbu update db handle to any required virtual table
166184 ** implementations.
166185 **
166186 ** * If the application uses the "rbu_delta()" feature described above,
166187 ** it must use sqlite3_create_function() or similar to register the
166188 ** rbu_delta() implementation with the target database handle.
166189 **
166190 ** If an error has occurred, either while opening or stepping the RBU object,
166191 ** this function may return NULL. The error code and message may be collected
166192 ** when sqlite3rbu_close() is called.
166193 **
166194 ** Database handles returned by this function remain valid until the next
166195 ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
166196 */
166197 SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
166198 
166199 /*
166200 ** Do some work towards applying the RBU update to the target db.
166201 **
166202 ** Return SQLITE_DONE if the update has been completely applied, or
166203 ** SQLITE_OK if no error occurs but there remains work to do to apply
166204 ** the RBU update. If an error does occur, some other error code is
166205 ** returned.
166206 **
166207 ** Once a call to sqlite3rbu_step() has returned a value other than
166208 ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
166209 ** that immediately return the same value.
166210 */
166211 SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
166212 
166213 /*
166214 ** Force RBU to save its state to disk.
166215 **
166216 ** If a power failure or application crash occurs during an update, following
166217 ** system recovery RBU may resume the update from the point at which the state
166218 ** was last saved. In other words, from the most recent successful call to
166219 ** sqlite3rbu_close() or this function.
166220 **
166221 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
166222 */
166223 SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
166224 
166225 /*
166226 ** Close an RBU handle.
166227 **
166228 ** If the RBU update has been completely applied, mark the RBU database
166229 ** as fully applied. Otherwise, assuming no error has occurred, save the
166230 ** current state of the RBU update appliation to the RBU database.
166231 **
166232 ** If an error has already occurred as part of an sqlite3rbu_step()
166233 ** or sqlite3rbu_open() call, or if one occurs within this function, an
166234 ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
166235 ** point to a buffer containing a utf-8 formatted English language error
166236 ** message. It is the responsibility of the caller to eventually free any
166237 ** such buffer using sqlite3_free().
166238 **
166239 ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
166240 ** update has been partially applied, or SQLITE_DONE if it has been
166241 ** completely applied.
166242 */
166243 SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
166244 
166245 /*
166246 ** Return the total number of key-value operations (inserts, deletes or
166247 ** updates) that have been performed on the target database since the
166248 ** current RBU update was started.
166249 */
166250 SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
166251 
166252 /*
166253 ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
166254 ** progress indications for the two stages of an RBU update. This API may
166255 ** be useful for driving GUI progress indicators and similar.
166256 **
166257 ** An RBU update is divided into two stages:
166258 **
166259 ** * Stage 1, in which changes are accumulated in an oal/wal file, and
166260 ** * Stage 2, in which the contents of the wal file are copied into the
166261 ** main database.
166262 **
166263 ** The update is visible to non-RBU clients during stage 2. During stage 1
166264 ** non-RBU reader clients may see the original database.
166265 **
166266 ** If this API is called during stage 2 of the update, output variable
166267 ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
166268 ** to a value between 0 and 10000 to indicate the permyriadage progress of
166269 ** stage 2. A value of 5000 indicates that stage 2 is half finished,
166270 ** 9000 indicates that it is 90% finished, and so on.
166271 **
166272 ** If this API is called during stage 1 of the update, output variable
166273 ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
166274 ** value to which (*pnOne) is set depends on whether or not the RBU
166275 ** database contains an "rbu_count" table. The rbu_count table, if it
166276 ** exists, must contain the same columns as the following:
166277 **
166278 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
166279 **
166280 ** There must be one row in the table for each source (data_xxx) table within
166281 ** the RBU database. The 'tbl' column should contain the name of the source
166282 ** table. The 'cnt' column should contain the number of rows within the
166283 ** source table.
166284 **
166285 ** If the rbu_count table is present and populated correctly and this
166286 ** API is called during stage 1, the *pnOne output variable is set to the
166287 ** permyriadage progress of the same stage. If the rbu_count table does
166288 ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
166289 ** table exists but is not correctly populated, the value of the *pnOne
166290 ** output variable during stage 1 is undefined.
166291 */
166292 SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
166293 
166294 /*
166295 ** Obtain an indication as to the current stage of an RBU update or vacuum.
166296 ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
166297 ** defined in this file. Return values should be interpreted as follows:
166298 **
166299 ** SQLITE_RBU_STATE_OAL:
166300 ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
166301 ** may either add further data to the *-oal file, or compute data that will
166302 ** be added by a subsequent call.
166303 **
166304 ** SQLITE_RBU_STATE_MOVE:
166305 ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
166306 ** will move the *-oal file to the equivalent *-wal path. If the current
166307 ** operation is an RBU update, then the updated version of the database
166308 ** file will become visible to ordinary SQLite clients following the next
166309 ** call to sqlite3rbu_step().
166310 **
166311 ** SQLITE_RBU_STATE_CHECKPOINT:
166312 ** RBU is currently performing an incremental checkpoint. The next call to
166313 ** sqlite3rbu_step() will copy a page of data from the *-wal file into
166314 ** the target database file.
166315 **
166316 ** SQLITE_RBU_STATE_DONE:
166317 ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
166318 ** will immediately return SQLITE_DONE.
166319 **
166320 ** SQLITE_RBU_STATE_ERROR:
166321 ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
166322 ** immediately return the SQLite error code associated with the error.
166323 */
166324 #define SQLITE_RBU_STATE_OAL 1
166325 #define SQLITE_RBU_STATE_MOVE 2
166326 #define SQLITE_RBU_STATE_CHECKPOINT 3
166327 #define SQLITE_RBU_STATE_DONE 4
166328 #define SQLITE_RBU_STATE_ERROR 5
166329 
166330 SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
166331 
166332 /*
166333 ** Create an RBU VFS named zName that accesses the underlying file-system
166334 ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
166335 ** then the new RBU VFS uses the default system VFS to access the file-system.
166336 ** The new object is registered as a non-default VFS with SQLite before
166337 ** returning.
166338 **
166339 ** Part of the RBU implementation uses a custom VFS object. Usually, this
166340 ** object is created and deleted automatically by RBU.
166341 **
166342 ** The exception is for applications that also use zipvfs. In this case,
166343 ** the custom VFS must be explicitly created by the user before the RBU
166344 ** handle is opened. The RBU VFS should be installed so that the zipvfs
166345 ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
166346 ** (for example multiplexor) to access the file-system. For example,
166347 ** to assemble an RBU enabled VFS stack that uses both zipvfs and
166348 ** multiplexor (error checking omitted):
166349 **
166350 ** // Create a VFS named "multiplex" (not the default).
166351 ** sqlite3_multiplex_initialize(0, 0);
166352 **
166353 ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
166354 ** // second argument were replaced with NULL, the "rbu" VFS would
166355 ** // access the file-system via the system default VFS, bypassing the
166356 ** // multiplexor.
166357 ** sqlite3rbu_create_vfs("rbu", "multiplex");
166358 **
166359 ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
166360 ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
166361 **
166362 ** // Make zipvfs the default VFS.
166363 ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
166364 **
166365 ** Because the default VFS created above includes a RBU functionality, it
166366 ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
166367 ** that does not include the RBU layer results in an error.
166368 **
166369 ** The overhead of adding the "rbu" VFS to the system is negligible for
166370 ** non-RBU users. There is no harm in an application accessing the
166371 ** file-system via "rbu" all the time, even if it only uses RBU functionality
166372 ** occasionally.
166373 */
166374 SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
166375 
166376 /*
166377 ** Deregister and destroy an RBU vfs created by an earlier call to
166378 ** sqlite3rbu_create_vfs().
166379 **
166380 ** VFS objects are not reference counted. If a VFS object is destroyed
166381 ** before all database handles that use it have been closed, the results
166382 ** are undefined.
166383 */
166384 SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
166385 
166386 #if 0
166387 } /* end of the 'extern "C"' block */
166388 #endif
166389 
166390 #endif /* _SQLITE3RBU_H */
166391 
166392 /************** End of sqlite3rbu.h ******************************************/
166393 /************** Continuing where we left off in sqlite3rbu.c *****************/
166394 
166395 #if defined(_WIN32_WCE)
166396 /* #include "windows.h" */
166397 #endif
166398 
166399 /* Maximum number of prepared UPDATE statements held by this module */
166400 #define SQLITE_RBU_UPDATE_CACHESIZE 16
166401 
166402 /*
166403 ** Swap two objects of type TYPE.
166404 */
166405 #if !defined(SQLITE_AMALGAMATION)
166406 # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
166407 #endif
166408 
166409 /*
166410 ** The rbu_state table is used to save the state of a partially applied
166411 ** update so that it can be resumed later. The table consists of integer
166412 ** keys mapped to values as follows:
166413 **
166414 ** RBU_STATE_STAGE:
166415 ** May be set to integer values 1, 2, 4 or 5. As follows:
166416 ** 1: the *-rbu file is currently under construction.
166417 ** 2: the *-rbu file has been constructed, but not yet moved
166418 ** to the *-wal path.
166419 ** 4: the checkpoint is underway.
166420 ** 5: the rbu update has been checkpointed.
166421 **
166422 ** RBU_STATE_TBL:
166423 ** Only valid if STAGE==1. The target database name of the table
166424 ** currently being written.
166425 **
166426 ** RBU_STATE_IDX:
166427 ** Only valid if STAGE==1. The target database name of the index
166428 ** currently being written, or NULL if the main table is currently being
166429 ** updated.
166430 **
166431 ** RBU_STATE_ROW:
166432 ** Only valid if STAGE==1. Number of rows already processed for the current
166433 ** table/index.
166434 **
166435 ** RBU_STATE_PROGRESS:
166436 ** Trbul number of sqlite3rbu_step() calls made so far as part of this
166437 ** rbu update.
166438 **
166439 ** RBU_STATE_CKPT:
166440 ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
166441 ** header created by recovering the *-wal file. This is used to detect
166442 ** cases when another client appends frames to the *-wal file in the
166443 ** middle of an incremental checkpoint (an incremental checkpoint cannot
166444 ** be continued if this happens).
166445 **
166446 ** RBU_STATE_COOKIE:
166447 ** Valid if STAGE==1. The current change-counter cookie value in the
166448 ** target db file.
166449 **
166450 ** RBU_STATE_OALSZ:
166451 ** Valid if STAGE==1. The size in bytes of the *-oal file.
166452 */
166453 #define RBU_STATE_STAGE 1
166454 #define RBU_STATE_TBL 2
166455 #define RBU_STATE_IDX 3
166456 #define RBU_STATE_ROW 4
166457 #define RBU_STATE_PROGRESS 5
166458 #define RBU_STATE_CKPT 6
166459 #define RBU_STATE_COOKIE 7
166460 #define RBU_STATE_OALSZ 8
166461 #define RBU_STATE_PHASEONESTEP 9
166462 
166463 #define RBU_STAGE_OAL 1
166464 #define RBU_STAGE_MOVE 2
166465 #define RBU_STAGE_CAPTURE 3
166466 #define RBU_STAGE_CKPT 4
166467 #define RBU_STAGE_DONE 5
166468 
166469 
166470 #define RBU_CREATE_STATE \
166471  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
166472 
166473 typedef struct RbuFrame RbuFrame;
166474 typedef struct RbuObjIter RbuObjIter;
166475 typedef struct RbuState RbuState;
166476 typedef struct rbu_vfs rbu_vfs;
166477 typedef struct rbu_file rbu_file;
166478 typedef struct RbuUpdateStmt RbuUpdateStmt;
166479 
166480 #if !defined(SQLITE_AMALGAMATION)
166481 typedef unsigned int u32;
166482 typedef unsigned short u16;
166483 typedef unsigned char u8;
166484 typedef sqlite3_int64 i64;
166485 #endif
166486 
166487 /*
166488 ** These values must match the values defined in wal.c for the equivalent
166489 ** locks. These are not magic numbers as they are part of the SQLite file
166490 ** format.
166491 */
166492 #define WAL_LOCK_WRITE 0
166493 #define WAL_LOCK_CKPT 1
166494 #define WAL_LOCK_READ0 3
166495 
166496 #define SQLITE_FCNTL_RBUCNT 5149216
166497 
166498 /*
166499 ** A structure to store values read from the rbu_state table in memory.
166500 */
166501 struct RbuState {
166502  int eStage;
166503  char *zTbl;
166504  char *zIdx;
166505  i64 iWalCksum;
166506  int nRow;
166507  i64 nProgress;
166508  u32 iCookie;
166509  i64 iOalSz;
166510  i64 nPhaseOneStep;
166511 };
166512 
166513 struct RbuUpdateStmt {
166514  char *zMask; /* Copy of update mask used with pUpdate */
166515  sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
166516  RbuUpdateStmt *pNext;
166517 };
166518 
166519 /*
166520 ** An iterator of this type is used to iterate through all objects in
166521 ** the target database that require updating. For each such table, the
166522 ** iterator visits, in order:
166523 **
166524 ** * the table itself,
166525 ** * each index of the table (zero or more points to visit), and
166526 ** * a special "cleanup table" state.
166527 **
166528 ** abIndexed:
166529 ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
166530 ** it points to an array of flags nTblCol elements in size. The flag is
166531 ** set for each column that is either a part of the PK or a part of an
166532 ** index. Or clear otherwise.
166533 **
166534 */
166535 struct RbuObjIter {
166536  sqlite3_stmt *pTblIter; /* Iterate through tables */
166537  sqlite3_stmt *pIdxIter; /* Index iterator */
166538  int nTblCol; /* Size of azTblCol[] array */
166539  char **azTblCol; /* Array of unquoted target column names */
166540  char **azTblType; /* Array of target column types */
166541  int *aiSrcOrder; /* src table col -> target table col */
166542  u8 *abTblPk; /* Array of flags, set on target PK columns */
166543  u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
166544  u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
166545  int eType; /* Table type - an RBU_PK_XXX value */
166546 
166547  /* Output variables. zTbl==0 implies EOF. */
166548  int bCleanup; /* True in "cleanup" state */
166549  const char *zTbl; /* Name of target db table */
166550  const char *zDataTbl; /* Name of rbu db table (or null) */
166551  const char *zIdx; /* Name of target db index (or null) */
166552  int iTnum; /* Root page of current object */
166553  int iPkTnum; /* If eType==EXTERNAL, root of PK index */
166554  int bUnique; /* Current index is unique */
166555  int nIndex; /* Number of aux. indexes on table zTbl */
166556 
166557  /* Statements created by rbuObjIterPrepareAll() */
166558  int nCol; /* Number of columns in current object */
166559  sqlite3_stmt *pSelect; /* Source data */
166560  sqlite3_stmt *pInsert; /* Statement for INSERT operations */
166561  sqlite3_stmt *pDelete; /* Statement for DELETE ops */
166562  sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
166563 
166564  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
166565  RbuUpdateStmt *pRbuUpdate;
166566 };
166567 
166568 /*
166569 ** Values for RbuObjIter.eType
166570 **
166571 ** 0: Table does not exist (error)
166572 ** 1: Table has an implicit rowid.
166573 ** 2: Table has an explicit IPK column.
166574 ** 3: Table has an external PK index.
166575 ** 4: Table is WITHOUT ROWID.
166576 ** 5: Table is a virtual table.
166577 */
166578 #define RBU_PK_NOTABLE 0
166579 #define RBU_PK_NONE 1
166580 #define RBU_PK_IPK 2
166581 #define RBU_PK_EXTERNAL 3
166582 #define RBU_PK_WITHOUT_ROWID 4
166583 #define RBU_PK_VTAB 5
166584 
166585 
166586 /*
166587 ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
166588 ** one of the following operations.
166589 */
166590 #define RBU_INSERT 1 /* Insert on a main table b-tree */
166591 #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
166592 #define RBU_REPLACE 3 /* Delete and then insert a row */
166593 #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
166594 #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
166595 
166596 #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
166597 
166598 /*
166599 ** A single step of an incremental checkpoint - frame iWalFrame of the wal
166600 ** file should be copied to page iDbPage of the database file.
166601 */
166602 struct RbuFrame {
166603  u32 iDbPage;
166604  u32 iWalFrame;
166605 };
166606 
166607 /*
166608 ** RBU handle.
166609 **
166610 ** nPhaseOneStep:
166611 ** If the RBU database contains an rbu_count table, this value is set to
166612 ** a running estimate of the number of b-tree operations required to
166613 ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
166614 ** API to calculate the permyriadage progress of populating the *-oal file
166615 ** using the formula:
166616 **
166617 ** permyriadage = (10000 * nProgress) / nPhaseOneStep
166618 **
166619 ** nPhaseOneStep is initialized to the sum of:
166620 **
166621 ** nRow * (nIndex + 1)
166622 **
166623 ** for all source tables in the RBU database, where nRow is the number
166624 ** of rows in the source table and nIndex the number of indexes on the
166625 ** corresponding target database table.
166626 **
166627 ** This estimate is accurate if the RBU update consists entirely of
166628 ** INSERT operations. However, it is inaccurate if:
166629 **
166630 ** * the RBU update contains any UPDATE operations. If the PK specified
166631 ** for an UPDATE operation does not exist in the target table, then
166632 ** no b-tree operations are required on index b-trees. Or if the
166633 ** specified PK does exist, then (nIndex*2) such operations are
166634 ** required (one delete and one insert on each index b-tree).
166635 **
166636 ** * the RBU update contains any DELETE operations for which the specified
166637 ** PK does not exist. In this case no operations are required on index
166638 ** b-trees.
166639 **
166640 ** * the RBU update contains REPLACE operations. These are similar to
166641 ** UPDATE operations.
166642 **
166643 ** nPhaseOneStep is updated to account for the conditions above during the
166644 ** first pass of each source table. The updated nPhaseOneStep value is
166645 ** stored in the rbu_state table if the RBU update is suspended.
166646 */
166647 struct sqlite3rbu {
166648  int eStage; /* Value of RBU_STATE_STAGE field */
166649  sqlite3 *dbMain; /* target database handle */
166650  sqlite3 *dbRbu; /* rbu database handle */
166651  char *zTarget; /* Path to target db */
166652  char *zRbu; /* Path to rbu db */
166653  char *zState; /* Path to state db (or NULL if zRbu) */
166654  char zStateDb[5]; /* Db name for state ("stat" or "main") */
166655  int rc; /* Value returned by last rbu_step() call */
166656  char *zErrmsg; /* Error message if rc!=SQLITE_OK */
166657  int nStep; /* Rows processed for current object */
166658  int nProgress; /* Rows processed for all objects */
166659  RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
166660  const char *zVfsName; /* Name of automatically created rbu vfs */
166661  rbu_file *pTargetFd; /* File handle open on target db */
166662  i64 iOalSz;
166663  i64 nPhaseOneStep;
166664 
166665  /* The following state variables are used as part of the incremental
166666  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
166667  ** function rbuSetupCheckpoint() for details. */
166668  u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
166669  u32 mLock;
166670  int nFrame; /* Entries in aFrame[] array */
166671  int nFrameAlloc; /* Allocated size of aFrame[] array */
166672  RbuFrame *aFrame;
166673  int pgsz;
166674  u8 *aBuf;
166675  i64 iWalCksum;
166676 
166677  /* Used in RBU vacuum mode only */
166678  int nRbu; /* Number of RBU VFS in the stack */
166679  rbu_file *pRbuFd; /* Fd for main db of dbRbu */
166680 };
166681 
166682 /*
166683 ** An rbu VFS is implemented using an instance of this structure.
166684 */
166685 struct rbu_vfs {
166686  sqlite3_vfs base; /* rbu VFS shim methods */
166687  sqlite3_vfs *pRealVfs; /* Underlying VFS */
166688  sqlite3_mutex *mutex; /* Mutex to protect pMain */
166689  rbu_file *pMain; /* Linked list of main db files */
166690 };
166691 
166692 /*
166693 ** Each file opened by an rbu VFS is represented by an instance of
166694 ** the following structure.
166695 */
166696 struct rbu_file {
166697  sqlite3_file base; /* sqlite3_file methods */
166698  sqlite3_file *pReal; /* Underlying file handle */
166699  rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
166700  sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
166701 
166702  int openFlags; /* Flags this file was opened with */
166703  u32 iCookie; /* Cookie value for main db files */
166704  u8 iWriteVer; /* "write-version" value for main db files */
166705  u8 bNolock; /* True to fail EXCLUSIVE locks */
166706 
166707  int nShm; /* Number of entries in apShm[] array */
166708  char **apShm; /* Array of mmap'd *-shm regions */
166709  char *zDel; /* Delete this when closing file */
166710 
166711  const char *zWal; /* Wal filename for this main db file */
166712  rbu_file *pWalFd; /* Wal file descriptor for this main db */
166713  rbu_file *pMainNext; /* Next MAIN_DB file */
166714 };
166715 
166716 /*
166717 ** True for an RBU vacuum handle, or false otherwise.
166718 */
166719 #define rbuIsVacuum(p) ((p)->zTarget==0)
166720 
166721 
166722 /*************************************************************************
166723 ** The following three functions, found below:
166724 **
166725 ** rbuDeltaGetInt()
166726 ** rbuDeltaChecksum()
166727 ** rbuDeltaApply()
166728 **
166729 ** are lifted from the fossil source code (http://fossil-scm.org). They
166730 ** are used to implement the scalar SQL function rbu_fossil_delta().
166731 */
166732 
166733 /*
166734 ** Read bytes from *pz and convert them into a positive integer. When
166735 ** finished, leave *pz pointing to the first character past the end of
166736 ** the integer. The *pLen parameter holds the length of the string
166737 ** in *pz and is decremented once for each character in the integer.
166738 */
166739 static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
166740  static const signed char zValue[] = {
166741  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
166742  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
166743  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
166744  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
166745  -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
166746  25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
166747  -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
166748  52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
166749  };
166750  unsigned int v = 0;
166751  int c;
166752  unsigned char *z = (unsigned char*)*pz;
166753  unsigned char *zStart = z;
166754  while( (c = zValue[0x7f&*(z++)])>=0 ){
166755  v = (v<<6) + c;
166756  }
166757  z--;
166758  *pLen -= z - zStart;
166759  *pz = (char*)z;
166760  return v;
166761 }
166762 
166763 /*
166764 ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
166765 */
166766 static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
166767  const unsigned char *z = (const unsigned char *)zIn;
166768  unsigned sum0 = 0;
166769  unsigned sum1 = 0;
166770  unsigned sum2 = 0;
166771  unsigned sum3 = 0;
166772  while(N >= 16){
166773  sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
166774  sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
166775  sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
166776  sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
166777  z += 16;
166778  N -= 16;
166779  }
166780  while(N >= 4){
166781  sum0 += z[0];
166782  sum1 += z[1];
166783  sum2 += z[2];
166784  sum3 += z[3];
166785  z += 4;
166786  N -= 4;
166787  }
166788  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
166789  switch(N){
166790  case 3: sum3 += (z[2] << 8);
166791  case 2: sum3 += (z[1] << 16);
166792  case 1: sum3 += (z[0] << 24);
166793  default: ;
166794  }
166795  return sum3;
166796 }
166797 
166798 /*
166799 ** Apply a delta.
166800 **
166801 ** The output buffer should be big enough to hold the whole output
166802 ** file and a NUL terminator at the end. The delta_output_size()
166803 ** routine will determine this size for you.
166804 **
166805 ** The delta string should be null-terminated. But the delta string
166806 ** may contain embedded NUL characters (if the input and output are
166807 ** binary files) so we also have to pass in the length of the delta in
166808 ** the lenDelta parameter.
166809 **
166810 ** This function returns the size of the output file in bytes (excluding
166811 ** the final NUL terminator character). Except, if the delta string is
166812 ** malformed or intended for use with a source file other than zSrc,
166813 ** then this routine returns -1.
166814 **
166815 ** Refer to the delta_create() documentation above for a description
166816 ** of the delta file format.
166817 */
166818 static int rbuDeltaApply(
166819  const char *zSrc, /* The source or pattern file */
166820  int lenSrc, /* Length of the source file */
166821  const char *zDelta, /* Delta to apply to the pattern */
166822  int lenDelta, /* Length of the delta */
166823  char *zOut /* Write the output into this preallocated buffer */
166824 ){
166825  unsigned int limit;
166826  unsigned int total = 0;
166827 #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
166828  char *zOrigOut = zOut;
166829 #endif
166830 
166831  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
166832  if( *zDelta!='\n' ){
166833  /* ERROR: size integer not terminated by "\n" */
166834  return -1;
166835  }
166836  zDelta++; lenDelta--;
166837  while( *zDelta && lenDelta>0 ){
166838  unsigned int cnt, ofst;
166839  cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
166840  switch( zDelta[0] ){
166841  case '@': {
166842  zDelta++; lenDelta--;
166843  ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
166844  if( lenDelta>0 && zDelta[0]!=',' ){
166845  /* ERROR: copy command not terminated by ',' */
166846  return -1;
166847  }
166848  zDelta++; lenDelta--;
166849  total += cnt;
166850  if( total>limit ){
166851  /* ERROR: copy exceeds output file size */
166852  return -1;
166853  }
166854  if( (int)(ofst+cnt) > lenSrc ){
166855  /* ERROR: copy extends past end of input */
166856  return -1;
166857  }
166858  memcpy(zOut, &zSrc[ofst], cnt);
166859  zOut += cnt;
166860  break;
166861  }
166862  case ':': {
166863  zDelta++; lenDelta--;
166864  total += cnt;
166865  if( total>limit ){
166866  /* ERROR: insert command gives an output larger than predicted */
166867  return -1;
166868  }
166869  if( (int)cnt>lenDelta ){
166870  /* ERROR: insert count exceeds size of delta */
166871  return -1;
166872  }
166873  memcpy(zOut, zDelta, cnt);
166874  zOut += cnt;
166875  zDelta += cnt;
166876  lenDelta -= cnt;
166877  break;
166878  }
166879  case ';': {
166880  zDelta++; lenDelta--;
166881  zOut[0] = 0;
166882 #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
166883  if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
166884  /* ERROR: bad checksum */
166885  return -1;
166886  }
166887 #endif
166888  if( total!=limit ){
166889  /* ERROR: generated size does not match predicted size */
166890  return -1;
166891  }
166892  return total;
166893  }
166894  default: {
166895  /* ERROR: unknown delta operator */
166896  return -1;
166897  }
166898  }
166899  }
166900  /* ERROR: unterminated delta */
166901  return -1;
166902 }
166903 
166904 static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
166905  int size;
166906  size = rbuDeltaGetInt(&zDelta, &lenDelta);
166907  if( *zDelta!='\n' ){
166908  /* ERROR: size integer not terminated by "\n" */
166909  return -1;
166910  }
166911  return size;
166912 }
166913 
166914 /*
166915 ** End of code taken from fossil.
166916 *************************************************************************/
166917 
166918 /*
166919 ** Implementation of SQL scalar function rbu_fossil_delta().
166920 **
166921 ** This function applies a fossil delta patch to a blob. Exactly two
166922 ** arguments must be passed to this function. The first is the blob to
166923 ** patch and the second the patch to apply. If no error occurs, this
166924 ** function returns the patched blob.
166925 */
166926 static void rbuFossilDeltaFunc(
166927  sqlite3_context *context,
166928  int argc,
166929  sqlite3_value **argv
166930 ){
166931  const char *aDelta;
166932  int nDelta;
166933  const char *aOrig;
166934  int nOrig;
166935 
166936  int nOut;
166937  int nOut2;
166938  char *aOut;
166939 
166940  assert( argc==2 );
166941 
166942  nOrig = sqlite3_value_bytes(argv[0]);
166943  aOrig = (const char*)sqlite3_value_blob(argv[0]);
166944  nDelta = sqlite3_value_bytes(argv[1]);
166945  aDelta = (const char*)sqlite3_value_blob(argv[1]);
166946 
166947  /* Figure out the size of the output */
166948  nOut = rbuDeltaOutputSize(aDelta, nDelta);
166949  if( nOut<0 ){
166950  sqlite3_result_error(context, "corrupt fossil delta", -1);
166951  return;
166952  }
166953 
166954  aOut = sqlite3_malloc(nOut+1);
166955  if( aOut==0 ){
166956  sqlite3_result_error_nomem(context);
166957  }else{
166958  nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
166959  if( nOut2!=nOut ){
166960  sqlite3_result_error(context, "corrupt fossil delta", -1);
166961  }else{
166962  sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
166963  }
166964  }
166965 }
166966 
166967 
166968 /*
166969 ** Prepare the SQL statement in buffer zSql against database handle db.
166970 ** If successful, set *ppStmt to point to the new statement and return
166971 ** SQLITE_OK.
166972 **
166973 ** Otherwise, if an error does occur, set *ppStmt to NULL and return
166974 ** an SQLite error code. Additionally, set output variable *pzErrmsg to
166975 ** point to a buffer containing an error message. It is the responsibility
166976 ** of the caller to (eventually) free this buffer using sqlite3_free().
166977 */
166978 static int prepareAndCollectError(
166979  sqlite3 *db,
166980  sqlite3_stmt **ppStmt,
166981  char **pzErrmsg,
166982  const char *zSql
166983 ){
166984  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
166985  if( rc!=SQLITE_OK ){
166986  *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
166987  *ppStmt = 0;
166988  }
166989  return rc;
166990 }
166991 
166992 /*
166993 ** Reset the SQL statement passed as the first argument. Return a copy
166994 ** of the value returned by sqlite3_reset().
166995 **
166996 ** If an error has occurred, then set *pzErrmsg to point to a buffer
166997 ** containing an error message. It is the responsibility of the caller
166998 ** to eventually free this buffer using sqlite3_free().
166999 */
167000 static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
167001  int rc = sqlite3_reset(pStmt);
167002  if( rc!=SQLITE_OK ){
167003  *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
167004  }
167005  return rc;
167006 }
167007 
167008 /*
167009 ** Unless it is NULL, argument zSql points to a buffer allocated using
167010 ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
167011 ** statement against database db and frees the buffer. If statement
167012 ** compilation is successful, *ppStmt is set to point to the new statement
167013 ** handle and SQLITE_OK is returned.
167014 **
167015 ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
167016 ** returned. In this case, *pzErrmsg may also be set to point to an error
167017 ** message. It is the responsibility of the caller to free this error message
167018 ** buffer using sqlite3_free().
167019 **
167020 ** If argument zSql is NULL, this function assumes that an OOM has occurred.
167021 ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
167022 */
167023 static int prepareFreeAndCollectError(
167024  sqlite3 *db,
167025  sqlite3_stmt **ppStmt,
167026  char **pzErrmsg,
167027  char *zSql
167028 ){
167029  int rc;
167030  assert( *pzErrmsg==0 );
167031  if( zSql==0 ){
167032  rc = SQLITE_NOMEM;
167033  *ppStmt = 0;
167034  }else{
167035  rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
167036  sqlite3_free(zSql);
167037  }
167038  return rc;
167039 }
167040 
167041 /*
167042 ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
167043 ** by an earlier call to rbuObjIterCacheTableInfo().
167044 */
167045 static void rbuObjIterFreeCols(RbuObjIter *pIter){
167046  int i;
167047  for(i=0; i<pIter->nTblCol; i++){
167048  sqlite3_free(pIter->azTblCol[i]);
167049  sqlite3_free(pIter->azTblType[i]);
167050  }
167051  sqlite3_free(pIter->azTblCol);
167052  pIter->azTblCol = 0;
167053  pIter->azTblType = 0;
167054  pIter->aiSrcOrder = 0;
167055  pIter->abTblPk = 0;
167056  pIter->abNotNull = 0;
167057  pIter->nTblCol = 0;
167058  pIter->eType = 0; /* Invalid value */
167059 }
167060 
167061 /*
167062 ** Finalize all statements and free all allocations that are specific to
167063 ** the current object (table/index pair).
167064 */
167065 static void rbuObjIterClearStatements(RbuObjIter *pIter){
167066  RbuUpdateStmt *pUp;
167067 
167068  sqlite3_finalize(pIter->pSelect);
167069  sqlite3_finalize(pIter->pInsert);
167070  sqlite3_finalize(pIter->pDelete);
167071  sqlite3_finalize(pIter->pTmpInsert);
167072  pUp = pIter->pRbuUpdate;
167073  while( pUp ){
167074  RbuUpdateStmt *pTmp = pUp->pNext;
167075  sqlite3_finalize(pUp->pUpdate);
167076  sqlite3_free(pUp);
167077  pUp = pTmp;
167078  }
167079 
167080  pIter->pSelect = 0;
167081  pIter->pInsert = 0;
167082  pIter->pDelete = 0;
167083  pIter->pRbuUpdate = 0;
167084  pIter->pTmpInsert = 0;
167085  pIter->nCol = 0;
167086 }
167087 
167088 /*
167089 ** Clean up any resources allocated as part of the iterator object passed
167090 ** as the only argument.
167091 */
167092 static void rbuObjIterFinalize(RbuObjIter *pIter){
167093  rbuObjIterClearStatements(pIter);
167094  sqlite3_finalize(pIter->pTblIter);
167095  sqlite3_finalize(pIter->pIdxIter);
167096  rbuObjIterFreeCols(pIter);
167097  memset(pIter, 0, sizeof(RbuObjIter));
167098 }
167099 
167100 /*
167101 ** Advance the iterator to the next position.
167102 **
167103 ** If no error occurs, SQLITE_OK is returned and the iterator is left
167104 ** pointing to the next entry. Otherwise, an error code and message is
167105 ** left in the RBU handle passed as the first argument. A copy of the
167106 ** error code is returned.
167107 */
167108 static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
167109  int rc = p->rc;
167110  if( rc==SQLITE_OK ){
167111 
167112  /* Free any SQLite statements used while processing the previous object */
167113  rbuObjIterClearStatements(pIter);
167114  if( pIter->zIdx==0 ){
167115  rc = sqlite3_exec(p->dbMain,
167116  "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
167117  "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
167118  "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
167119  "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
167120  , 0, 0, &p->zErrmsg
167121  );
167122  }
167123 
167124  if( rc==SQLITE_OK ){
167125  if( pIter->bCleanup ){
167126  rbuObjIterFreeCols(pIter);
167127  pIter->bCleanup = 0;
167128  rc = sqlite3_step(pIter->pTblIter);
167129  if( rc!=SQLITE_ROW ){
167130  rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
167131  pIter->zTbl = 0;
167132  }else{
167133  pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
167134  pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
167135  rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
167136  }
167137  }else{
167138  if( pIter->zIdx==0 ){
167139  sqlite3_stmt *pIdx = pIter->pIdxIter;
167140  rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
167141  }
167142  if( rc==SQLITE_OK ){
167143  rc = sqlite3_step(pIter->pIdxIter);
167144  if( rc!=SQLITE_ROW ){
167145  rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
167146  pIter->bCleanup = 1;
167147  pIter->zIdx = 0;
167148  }else{
167149  pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
167150  pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
167151  pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
167152  rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
167153  }
167154  }
167155  }
167156  }
167157  }
167158 
167159  if( rc!=SQLITE_OK ){
167160  rbuObjIterFinalize(pIter);
167161  p->rc = rc;
167162  }
167163  return rc;
167164 }
167165 
167166 
167167 /*
167168 ** The implementation of the rbu_target_name() SQL function. This function
167169 ** accepts one or two arguments. The first argument is the name of a table -
167170 ** the name of a table in the RBU database. The second, if it is present, is 1
167171 ** for a view or 0 for a table.
167172 **
167173 ** For a non-vacuum RBU handle, if the table name matches the pattern:
167174 **
167175 ** data[0-9]_<name>
167176 **
167177 ** where <name> is any sequence of 1 or more characters, <name> is returned.
167178 ** Otherwise, if the only argument does not match the above pattern, an SQL
167179 ** NULL is returned.
167180 **
167181 ** "data_t1" -> "t1"
167182 ** "data0123_t2" -> "t2"
167183 ** "dataAB_t3" -> NULL
167184 **
167185 ** For an rbu vacuum handle, a copy of the first argument is returned if
167186 ** the second argument is either missing or 0 (not a view).
167187 */
167188 static void rbuTargetNameFunc(
167189  sqlite3_context *pCtx,
167190  int argc,
167191  sqlite3_value **argv
167192 ){
167193  sqlite3rbu *p = sqlite3_user_data(pCtx);
167194  const char *zIn;
167195  assert( argc==1 || argc==2 );
167196 
167197  zIn = (const char*)sqlite3_value_text(argv[0]);
167198  if( zIn ){
167199  if( rbuIsVacuum(p) ){
167200  if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
167201  sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
167202  }
167203  }else{
167204  if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
167205  int i;
167206  for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
167207  if( zIn[i]=='_' && zIn[i+1] ){
167208  sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
167209  }
167210  }
167211  }
167212  }
167213 }
167214 
167215 /*
167216 ** Initialize the iterator structure passed as the second argument.
167217 **
167218 ** If no error occurs, SQLITE_OK is returned and the iterator is left
167219 ** pointing to the first entry. Otherwise, an error code and message is
167220 ** left in the RBU handle passed as the first argument. A copy of the
167221 ** error code is returned.
167222 */
167223 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
167224  int rc;
167225  memset(pIter, 0, sizeof(RbuObjIter));
167226 
167227  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
167228  sqlite3_mprintf(
167229  "SELECT rbu_target_name(name, type='view') AS target, name "
167230  "FROM sqlite_master "
167231  "WHERE type IN ('table', 'view') AND target IS NOT NULL "
167232  " %s "
167233  "ORDER BY name"
167234  , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
167235 
167236  if( rc==SQLITE_OK ){
167237  rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
167238  "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
167239  " FROM main.sqlite_master "
167240  " WHERE type='index' AND tbl_name = ?"
167241  );
167242  }
167243 
167244  pIter->bCleanup = 1;
167245  p->rc = rc;
167246  return rbuObjIterNext(p, pIter);
167247 }
167248 
167249 /*
167250 ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
167251 ** an error code is stored in the RBU handle passed as the first argument.
167252 **
167253 ** If an error has already occurred (p->rc is already set to something other
167254 ** than SQLITE_OK), then this function returns NULL without modifying the
167255 ** stored error code. In this case it still calls sqlite3_free() on any
167256 ** printf() parameters associated with %z conversions.
167257 */
167258 static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
167259  char *zSql = 0;
167260  va_list ap;
167261  va_start(ap, zFmt);
167262  zSql = sqlite3_vmprintf(zFmt, ap);
167263  if( p->rc==SQLITE_OK ){
167264  if( zSql==0 ) p->rc = SQLITE_NOMEM;
167265  }else{
167266  sqlite3_free(zSql);
167267  zSql = 0;
167268  }
167269  va_end(ap);
167270  return zSql;
167271 }
167272 
167273 /*
167274 ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
167275 ** arguments are the usual subsitution values. This function performs
167276 ** the printf() style substitutions and executes the result as an SQL
167277 ** statement on the RBU handles database.
167278 **
167279 ** If an error occurs, an error code and error message is stored in the
167280 ** RBU handle. If an error has already occurred when this function is
167281 ** called, it is a no-op.
167282 */
167283 static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
167284  va_list ap;
167285  char *zSql;
167286  va_start(ap, zFmt);
167287  zSql = sqlite3_vmprintf(zFmt, ap);
167288  if( p->rc==SQLITE_OK ){
167289  if( zSql==0 ){
167290  p->rc = SQLITE_NOMEM;
167291  }else{
167292  p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
167293  }
167294  }
167295  sqlite3_free(zSql);
167296  va_end(ap);
167297  return p->rc;
167298 }
167299 
167300 /*
167301 ** Attempt to allocate and return a pointer to a zeroed block of nByte
167302 ** bytes.
167303 **
167304 ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
167305 ** error code in the rbu handle passed as the first argument. Or, if an
167306 ** error has already occurred when this function is called, return NULL
167307 ** immediately without attempting the allocation or modifying the stored
167308 ** error code.
167309 */
167310 static void *rbuMalloc(sqlite3rbu *p, int nByte){
167311  void *pRet = 0;
167312  if( p->rc==SQLITE_OK ){
167313  assert( nByte>0 );
167314  pRet = sqlite3_malloc64(nByte);
167315  if( pRet==0 ){
167316  p->rc = SQLITE_NOMEM;
167317  }else{
167318  memset(pRet, 0, nByte);
167319  }
167320  }
167321  return pRet;
167322 }
167323 
167324 
167325 /*
167326 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
167327 ** there is room for at least nCol elements. If an OOM occurs, store an
167328 ** error code in the RBU handle passed as the first argument.
167329 */
167330 static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
167331  int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
167332  char **azNew;
167333 
167334  azNew = (char**)rbuMalloc(p, nByte);
167335  if( azNew ){
167336  pIter->azTblCol = azNew;
167337  pIter->azTblType = &azNew[nCol];
167338  pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
167339  pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
167340  pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
167341  pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
167342  }
167343 }
167344 
167345 /*
167346 ** The first argument must be a nul-terminated string. This function
167347 ** returns a copy of the string in memory obtained from sqlite3_malloc().
167348 ** It is the responsibility of the caller to eventually free this memory
167349 ** using sqlite3_free().
167350 **
167351 ** If an OOM condition is encountered when attempting to allocate memory,
167352 ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
167353 ** if the allocation succeeds, (*pRc) is left unchanged.
167354 */
167355 static char *rbuStrndup(const char *zStr, int *pRc){
167356  char *zRet = 0;
167357 
167358  assert( *pRc==SQLITE_OK );
167359  if( zStr ){
167360  size_t nCopy = strlen(zStr) + 1;
167361  zRet = (char*)sqlite3_malloc64(nCopy);
167362  if( zRet ){
167363  memcpy(zRet, zStr, nCopy);
167364  }else{
167365  *pRc = SQLITE_NOMEM;
167366  }
167367  }
167368 
167369  return zRet;
167370 }
167371 
167372 /*
167373 ** Finalize the statement passed as the second argument.
167374 **
167375 ** If the sqlite3_finalize() call indicates that an error occurs, and the
167376 ** rbu handle error code is not already set, set the error code and error
167377 ** message accordingly.
167378 */
167379 static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
167380  sqlite3 *db = sqlite3_db_handle(pStmt);
167381  int rc = sqlite3_finalize(pStmt);
167382  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
167383  p->rc = rc;
167384  p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
167385  }
167386 }
167387 
167388 /* Determine the type of a table.
167389 **
167390 ** peType is of type (int*), a pointer to an output parameter of type
167391 ** (int). This call sets the output parameter as follows, depending
167392 ** on the type of the table specified by parameters dbName and zTbl.
167393 **
167394 ** RBU_PK_NOTABLE: No such table.
167395 ** RBU_PK_NONE: Table has an implicit rowid.
167396 ** RBU_PK_IPK: Table has an explicit IPK column.
167397 ** RBU_PK_EXTERNAL: Table has an external PK index.
167398 ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
167399 ** RBU_PK_VTAB: Table is a virtual table.
167400 **
167401 ** Argument *piPk is also of type (int*), and also points to an output
167402 ** parameter. Unless the table has an external primary key index
167403 ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
167404 ** if the table does have an external primary key index, then *piPk
167405 ** is set to the root page number of the primary key index before
167406 ** returning.
167407 **
167408 ** ALGORITHM:
167409 **
167410 ** if( no entry exists in sqlite_master ){
167411 ** return RBU_PK_NOTABLE
167412 ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
167413 ** return RBU_PK_VTAB
167414 ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
167415 ** if( the index that is the pk exists in sqlite_master ){
167416 ** *piPK = rootpage of that index.
167417 ** return RBU_PK_EXTERNAL
167418 ** }else{
167419 ** return RBU_PK_WITHOUT_ROWID
167420 ** }
167421 ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
167422 ** return RBU_PK_IPK
167423 ** }else{
167424 ** return RBU_PK_NONE
167425 ** }
167426 */
167427 static void rbuTableType(
167428  sqlite3rbu *p,
167429  const char *zTab,
167430  int *peType,
167431  int *piTnum,
167432  int *piPk
167433 ){
167434  /*
167435  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
167436  ** 1) PRAGMA index_list = ?
167437  ** 2) SELECT count(*) FROM sqlite_master where name=%Q
167438  ** 3) PRAGMA table_info = ?
167439  */
167440  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
167441 
167442  *peType = RBU_PK_NOTABLE;
167443  *piPk = 0;
167444 
167445  assert( p->rc==SQLITE_OK );
167446  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
167447  sqlite3_mprintf(
167448  "SELECT (sql LIKE 'create virtual%%'), rootpage"
167449  " FROM sqlite_master"
167450  " WHERE name=%Q", zTab
167451  ));
167452  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
167453  /* Either an error, or no such table. */
167454  goto rbuTableType_end;
167455  }
167456  if( sqlite3_column_int(aStmt[0], 0) ){
167457  *peType = RBU_PK_VTAB; /* virtual table */
167458  goto rbuTableType_end;
167459  }
167460  *piTnum = sqlite3_column_int(aStmt[0], 1);
167461 
167462  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
167463  sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
167464  );
167465  if( p->rc ) goto rbuTableType_end;
167466  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
167467  const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
167468  const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
167469  if( zOrig && zIdx && zOrig[0]=='p' ){
167470  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
167471  sqlite3_mprintf(
167472  "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
167473  ));
167474  if( p->rc==SQLITE_OK ){
167475  if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
167476  *piPk = sqlite3_column_int(aStmt[2], 0);
167477  *peType = RBU_PK_EXTERNAL;
167478  }else{
167479  *peType = RBU_PK_WITHOUT_ROWID;
167480  }
167481  }
167482  goto rbuTableType_end;
167483  }
167484  }
167485 
167486  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
167487  sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
167488  );
167489  if( p->rc==SQLITE_OK ){
167490  while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
167491  if( sqlite3_column_int(aStmt[3],5)>0 ){
167492  *peType = RBU_PK_IPK; /* explicit IPK column */
167493  goto rbuTableType_end;
167494  }
167495  }
167496  *peType = RBU_PK_NONE;
167497  }
167498 
167499 rbuTableType_end: {
167500  unsigned int i;
167501  for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
167502  rbuFinalize(p, aStmt[i]);
167503  }
167504  }
167505 }
167506 
167507 /*
167508 ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
167509 ** the pIter->abIndexed[] array.
167510 */
167511 static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
167512  sqlite3_stmt *pList = 0;
167513  int bIndex = 0;
167514 
167515  if( p->rc==SQLITE_OK ){
167516  memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
167517  p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
167518  sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
167519  );
167520  }
167521 
167522  pIter->nIndex = 0;
167523  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
167524  const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
167525  sqlite3_stmt *pXInfo = 0;
167526  if( zIdx==0 ) break;
167527  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
167528  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
167529  );
167530  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
167531  int iCid = sqlite3_column_int(pXInfo, 1);
167532  if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
167533  }
167534  rbuFinalize(p, pXInfo);
167535  bIndex = 1;
167536  pIter->nIndex++;
167537  }
167538 
167539  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
167540  /* "PRAGMA index_list" includes the main PK b-tree */
167541  pIter->nIndex--;
167542  }
167543 
167544  rbuFinalize(p, pList);
167545  if( bIndex==0 ) pIter->abIndexed = 0;
167546 }
167547 
167548 
167549 /*
167550 ** If they are not already populated, populate the pIter->azTblCol[],
167551 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
167552 ** the table (not index) that the iterator currently points to.
167553 **
167554 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
167555 ** an error does occur, an error code and error message are also left in
167556 ** the RBU handle.
167557 */
167558 static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
167559  if( pIter->azTblCol==0 ){
167560  sqlite3_stmt *pStmt = 0;
167561  int nCol = 0;
167562  int i; /* for() loop iterator variable */
167563  int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
167564  int iOrder = 0;
167565  int iTnum = 0;
167566 
167567  /* Figure out the type of table this step will deal with. */
167568  assert( pIter->eType==0 );
167569  rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
167570  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
167571  p->rc = SQLITE_ERROR;
167572  p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
167573  }
167574  if( p->rc ) return p->rc;
167575  if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
167576 
167577  assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
167578  || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
167579  || pIter->eType==RBU_PK_VTAB
167580  );
167581 
167582  /* Populate the azTblCol[] and nTblCol variables based on the columns
167583  ** of the input table. Ignore any input table columns that begin with
167584  ** "rbu_". */
167585  p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
167586  sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
167587  );
167588  if( p->rc==SQLITE_OK ){
167589  nCol = sqlite3_column_count(pStmt);
167590  rbuAllocateIterArrays(p, pIter, nCol);
167591  }
167592  for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
167593  const char *zName = (const char*)sqlite3_column_name(pStmt, i);
167594  if( sqlite3_strnicmp("rbu_", zName, 4) ){
167595  char *zCopy = rbuStrndup(zName, &p->rc);
167596  pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
167597  pIter->azTblCol[pIter->nTblCol++] = zCopy;
167598  }
167599  else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
167600  bRbuRowid = 1;
167601  }
167602  }
167603  sqlite3_finalize(pStmt);
167604  pStmt = 0;
167605 
167606  if( p->rc==SQLITE_OK
167607  && rbuIsVacuum(p)==0
167608  && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
167609  ){
167610  p->rc = SQLITE_ERROR;
167611  p->zErrmsg = sqlite3_mprintf(
167612  "table %q %s rbu_rowid column", pIter->zDataTbl,
167613  (bRbuRowid ? "may not have" : "requires")
167614  );
167615  }
167616 
167617  /* Check that all non-HIDDEN columns in the destination table are also
167618  ** present in the input table. Populate the abTblPk[], azTblType[] and
167619  ** aiTblOrder[] arrays at the same time. */
167620  if( p->rc==SQLITE_OK ){
167621  p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
167622  sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
167623  );
167624  }
167625  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
167626  const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
167627  if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
167628  for(i=iOrder; i<pIter->nTblCol; i++){
167629  if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
167630  }
167631  if( i==pIter->nTblCol ){
167632  p->rc = SQLITE_ERROR;
167633  p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
167634  pIter->zDataTbl, zName
167635  );
167636  }else{
167637  int iPk = sqlite3_column_int(pStmt, 5);
167638  int bNotNull = sqlite3_column_int(pStmt, 3);
167639  const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
167640 
167641  if( i!=iOrder ){
167642  SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
167643  SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
167644  }
167645 
167646  pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
167647  pIter->abTblPk[iOrder] = (iPk!=0);
167648  pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
167649  iOrder++;
167650  }
167651  }
167652 
167653  rbuFinalize(p, pStmt);
167654  rbuObjIterCacheIndexedCols(p, pIter);
167655  assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
167656  assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
167657  }
167658 
167659  return p->rc;
167660 }
167661 
167662 /*
167663 ** This function constructs and returns a pointer to a nul-terminated
167664 ** string containing some SQL clause or list based on one or more of the
167665 ** column names currently stored in the pIter->azTblCol[] array.
167666 */
167667 static char *rbuObjIterGetCollist(
167668  sqlite3rbu *p, /* RBU object */
167669  RbuObjIter *pIter /* Object iterator for column names */
167670 ){
167671  char *zList = 0;
167672  const char *zSep = "";
167673  int i;
167674  for(i=0; i<pIter->nTblCol; i++){
167675  const char *z = pIter->azTblCol[i];
167676  zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
167677  zSep = ", ";
167678  }
167679  return zList;
167680 }
167681 
167682 /*
167683 ** This function is used to create a SELECT list (the list of SQL
167684 ** expressions that follows a SELECT keyword) for a SELECT statement
167685 ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
167686 ** index object currently indicated by the iterator object passed as the
167687 ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
167688 ** to obtain the required information.
167689 **
167690 ** If the index is of the following form:
167691 **
167692 ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
167693 **
167694 ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
167695 ** "ipk", the returned string is:
167696 **
167697 ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
167698 **
167699 ** As well as the returned string, three other malloc'd strings are
167700 ** returned via output parameters. As follows:
167701 **
167702 ** pzImposterCols: ...
167703 ** pzImposterPk: ...
167704 ** pzWhere: ...
167705 */
167706 static char *rbuObjIterGetIndexCols(
167707  sqlite3rbu *p, /* RBU object */
167708  RbuObjIter *pIter, /* Object iterator for column names */
167709  char **pzImposterCols, /* OUT: Columns for imposter table */
167710  char **pzImposterPk, /* OUT: Imposter PK clause */
167711  char **pzWhere, /* OUT: WHERE clause */
167712  int *pnBind /* OUT: Trbul number of columns */
167713 ){
167714  int rc = p->rc; /* Error code */
167715  int rc2; /* sqlite3_finalize() return code */
167716  char *zRet = 0; /* String to return */
167717  char *zImpCols = 0; /* String to return via *pzImposterCols */
167718  char *zImpPK = 0; /* String to return via *pzImposterPK */
167719  char *zWhere = 0; /* String to return via *pzWhere */
167720  int nBind = 0; /* Value to return via *pnBind */
167721  const char *zCom = ""; /* Set to ", " later on */
167722  const char *zAnd = ""; /* Set to " AND " later on */
167723  sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
167724 
167725  if( rc==SQLITE_OK ){
167726  assert( p->zErrmsg==0 );
167727  rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
167728  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
167729  );
167730  }
167731 
167732  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
167733  int iCid = sqlite3_column_int(pXInfo, 1);
167734  int bDesc = sqlite3_column_int(pXInfo, 3);
167735  const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
167736  const char *zCol;
167737  const char *zType;
167738 
167739  if( iCid<0 ){
167740  /* An integer primary key. If the table has an explicit IPK, use
167741  ** its name. Otherwise, use "rbu_rowid". */
167742  if( pIter->eType==RBU_PK_IPK ){
167743  int i;
167744  for(i=0; pIter->abTblPk[i]==0; i++);
167745  assert( i<pIter->nTblCol );
167746  zCol = pIter->azTblCol[i];
167747  }else if( rbuIsVacuum(p) ){
167748  zCol = "_rowid_";
167749  }else{
167750  zCol = "rbu_rowid";
167751  }
167752  zType = "INTEGER";
167753  }else{
167754  zCol = pIter->azTblCol[iCid];
167755  zType = pIter->azTblType[iCid];
167756  }
167757 
167758  zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
167759  if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
167760  const char *zOrder = (bDesc ? " DESC" : "");
167761  zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
167762  zImpPK, zCom, nBind, zCol, zOrder
167763  );
167764  }
167765  zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
167766  zImpCols, zCom, nBind, zCol, zType, zCollate
167767  );
167768  zWhere = sqlite3_mprintf(
167769  "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
167770  );
167771  if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
167772  zCom = ", ";
167773  zAnd = " AND ";
167774  nBind++;
167775  }
167776 
167777  rc2 = sqlite3_finalize(pXInfo);
167778  if( rc==SQLITE_OK ) rc = rc2;
167779 
167780  if( rc!=SQLITE_OK ){
167781  sqlite3_free(zRet);
167782  sqlite3_free(zImpCols);
167783  sqlite3_free(zImpPK);
167784  sqlite3_free(zWhere);
167785  zRet = 0;
167786  zImpCols = 0;
167787  zImpPK = 0;
167788  zWhere = 0;
167789  p->rc = rc;
167790  }
167791 
167792  *pzImposterCols = zImpCols;
167793  *pzImposterPk = zImpPK;
167794  *pzWhere = zWhere;
167795  *pnBind = nBind;
167796  return zRet;
167797 }
167798 
167799 /*
167800 ** Assuming the current table columns are "a", "b" and "c", and the zObj
167801 ** paramter is passed "old", return a string of the form:
167802 **
167803 ** "old.a, old.b, old.b"
167804 **
167805 ** With the column names escaped.
167806 **
167807 ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
167808 ** the text ", old._rowid_" to the returned value.
167809 */
167810 static char *rbuObjIterGetOldlist(
167811  sqlite3rbu *p,
167812  RbuObjIter *pIter,
167813  const char *zObj
167814 ){
167815  char *zList = 0;
167816  if( p->rc==SQLITE_OK && pIter->abIndexed ){
167817  const char *zS = "";
167818  int i;
167819  for(i=0; i<pIter->nTblCol; i++){
167820  if( pIter->abIndexed[i] ){
167821  const char *zCol = pIter->azTblCol[i];
167822  zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
167823  }else{
167824  zList = sqlite3_mprintf("%z%sNULL", zList, zS);
167825  }
167826  zS = ", ";
167827  if( zList==0 ){
167828  p->rc = SQLITE_NOMEM;
167829  break;
167830  }
167831  }
167832 
167833  /* For a table with implicit rowids, append "old._rowid_" to the list. */
167834  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
167835  zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
167836  }
167837  }
167838  return zList;
167839 }
167840 
167841 /*
167842 ** Return an expression that can be used in a WHERE clause to match the
167843 ** primary key of the current table. For example, if the table is:
167844 **
167845 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
167846 **
167847 ** Return the string:
167848 **
167849 ** "b = ?1 AND c = ?2"
167850 */
167851 static char *rbuObjIterGetWhere(
167852  sqlite3rbu *p,
167853  RbuObjIter *pIter
167854 ){
167855  char *zList = 0;
167856  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
167857  zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
167858  }else if( pIter->eType==RBU_PK_EXTERNAL ){
167859  const char *zSep = "";
167860  int i;
167861  for(i=0; i<pIter->nTblCol; i++){
167862  if( pIter->abTblPk[i] ){
167863  zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
167864  zSep = " AND ";
167865  }
167866  }
167867  zList = rbuMPrintf(p,
167868  "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
167869  );
167870 
167871  }else{
167872  const char *zSep = "";
167873  int i;
167874  for(i=0; i<pIter->nTblCol; i++){
167875  if( pIter->abTblPk[i] ){
167876  const char *zCol = pIter->azTblCol[i];
167877  zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
167878  zSep = " AND ";
167879  }
167880  }
167881  }
167882  return zList;
167883 }
167884 
167885 /*
167886 ** The SELECT statement iterating through the keys for the current object
167887 ** (p->objiter.pSelect) currently points to a valid row. However, there
167888 ** is something wrong with the rbu_control value in the rbu_control value
167889 ** stored in the (p->nCol+1)'th column. Set the error code and error message
167890 ** of the RBU handle to something reflecting this.
167891 */
167892 static void rbuBadControlError(sqlite3rbu *p){
167893  p->rc = SQLITE_ERROR;
167894  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
167895 }
167896 
167897 
167898 /*
167899 ** Return a nul-terminated string containing the comma separated list of
167900 ** assignments that should be included following the "SET" keyword of
167901 ** an UPDATE statement used to update the table object that the iterator
167902 ** passed as the second argument currently points to if the rbu_control
167903 ** column of the data_xxx table entry is set to zMask.
167904 **
167905 ** The memory for the returned string is obtained from sqlite3_malloc().
167906 ** It is the responsibility of the caller to eventually free it using
167907 ** sqlite3_free().
167908 **
167909 ** If an OOM error is encountered when allocating space for the new
167910 ** string, an error code is left in the rbu handle passed as the first
167911 ** argument and NULL is returned. Or, if an error has already occurred
167912 ** when this function is called, NULL is returned immediately, without
167913 ** attempting the allocation or modifying the stored error code.
167914 */
167915 static char *rbuObjIterGetSetlist(
167916  sqlite3rbu *p,
167917  RbuObjIter *pIter,
167918  const char *zMask
167919 ){
167920  char *zList = 0;
167921  if( p->rc==SQLITE_OK ){
167922  int i;
167923 
167924  if( (int)strlen(zMask)!=pIter->nTblCol ){
167925  rbuBadControlError(p);
167926  }else{
167927  const char *zSep = "";
167928  for(i=0; i<pIter->nTblCol; i++){
167929  char c = zMask[pIter->aiSrcOrder[i]];
167930  if( c=='x' ){
167931  zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
167932  zList, zSep, pIter->azTblCol[i], i+1
167933  );
167934  zSep = ", ";
167935  }
167936  else if( c=='d' ){
167937  zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
167938  zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
167939  );
167940  zSep = ", ";
167941  }
167942  else if( c=='f' ){
167943  zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
167944  zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
167945  );
167946  zSep = ", ";
167947  }
167948  }
167949  }
167950  }
167951  return zList;
167952 }
167953 
167954 /*
167955 ** Return a nul-terminated string consisting of nByte comma separated
167956 ** "?" expressions. For example, if nByte is 3, return a pointer to
167957 ** a buffer containing the string "?,?,?".
167958 **
167959 ** The memory for the returned string is obtained from sqlite3_malloc().
167960 ** It is the responsibility of the caller to eventually free it using
167961 ** sqlite3_free().
167962 **
167963 ** If an OOM error is encountered when allocating space for the new
167964 ** string, an error code is left in the rbu handle passed as the first
167965 ** argument and NULL is returned. Or, if an error has already occurred
167966 ** when this function is called, NULL is returned immediately, without
167967 ** attempting the allocation or modifying the stored error code.
167968 */
167969 static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
167970  char *zRet = 0;
167971  int nByte = nBind*2 + 1;
167972 
167973  zRet = (char*)rbuMalloc(p, nByte);
167974  if( zRet ){
167975  int i;
167976  for(i=0; i<nBind; i++){
167977  zRet[i*2] = '?';
167978  zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
167979  }
167980  }
167981  return zRet;
167982 }
167983 
167984 /*
167985 ** The iterator currently points to a table (not index) of type
167986 ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
167987 ** declaration for the corresponding imposter table. For example,
167988 ** if the iterator points to a table created as:
167989 **
167990 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
167991 **
167992 ** this function returns:
167993 **
167994 ** PRIMARY KEY("b", "a" DESC)
167995 */
167996 static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
167997  char *z = 0;
167998  assert( pIter->zIdx==0 );
167999  if( p->rc==SQLITE_OK ){
168000  const char *zSep = "PRIMARY KEY(";
168001  sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
168002  sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
168003 
168004  p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
168005  sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
168006  );
168007  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
168008  const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
168009  if( zOrig && strcmp(zOrig, "pk")==0 ){
168010  const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
168011  if( zIdx ){
168012  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
168013  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
168014  );
168015  }
168016  break;
168017  }
168018  }
168019  rbuFinalize(p, pXList);
168020 
168021  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
168022  if( sqlite3_column_int(pXInfo, 5) ){
168023  /* int iCid = sqlite3_column_int(pXInfo, 0); */
168024  const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
168025  const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
168026  z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
168027  zSep = ", ";
168028  }
168029  }
168030  z = rbuMPrintf(p, "%z)", z);
168031  rbuFinalize(p, pXInfo);
168032  }
168033  return z;
168034 }
168035 
168036 /*
168037 ** This function creates the second imposter table used when writing to
168038 ** a table b-tree where the table has an external primary key. If the
168039 ** iterator passed as the second argument does not currently point to
168040 ** a table (not index) with an external primary key, this function is a
168041 ** no-op.
168042 **
168043 ** Assuming the iterator does point to a table with an external PK, this
168044 ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
168045 ** used to access that PK index. For example, if the target table is
168046 ** declared as follows:
168047 **
168048 ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
168049 **
168050 ** then the imposter table schema is:
168051 **
168052 ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
168053 **
168054 */
168055 static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
168056  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
168057  int tnum = pIter->iPkTnum; /* Root page of PK index */
168058  sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
168059  const char *zIdx = 0; /* Name of PK index */
168060  sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
168061  const char *zComma = "";
168062  char *zCols = 0; /* Used to build up list of table cols */
168063  char *zPk = 0; /* Used to build up table PK declaration */
168064 
168065  /* Figure out the name of the primary key index for the current table.
168066  ** This is needed for the argument to "PRAGMA index_xinfo". Set
168067  ** zIdx to point to a nul-terminated string containing this name. */
168068  p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
168069  "SELECT name FROM sqlite_master WHERE rootpage = ?"
168070  );
168071  if( p->rc==SQLITE_OK ){
168072  sqlite3_bind_int(pQuery, 1, tnum);
168073  if( SQLITE_ROW==sqlite3_step(pQuery) ){
168074  zIdx = (const char*)sqlite3_column_text(pQuery, 0);
168075  }
168076  }
168077  if( zIdx ){
168078  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
168079  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
168080  );
168081  }
168082  rbuFinalize(p, pQuery);
168083 
168084  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
168085  int bKey = sqlite3_column_int(pXInfo, 5);
168086  if( bKey ){
168087  int iCid = sqlite3_column_int(pXInfo, 1);
168088  int bDesc = sqlite3_column_int(pXInfo, 3);
168089  const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
168090  zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
168091  iCid, pIter->azTblType[iCid], zCollate
168092  );
168093  zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
168094  zComma = ", ";
168095  }
168096  }
168097  zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
168098  rbuFinalize(p, pXInfo);
168099 
168100  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
168101  rbuMPrintfExec(p, p->dbMain,
168102  "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
168103  zCols, zPk
168104  );
168105  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
168106  }
168107 }
168108 
168109 /*
168110 ** If an error has already occurred when this function is called, it
168111 ** immediately returns zero (without doing any work). Or, if an error
168112 ** occurs during the execution of this function, it sets the error code
168113 ** in the sqlite3rbu object indicated by the first argument and returns
168114 ** zero.
168115 **
168116 ** The iterator passed as the second argument is guaranteed to point to
168117 ** a table (not an index) when this function is called. This function
168118 ** attempts to create any imposter table required to write to the main
168119 ** table b-tree of the table before returning. Non-zero is returned if
168120 ** an imposter table are created, or zero otherwise.
168121 **
168122 ** An imposter table is required in all cases except RBU_PK_VTAB. Only
168123 ** virtual tables are written to directly. The imposter table has the
168124 ** same schema as the actual target table (less any UNIQUE constraints).
168125 ** More precisely, the "same schema" means the same columns, types,
168126 ** collation sequences. For tables that do not have an external PRIMARY
168127 ** KEY, it also means the same PRIMARY KEY declaration.
168128 */
168129 static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
168130  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
168131  int tnum = pIter->iTnum;
168132  const char *zComma = "";
168133  char *zSql = 0;
168134  int iCol;
168135  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
168136 
168137  for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
168138  const char *zPk = "";
168139  const char *zCol = pIter->azTblCol[iCol];
168140  const char *zColl = 0;
168141 
168142  p->rc = sqlite3_table_column_metadata(
168143  p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
168144  );
168145 
168146  if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
168147  /* If the target table column is an "INTEGER PRIMARY KEY", add
168148  ** "PRIMARY KEY" to the imposter table column declaration. */
168149  zPk = "PRIMARY KEY ";
168150  }
168151  zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
168152  zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
168153  (pIter->abNotNull[iCol] ? " NOT NULL" : "")
168154  );
168155  zComma = ", ";
168156  }
168157 
168158  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
168159  char *zPk = rbuWithoutRowidPK(p, pIter);
168160  if( zPk ){
168161  zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
168162  }
168163  }
168164 
168165  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
168166  rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
168167  pIter->zTbl, zSql,
168168  (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
168169  );
168170  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
168171  }
168172 }
168173 
168174 /*
168175 ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
168176 ** Specifically a statement of the form:
168177 **
168178 ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
168179 **
168180 ** The number of bound variables is equal to the number of columns in
168181 ** the target table, plus one (for the rbu_control column), plus one more
168182 ** (for the rbu_rowid column) if the target table is an implicit IPK or
168183 ** virtual table.
168184 */
168185 static void rbuObjIterPrepareTmpInsert(
168186  sqlite3rbu *p,
168187  RbuObjIter *pIter,
168188  const char *zCollist,
168189  const char *zRbuRowid
168190 ){
168191  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
168192  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
168193  if( zBind ){
168194  assert( pIter->pTmpInsert==0 );
168195  p->rc = prepareFreeAndCollectError(
168196  p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
168197  "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
168198  p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
168199  ));
168200  }
168201 }
168202 
168203 static void rbuTmpInsertFunc(
168204  sqlite3_context *pCtx,
168205  int nVal,
168206  sqlite3_value **apVal
168207 ){
168208  sqlite3rbu *p = sqlite3_user_data(pCtx);
168209  int rc = SQLITE_OK;
168210  int i;
168211 
168212  assert( sqlite3_value_int(apVal[0])!=0
168213  || p->objiter.eType==RBU_PK_EXTERNAL
168214  || p->objiter.eType==RBU_PK_NONE
168215  );
168216  if( sqlite3_value_int(apVal[0])!=0 ){
168217  p->nPhaseOneStep += p->objiter.nIndex;
168218  }
168219 
168220  for(i=0; rc==SQLITE_OK && i<nVal; i++){
168221  rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
168222  }
168223  if( rc==SQLITE_OK ){
168224  sqlite3_step(p->objiter.pTmpInsert);
168225  rc = sqlite3_reset(p->objiter.pTmpInsert);
168226  }
168227 
168228  if( rc!=SQLITE_OK ){
168229  sqlite3_result_error_code(pCtx, rc);
168230  }
168231 }
168232 
168233 /*
168234 ** Ensure that the SQLite statement handles required to update the
168235 ** target database object currently indicated by the iterator passed
168236 ** as the second argument are available.
168237 */
168238 static int rbuObjIterPrepareAll(
168239  sqlite3rbu *p,
168240  RbuObjIter *pIter,
168241  int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
168242 ){
168243  assert( pIter->bCleanup==0 );
168244  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
168245  const int tnum = pIter->iTnum;
168246  char *zCollist = 0; /* List of indexed columns */
168247  char **pz = &p->zErrmsg;
168248  const char *zIdx = pIter->zIdx;
168249  char *zLimit = 0;
168250 
168251  if( nOffset ){
168252  zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
168253  if( !zLimit ) p->rc = SQLITE_NOMEM;
168254  }
168255 
168256  if( zIdx ){
168257  const char *zTbl = pIter->zTbl;
168258  char *zImposterCols = 0; /* Columns for imposter table */
168259  char *zImposterPK = 0; /* Primary key declaration for imposter */
168260  char *zWhere = 0; /* WHERE clause on PK columns */
168261  char *zBind = 0;
168262  int nBind = 0;
168263 
168264  assert( pIter->eType!=RBU_PK_VTAB );
168265  zCollist = rbuObjIterGetIndexCols(
168266  p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
168267  );
168268  zBind = rbuObjIterGetBindlist(p, nBind);
168269 
168270  /* Create the imposter table used to write to this index. */
168271  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
168272  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
168273  rbuMPrintfExec(p, p->dbMain,
168274  "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
168275  zTbl, zImposterCols, zImposterPK
168276  );
168277  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
168278 
168279  /* Create the statement to insert index entries */
168280  pIter->nCol = nBind;
168281  if( p->rc==SQLITE_OK ){
168282  p->rc = prepareFreeAndCollectError(
168283  p->dbMain, &pIter->pInsert, &p->zErrmsg,
168284  sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
168285  );
168286  }
168287 
168288  /* And to delete index entries */
168289  if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
168290  p->rc = prepareFreeAndCollectError(
168291  p->dbMain, &pIter->pDelete, &p->zErrmsg,
168292  sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
168293  );
168294  }
168295 
168296  /* Create the SELECT statement to read keys in sorted order */
168297  if( p->rc==SQLITE_OK ){
168298  char *zSql;
168299  if( rbuIsVacuum(p) ){
168300  zSql = sqlite3_mprintf(
168301  "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
168302  zCollist,
168303  pIter->zDataTbl,
168304  zCollist, zLimit
168305  );
168306  }else
168307 
168308  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
168309  zSql = sqlite3_mprintf(
168310  "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
168311  zCollist, p->zStateDb, pIter->zDataTbl,
168312  zCollist, zLimit
168313  );
168314  }else{
168315  zSql = sqlite3_mprintf(
168316  "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
168317  "UNION ALL "
168318  "SELECT %s, rbu_control FROM '%q' "
168319  "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
168320  "ORDER BY %s%s",
168321  zCollist, p->zStateDb, pIter->zDataTbl,
168322  zCollist, pIter->zDataTbl,
168323  zCollist, zLimit
168324  );
168325  }
168326  p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
168327  }
168328 
168329  sqlite3_free(zImposterCols);
168330  sqlite3_free(zImposterPK);
168331  sqlite3_free(zWhere);
168332  sqlite3_free(zBind);
168333  }else{
168334  int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
168335  ||(pIter->eType==RBU_PK_NONE)
168336  ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
168337  const char *zTbl = pIter->zTbl; /* Table this step applies to */
168338  const char *zWrite; /* Imposter table name */
168339 
168340  char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
168341  char *zWhere = rbuObjIterGetWhere(p, pIter);
168342  char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
168343  char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
168344 
168345  zCollist = rbuObjIterGetCollist(p, pIter);
168346  pIter->nCol = pIter->nTblCol;
168347 
168348  /* Create the imposter table or tables (if required). */
168349  rbuCreateImposterTable(p, pIter);
168350  rbuCreateImposterTable2(p, pIter);
168351  zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
168352 
168353  /* Create the INSERT statement to write to the target PK b-tree */
168354  if( p->rc==SQLITE_OK ){
168355  p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
168356  sqlite3_mprintf(
168357  "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
168358  zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
168359  )
168360  );
168361  }
168362 
168363  /* Create the DELETE statement to write to the target PK b-tree.
168364  ** Because it only performs INSERT operations, this is not required for
168365  ** an rbu vacuum handle. */
168366  if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
168367  p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
168368  sqlite3_mprintf(
168369  "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
168370  )
168371  );
168372  }
168373 
168374  if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
168375  const char *zRbuRowid = "";
168376  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
168377  zRbuRowid = ", rbu_rowid";
168378  }
168379 
168380  /* Create the rbu_tmp_xxx table and the triggers to populate it. */
168381  rbuMPrintfExec(p, p->dbRbu,
168382  "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
168383  "SELECT *%s FROM '%q' WHERE 0;"
168384  , p->zStateDb, pIter->zDataTbl
168385  , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
168386  , pIter->zDataTbl
168387  );
168388 
168389  rbuMPrintfExec(p, p->dbMain,
168390  "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
168391  "BEGIN "
168392  " SELECT rbu_tmp_insert(3, %s);"
168393  "END;"
168394 
168395  "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
168396  "BEGIN "
168397  " SELECT rbu_tmp_insert(3, %s);"
168398  "END;"
168399 
168400  "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
168401  "BEGIN "
168402  " SELECT rbu_tmp_insert(4, %s);"
168403  "END;",
168404  zWrite, zTbl, zOldlist,
168405  zWrite, zTbl, zOldlist,
168406  zWrite, zTbl, zNewlist
168407  );
168408 
168409  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
168410  rbuMPrintfExec(p, p->dbMain,
168411  "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
168412  "BEGIN "
168413  " SELECT rbu_tmp_insert(0, %s);"
168414  "END;",
168415  zWrite, zTbl, zNewlist
168416  );
168417  }
168418 
168419  rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
168420  }
168421 
168422  /* Create the SELECT statement to read keys from data_xxx */
168423  if( p->rc==SQLITE_OK ){
168424  const char *zRbuRowid = "";
168425  if( bRbuRowid ){
168426  zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
168427  }
168428  p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
168429  sqlite3_mprintf(
168430  "SELECT %s,%s rbu_control%s FROM '%q'%s",
168431  zCollist,
168432  (rbuIsVacuum(p) ? "0 AS " : ""),
168433  zRbuRowid,
168434  pIter->zDataTbl, zLimit
168435  )
168436  );
168437  }
168438 
168439  sqlite3_free(zWhere);
168440  sqlite3_free(zOldlist);
168441  sqlite3_free(zNewlist);
168442  sqlite3_free(zBindings);
168443  }
168444  sqlite3_free(zCollist);
168445  sqlite3_free(zLimit);
168446  }
168447 
168448  return p->rc;
168449 }
168450 
168451 /*
168452 ** Set output variable *ppStmt to point to an UPDATE statement that may
168453 ** be used to update the imposter table for the main table b-tree of the
168454 ** table object that pIter currently points to, assuming that the
168455 ** rbu_control column of the data_xyz table contains zMask.
168456 **
168457 ** If the zMask string does not specify any columns to update, then this
168458 ** is not an error. Output variable *ppStmt is set to NULL in this case.
168459 */
168460 static int rbuGetUpdateStmt(
168461  sqlite3rbu *p, /* RBU handle */
168462  RbuObjIter *pIter, /* Object iterator */
168463  const char *zMask, /* rbu_control value ('x.x.') */
168464  sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
168465 ){
168466  RbuUpdateStmt **pp;
168467  RbuUpdateStmt *pUp = 0;
168468  int nUp = 0;
168469 
168470  /* In case an error occurs */
168471  *ppStmt = 0;
168472 
168473  /* Search for an existing statement. If one is found, shift it to the front
168474  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
168475  ** to the number of statements currently in the cache and pUp to the
168476  ** last object in the list. */
168477  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
168478  pUp = *pp;
168479  if( strcmp(pUp->zMask, zMask)==0 ){
168480  *pp = pUp->pNext;
168481  pUp->pNext = pIter->pRbuUpdate;
168482  pIter->pRbuUpdate = pUp;
168483  *ppStmt = pUp->pUpdate;
168484  return SQLITE_OK;
168485  }
168486  nUp++;
168487  }
168488  assert( pUp==0 || pUp->pNext==0 );
168489 
168490  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
168491  for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
168492  *pp = 0;
168493  sqlite3_finalize(pUp->pUpdate);
168494  pUp->pUpdate = 0;
168495  }else{
168496  pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
168497  }
168498 
168499  if( pUp ){
168500  char *zWhere = rbuObjIterGetWhere(p, pIter);
168501  char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
168502  char *zUpdate = 0;
168503 
168504  pUp->zMask = (char*)&pUp[1];
168505  memcpy(pUp->zMask, zMask, pIter->nTblCol);
168506  pUp->pNext = pIter->pRbuUpdate;
168507  pIter->pRbuUpdate = pUp;
168508 
168509  if( zSet ){
168510  const char *zPrefix = "";
168511 
168512  if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
168513  zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
168514  zPrefix, pIter->zTbl, zSet, zWhere
168515  );
168516  p->rc = prepareFreeAndCollectError(
168517  p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
168518  );
168519  *ppStmt = pUp->pUpdate;
168520  }
168521  sqlite3_free(zWhere);
168522  sqlite3_free(zSet);
168523  }
168524 
168525  return p->rc;
168526 }
168527 
168528 static sqlite3 *rbuOpenDbhandle(
168529  sqlite3rbu *p,
168530  const char *zName,
168531  int bUseVfs
168532 ){
168533  sqlite3 *db = 0;
168534  if( p->rc==SQLITE_OK ){
168535  const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
168536  p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
168537  if( p->rc ){
168538  p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
168539  sqlite3_close(db);
168540  db = 0;
168541  }
168542  }
168543  return db;
168544 }
168545 
168546 /*
168547 ** Free an RbuState object allocated by rbuLoadState().
168548 */
168549 static void rbuFreeState(RbuState *p){
168550  if( p ){
168551  sqlite3_free(p->zTbl);
168552  sqlite3_free(p->zIdx);
168553  sqlite3_free(p);
168554  }
168555 }
168556 
168557 /*
168558 ** Allocate an RbuState object and load the contents of the rbu_state
168559 ** table into it. Return a pointer to the new object. It is the
168560 ** responsibility of the caller to eventually free the object using
168561 ** sqlite3_free().
168562 **
168563 ** If an error occurs, leave an error code and message in the rbu handle
168564 ** and return NULL.
168565 */
168566 static RbuState *rbuLoadState(sqlite3rbu *p){
168567  RbuState *pRet = 0;
168568  sqlite3_stmt *pStmt = 0;
168569  int rc;
168570  int rc2;
168571 
168572  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
168573  if( pRet==0 ) return 0;
168574 
168575  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
168576  sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
168577  );
168578  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
168579  switch( sqlite3_column_int(pStmt, 0) ){
168580  case RBU_STATE_STAGE:
168581  pRet->eStage = sqlite3_column_int(pStmt, 1);
168582  if( pRet->eStage!=RBU_STAGE_OAL
168583  && pRet->eStage!=RBU_STAGE_MOVE
168584  && pRet->eStage!=RBU_STAGE_CKPT
168585  ){
168586  p->rc = SQLITE_CORRUPT;
168587  }
168588  break;
168589 
168590  case RBU_STATE_TBL:
168591  pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
168592  break;
168593 
168594  case RBU_STATE_IDX:
168595  pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
168596  break;
168597 
168598  case RBU_STATE_ROW:
168599  pRet->nRow = sqlite3_column_int(pStmt, 1);
168600  break;
168601 
168602  case RBU_STATE_PROGRESS:
168603  pRet->nProgress = sqlite3_column_int64(pStmt, 1);
168604  break;
168605 
168606  case RBU_STATE_CKPT:
168607  pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
168608  break;
168609 
168610  case RBU_STATE_COOKIE:
168611  pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
168612  break;
168613 
168614  case RBU_STATE_OALSZ:
168615  pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
168616  break;
168617 
168618  case RBU_STATE_PHASEONESTEP:
168619  pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
168620  break;
168621 
168622  default:
168623  rc = SQLITE_CORRUPT;
168624  break;
168625  }
168626  }
168627  rc2 = sqlite3_finalize(pStmt);
168628  if( rc==SQLITE_OK ) rc = rc2;
168629 
168630  p->rc = rc;
168631  return pRet;
168632 }
168633 
168634 
168635 /*
168636 ** Open the database handle and attach the RBU database as "rbu". If an
168637 ** error occurs, leave an error code and message in the RBU handle.
168638 */
168639 static void rbuOpenDatabase(sqlite3rbu *p){
168640  assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
168641  assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
168642 
168643  /* Open the RBU database */
168644  p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
168645 
168646  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
168647  sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
168648  if( p->zState==0 ){
168649  const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
168650  p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
168651  }
168652  }
168653 
168654  /* If using separate RBU and state databases, attach the state database to
168655  ** the RBU db handle now. */
168656  if( p->zState ){
168657  rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
168658  memcpy(p->zStateDb, "stat", 4);
168659  }else{
168660  memcpy(p->zStateDb, "main", 4);
168661  }
168662 
168663 #if 0
168664  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
168665  p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
168666  }
168667 #endif
168668 
168669  /* If it has not already been created, create the rbu_state table */
168670  rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
168671 
168672 #if 0
168673  if( rbuIsVacuum(p) ){
168674  if( p->rc==SQLITE_OK ){
168675  int rc2;
168676  int bOk = 0;
168677  sqlite3_stmt *pCnt = 0;
168678  p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
168679  "SELECT count(*) FROM stat.sqlite_master"
168680  );
168681  if( p->rc==SQLITE_OK
168682  && sqlite3_step(pCnt)==SQLITE_ROW
168683  && 1==sqlite3_column_int(pCnt, 0)
168684  ){
168685  bOk = 1;
168686  }
168687  rc2 = sqlite3_finalize(pCnt);
168688  if( p->rc==SQLITE_OK ) p->rc = rc2;
168689 
168690  if( p->rc==SQLITE_OK && bOk==0 ){
168691  p->rc = SQLITE_ERROR;
168692  p->zErrmsg = sqlite3_mprintf("invalid state database");
168693  }
168694 
168695  if( p->rc==SQLITE_OK ){
168696  p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
168697  }
168698  }
168699  }
168700 #endif
168701 
168702  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
168703  int bOpen = 0;
168704  int rc;
168705  p->nRbu = 0;
168706  p->pRbuFd = 0;
168707  rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
168708  if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
168709  if( p->eStage>=RBU_STAGE_MOVE ){
168710  bOpen = 1;
168711  }else{
168712  RbuState *pState = rbuLoadState(p);
168713  if( pState ){
168714  bOpen = (pState->eStage>RBU_STAGE_MOVE);
168715  rbuFreeState(pState);
168716  }
168717  }
168718  if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
168719  }
168720 
168721  p->eStage = 0;
168722  if( p->rc==SQLITE_OK && p->dbMain==0 ){
168723  if( !rbuIsVacuum(p) ){
168724  p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
168725  }else if( p->pRbuFd->pWalFd ){
168726  p->rc = SQLITE_ERROR;
168727  p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
168728  }else{
168729  char *zTarget;
168730  char *zExtra = 0;
168731  if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
168732  zExtra = &p->zRbu[5];
168733  while( *zExtra ){
168734  if( *zExtra++=='?' ) break;
168735  }
168736  if( *zExtra=='\0' ) zExtra = 0;
168737  }
168738 
168739  zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
168740  sqlite3_db_filename(p->dbRbu, "main"),
168741  (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
168742  );
168743 
168744  if( zTarget==0 ){
168745  p->rc = SQLITE_NOMEM;
168746  return;
168747  }
168748  p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
168749  sqlite3_free(zTarget);
168750  }
168751  }
168752 
168753  if( p->rc==SQLITE_OK ){
168754  p->rc = sqlite3_create_function(p->dbMain,
168755  "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
168756  );
168757  }
168758 
168759  if( p->rc==SQLITE_OK ){
168760  p->rc = sqlite3_create_function(p->dbMain,
168761  "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
168762  );
168763  }
168764 
168765  if( p->rc==SQLITE_OK ){
168766  p->rc = sqlite3_create_function(p->dbRbu,
168767  "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
168768  );
168769  }
168770 
168771  if( p->rc==SQLITE_OK ){
168772  p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
168773  }
168774  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
168775 
168776  /* Mark the database file just opened as an RBU target database. If
168777  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
168778  ** This is an error. */
168779  if( p->rc==SQLITE_OK ){
168780  p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
168781  }
168782 
168783  if( p->rc==SQLITE_NOTFOUND ){
168784  p->rc = SQLITE_ERROR;
168785  p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
168786  }
168787 }
168788 
168789 /*
168790 ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
168791 ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
168792 **
168793 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
168794 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
168795 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
168796 ** three characters, then shorten the suffix on z[] to be the last three
168797 ** characters of the original suffix.
168798 **
168799 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
168800 ** do the suffix shortening regardless of URI parameter.
168801 **
168802 ** Examples:
168803 **
168804 ** test.db-journal => test.nal
168805 ** test.db-wal => test.wal
168806 ** test.db-shm => test.shm
168807 ** test.db-mj7f3319fa => test.9fa
168808 */
168809 static void rbuFileSuffix3(const char *zBase, char *z){
168810 #ifdef SQLITE_ENABLE_8_3_NAMES
168811 #if SQLITE_ENABLE_8_3_NAMES<2
168812  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
168813 #endif
168814  {
168815  int i, sz;
168816  sz = (int)strlen(z)&0xffffff;
168817  for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
168818  if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
168819  }
168820 #endif
168821 }
168822 
168823 /*
168824 ** Return the current wal-index header checksum for the target database
168825 ** as a 64-bit integer.
168826 **
168827 ** The checksum is store in the first page of xShmMap memory as an 8-byte
168828 ** blob starting at byte offset 40.
168829 */
168830 static i64 rbuShmChecksum(sqlite3rbu *p){
168831  i64 iRet = 0;
168832  if( p->rc==SQLITE_OK ){
168833  sqlite3_file *pDb = p->pTargetFd->pReal;
168834  u32 volatile *ptr;
168835  p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
168836  if( p->rc==SQLITE_OK ){
168837  iRet = ((i64)ptr[10] << 32) + ptr[11];
168838  }
168839  }
168840  return iRet;
168841 }
168842 
168843 /*
168844 ** This function is called as part of initializing or reinitializing an
168845 ** incremental checkpoint.
168846 **
168847 ** It populates the sqlite3rbu.aFrame[] array with the set of
168848 ** (wal frame -> db page) copy operations required to checkpoint the
168849 ** current wal file, and obtains the set of shm locks required to safely
168850 ** perform the copy operations directly on the file-system.
168851 **
168852 ** If argument pState is not NULL, then the incremental checkpoint is
168853 ** being resumed. In this case, if the checksum of the wal-index-header
168854 ** following recovery is not the same as the checksum saved in the RbuState
168855 ** object, then the rbu handle is set to DONE state. This occurs if some
168856 ** other client appends a transaction to the wal file in the middle of
168857 ** an incremental checkpoint.
168858 */
168859 static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
168860 
168861  /* If pState is NULL, then the wal file may not have been opened and
168862  ** recovered. Running a read-statement here to ensure that doing so
168863  ** does not interfere with the "capture" process below. */
168864  if( pState==0 ){
168865  p->eStage = 0;
168866  if( p->rc==SQLITE_OK ){
168867  p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
168868  }
168869  }
168870 
168871  /* Assuming no error has occurred, run a "restart" checkpoint with the
168872  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
168873  ** special behaviour in the rbu VFS:
168874  **
168875  ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
168876  ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
168877  ** proceed with running a passive checkpoint instead of failing).
168878  **
168879  ** * Attempts to read from the *-wal file or write to the database file
168880  ** do not perform any IO. Instead, the frame/page combinations that
168881  ** would be read/written are recorded in the sqlite3rbu.aFrame[]
168882  ** array.
168883  **
168884  ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
168885  ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
168886  ** no-ops. These locks will not be released until the connection
168887  ** is closed.
168888  **
168889  ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
168890  ** error.
168891  **
168892  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
168893  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
168894  ** array populated with a set of (frame -> page) mappings. Because the
168895  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
168896  ** data from the wal file into the database file according to the
168897  ** contents of aFrame[].
168898  */
168899  if( p->rc==SQLITE_OK ){
168900  int rc2;
168901  p->eStage = RBU_STAGE_CAPTURE;
168902  rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
168903  if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
168904  }
168905 
168906  if( p->rc==SQLITE_OK ){
168907  p->eStage = RBU_STAGE_CKPT;
168908  p->nStep = (pState ? pState->nRow : 0);
168909  p->aBuf = rbuMalloc(p, p->pgsz);
168910  p->iWalCksum = rbuShmChecksum(p);
168911  }
168912 
168913  if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
168914  p->rc = SQLITE_DONE;
168915  p->eStage = RBU_STAGE_DONE;
168916  }
168917 }
168918 
168919 /*
168920 ** Called when iAmt bytes are read from offset iOff of the wal file while
168921 ** the rbu object is in capture mode. Record the frame number of the frame
168922 ** being read in the aFrame[] array.
168923 */
168924 static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
168925  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
168926  u32 iFrame;
168927 
168928  if( pRbu->mLock!=mReq ){
168929  pRbu->rc = SQLITE_BUSY;
168930  return SQLITE_INTERNAL;
168931  }
168932 
168933  pRbu->pgsz = iAmt;
168934  if( pRbu->nFrame==pRbu->nFrameAlloc ){
168935  int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
168936  RbuFrame *aNew;
168937  aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
168938  if( aNew==0 ) return SQLITE_NOMEM;
168939  pRbu->aFrame = aNew;
168940  pRbu->nFrameAlloc = nNew;
168941  }
168942 
168943  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
168944  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
168945  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
168946  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
168947  pRbu->nFrame++;
168948  return SQLITE_OK;
168949 }
168950 
168951 /*
168952 ** Called when a page of data is written to offset iOff of the database
168953 ** file while the rbu handle is in capture mode. Record the page number
168954 ** of the page being written in the aFrame[] array.
168955 */
168956 static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
168957  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
168958  return SQLITE_OK;
168959 }
168960 
168961 /*
168962 ** This is called as part of an incremental checkpoint operation. Copy
168963 ** a single frame of data from the wal file into the database file, as
168964 ** indicated by the RbuFrame object.
168965 */
168966 static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
168967  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
168968  sqlite3_file *pDb = p->pTargetFd->pReal;
168969  i64 iOff;
168970 
168971  assert( p->rc==SQLITE_OK );
168972  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
168973  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
168974  if( p->rc ) return;
168975 
168976  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
168977  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
168978 }
168979 
168980 
168981 /*
168982 ** Take an EXCLUSIVE lock on the database file.
168983 */
168984 static void rbuLockDatabase(sqlite3rbu *p){
168985  sqlite3_file *pReal = p->pTargetFd->pReal;
168986  assert( p->rc==SQLITE_OK );
168987  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
168988  if( p->rc==SQLITE_OK ){
168989  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
168990  }
168991 }
168992 
168993 #if defined(_WIN32_WCE)
168994 static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
168995  int nChar;
168996  LPWSTR zWideFilename;
168997 
168998  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
168999  if( nChar==0 ){
169000  return 0;
169001  }
169002  zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
169003  if( zWideFilename==0 ){
169004  return 0;
169005  }
169006  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
169007  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
169008  nChar);
169009  if( nChar==0 ){
169010  sqlite3_free(zWideFilename);
169011  zWideFilename = 0;
169012  }
169013  return zWideFilename;
169014 }
169015 #endif
169016 
169017 /*
169018 ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
169019 ** on the database file. This proc moves the *-oal file to the *-wal path,
169020 ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
169021 ** If an error occurs, leave an error code and error message in the rbu
169022 ** handle.
169023 */
169024 static void rbuMoveOalFile(sqlite3rbu *p){
169025  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
169026  const char *zMove = zBase;
169027  char *zOal;
169028  char *zWal;
169029 
169030  if( rbuIsVacuum(p) ){
169031  zMove = sqlite3_db_filename(p->dbRbu, "main");
169032  }
169033  zOal = sqlite3_mprintf("%s-oal", zMove);
169034  zWal = sqlite3_mprintf("%s-wal", zMove);
169035 
169036  assert( p->eStage==RBU_STAGE_MOVE );
169037  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
169038  if( zWal==0 || zOal==0 ){
169039  p->rc = SQLITE_NOMEM;
169040  }else{
169041  /* Move the *-oal file to *-wal. At this point connection p->db is
169042  ** holding a SHARED lock on the target database file (because it is
169043  ** in WAL mode). So no other connection may be writing the db.
169044  **
169045  ** In order to ensure that there are no database readers, an EXCLUSIVE
169046  ** lock is obtained here before the *-oal is moved to *-wal.
169047  */
169048  rbuLockDatabase(p);
169049  if( p->rc==SQLITE_OK ){
169050  rbuFileSuffix3(zBase, zWal);
169051  rbuFileSuffix3(zBase, zOal);
169052 
169053  /* Re-open the databases. */
169054  rbuObjIterFinalize(&p->objiter);
169055  sqlite3_close(p->dbRbu);
169056  sqlite3_close(p->dbMain);
169057  p->dbMain = 0;
169058  p->dbRbu = 0;
169059 
169060 #if defined(_WIN32_WCE)
169061  {
169062  LPWSTR zWideOal;
169063  LPWSTR zWideWal;
169064 
169065  zWideOal = rbuWinUtf8ToUnicode(zOal);
169066  if( zWideOal ){
169067  zWideWal = rbuWinUtf8ToUnicode(zWal);
169068  if( zWideWal ){
169069  if( MoveFileW(zWideOal, zWideWal) ){
169070  p->rc = SQLITE_OK;
169071  }else{
169072  p->rc = SQLITE_IOERR;
169073  }
169074  sqlite3_free(zWideWal);
169075  }else{
169076  p->rc = SQLITE_IOERR_NOMEM;
169077  }
169078  sqlite3_free(zWideOal);
169079  }else{
169080  p->rc = SQLITE_IOERR_NOMEM;
169081  }
169082  }
169083 #else
169084  p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
169085 #endif
169086 
169087  if( p->rc==SQLITE_OK ){
169088  rbuOpenDatabase(p);
169089  rbuSetupCheckpoint(p, 0);
169090  }
169091  }
169092  }
169093 
169094  sqlite3_free(zWal);
169095  sqlite3_free(zOal);
169096 }
169097 
169098 /*
169099 ** The SELECT statement iterating through the keys for the current object
169100 ** (p->objiter.pSelect) currently points to a valid row. This function
169101 ** determines the type of operation requested by this row and returns
169102 ** one of the following values to indicate the result:
169103 **
169104 ** * RBU_INSERT
169105 ** * RBU_DELETE
169106 ** * RBU_IDX_DELETE
169107 ** * RBU_UPDATE
169108 **
169109 ** If RBU_UPDATE is returned, then output variable *pzMask is set to
169110 ** point to the text value indicating the columns to update.
169111 **
169112 ** If the rbu_control field contains an invalid value, an error code and
169113 ** message are left in the RBU handle and zero returned.
169114 */
169115 static int rbuStepType(sqlite3rbu *p, const char **pzMask){
169116  int iCol = p->objiter.nCol; /* Index of rbu_control column */
169117  int res = 0; /* Return value */
169118 
169119  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
169120  case SQLITE_INTEGER: {
169121  int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
169122  switch( iVal ){
169123  case 0: res = RBU_INSERT; break;
169124  case 1: res = RBU_DELETE; break;
169125  case 2: res = RBU_REPLACE; break;
169126  case 3: res = RBU_IDX_DELETE; break;
169127  case 4: res = RBU_IDX_INSERT; break;
169128  }
169129  break;
169130  }
169131 
169132  case SQLITE_TEXT: {
169133  const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
169134  if( z==0 ){
169135  p->rc = SQLITE_NOMEM;
169136  }else{
169137  *pzMask = (const char*)z;
169138  }
169139  res = RBU_UPDATE;
169140 
169141  break;
169142  }
169143 
169144  default:
169145  break;
169146  }
169147 
169148  if( res==0 ){
169149  rbuBadControlError(p);
169150  }
169151  return res;
169152 }
169153 
169154 #ifdef SQLITE_DEBUG
169155 /*
169156 ** Assert that column iCol of statement pStmt is named zName.
169157 */
169158 static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
169159  const char *zCol = sqlite3_column_name(pStmt, iCol);
169160  assert( 0==sqlite3_stricmp(zName, zCol) );
169161 }
169162 #else
169163 # define assertColumnName(x,y,z)
169164 #endif
169165 
169166 /*
169167 ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
169168 ** RBU_IDX_DELETE. This function performs the work of a single
169169 ** sqlite3rbu_step() call for the type of operation specified by eType.
169170 */
169171 static void rbuStepOneOp(sqlite3rbu *p, int eType){
169172  RbuObjIter *pIter = &p->objiter;
169173  sqlite3_value *pVal;
169174  sqlite3_stmt *pWriter;
169175  int i;
169176 
169177  assert( p->rc==SQLITE_OK );
169178  assert( eType!=RBU_DELETE || pIter->zIdx==0 );
169179  assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
169180  || eType==RBU_INSERT || eType==RBU_IDX_INSERT
169181  );
169182 
169183  /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
169184  ** statement below does actually delete a row, nPhaseOneStep will be
169185  ** incremented by the same amount when SQL function rbu_tmp_insert()
169186  ** is invoked by the trigger. */
169187  if( eType==RBU_DELETE ){
169188  p->nPhaseOneStep -= p->objiter.nIndex;
169189  }
169190 
169191  if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
169192  pWriter = pIter->pDelete;
169193  }else{
169194  pWriter = pIter->pInsert;
169195  }
169196 
169197  for(i=0; i<pIter->nCol; i++){
169198  /* If this is an INSERT into a table b-tree and the table has an
169199  ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
169200  ** to write a NULL into the IPK column. That is not permitted. */
169201  if( eType==RBU_INSERT
169202  && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
169203  && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
169204  ){
169205  p->rc = SQLITE_MISMATCH;
169206  p->zErrmsg = sqlite3_mprintf("datatype mismatch");
169207  return;
169208  }
169209 
169210  if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
169211  continue;
169212  }
169213 
169214  pVal = sqlite3_column_value(pIter->pSelect, i);
169215  p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
169216  if( p->rc ) return;
169217  }
169218  if( pIter->zIdx==0 ){
169219  if( pIter->eType==RBU_PK_VTAB
169220  || pIter->eType==RBU_PK_NONE
169221  || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
169222  ){
169223  /* For a virtual table, or a table with no primary key, the
169224  ** SELECT statement is:
169225  **
169226  ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
169227  **
169228  ** Hence column_value(pIter->nCol+1).
169229  */
169230  assertColumnName(pIter->pSelect, pIter->nCol+1,
169231  rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
169232  );
169233  pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
169234  p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
169235  }
169236  }
169237  if( p->rc==SQLITE_OK ){
169238  sqlite3_step(pWriter);
169239  p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
169240  }
169241 }
169242 
169243 /*
169244 ** This function does the work for an sqlite3rbu_step() call.
169245 **
169246 ** The object-iterator (p->objiter) currently points to a valid object,
169247 ** and the input cursor (p->objiter.pSelect) currently points to a valid
169248 ** input row. Perform whatever processing is required and return.
169249 **
169250 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
169251 ** and message is left in the RBU handle and a copy of the error code
169252 ** returned.
169253 */
169254 static int rbuStep(sqlite3rbu *p){
169255  RbuObjIter *pIter = &p->objiter;
169256  const char *zMask = 0;
169257  int eType = rbuStepType(p, &zMask);
169258 
169259  if( eType ){
169260  assert( eType==RBU_INSERT || eType==RBU_DELETE
169261  || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
169262  || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
169263  );
169264  assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
169265 
169266  if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
169267  rbuBadControlError(p);
169268  }
169269  else if( eType==RBU_REPLACE ){
169270  if( pIter->zIdx==0 ){
169271  p->nPhaseOneStep += p->objiter.nIndex;
169272  rbuStepOneOp(p, RBU_DELETE);
169273  }
169274  if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
169275  }
169276  else if( eType!=RBU_UPDATE ){
169277  rbuStepOneOp(p, eType);
169278  }
169279  else{
169280  sqlite3_value *pVal;
169281  sqlite3_stmt *pUpdate = 0;
169282  assert( eType==RBU_UPDATE );
169283  p->nPhaseOneStep -= p->objiter.nIndex;
169284  rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
169285  if( pUpdate ){
169286  int i;
169287  for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
169288  char c = zMask[pIter->aiSrcOrder[i]];
169289  pVal = sqlite3_column_value(pIter->pSelect, i);
169290  if( pIter->abTblPk[i] || c!='.' ){
169291  p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
169292  }
169293  }
169294  if( p->rc==SQLITE_OK
169295  && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
169296  ){
169297  /* Bind the rbu_rowid value to column _rowid_ */
169298  assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
169299  pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
169300  p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
169301  }
169302  if( p->rc==SQLITE_OK ){
169303  sqlite3_step(pUpdate);
169304  p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
169305  }
169306  }
169307  }
169308  }
169309  return p->rc;
169310 }
169311 
169312 /*
169313 ** Increment the schema cookie of the main database opened by p->dbMain.
169314 **
169315 ** Or, if this is an RBU vacuum, set the schema cookie of the main db
169316 ** opened by p->dbMain to one more than the schema cookie of the main
169317 ** db opened by p->dbRbu.
169318 */
169319 static void rbuIncrSchemaCookie(sqlite3rbu *p){
169320  if( p->rc==SQLITE_OK ){
169321  sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
169322  int iCookie = 1000000;
169323  sqlite3_stmt *pStmt;
169324 
169325  p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
169326  "PRAGMA schema_version"
169327  );
169328  if( p->rc==SQLITE_OK ){
169329  /* Coverage: it may be that this sqlite3_step() cannot fail. There
169330  ** is already a transaction open, so the prepared statement cannot
169331  ** throw an SQLITE_SCHEMA exception. The only database page the
169332  ** statement reads is page 1, which is guaranteed to be in the cache.
169333  ** And no memory allocations are required. */
169334  if( SQLITE_ROW==sqlite3_step(pStmt) ){
169335  iCookie = sqlite3_column_int(pStmt, 0);
169336  }
169337  rbuFinalize(p, pStmt);
169338  }
169339  if( p->rc==SQLITE_OK ){
169340  rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
169341  }
169342  }
169343 }
169344 
169345 /*
169346 ** Update the contents of the rbu_state table within the rbu database. The
169347 ** value stored in the RBU_STATE_STAGE column is eStage. All other values
169348 ** are determined by inspecting the rbu handle passed as the first argument.
169349 */
169350 static void rbuSaveState(sqlite3rbu *p, int eStage){
169351  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
169352  sqlite3_stmt *pInsert = 0;
169353  rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
169354  int rc;
169355 
169356  assert( p->zErrmsg==0 );
169357  rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
169358  sqlite3_mprintf(
169359  "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
169360  "(%d, %d), "
169361  "(%d, %Q), "
169362  "(%d, %Q), "
169363  "(%d, %d), "
169364  "(%d, %d), "
169365  "(%d, %lld), "
169366  "(%d, %lld), "
169367  "(%d, %lld), "
169368  "(%d, %lld) ",
169369  p->zStateDb,
169370  RBU_STATE_STAGE, eStage,
169371  RBU_STATE_TBL, p->objiter.zTbl,
169372  RBU_STATE_IDX, p->objiter.zIdx,
169373  RBU_STATE_ROW, p->nStep,
169374  RBU_STATE_PROGRESS, p->nProgress,
169375  RBU_STATE_CKPT, p->iWalCksum,
169376  RBU_STATE_COOKIE, (i64)pFd->iCookie,
169377  RBU_STATE_OALSZ, p->iOalSz,
169378  RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
169379  )
169380  );
169381  assert( pInsert==0 || rc==SQLITE_OK );
169382 
169383  if( rc==SQLITE_OK ){
169384  sqlite3_step(pInsert);
169385  rc = sqlite3_finalize(pInsert);
169386  }
169387  if( rc!=SQLITE_OK ) p->rc = rc;
169388  }
169389 }
169390 
169391 
169392 /*
169393 ** The second argument passed to this function is the name of a PRAGMA
169394 ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
169395 ** This function executes the following on sqlite3rbu.dbRbu:
169396 **
169397 ** "PRAGMA main.$zPragma"
169398 **
169399 ** where $zPragma is the string passed as the second argument, then
169400 ** on sqlite3rbu.dbMain:
169401 **
169402 ** "PRAGMA main.$zPragma = $val"
169403 **
169404 ** where $val is the value returned by the first PRAGMA invocation.
169405 **
169406 ** In short, it copies the value of the specified PRAGMA setting from
169407 ** dbRbu to dbMain.
169408 */
169409 static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
169410  if( p->rc==SQLITE_OK ){
169411  sqlite3_stmt *pPragma = 0;
169412  p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
169413  sqlite3_mprintf("PRAGMA main.%s", zPragma)
169414  );
169415  if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
169416  p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
169417  zPragma, sqlite3_column_int(pPragma, 0)
169418  );
169419  }
169420  rbuFinalize(p, pPragma);
169421  }
169422 }
169423 
169424 /*
169425 ** The RBU handle passed as the only argument has just been opened and
169426 ** the state database is empty. If this RBU handle was opened for an
169427 ** RBU vacuum operation, create the schema in the target db.
169428 */
169429 static void rbuCreateTargetSchema(sqlite3rbu *p){
169430  sqlite3_stmt *pSql = 0;
169431  sqlite3_stmt *pInsert = 0;
169432 
169433  assert( rbuIsVacuum(p) );
169434  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
169435  if( p->rc==SQLITE_OK ){
169436  p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
169437  "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
169438  " AND name!='sqlite_sequence' "
169439  " ORDER BY type DESC"
169440  );
169441  }
169442 
169443  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
169444  const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
169445  p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
169446  }
169447  rbuFinalize(p, pSql);
169448  if( p->rc!=SQLITE_OK ) return;
169449 
169450  if( p->rc==SQLITE_OK ){
169451  p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
169452  "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
169453  );
169454  }
169455 
169456  if( p->rc==SQLITE_OK ){
169457  p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
169458  "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
169459  );
169460  }
169461 
169462  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
169463  int i;
169464  for(i=0; i<5; i++){
169465  sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
169466  }
169467  sqlite3_step(pInsert);
169468  p->rc = sqlite3_reset(pInsert);
169469  }
169470  if( p->rc==SQLITE_OK ){
169471  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
169472  }
169473 
169474  rbuFinalize(p, pSql);
169475  rbuFinalize(p, pInsert);
169476 }
169477 
169478 /*
169479 ** Step the RBU object.
169480 */
169481 SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
169482  if( p ){
169483  switch( p->eStage ){
169484  case RBU_STAGE_OAL: {
169485  RbuObjIter *pIter = &p->objiter;
169486 
169487  /* If this is an RBU vacuum operation and the state table was empty
169488  ** when this handle was opened, create the target database schema. */
169489  if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
169490  rbuCreateTargetSchema(p);
169491  rbuCopyPragma(p, "user_version");
169492  rbuCopyPragma(p, "application_id");
169493  }
169494 
169495  while( p->rc==SQLITE_OK && pIter->zTbl ){
169496 
169497  if( pIter->bCleanup ){
169498  /* Clean up the rbu_tmp_xxx table for the previous table. It
169499  ** cannot be dropped as there are currently active SQL statements.
169500  ** But the contents can be deleted. */
169501  if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
169502  rbuMPrintfExec(p, p->dbRbu,
169503  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
169504  );
169505  }
169506  }else{
169507  rbuObjIterPrepareAll(p, pIter, 0);
169508 
169509  /* Advance to the next row to process. */
169510  if( p->rc==SQLITE_OK ){
169511  int rc = sqlite3_step(pIter->pSelect);
169512  if( rc==SQLITE_ROW ){
169513  p->nProgress++;
169514  p->nStep++;
169515  return rbuStep(p);
169516  }
169517  p->rc = sqlite3_reset(pIter->pSelect);
169518  p->nStep = 0;
169519  }
169520  }
169521 
169522  rbuObjIterNext(p, pIter);
169523  }
169524 
169525  if( p->rc==SQLITE_OK ){
169526  assert( pIter->zTbl==0 );
169527  rbuSaveState(p, RBU_STAGE_MOVE);
169528  rbuIncrSchemaCookie(p);
169529  if( p->rc==SQLITE_OK ){
169530  p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
169531  }
169532  if( p->rc==SQLITE_OK ){
169533  p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
169534  }
169535  p->eStage = RBU_STAGE_MOVE;
169536  }
169537  break;
169538  }
169539 
169540  case RBU_STAGE_MOVE: {
169541  if( p->rc==SQLITE_OK ){
169542  rbuMoveOalFile(p);
169543  p->nProgress++;
169544  }
169545  break;
169546  }
169547 
169548  case RBU_STAGE_CKPT: {
169549  if( p->rc==SQLITE_OK ){
169550  if( p->nStep>=p->nFrame ){
169551  sqlite3_file *pDb = p->pTargetFd->pReal;
169552 
169553  /* Sync the db file */
169554  p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
169555 
169556  /* Update nBackfill */
169557  if( p->rc==SQLITE_OK ){
169558  void volatile *ptr;
169559  p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
169560  if( p->rc==SQLITE_OK ){
169561  ((u32 volatile*)ptr)[24] = p->iMaxFrame;
169562  }
169563  }
169564 
169565  if( p->rc==SQLITE_OK ){
169566  p->eStage = RBU_STAGE_DONE;
169567  p->rc = SQLITE_DONE;
169568  }
169569  }else{
169570  RbuFrame *pFrame = &p->aFrame[p->nStep];
169571  rbuCheckpointFrame(p, pFrame);
169572  p->nStep++;
169573  }
169574  p->nProgress++;
169575  }
169576  break;
169577  }
169578 
169579  default:
169580  break;
169581  }
169582  return p->rc;
169583  }else{
169584  return SQLITE_NOMEM;
169585  }
169586 }
169587 
169588 /*
169589 ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
169590 ** otherwise. Either or both argument may be NULL. Two NULL values are
169591 ** considered equal, and NULL is considered distinct from all other values.
169592 */
169593 static int rbuStrCompare(const char *z1, const char *z2){
169594  if( z1==0 && z2==0 ) return 0;
169595  if( z1==0 || z2==0 ) return 1;
169596  return (sqlite3_stricmp(z1, z2)!=0);
169597 }
169598 
169599 /*
169600 ** This function is called as part of sqlite3rbu_open() when initializing
169601 ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
169602 ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
169603 ** things so that the next call to sqlite3rbu_step() continues on from
169604 ** where the previous rbu handle left off.
169605 **
169606 ** If an error occurs, an error code and error message are left in the
169607 ** rbu handle passed as the first argument.
169608 */
169609 static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
169610  assert( p->rc==SQLITE_OK );
169611  if( pState->zTbl ){
169612  RbuObjIter *pIter = &p->objiter;
169613  int rc = SQLITE_OK;
169614 
169615  while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
169616  || rbuStrCompare(pIter->zIdx, pState->zIdx)
169617  || rbuStrCompare(pIter->zTbl, pState->zTbl)
169618  )){
169619  rc = rbuObjIterNext(p, pIter);
169620  }
169621 
169622  if( rc==SQLITE_OK && !pIter->zTbl ){
169623  rc = SQLITE_ERROR;
169624  p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
169625  }
169626 
169627  if( rc==SQLITE_OK ){
169628  p->nStep = pState->nRow;
169629  rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
169630  }
169631 
169632  p->rc = rc;
169633  }
169634 }
169635 
169636 /*
169637 ** If there is a "*-oal" file in the file-system corresponding to the
169638 ** target database in the file-system, delete it. If an error occurs,
169639 ** leave an error code and error message in the rbu handle.
169640 */
169641 static void rbuDeleteOalFile(sqlite3rbu *p){
169642  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
169643  if( zOal ){
169644  sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
169645  assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
169646  pVfs->xDelete(pVfs, zOal, 0);
169647  sqlite3_free(zOal);
169648  }
169649 }
169650 
169651 /*
169652 ** Allocate a private rbu VFS for the rbu handle passed as the only
169653 ** argument. This VFS will be used unless the call to sqlite3rbu_open()
169654 ** specified a URI with a vfs=? option in place of a target database
169655 ** file name.
169656 */
169657 static void rbuCreateVfs(sqlite3rbu *p){
169658  int rnd;
169659  char zRnd[64];
169660 
169661  assert( p->rc==SQLITE_OK );
169662  sqlite3_randomness(sizeof(int), (void*)&rnd);
169663  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
169664  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
169665  if( p->rc==SQLITE_OK ){
169666  sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
169667  assert( pVfs );
169668  p->zVfsName = pVfs->zName;
169669  }
169670 }
169671 
169672 /*
169673 ** Destroy the private VFS created for the rbu handle passed as the only
169674 ** argument by an earlier call to rbuCreateVfs().
169675 */
169676 static void rbuDeleteVfs(sqlite3rbu *p){
169677  if( p->zVfsName ){
169678  sqlite3rbu_destroy_vfs(p->zVfsName);
169679  p->zVfsName = 0;
169680  }
169681 }
169682 
169683 /*
169684 ** This user-defined SQL function is invoked with a single argument - the
169685 ** name of a table expected to appear in the target database. It returns
169686 ** the number of auxilliary indexes on the table.
169687 */
169688 static void rbuIndexCntFunc(
169689  sqlite3_context *pCtx,
169690  int nVal,
169691  sqlite3_value **apVal
169692 ){
169693  sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
169694  sqlite3_stmt *pStmt = 0;
169695  char *zErrmsg = 0;
169696  int rc;
169697 
169698  assert( nVal==1 );
169699 
169700  rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
169701  sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
169702  "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
169703  );
169704  if( rc!=SQLITE_OK ){
169705  sqlite3_result_error(pCtx, zErrmsg, -1);
169706  }else{
169707  int nIndex = 0;
169708  if( SQLITE_ROW==sqlite3_step(pStmt) ){
169709  nIndex = sqlite3_column_int(pStmt, 0);
169710  }
169711  rc = sqlite3_finalize(pStmt);
169712  if( rc==SQLITE_OK ){
169713  sqlite3_result_int(pCtx, nIndex);
169714  }else{
169715  sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
169716  }
169717  }
169718 
169719  sqlite3_free(zErrmsg);
169720 }
169721 
169722 /*
169723 ** If the RBU database contains the rbu_count table, use it to initialize
169724 ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
169725 ** is assumed to contain the same columns as:
169726 **
169727 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
169728 **
169729 ** There should be one row in the table for each data_xxx table in the
169730 ** database. The 'tbl' column should contain the name of a data_xxx table,
169731 ** and the cnt column the number of rows it contains.
169732 **
169733 ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
169734 ** for all rows in the rbu_count table, where nIndex is the number of
169735 ** indexes on the corresponding target database table.
169736 */
169737 static void rbuInitPhaseOneSteps(sqlite3rbu *p){
169738  if( p->rc==SQLITE_OK ){
169739  sqlite3_stmt *pStmt = 0;
169740  int bExists = 0; /* True if rbu_count exists */
169741 
169742  p->nPhaseOneStep = -1;
169743 
169744  p->rc = sqlite3_create_function(p->dbRbu,
169745  "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
169746  );
169747 
169748  /* Check for the rbu_count table. If it does not exist, or if an error
169749  ** occurs, nPhaseOneStep will be left set to -1. */
169750  if( p->rc==SQLITE_OK ){
169751  p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
169752  "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
169753  );
169754  }
169755  if( p->rc==SQLITE_OK ){
169756  if( SQLITE_ROW==sqlite3_step(pStmt) ){
169757  bExists = 1;
169758  }
169759  p->rc = sqlite3_finalize(pStmt);
169760  }
169761 
169762  if( p->rc==SQLITE_OK && bExists ){
169763  p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
169764  "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
169765  "FROM rbu_count"
169766  );
169767  if( p->rc==SQLITE_OK ){
169768  if( SQLITE_ROW==sqlite3_step(pStmt) ){
169769  p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
169770  }
169771  p->rc = sqlite3_finalize(pStmt);
169772  }
169773  }
169774  }
169775 }
169776 
169777 
169778 static sqlite3rbu *openRbuHandle(
169779  const char *zTarget,
169780  const char *zRbu,
169781  const char *zState
169782 ){
169783  sqlite3rbu *p;
169784  size_t nTarget = zTarget ? strlen(zTarget) : 0;
169785  size_t nRbu = strlen(zRbu);
169786  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
169787 
169788  p = (sqlite3rbu*)sqlite3_malloc64(nByte);
169789  if( p ){
169790  RbuState *pState = 0;
169791 
169792  /* Create the custom VFS. */
169793  memset(p, 0, sizeof(sqlite3rbu));
169794  rbuCreateVfs(p);
169795 
169796  /* Open the target, RBU and state databases */
169797  if( p->rc==SQLITE_OK ){
169798  char *pCsr = (char*)&p[1];
169799  if( zTarget ){
169800  p->zTarget = pCsr;
169801  memcpy(p->zTarget, zTarget, nTarget+1);
169802  pCsr += nTarget+1;
169803  }
169804  p->zRbu = pCsr;
169805  memcpy(p->zRbu, zRbu, nRbu+1);
169806  pCsr += nRbu+1;
169807  if( zState ){
169808  p->zState = rbuMPrintf(p, "%s", zState);
169809  }
169810  rbuOpenDatabase(p);
169811  }
169812 
169813  if( p->rc==SQLITE_OK ){
169814  pState = rbuLoadState(p);
169815  assert( pState || p->rc!=SQLITE_OK );
169816  if( p->rc==SQLITE_OK ){
169817 
169818  if( pState->eStage==0 ){
169819  rbuDeleteOalFile(p);
169820  rbuInitPhaseOneSteps(p);
169821  p->eStage = RBU_STAGE_OAL;
169822  }else{
169823  p->eStage = pState->eStage;
169824  p->nPhaseOneStep = pState->nPhaseOneStep;
169825  }
169826  p->nProgress = pState->nProgress;
169827  p->iOalSz = pState->iOalSz;
169828  }
169829  }
169830  assert( p->rc!=SQLITE_OK || p->eStage!=0 );
169831 
169832  if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
169833  if( p->eStage==RBU_STAGE_OAL ){
169834  p->rc = SQLITE_ERROR;
169835  p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
169836  }else if( p->eStage==RBU_STAGE_MOVE ){
169837  p->eStage = RBU_STAGE_CKPT;
169838  p->nStep = 0;
169839  }
169840  }
169841 
169842  if( p->rc==SQLITE_OK
169843  && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
169844  && pState->eStage!=0
169845  ){
169846  rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
169847  if( pFd->iCookie!=pState->iCookie ){
169848  /* At this point (pTargetFd->iCookie) contains the value of the
169849  ** change-counter cookie (the thing that gets incremented when a
169850  ** transaction is committed in rollback mode) currently stored on
169851  ** page 1 of the database file. */
169852  p->rc = SQLITE_BUSY;
169853  p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
169854  (rbuIsVacuum(p) ? "vacuum" : "update")
169855  );
169856  }
169857  }
169858 
169859  if( p->rc==SQLITE_OK ){
169860  if( p->eStage==RBU_STAGE_OAL ){
169861  sqlite3 *db = p->dbMain;
169862  p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
169863 
169864  /* Point the object iterator at the first object */
169865  if( p->rc==SQLITE_OK ){
169866  p->rc = rbuObjIterFirst(p, &p->objiter);
169867  }
169868 
169869  /* If the RBU database contains no data_xxx tables, declare the RBU
169870  ** update finished. */
169871  if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
169872  p->rc = SQLITE_DONE;
169873  p->eStage = RBU_STAGE_DONE;
169874  }else{
169875  if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
169876  rbuCopyPragma(p, "page_size");
169877  rbuCopyPragma(p, "auto_vacuum");
169878  }
169879 
169880  /* Open transactions both databases. The *-oal file is opened or
169881  ** created at this point. */
169882  if( p->rc==SQLITE_OK ){
169883  p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
169884  }
169885 
169886  /* Check if the main database is a zipvfs db. If it is, set the upper
169887  ** level pager to use "journal_mode=off". This prevents it from
169888  ** generating a large journal using a temp file. */
169889  if( p->rc==SQLITE_OK ){
169890  int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
169891  if( frc==SQLITE_OK ){
169892  p->rc = sqlite3_exec(
169893  db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
169894  }
169895  }
169896 
169897  if( p->rc==SQLITE_OK ){
169898  rbuSetupOal(p, pState);
169899  }
169900  }
169901  }else if( p->eStage==RBU_STAGE_MOVE ){
169902  /* no-op */
169903  }else if( p->eStage==RBU_STAGE_CKPT ){
169904  rbuSetupCheckpoint(p, pState);
169905  }else if( p->eStage==RBU_STAGE_DONE ){
169906  p->rc = SQLITE_DONE;
169907  }else{
169908  p->rc = SQLITE_CORRUPT;
169909  }
169910  }
169911 
169912  rbuFreeState(pState);
169913  }
169914 
169915  return p;
169916 }
169917 
169918 /*
169919 ** Allocate and return an RBU handle with all fields zeroed except for the
169920 ** error code, which is set to SQLITE_MISUSE.
169921 */
169922 static sqlite3rbu *rbuMisuseError(void){
169923  sqlite3rbu *pRet;
169924  pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
169925  if( pRet ){
169926  memset(pRet, 0, sizeof(sqlite3rbu));
169927  pRet->rc = SQLITE_MISUSE;
169928  }
169929  return pRet;
169930 }
169931 
169932 /*
169933 ** Open and return a new RBU handle.
169934 */
169935 SQLITE_API sqlite3rbu *sqlite3rbu_open(
169936  const char *zTarget,
169937  const char *zRbu,
169938  const char *zState
169939 ){
169940  if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
169941  /* TODO: Check that zTarget and zRbu are non-NULL */
169942  return openRbuHandle(zTarget, zRbu, zState);
169943 }
169944 
169945 /*
169946 ** Open a handle to begin or resume an RBU VACUUM operation.
169947 */
169948 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
169949  const char *zTarget,
169950  const char *zState
169951 ){
169952  if( zTarget==0 ){ return rbuMisuseError(); }
169953  /* TODO: Check that both arguments are non-NULL */
169954  return openRbuHandle(0, zTarget, zState);
169955 }
169956 
169957 /*
169958 ** Return the database handle used by pRbu.
169959 */
169960 SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
169961  sqlite3 *db = 0;
169962  if( pRbu ){
169963  db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
169964  }
169965  return db;
169966 }
169967 
169968 
169969 /*
169970 ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
169971 ** then edit any error message string so as to remove all occurrences of
169972 ** the pattern "rbu_imp_[0-9]*".
169973 */
169974 static void rbuEditErrmsg(sqlite3rbu *p){
169975  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
169976  unsigned int i;
169977  size_t nErrmsg = strlen(p->zErrmsg);
169978  for(i=0; i<(nErrmsg-8); i++){
169979  if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
169980  int nDel = 8;
169981  while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
169982  memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
169983  nErrmsg -= nDel;
169984  }
169985  }
169986  }
169987 }
169988 
169989 /*
169990 ** Close the RBU handle.
169991 */
169992 SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
169993  int rc;
169994  if( p ){
169995 
169996  /* Commit the transaction to the *-oal file. */
169997  if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
169998  p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
169999  }
170000 
170001  rbuSaveState(p, p->eStage);
170002 
170003  if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
170004  p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
170005  }
170006 
170007  /* Close any open statement handles. */
170008  rbuObjIterFinalize(&p->objiter);
170009 
170010  /* If this is an RBU vacuum handle and the vacuum has either finished
170011  ** successfully or encountered an error, delete the contents of the
170012  ** state table. This causes the next call to sqlite3rbu_vacuum()
170013  ** specifying the current target and state databases to start a new
170014  ** vacuum from scratch. */
170015  if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
170016  int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
170017  if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
170018  }
170019 
170020  /* Close the open database handle and VFS object. */
170021  sqlite3_close(p->dbRbu);
170022  sqlite3_close(p->dbMain);
170023  rbuDeleteVfs(p);
170024  sqlite3_free(p->aBuf);
170025  sqlite3_free(p->aFrame);
170026 
170027  rbuEditErrmsg(p);
170028  rc = p->rc;
170029  *pzErrmsg = p->zErrmsg;
170030  sqlite3_free(p->zState);
170031  sqlite3_free(p);
170032  }else{
170033  rc = SQLITE_NOMEM;
170034  *pzErrmsg = 0;
170035  }
170036  return rc;
170037 }
170038 
170039 /*
170040 ** Return the total number of key-value operations (inserts, deletes or
170041 ** updates) that have been performed on the target database since the
170042 ** current RBU update was started.
170043 */
170044 SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
170045  return pRbu->nProgress;
170046 }
170047 
170048 /*
170049 ** Return permyriadage progress indications for the two main stages of
170050 ** an RBU update.
170051 */
170052 SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
170053  const int MAX_PROGRESS = 10000;
170054  switch( p->eStage ){
170055  case RBU_STAGE_OAL:
170056  if( p->nPhaseOneStep>0 ){
170057  *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
170058  }else{
170059  *pnOne = -1;
170060  }
170061  *pnTwo = 0;
170062  break;
170063 
170064  case RBU_STAGE_MOVE:
170065  *pnOne = MAX_PROGRESS;
170066  *pnTwo = 0;
170067  break;
170068 
170069  case RBU_STAGE_CKPT:
170070  *pnOne = MAX_PROGRESS;
170071  *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
170072  break;
170073 
170074  case RBU_STAGE_DONE:
170075  *pnOne = MAX_PROGRESS;
170076  *pnTwo = MAX_PROGRESS;
170077  break;
170078 
170079  default:
170080  assert( 0 );
170081  }
170082 }
170083 
170084 /*
170085 ** Return the current state of the RBU vacuum or update operation.
170086 */
170087 SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
170088  int aRes[] = {
170089  0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
170090  0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
170091  };
170092 
170093  assert( RBU_STAGE_OAL==1 );
170094  assert( RBU_STAGE_MOVE==2 );
170095  assert( RBU_STAGE_CKPT==4 );
170096  assert( RBU_STAGE_DONE==5 );
170097  assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
170098  assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
170099  assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
170100  assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
170101 
170102  if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
170103  return SQLITE_RBU_STATE_ERROR;
170104  }else{
170105  assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
170106  assert( p->eStage==RBU_STAGE_OAL
170107  || p->eStage==RBU_STAGE_MOVE
170108  || p->eStage==RBU_STAGE_CKPT
170109  || p->eStage==RBU_STAGE_DONE
170110  );
170111  return aRes[p->eStage];
170112  }
170113 }
170114 
170115 SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
170116  int rc = p->rc;
170117  if( rc==SQLITE_DONE ) return SQLITE_OK;
170118 
170119  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
170120  if( p->eStage==RBU_STAGE_OAL ){
170121  assert( rc!=SQLITE_DONE );
170122  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
170123  }
170124 
170125  p->rc = rc;
170126  rbuSaveState(p, p->eStage);
170127  rc = p->rc;
170128 
170129  if( p->eStage==RBU_STAGE_OAL ){
170130  assert( rc!=SQLITE_DONE );
170131  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
170132  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
170133  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
170134  }
170135 
170136  p->rc = rc;
170137  return rc;
170138 }
170139 
170140 /**************************************************************************
170141 ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
170142 ** of a standard VFS in the following ways:
170143 **
170144 ** 1. Whenever the first page of a main database file is read or
170145 ** written, the value of the change-counter cookie is stored in
170146 ** rbu_file.iCookie. Similarly, the value of the "write-version"
170147 ** database header field is stored in rbu_file.iWriteVer. This ensures
170148 ** that the values are always trustworthy within an open transaction.
170149 **
170150 ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
170151 ** member variable of the associated database file descriptor is set
170152 ** to point to the new file. A mutex protected linked list of all main
170153 ** db fds opened using a particular RBU VFS is maintained at
170154 ** rbu_vfs.pMain to facilitate this.
170155 **
170156 ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
170157 ** object can be marked as the target database of an RBU update. This
170158 ** turns on the following extra special behaviour:
170159 **
170160 ** 3a. If xAccess() is called to check if there exists a *-wal file
170161 ** associated with an RBU target database currently in RBU_STAGE_OAL
170162 ** stage (preparing the *-oal file), the following special handling
170163 ** applies:
170164 **
170165 ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
170166 ** target database may not be in wal mode already.
170167 **
170168 ** * if the *-wal file does not exist, set the output parameter to
170169 ** non-zero (to tell SQLite that it does exist) anyway.
170170 **
170171 ** Then, when xOpen() is called to open the *-wal file associated with
170172 ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
170173 ** file, the rbu vfs opens the corresponding *-oal file instead.
170174 **
170175 ** 3b. The *-shm pages returned by xShmMap() for a target db file in
170176 ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
170177 ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
170178 ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
170179 ** because assert() statements in some VFS implementations fail if
170180 ** xShmLock() is called before xShmMap().
170181 **
170182 ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
170183 ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
170184 ** fails with an SQLITE_BUSY error. This is to stop RBU connections
170185 ** from automatically checkpointing a *-wal (or *-oal) file from within
170186 ** sqlite3_close().
170187 **
170188 ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
170189 ** all xWrite() calls on the target database file perform no IO.
170190 ** Instead the frame and page numbers that would be read and written
170191 ** are recorded. Additionally, successful attempts to obtain exclusive
170192 ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
170193 ** database file are recorded. xShmLock() calls to unlock the same
170194 ** locks are no-ops (so that once obtained, these locks are never
170195 ** relinquished). Finally, calls to xSync() on the target database
170196 ** file fail with SQLITE_INTERNAL errors.
170197 */
170198 
170199 static void rbuUnlockShm(rbu_file *p){
170200  if( p->pRbu ){
170201  int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
170202  int i;
170203  for(i=0; i<SQLITE_SHM_NLOCK;i++){
170204  if( (1<<i) & p->pRbu->mLock ){
170205  xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
170206  }
170207  }
170208  p->pRbu->mLock = 0;
170209  }
170210 }
170211 
170212 /*
170213 ** Close an rbu file.
170214 */
170215 static int rbuVfsClose(sqlite3_file *pFile){
170216  rbu_file *p = (rbu_file*)pFile;
170217  int rc;
170218  int i;
170219 
170220  /* Free the contents of the apShm[] array. And the array itself. */
170221  for(i=0; i<p->nShm; i++){
170222  sqlite3_free(p->apShm[i]);
170223  }
170224  sqlite3_free(p->apShm);
170225  p->apShm = 0;
170226  sqlite3_free(p->zDel);
170227 
170228  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
170229  rbu_file **pp;
170230  sqlite3_mutex_enter(p->pRbuVfs->mutex);
170231  for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
170232  *pp = p->pMainNext;
170233  sqlite3_mutex_leave(p->pRbuVfs->mutex);
170234  rbuUnlockShm(p);
170235  p->pReal->pMethods->xShmUnmap(p->pReal, 0);
170236  }
170237 
170238  /* Close the underlying file handle */
170239  rc = p->pReal->pMethods->xClose(p->pReal);
170240  return rc;
170241 }
170242 
170243 
170244 /*
170245 ** Read and return an unsigned 32-bit big-endian integer from the buffer
170246 ** passed as the only argument.
170247 */
170248 static u32 rbuGetU32(u8 *aBuf){
170249  return ((u32)aBuf[0] << 24)
170250  + ((u32)aBuf[1] << 16)
170251  + ((u32)aBuf[2] << 8)
170252  + ((u32)aBuf[3]);
170253 }
170254 
170255 /*
170256 ** Write an unsigned 32-bit value in big-endian format to the supplied
170257 ** buffer.
170258 */
170259 static void rbuPutU32(u8 *aBuf, u32 iVal){
170260  aBuf[0] = (iVal >> 24) & 0xFF;
170261  aBuf[1] = (iVal >> 16) & 0xFF;
170262  aBuf[2] = (iVal >> 8) & 0xFF;
170263  aBuf[3] = (iVal >> 0) & 0xFF;
170264 }
170265 
170266 static void rbuPutU16(u8 *aBuf, u16 iVal){
170267  aBuf[0] = (iVal >> 8) & 0xFF;
170268  aBuf[1] = (iVal >> 0) & 0xFF;
170269 }
170270 
170271 /*
170272 ** Read data from an rbuVfs-file.
170273 */
170274 static int rbuVfsRead(
170275  sqlite3_file *pFile,
170276  void *zBuf,
170277  int iAmt,
170278  sqlite_int64 iOfst
170279 ){
170280  rbu_file *p = (rbu_file*)pFile;
170281  sqlite3rbu *pRbu = p->pRbu;
170282  int rc;
170283 
170284  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
170285  assert( p->openFlags & SQLITE_OPEN_WAL );
170286  rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
170287  }else{
170288  if( pRbu && pRbu->eStage==RBU_STAGE_OAL
170289  && (p->openFlags & SQLITE_OPEN_WAL)
170290  && iOfst>=pRbu->iOalSz
170291  ){
170292  rc = SQLITE_OK;
170293  memset(zBuf, 0, iAmt);
170294  }else{
170295  rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
170296 #if 1
170297  /* If this is being called to read the first page of the target
170298  ** database as part of an rbu vacuum operation, synthesize the
170299  ** contents of the first page if it does not yet exist. Otherwise,
170300  ** SQLite will not check for a *-wal file. */
170301  if( pRbu && rbuIsVacuum(pRbu)
170302  && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
170303  && (p->openFlags & SQLITE_OPEN_MAIN_DB)
170304  && pRbu->rc==SQLITE_OK
170305  ){
170306  sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
170307  rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
170308  if( rc==SQLITE_OK ){
170309  u8 *aBuf = (u8*)zBuf;
170310  u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
170311  rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
170312  rbuPutU32(&aBuf[36], 0); /* number of free pages */
170313  rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
170314  rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
170315  rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
170316 
170317  if( iAmt>100 ){
170318  memset(&aBuf[100], 0, iAmt-100);
170319  rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
170320  aBuf[100] = 0x0D;
170321  }
170322  }
170323  }
170324 #endif
170325  }
170326  if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
170327  /* These look like magic numbers. But they are stable, as they are part
170328  ** of the definition of the SQLite file format, which may not change. */
170329  u8 *pBuf = (u8*)zBuf;
170330  p->iCookie = rbuGetU32(&pBuf[24]);
170331  p->iWriteVer = pBuf[19];
170332  }
170333  }
170334  return rc;
170335 }
170336 
170337 /*
170338 ** Write data to an rbuVfs-file.
170339 */
170340 static int rbuVfsWrite(
170341  sqlite3_file *pFile,
170342  const void *zBuf,
170343  int iAmt,
170344  sqlite_int64 iOfst
170345 ){
170346  rbu_file *p = (rbu_file*)pFile;
170347  sqlite3rbu *pRbu = p->pRbu;
170348  int rc;
170349 
170350  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
170351  assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
170352  rc = rbuCaptureDbWrite(p->pRbu, iOfst);
170353  }else{
170354  if( pRbu && pRbu->eStage==RBU_STAGE_OAL
170355  && (p->openFlags & SQLITE_OPEN_WAL)
170356  && iOfst>=pRbu->iOalSz
170357  ){
170358  pRbu->iOalSz = iAmt + iOfst;
170359  }
170360  rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
170361  if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
170362  /* These look like magic numbers. But they are stable, as they are part
170363  ** of the definition of the SQLite file format, which may not change. */
170364  u8 *pBuf = (u8*)zBuf;
170365  p->iCookie = rbuGetU32(&pBuf[24]);
170366  p->iWriteVer = pBuf[19];
170367  }
170368  }
170369  return rc;
170370 }
170371 
170372 /*
170373 ** Truncate an rbuVfs-file.
170374 */
170375 static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
170376  rbu_file *p = (rbu_file*)pFile;
170377  return p->pReal->pMethods->xTruncate(p->pReal, size);
170378 }
170379 
170380 /*
170381 ** Sync an rbuVfs-file.
170382 */
170383 static int rbuVfsSync(sqlite3_file *pFile, int flags){
170384  rbu_file *p = (rbu_file *)pFile;
170385  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
170386  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
170387  return SQLITE_INTERNAL;
170388  }
170389  return SQLITE_OK;
170390  }
170391  return p->pReal->pMethods->xSync(p->pReal, flags);
170392 }
170393 
170394 /*
170395 ** Return the current file-size of an rbuVfs-file.
170396 */
170397 static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
170398  rbu_file *p = (rbu_file *)pFile;
170399  int rc;
170400  rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
170401 
170402  /* If this is an RBU vacuum operation and this is the target database,
170403  ** pretend that it has at least one page. Otherwise, SQLite will not
170404  ** check for the existance of a *-wal file. rbuVfsRead() contains
170405  ** similar logic. */
170406  if( rc==SQLITE_OK && *pSize==0
170407  && p->pRbu && rbuIsVacuum(p->pRbu)
170408  && (p->openFlags & SQLITE_OPEN_MAIN_DB)
170409  ){
170410  *pSize = 1024;
170411  }
170412  return rc;
170413 }
170414 
170415 /*
170416 ** Lock an rbuVfs-file.
170417 */
170418 static int rbuVfsLock(sqlite3_file *pFile, int eLock){
170419  rbu_file *p = (rbu_file*)pFile;
170420  sqlite3rbu *pRbu = p->pRbu;
170421  int rc = SQLITE_OK;
170422 
170423  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
170424  if( eLock==SQLITE_LOCK_EXCLUSIVE
170425  && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
170426  ){
170427  /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
170428  ** prevents it from checkpointing the database from sqlite3_close(). */
170429  rc = SQLITE_BUSY;
170430  }else{
170431  rc = p->pReal->pMethods->xLock(p->pReal, eLock);
170432  }
170433 
170434  return rc;
170435 }
170436 
170437 /*
170438 ** Unlock an rbuVfs-file.
170439 */
170440 static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
170441  rbu_file *p = (rbu_file *)pFile;
170442  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
170443 }
170444 
170445 /*
170446 ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
170447 */
170448 static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
170449  rbu_file *p = (rbu_file *)pFile;
170450  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
170451 }
170452 
170453 /*
170454 ** File control method. For custom operations on an rbuVfs-file.
170455 */
170456 static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
170457  rbu_file *p = (rbu_file *)pFile;
170458  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
170459  int rc;
170460 
170461  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
170462  || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
170463  );
170464  if( op==SQLITE_FCNTL_RBU ){
170465  sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
170466 
170467  /* First try to find another RBU vfs lower down in the vfs stack. If
170468  ** one is found, this vfs will operate in pass-through mode. The lower
170469  ** level vfs will do the special RBU handling. */
170470  rc = xControl(p->pReal, op, pArg);
170471 
170472  if( rc==SQLITE_NOTFOUND ){
170473  /* Now search for a zipvfs instance lower down in the VFS stack. If
170474  ** one is found, this is an error. */
170475  void *dummy = 0;
170476  rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
170477  if( rc==SQLITE_OK ){
170478  rc = SQLITE_ERROR;
170479  pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
170480  }else if( rc==SQLITE_NOTFOUND ){
170481  pRbu->pTargetFd = p;
170482  p->pRbu = pRbu;
170483  if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
170484  rc = SQLITE_OK;
170485  }
170486  }
170487  return rc;
170488  }
170489  else if( op==SQLITE_FCNTL_RBUCNT ){
170490  sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
170491  pRbu->nRbu++;
170492  pRbu->pRbuFd = p;
170493  p->bNolock = 1;
170494  }
170495 
170496  rc = xControl(p->pReal, op, pArg);
170497  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
170498  rbu_vfs *pRbuVfs = p->pRbuVfs;
170499  char *zIn = *(char**)pArg;
170500  char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
170501  *(char**)pArg = zOut;
170502  if( zOut==0 ) rc = SQLITE_NOMEM;
170503  }
170504 
170505  return rc;
170506 }
170507 
170508 /*
170509 ** Return the sector-size in bytes for an rbuVfs-file.
170510 */
170511 static int rbuVfsSectorSize(sqlite3_file *pFile){
170512  rbu_file *p = (rbu_file *)pFile;
170513  return p->pReal->pMethods->xSectorSize(p->pReal);
170514 }
170515 
170516 /*
170517 ** Return the device characteristic flags supported by an rbuVfs-file.
170518 */
170519 static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
170520  rbu_file *p = (rbu_file *)pFile;
170521  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
170522 }
170523 
170524 /*
170525 ** Take or release a shared-memory lock.
170526 */
170527 static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
170528  rbu_file *p = (rbu_file*)pFile;
170529  sqlite3rbu *pRbu = p->pRbu;
170530  int rc = SQLITE_OK;
170531 
170532 #ifdef SQLITE_AMALGAMATION
170533  assert( WAL_CKPT_LOCK==1 );
170534 #endif
170535 
170536  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
170537  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
170538  /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
170539  ** taking this lock also prevents any checkpoints from occurring.
170540  ** todo: really, it's not clear why this might occur, as
170541  ** wal_autocheckpoint ought to be turned off. */
170542  if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
170543  }else{
170544  int bCapture = 0;
170545  if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
170546  && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
170547  && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
170548  ){
170549  bCapture = 1;
170550  }
170551 
170552  if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
170553  rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
170554  if( bCapture && rc==SQLITE_OK ){
170555  pRbu->mLock |= (1 << ofst);
170556  }
170557  }
170558  }
170559 
170560  return rc;
170561 }
170562 
170563 /*
170564 ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
170565 */
170566 static int rbuVfsShmMap(
170567  sqlite3_file *pFile,
170568  int iRegion,
170569  int szRegion,
170570  int isWrite,
170571  void volatile **pp
170572 ){
170573  rbu_file *p = (rbu_file*)pFile;
170574  int rc = SQLITE_OK;
170575  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
170576 
170577  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
170578  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
170579  ** instead of a file on disk. */
170580  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
170581  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
170582  if( iRegion<=p->nShm ){
170583  int nByte = (iRegion+1) * sizeof(char*);
170584  char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
170585  if( apNew==0 ){
170586  rc = SQLITE_NOMEM;
170587  }else{
170588  memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
170589  p->apShm = apNew;
170590  p->nShm = iRegion+1;
170591  }
170592  }
170593 
170594  if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
170595  char *pNew = (char*)sqlite3_malloc64(szRegion);
170596  if( pNew==0 ){
170597  rc = SQLITE_NOMEM;
170598  }else{
170599  memset(pNew, 0, szRegion);
170600  p->apShm[iRegion] = pNew;
170601  }
170602  }
170603 
170604  if( rc==SQLITE_OK ){
170605  *pp = p->apShm[iRegion];
170606  }else{
170607  *pp = 0;
170608  }
170609  }else{
170610  assert( p->apShm==0 );
170611  rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
170612  }
170613 
170614  return rc;
170615 }
170616 
170617 /*
170618 ** Memory barrier.
170619 */
170620 static void rbuVfsShmBarrier(sqlite3_file *pFile){
170621  rbu_file *p = (rbu_file *)pFile;
170622  p->pReal->pMethods->xShmBarrier(p->pReal);
170623 }
170624 
170625 /*
170626 ** The xShmUnmap method.
170627 */
170628 static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
170629  rbu_file *p = (rbu_file*)pFile;
170630  int rc = SQLITE_OK;
170631  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
170632 
170633  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
170634  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
170635  /* no-op */
170636  }else{
170637  /* Release the checkpointer and writer locks */
170638  rbuUnlockShm(p);
170639  rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
170640  }
170641  return rc;
170642 }
170643 
170644 /*
170645 ** Given that zWal points to a buffer containing a wal file name passed to
170646 ** either the xOpen() or xAccess() VFS method, return a pointer to the
170647 ** file-handle opened by the same database connection on the corresponding
170648 ** database file.
170649 */
170650 static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
170651  rbu_file *pDb;
170652  sqlite3_mutex_enter(pRbuVfs->mutex);
170653  for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
170654  sqlite3_mutex_leave(pRbuVfs->mutex);
170655  return pDb;
170656 }
170657 
170658 /*
170659 ** A main database named zName has just been opened. The following
170660 ** function returns a pointer to a buffer owned by SQLite that contains
170661 ** the name of the *-wal file this db connection will use. SQLite
170662 ** happens to pass a pointer to this buffer when using xAccess()
170663 ** or xOpen() to operate on the *-wal file.
170664 */
170665 static const char *rbuMainToWal(const char *zName, int flags){
170666  int n = (int)strlen(zName);
170667  const char *z = &zName[n];
170668  if( flags & SQLITE_OPEN_URI ){
170669  int odd = 0;
170670  while( 1 ){
170671  if( z[0]==0 ){
170672  odd = 1 - odd;
170673  if( odd && z[1]==0 ) break;
170674  }
170675  z++;
170676  }
170677  z += 2;
170678  }else{
170679  while( *z==0 ) z++;
170680  }
170681  z += (n + 8 + 1);
170682  return z;
170683 }
170684 
170685 /*
170686 ** Open an rbu file handle.
170687 */
170688 static int rbuVfsOpen(
170689  sqlite3_vfs *pVfs,
170690  const char *zName,
170691  sqlite3_file *pFile,
170692  int flags,
170693  int *pOutFlags
170694 ){
170695  static sqlite3_io_methods rbuvfs_io_methods = {
170696  2, /* iVersion */
170697  rbuVfsClose, /* xClose */
170698  rbuVfsRead, /* xRead */
170699  rbuVfsWrite, /* xWrite */
170700  rbuVfsTruncate, /* xTruncate */
170701  rbuVfsSync, /* xSync */
170702  rbuVfsFileSize, /* xFileSize */
170703  rbuVfsLock, /* xLock */
170704  rbuVfsUnlock, /* xUnlock */
170705  rbuVfsCheckReservedLock, /* xCheckReservedLock */
170706  rbuVfsFileControl, /* xFileControl */
170707  rbuVfsSectorSize, /* xSectorSize */
170708  rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
170709  rbuVfsShmMap, /* xShmMap */
170710  rbuVfsShmLock, /* xShmLock */
170711  rbuVfsShmBarrier, /* xShmBarrier */
170712  rbuVfsShmUnmap, /* xShmUnmap */
170713  0, 0 /* xFetch, xUnfetch */
170714  };
170715  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
170716  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
170717  rbu_file *pFd = (rbu_file *)pFile;
170718  int rc = SQLITE_OK;
170719  const char *zOpen = zName;
170720  int oflags = flags;
170721 
170722  memset(pFd, 0, sizeof(rbu_file));
170723  pFd->pReal = (sqlite3_file*)&pFd[1];
170724  pFd->pRbuVfs = pRbuVfs;
170725  pFd->openFlags = flags;
170726  if( zName ){
170727  if( flags & SQLITE_OPEN_MAIN_DB ){
170728  /* A main database has just been opened. The following block sets
170729  ** (pFd->zWal) to point to a buffer owned by SQLite that contains
170730  ** the name of the *-wal file this db connection will use. SQLite
170731  ** happens to pass a pointer to this buffer when using xAccess()
170732  ** or xOpen() to operate on the *-wal file. */
170733  pFd->zWal = rbuMainToWal(zName, flags);
170734  }
170735  else if( flags & SQLITE_OPEN_WAL ){
170736  rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
170737  if( pDb ){
170738  if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
170739  /* This call is to open a *-wal file. Intead, open the *-oal. This
170740  ** code ensures that the string passed to xOpen() is terminated by a
170741  ** pair of '\0' bytes in case the VFS attempts to extract a URI
170742  ** parameter from it. */
170743  const char *zBase = zName;
170744  size_t nCopy;
170745  char *zCopy;
170746  if( rbuIsVacuum(pDb->pRbu) ){
170747  zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
170748  zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
170749  }
170750  nCopy = strlen(zBase);
170751  zCopy = sqlite3_malloc64(nCopy+2);
170752  if( zCopy ){
170753  memcpy(zCopy, zBase, nCopy);
170754  zCopy[nCopy-3] = 'o';
170755  zCopy[nCopy] = '\0';
170756  zCopy[nCopy+1] = '\0';
170757  zOpen = (const char*)(pFd->zDel = zCopy);
170758  }else{
170759  rc = SQLITE_NOMEM;
170760  }
170761  pFd->pRbu = pDb->pRbu;
170762  }
170763  pDb->pWalFd = pFd;
170764  }
170765  }
170766  }
170767 
170768  if( oflags & SQLITE_OPEN_MAIN_DB
170769  && sqlite3_uri_boolean(zName, "rbu_memory", 0)
170770  ){
170771  assert( oflags & SQLITE_OPEN_MAIN_DB );
170772  oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
170773  SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
170774  zOpen = 0;
170775  }
170776 
170777  if( rc==SQLITE_OK ){
170778  rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
170779  }
170780  if( pFd->pReal->pMethods ){
170781  /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
170782  ** pointer and, if the file is a main database file, link it into the
170783  ** mutex protected linked list of all such files. */
170784  pFile->pMethods = &rbuvfs_io_methods;
170785  if( flags & SQLITE_OPEN_MAIN_DB ){
170786  sqlite3_mutex_enter(pRbuVfs->mutex);
170787  pFd->pMainNext = pRbuVfs->pMain;
170788  pRbuVfs->pMain = pFd;
170789  sqlite3_mutex_leave(pRbuVfs->mutex);
170790  }
170791  }else{
170792  sqlite3_free(pFd->zDel);
170793  }
170794 
170795  return rc;
170796 }
170797 
170798 /*
170799 ** Delete the file located at zPath.
170800 */
170801 static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
170802  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170803  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
170804 }
170805 
170806 /*
170807 ** Test for access permissions. Return true if the requested permission
170808 ** is available, or false otherwise.
170809 */
170810 static int rbuVfsAccess(
170811  sqlite3_vfs *pVfs,
170812  const char *zPath,
170813  int flags,
170814  int *pResOut
170815 ){
170816  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
170817  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
170818  int rc;
170819 
170820  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
170821 
170822  /* If this call is to check if a *-wal file associated with an RBU target
170823  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
170824  ** the following special handling is activated:
170825  **
170826  ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
170827  ** ensures that the RBU extension never tries to update a database
170828  ** in wal mode, even if the first page of the database file has
170829  ** been damaged.
170830  **
170831  ** b) if the *-wal file does not exist, claim that it does anyway,
170832  ** causing SQLite to call xOpen() to open it. This call will also
170833  ** be intercepted (see the rbuVfsOpen() function) and the *-oal
170834  ** file opened instead.
170835  */
170836  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
170837  rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
170838  if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
170839  if( *pResOut ){
170840  rc = SQLITE_CANTOPEN;
170841  }else{
170842  *pResOut = 1;
170843  }
170844  }
170845  }
170846 
170847  return rc;
170848 }
170849 
170850 /*
170851 ** Populate buffer zOut with the full canonical pathname corresponding
170852 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
170853 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
170854 */
170855 static int rbuVfsFullPathname(
170856  sqlite3_vfs *pVfs,
170857  const char *zPath,
170858  int nOut,
170859  char *zOut
170860 ){
170861  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170862  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
170863 }
170864 
170865 #ifndef SQLITE_OMIT_LOAD_EXTENSION
170866 /*
170867 ** Open the dynamic library located at zPath and return a handle.
170868 */
170869 static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
170870  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170871  return pRealVfs->xDlOpen(pRealVfs, zPath);
170872 }
170873 
170874 /*
170875 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
170876 ** utf-8 string describing the most recent error encountered associated
170877 ** with dynamic libraries.
170878 */
170879 static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
170880  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170881  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
170882 }
170883 
170884 /*
170885 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
170886 */
170887 static void (*rbuVfsDlSym(
170888  sqlite3_vfs *pVfs,
170889  void *pArg,
170890  const char *zSym
170891 ))(void){
170892  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170893  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
170894 }
170895 
170896 /*
170897 ** Close the dynamic library handle pHandle.
170898 */
170899 static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
170900  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170901  pRealVfs->xDlClose(pRealVfs, pHandle);
170902 }
170903 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
170904 
170905 /*
170906 ** Populate the buffer pointed to by zBufOut with nByte bytes of
170907 ** random data.
170908 */
170909 static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
170910  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170911  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
170912 }
170913 
170914 /*
170915 ** Sleep for nMicro microseconds. Return the number of microseconds
170916 ** actually slept.
170917 */
170918 static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
170919  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170920  return pRealVfs->xSleep(pRealVfs, nMicro);
170921 }
170922 
170923 /*
170924 ** Return the current time as a Julian Day number in *pTimeOut.
170925 */
170926 static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
170927  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170928  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
170929 }
170930 
170931 /*
170932 ** No-op.
170933 */
170934 static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
170935  return 0;
170936 }
170937 
170938 /*
170939 ** Deregister and destroy an RBU vfs created by an earlier call to
170940 ** sqlite3rbu_create_vfs().
170941 */
170942 SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
170943  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
170944  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
170945  sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
170946  sqlite3_vfs_unregister(pVfs);
170947  sqlite3_free(pVfs);
170948  }
170949 }
170950 
170951 /*
170952 ** Create an RBU VFS named zName that accesses the underlying file-system
170953 ** via existing VFS zParent. The new object is registered as a non-default
170954 ** VFS with SQLite before returning.
170955 */
170956 SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
170957 
170958  /* Template for VFS */
170959  static sqlite3_vfs vfs_template = {
170960  1, /* iVersion */
170961  0, /* szOsFile */
170962  0, /* mxPathname */
170963  0, /* pNext */
170964  0, /* zName */
170965  0, /* pAppData */
170966  rbuVfsOpen, /* xOpen */
170967  rbuVfsDelete, /* xDelete */
170968  rbuVfsAccess, /* xAccess */
170969  rbuVfsFullPathname, /* xFullPathname */
170970 
170971 #ifndef SQLITE_OMIT_LOAD_EXTENSION
170972  rbuVfsDlOpen, /* xDlOpen */
170973  rbuVfsDlError, /* xDlError */
170974  rbuVfsDlSym, /* xDlSym */
170975  rbuVfsDlClose, /* xDlClose */
170976 #else
170977  0, 0, 0, 0,
170978 #endif
170979 
170980  rbuVfsRandomness, /* xRandomness */
170981  rbuVfsSleep, /* xSleep */
170982  rbuVfsCurrentTime, /* xCurrentTime */
170983  rbuVfsGetLastError, /* xGetLastError */
170984  0, /* xCurrentTimeInt64 (version 2) */
170985  0, 0, 0 /* Unimplemented version 3 methods */
170986  };
170987 
170988  rbu_vfs *pNew = 0; /* Newly allocated VFS */
170989  int rc = SQLITE_OK;
170990  size_t nName;
170991  size_t nByte;
170992 
170993  nName = strlen(zName);
170994  nByte = sizeof(rbu_vfs) + nName + 1;
170995  pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
170996  if( pNew==0 ){
170997  rc = SQLITE_NOMEM;
170998  }else{
170999  sqlite3_vfs *pParent; /* Parent VFS */
171000  memset(pNew, 0, nByte);
171001  pParent = sqlite3_vfs_find(zParent);
171002  if( pParent==0 ){
171003  rc = SQLITE_NOTFOUND;
171004  }else{
171005  char *zSpace;
171006  memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
171007  pNew->base.mxPathname = pParent->mxPathname;
171008  pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
171009  pNew->pRealVfs = pParent;
171010  pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
171011  memcpy(zSpace, zName, nName);
171012 
171013  /* Allocate the mutex and register the new VFS (not as the default) */
171014  pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
171015  if( pNew->mutex==0 ){
171016  rc = SQLITE_NOMEM;
171017  }else{
171018  rc = sqlite3_vfs_register(&pNew->base, 0);
171019  }
171020  }
171021 
171022  if( rc!=SQLITE_OK ){
171023  sqlite3_mutex_free(pNew->mutex);
171024  sqlite3_free(pNew);
171025  }
171026  }
171027 
171028  return rc;
171029 }
171030 
171031 
171032 /**************************************************************************/
171033 
171034 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
171035 
171036 /************** End of sqlite3rbu.c ******************************************/
171037 /************** Begin file dbstat.c ******************************************/
171038 /*
171039 ** 2010 July 12
171040 **
171041 ** The author disclaims copyright to this source code. In place of
171042 ** a legal notice, here is a blessing:
171043 **
171044 ** May you do good and not evil.
171045 ** May you find forgiveness for yourself and forgive others.
171046 ** May you share freely, never taking more than you give.
171047 **
171048 ******************************************************************************
171049 **
171050 ** This file contains an implementation of the "dbstat" virtual table.
171051 **
171052 ** The dbstat virtual table is used to extract low-level formatting
171053 ** information from an SQLite database in order to implement the
171054 ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
171055 ** for an example implementation.
171056 **
171057 ** Additional information is available on the "dbstat.html" page of the
171058 ** official SQLite documentation.
171059 */
171060 
171061 /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
171062 #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
171063  && !defined(SQLITE_OMIT_VIRTUALTABLE)
171064 
171065 /*
171066 ** Page paths:
171067 **
171068 ** The value of the 'path' column describes the path taken from the
171069 ** root-node of the b-tree structure to each page. The value of the
171070 ** root-node path is '/'.
171071 **
171072 ** The value of the path for the left-most child page of the root of
171073 ** a b-tree is '/000/'. (Btrees store content ordered from left to right
171074 ** so the pages to the left have smaller keys than the pages to the right.)
171075 ** The next to left-most child of the root page is
171076 ** '/001', and so on, each sibling page identified by a 3-digit hex
171077 ** value. The children of the 451st left-most sibling have paths such
171078 ** as '/1c2/000/, '/1c2/001/' etc.
171079 **
171080 ** Overflow pages are specified by appending a '+' character and a
171081 ** six-digit hexadecimal value to the path to the cell they are linked
171082 ** from. For example, the three overflow pages in a chain linked from
171083 ** the left-most cell of the 450th child of the root page are identified
171084 ** by the paths:
171085 **
171086 ** '/1c2/000+000000' // First page in overflow chain
171087 ** '/1c2/000+000001' // Second page in overflow chain
171088 ** '/1c2/000+000002' // Third page in overflow chain
171089 **
171090 ** If the paths are sorted using the BINARY collation sequence, then
171091 ** the overflow pages associated with a cell will appear earlier in the
171092 ** sort-order than its child page:
171093 **
171094 ** '/1c2/000/' // Left-most child of 451st child of root
171095 */
171096 #define VTAB_SCHEMA \
171097  "CREATE TABLE xx( " \
171098  " name TEXT, /* Name of table or index */" \
171099  " path TEXT, /* Path to page from root */" \
171100  " pageno INTEGER, /* Page number */" \
171101  " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
171102  " ncell INTEGER, /* Cells on page (0 for overflow) */" \
171103  " payload INTEGER, /* Bytes of payload on this page */" \
171104  " unused INTEGER, /* Bytes of unused space on this page */" \
171105  " mx_payload INTEGER, /* Largest payload size of all cells */" \
171106  " pgoffset INTEGER, /* Offset of page in file */" \
171107  " pgsize INTEGER, /* Size of the page */" \
171108  " schema TEXT HIDDEN /* Database schema being analyzed */" \
171109  ");"
171110 
171111 
171112 typedef struct StatTable StatTable;
171113 typedef struct StatCursor StatCursor;
171114 typedef struct StatPage StatPage;
171115 typedef struct StatCell StatCell;
171116 
171117 struct StatCell {
171118  int nLocal; /* Bytes of local payload */
171119  u32 iChildPg; /* Child node (or 0 if this is a leaf) */
171120  int nOvfl; /* Entries in aOvfl[] */
171121  u32 *aOvfl; /* Array of overflow page numbers */
171122  int nLastOvfl; /* Bytes of payload on final overflow page */
171123  int iOvfl; /* Iterates through aOvfl[] */
171124 };
171125 
171126 struct StatPage {
171127  u32 iPgno;
171128  DbPage *pPg;
171129  int iCell;
171130 
171131  char *zPath; /* Path to this page */
171132 
171133  /* Variables populated by statDecodePage(): */
171134  u8 flags; /* Copy of flags byte */
171135  int nCell; /* Number of cells on page */
171136  int nUnused; /* Number of unused bytes on page */
171137  StatCell *aCell; /* Array of parsed cells */
171138  u32 iRightChildPg; /* Right-child page number (or 0) */
171139  int nMxPayload; /* Largest payload of any cell on this page */
171140 };
171141 
171142 struct StatCursor {
171143  sqlite3_vtab_cursor base;
171144  sqlite3_stmt *pStmt; /* Iterates through set of root pages */
171145  int isEof; /* After pStmt has returned SQLITE_DONE */
171146  int iDb; /* Schema used for this query */
171147 
171148  StatPage aPage[32];
171149  int iPage; /* Current entry in aPage[] */
171150 
171151  /* Values to return. */
171152  char *zName; /* Value of 'name' column */
171153  char *zPath; /* Value of 'path' column */
171154  u32 iPageno; /* Value of 'pageno' column */
171155  char *zPagetype; /* Value of 'pagetype' column */
171156  int nCell; /* Value of 'ncell' column */
171157  int nPayload; /* Value of 'payload' column */
171158  int nUnused; /* Value of 'unused' column */
171159  int nMxPayload; /* Value of 'mx_payload' column */
171160  i64 iOffset; /* Value of 'pgOffset' column */
171161  int szPage; /* Value of 'pgSize' column */
171162 };
171163 
171164 struct StatTable {
171165  sqlite3_vtab base;
171166  sqlite3 *db;
171167  int iDb; /* Index of database to analyze */
171168 };
171169 
171170 #ifndef get2byte
171171 # define get2byte(x) ((x)[0]<<8 | (x)[1])
171172 #endif
171173 
171174 /*
171175 ** Connect to or create a statvfs virtual table.
171176 */
171177 static int statConnect(
171178  sqlite3 *db,
171179  void *pAux,
171180  int argc, const char *const*argv,
171181  sqlite3_vtab **ppVtab,
171182  char **pzErr
171183 ){
171184  StatTable *pTab = 0;
171185  int rc = SQLITE_OK;
171186  int iDb;
171187 
171188  if( argc>=4 ){
171189  Token nm;
171190  sqlite3TokenInit(&nm, (char*)argv[3]);
171191  iDb = sqlite3FindDb(db, &nm);
171192  if( iDb<0 ){
171193  *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
171194  return SQLITE_ERROR;
171195  }
171196  }else{
171197  iDb = 0;
171198  }
171199  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
171200  if( rc==SQLITE_OK ){
171201  pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
171202  if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
171203  }
171204 
171205  assert( rc==SQLITE_OK || pTab==0 );
171206  if( rc==SQLITE_OK ){
171207  memset(pTab, 0, sizeof(StatTable));
171208  pTab->db = db;
171209  pTab->iDb = iDb;
171210  }
171211 
171212  *ppVtab = (sqlite3_vtab*)pTab;
171213  return rc;
171214 }
171215 
171216 /*
171217 ** Disconnect from or destroy a statvfs virtual table.
171218 */
171219 static int statDisconnect(sqlite3_vtab *pVtab){
171220  sqlite3_free(pVtab);
171221  return SQLITE_OK;
171222 }
171223 
171224 /*
171225 ** There is no "best-index". This virtual table always does a linear
171226 ** scan. However, a schema=? constraint should cause this table to
171227 ** operate on a different database schema, so check for it.
171228 **
171229 ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
171230 */
171231 static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
171232  int i;
171233 
171234  pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
171235 
171236  /* Look for a valid schema=? constraint. If found, change the idxNum to
171237  ** 1 and request the value of that constraint be sent to xFilter. And
171238  ** lower the cost estimate to encourage the constrained version to be
171239  ** used.
171240  */
171241  for(i=0; i<pIdxInfo->nConstraint; i++){
171242  if( pIdxInfo->aConstraint[i].usable==0 ) continue;
171243  if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
171244  if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
171245  pIdxInfo->idxNum = 1;
171246  pIdxInfo->estimatedCost = 1.0;
171247  pIdxInfo->aConstraintUsage[i].argvIndex = 1;
171248  pIdxInfo->aConstraintUsage[i].omit = 1;
171249  break;
171250  }
171251 
171252 
171253  /* Records are always returned in ascending order of (name, path).
171254  ** If this will satisfy the client, set the orderByConsumed flag so that
171255  ** SQLite does not do an external sort.
171256  */
171257  if( ( pIdxInfo->nOrderBy==1
171258  && pIdxInfo->aOrderBy[0].iColumn==0
171259  && pIdxInfo->aOrderBy[0].desc==0
171260  ) ||
171261  ( pIdxInfo->nOrderBy==2
171262  && pIdxInfo->aOrderBy[0].iColumn==0
171263  && pIdxInfo->aOrderBy[0].desc==0
171264  && pIdxInfo->aOrderBy[1].iColumn==1
171265  && pIdxInfo->aOrderBy[1].desc==0
171266  )
171267  ){
171268  pIdxInfo->orderByConsumed = 1;
171269  }
171270 
171271  return SQLITE_OK;
171272 }
171273 
171274 /*
171275 ** Open a new statvfs cursor.
171276 */
171277 static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
171278  StatTable *pTab = (StatTable *)pVTab;
171279  StatCursor *pCsr;
171280 
171281  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
171282  if( pCsr==0 ){
171283  return SQLITE_NOMEM_BKPT;
171284  }else{
171285  memset(pCsr, 0, sizeof(StatCursor));
171286  pCsr->base.pVtab = pVTab;
171287  pCsr->iDb = pTab->iDb;
171288  }
171289 
171290  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
171291  return SQLITE_OK;
171292 }
171293 
171294 static void statClearPage(StatPage *p){
171295  int i;
171296  if( p->aCell ){
171297  for(i=0; i<p->nCell; i++){
171298  sqlite3_free(p->aCell[i].aOvfl);
171299  }
171300  sqlite3_free(p->aCell);
171301  }
171302  sqlite3PagerUnref(p->pPg);
171303  sqlite3_free(p->zPath);
171304  memset(p, 0, sizeof(StatPage));
171305 }
171306 
171307 static void statResetCsr(StatCursor *pCsr){
171308  int i;
171309  sqlite3_reset(pCsr->pStmt);
171310  for(i=0; i<ArraySize(pCsr->aPage); i++){
171311  statClearPage(&pCsr->aPage[i]);
171312  }
171313  pCsr->iPage = 0;
171314  sqlite3_free(pCsr->zPath);
171315  pCsr->zPath = 0;
171316  pCsr->isEof = 0;
171317 }
171318 
171319 /*
171320 ** Close a statvfs cursor.
171321 */
171322 static int statClose(sqlite3_vtab_cursor *pCursor){
171323  StatCursor *pCsr = (StatCursor *)pCursor;
171324  statResetCsr(pCsr);
171325  sqlite3_finalize(pCsr->pStmt);
171326  sqlite3_free(pCsr);
171327  return SQLITE_OK;
171328 }
171329 
171330 static void getLocalPayload(
171331  int nUsable, /* Usable bytes per page */
171332  u8 flags, /* Page flags */
171333  int nTotal, /* Total record (payload) size */
171334  int *pnLocal /* OUT: Bytes stored locally */
171335 ){
171336  int nLocal;
171337  int nMinLocal;
171338  int nMaxLocal;
171339 
171340  if( flags==0x0D ){ /* Table leaf node */
171341  nMinLocal = (nUsable - 12) * 32 / 255 - 23;
171342  nMaxLocal = nUsable - 35;
171343  }else{ /* Index interior and leaf nodes */
171344  nMinLocal = (nUsable - 12) * 32 / 255 - 23;
171345  nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
171346  }
171347 
171348  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
171349  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
171350  *pnLocal = nLocal;
171351 }
171352 
171353 static int statDecodePage(Btree *pBt, StatPage *p){
171354  int nUnused;
171355  int iOff;
171356  int nHdr;
171357  int isLeaf;
171358  int szPage;
171359 
171360  u8 *aData = sqlite3PagerGetData(p->pPg);
171361  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
171362 
171363  p->flags = aHdr[0];
171364  p->nCell = get2byte(&aHdr[3]);
171365  p->nMxPayload = 0;
171366 
171367  isLeaf = (p->flags==0x0A || p->flags==0x0D);
171368  nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
171369 
171370  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
171371  nUnused += (int)aHdr[7];
171372  iOff = get2byte(&aHdr[1]);
171373  while( iOff ){
171374  nUnused += get2byte(&aData[iOff+2]);
171375  iOff = get2byte(&aData[iOff]);
171376  }
171377  p->nUnused = nUnused;
171378  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
171379  szPage = sqlite3BtreeGetPageSize(pBt);
171380 
171381  if( p->nCell ){
171382  int i; /* Used to iterate through cells */
171383  int nUsable; /* Usable bytes per page */
171384 
171385  sqlite3BtreeEnter(pBt);
171386  nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
171387  sqlite3BtreeLeave(pBt);
171388  p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
171389  if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
171390  memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
171391 
171392  for(i=0; i<p->nCell; i++){
171393  StatCell *pCell = &p->aCell[i];
171394 
171395  iOff = get2byte(&aData[nHdr+i*2]);
171396  if( !isLeaf ){
171397  pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
171398  iOff += 4;
171399  }
171400  if( p->flags==0x05 ){
171401  /* A table interior node. nPayload==0. */
171402  }else{
171403  u32 nPayload; /* Bytes of payload total (local+overflow) */
171404  int nLocal; /* Bytes of payload stored locally */
171405  iOff += getVarint32(&aData[iOff], nPayload);
171406  if( p->flags==0x0D ){
171407  u64 dummy;
171408  iOff += sqlite3GetVarint(&aData[iOff], &dummy);
171409  }
171410  if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
171411  getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
171412  pCell->nLocal = nLocal;
171413  assert( nLocal>=0 );
171414  assert( nPayload>=(u32)nLocal );
171415  assert( nLocal<=(nUsable-35) );
171416  if( nPayload>(u32)nLocal ){
171417  int j;
171418  int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
171419  pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
171420  pCell->nOvfl = nOvfl;
171421  pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
171422  if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
171423  pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
171424  for(j=1; j<nOvfl; j++){
171425  int rc;
171426  u32 iPrev = pCell->aOvfl[j-1];
171427  DbPage *pPg = 0;
171428  rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
171429  if( rc!=SQLITE_OK ){
171430  assert( pPg==0 );
171431  return rc;
171432  }
171433  pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
171434  sqlite3PagerUnref(pPg);
171435  }
171436  }
171437  }
171438  }
171439  }
171440 
171441  return SQLITE_OK;
171442 }
171443 
171444 /*
171445 ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
171446 ** the current value of pCsr->iPageno.
171447 */
171448 static void statSizeAndOffset(StatCursor *pCsr){
171449  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
171450  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
171451  Pager *pPager = sqlite3BtreePager(pBt);
171452  sqlite3_file *fd;
171453  sqlite3_int64 x[2];
171454 
171455  /* The default page size and offset */
171456  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
171457  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
171458 
171459  /* If connected to a ZIPVFS backend, override the page size and
171460  ** offset with actual values obtained from ZIPVFS.
171461  */
171462  fd = sqlite3PagerFile(pPager);
171463  x[0] = pCsr->iPageno;
171464  if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
171465  pCsr->iOffset = x[0];
171466  pCsr->szPage = (int)x[1];
171467  }
171468 }
171469 
171470 /*
171471 ** Move a statvfs cursor to the next entry in the file.
171472 */
171473 static int statNext(sqlite3_vtab_cursor *pCursor){
171474  int rc;
171475  int nPayload;
171476  char *z;
171477  StatCursor *pCsr = (StatCursor *)pCursor;
171478  StatTable *pTab = (StatTable *)pCursor->pVtab;
171479  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
171480  Pager *pPager = sqlite3BtreePager(pBt);
171481 
171482  sqlite3_free(pCsr->zPath);
171483  pCsr->zPath = 0;
171484 
171485 statNextRestart:
171486  if( pCsr->aPage[0].pPg==0 ){
171487  rc = sqlite3_step(pCsr->pStmt);
171488  if( rc==SQLITE_ROW ){
171489  int nPage;
171490  u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
171491  sqlite3PagerPagecount(pPager, &nPage);
171492  if( nPage==0 ){
171493  pCsr->isEof = 1;
171494  return sqlite3_reset(pCsr->pStmt);
171495  }
171496  rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
171497  pCsr->aPage[0].iPgno = iRoot;
171498  pCsr->aPage[0].iCell = 0;
171499  pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
171500  pCsr->iPage = 0;
171501  if( z==0 ) rc = SQLITE_NOMEM_BKPT;
171502  }else{
171503  pCsr->isEof = 1;
171504  return sqlite3_reset(pCsr->pStmt);
171505  }
171506  }else{
171507 
171508  /* Page p itself has already been visited. */
171509  StatPage *p = &pCsr->aPage[pCsr->iPage];
171510 
171511  while( p->iCell<p->nCell ){
171512  StatCell *pCell = &p->aCell[p->iCell];
171513  if( pCell->iOvfl<pCell->nOvfl ){
171514  int nUsable;
171515  sqlite3BtreeEnter(pBt);
171516  nUsable = sqlite3BtreeGetPageSize(pBt) -
171517  sqlite3BtreeGetReserveNoMutex(pBt);
171518  sqlite3BtreeLeave(pBt);
171519  pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
171520  pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
171521  pCsr->zPagetype = "overflow";
171522  pCsr->nCell = 0;
171523  pCsr->nMxPayload = 0;
171524  pCsr->zPath = z = sqlite3_mprintf(
171525  "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
171526  );
171527  if( pCell->iOvfl<pCell->nOvfl-1 ){
171528  pCsr->nUnused = 0;
171529  pCsr->nPayload = nUsable - 4;
171530  }else{
171531  pCsr->nPayload = pCell->nLastOvfl;
171532  pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
171533  }
171534  pCell->iOvfl++;
171535  statSizeAndOffset(pCsr);
171536  return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
171537  }
171538  if( p->iRightChildPg ) break;
171539  p->iCell++;
171540  }
171541 
171542  if( !p->iRightChildPg || p->iCell>p->nCell ){
171543  statClearPage(p);
171544  if( pCsr->iPage==0 ) return statNext(pCursor);
171545  pCsr->iPage--;
171546  goto statNextRestart; /* Tail recursion */
171547  }
171548  pCsr->iPage++;
171549  assert( p==&pCsr->aPage[pCsr->iPage-1] );
171550 
171551  if( p->iCell==p->nCell ){
171552  p[1].iPgno = p->iRightChildPg;
171553  }else{
171554  p[1].iPgno = p->aCell[p->iCell].iChildPg;
171555  }
171556  rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
171557  p[1].iCell = 0;
171558  p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
171559  p->iCell++;
171560  if( z==0 ) rc = SQLITE_NOMEM_BKPT;
171561  }
171562 
171563 
171564  /* Populate the StatCursor fields with the values to be returned
171565  ** by the xColumn() and xRowid() methods.
171566  */
171567  if( rc==SQLITE_OK ){
171568  int i;
171569  StatPage *p = &pCsr->aPage[pCsr->iPage];
171570  pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
171571  pCsr->iPageno = p->iPgno;
171572 
171573  rc = statDecodePage(pBt, p);
171574  if( rc==SQLITE_OK ){
171575  statSizeAndOffset(pCsr);
171576 
171577  switch( p->flags ){
171578  case 0x05: /* table internal */
171579  case 0x02: /* index internal */
171580  pCsr->zPagetype = "internal";
171581  break;
171582  case 0x0D: /* table leaf */
171583  case 0x0A: /* index leaf */
171584  pCsr->zPagetype = "leaf";
171585  break;
171586  default:
171587  pCsr->zPagetype = "corrupted";
171588  break;
171589  }
171590  pCsr->nCell = p->nCell;
171591  pCsr->nUnused = p->nUnused;
171592  pCsr->nMxPayload = p->nMxPayload;
171593  pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
171594  if( z==0 ) rc = SQLITE_NOMEM_BKPT;
171595  nPayload = 0;
171596  for(i=0; i<p->nCell; i++){
171597  nPayload += p->aCell[i].nLocal;
171598  }
171599  pCsr->nPayload = nPayload;
171600  }
171601  }
171602 
171603  return rc;
171604 }
171605 
171606 static int statEof(sqlite3_vtab_cursor *pCursor){
171607  StatCursor *pCsr = (StatCursor *)pCursor;
171608  return pCsr->isEof;
171609 }
171610 
171611 static int statFilter(
171612  sqlite3_vtab_cursor *pCursor,
171613  int idxNum, const char *idxStr,
171614  int argc, sqlite3_value **argv
171615 ){
171616  StatCursor *pCsr = (StatCursor *)pCursor;
171617  StatTable *pTab = (StatTable*)(pCursor->pVtab);
171618  char *zSql;
171619  int rc = SQLITE_OK;
171620  char *zMaster;
171621 
171622  if( idxNum==1 ){
171623  const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
171624  pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
171625  if( pCsr->iDb<0 ){
171626  sqlite3_free(pCursor->pVtab->zErrMsg);
171627  pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
171628  return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
171629  }
171630  }else{
171631  pCsr->iDb = pTab->iDb;
171632  }
171633  statResetCsr(pCsr);
171634  sqlite3_finalize(pCsr->pStmt);
171635  pCsr->pStmt = 0;
171636  zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
171637  zSql = sqlite3_mprintf(
171638  "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
171639  " UNION ALL "
171640  "SELECT name, rootpage, type"
171641  " FROM \"%w\".%s WHERE rootpage!=0"
171642  " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
171643  if( zSql==0 ){
171644  return SQLITE_NOMEM_BKPT;
171645  }else{
171646  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
171647  sqlite3_free(zSql);
171648  }
171649 
171650  if( rc==SQLITE_OK ){
171651  rc = statNext(pCursor);
171652  }
171653  return rc;
171654 }
171655 
171656 static int statColumn(
171657  sqlite3_vtab_cursor *pCursor,
171658  sqlite3_context *ctx,
171659  int i
171660 ){
171661  StatCursor *pCsr = (StatCursor *)pCursor;
171662  switch( i ){
171663  case 0: /* name */
171664  sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
171665  break;
171666  case 1: /* path */
171667  sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
171668  break;
171669  case 2: /* pageno */
171670  sqlite3_result_int64(ctx, pCsr->iPageno);
171671  break;
171672  case 3: /* pagetype */
171673  sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
171674  break;
171675  case 4: /* ncell */
171676  sqlite3_result_int(ctx, pCsr->nCell);
171677  break;
171678  case 5: /* payload */
171679  sqlite3_result_int(ctx, pCsr->nPayload);
171680  break;
171681  case 6: /* unused */
171682  sqlite3_result_int(ctx, pCsr->nUnused);
171683  break;
171684  case 7: /* mx_payload */
171685  sqlite3_result_int(ctx, pCsr->nMxPayload);
171686  break;
171687  case 8: /* pgoffset */
171688  sqlite3_result_int64(ctx, pCsr->iOffset);
171689  break;
171690  case 9: /* pgsize */
171691  sqlite3_result_int(ctx, pCsr->szPage);
171692  break;
171693  default: { /* schema */
171694  sqlite3 *db = sqlite3_context_db_handle(ctx);
171695  int iDb = pCsr->iDb;
171696  sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
171697  break;
171698  }
171699  }
171700  return SQLITE_OK;
171701 }
171702 
171703 static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
171704  StatCursor *pCsr = (StatCursor *)pCursor;
171705  *pRowid = pCsr->iPageno;
171706  return SQLITE_OK;
171707 }
171708 
171709 /*
171710 ** Invoke this routine to register the "dbstat" virtual table module
171711 */
171712 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
171713  static sqlite3_module dbstat_module = {
171714  0, /* iVersion */
171715  statConnect, /* xCreate */
171716  statConnect, /* xConnect */
171717  statBestIndex, /* xBestIndex */
171718  statDisconnect, /* xDisconnect */
171719  statDisconnect, /* xDestroy */
171720  statOpen, /* xOpen - open a cursor */
171721  statClose, /* xClose - close a cursor */
171722  statFilter, /* xFilter - configure scan constraints */
171723  statNext, /* xNext - advance a cursor */
171724  statEof, /* xEof - check for end of scan */
171725  statColumn, /* xColumn - read data */
171726  statRowid, /* xRowid - read data */
171727  0, /* xUpdate */
171728  0, /* xBegin */
171729  0, /* xSync */
171730  0, /* xCommit */
171731  0, /* xRollback */
171732  0, /* xFindMethod */
171733  0, /* xRename */
171734  };
171735  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
171736 }
171737 #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
171738 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
171739 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
171740 
171741 /************** End of dbstat.c **********************************************/
171742 /************** Begin file sqlite3session.c **********************************/
171743 
171744 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
171745 /* #include "sqlite3session.h" */
171746 /* #include <assert.h> */
171747 /* #include <string.h> */
171748 
171749 #ifndef SQLITE_AMALGAMATION
171750 /* # include "sqliteInt.h" */
171751 /* # include "vdbeInt.h" */
171752 #endif
171753 
171754 typedef struct SessionTable SessionTable;
171755 typedef struct SessionChange SessionChange;
171756 typedef struct SessionBuffer SessionBuffer;
171757 typedef struct SessionInput SessionInput;
171758 
171759 /*
171760 ** Minimum chunk size used by streaming versions of functions.
171761 */
171762 #ifndef SESSIONS_STRM_CHUNK_SIZE
171763 # ifdef SQLITE_TEST
171764 # define SESSIONS_STRM_CHUNK_SIZE 64
171765 # else
171766 # define SESSIONS_STRM_CHUNK_SIZE 1024
171767 # endif
171768 #endif
171769 
171770 typedef struct SessionHook SessionHook;
171771 struct SessionHook {
171772  void *pCtx;
171773  int (*xOld)(void*,int,sqlite3_value**);
171774  int (*xNew)(void*,int,sqlite3_value**);
171775  int (*xCount)(void*);
171776  int (*xDepth)(void*);
171777 };
171778 
171779 /*
171780 ** Session handle structure.
171781 */
171782 struct sqlite3_session {
171783  sqlite3 *db; /* Database handle session is attached to */
171784  char *zDb; /* Name of database session is attached to */
171785  int bEnable; /* True if currently recording */
171786  int bIndirect; /* True if all changes are indirect */
171787  int bAutoAttach; /* True to auto-attach tables */
171788  int rc; /* Non-zero if an error has occurred */
171789  void *pFilterCtx; /* First argument to pass to xTableFilter */
171790  int (*xTableFilter)(void *pCtx, const char *zTab);
171791  sqlite3_session *pNext; /* Next session object on same db. */
171792  SessionTable *pTable; /* List of attached tables */
171793  SessionHook hook; /* APIs to grab new and old data with */
171794 };
171795 
171796 /*
171797 ** Instances of this structure are used to build strings or binary records.
171798 */
171799 struct SessionBuffer {
171800  u8 *aBuf; /* Pointer to changeset buffer */
171801  int nBuf; /* Size of buffer aBuf */
171802  int nAlloc; /* Size of allocation containing aBuf */
171803 };
171804 
171805 /*
171806 ** An object of this type is used internally as an abstraction for
171807 ** input data. Input data may be supplied either as a single large buffer
171808 ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
171809 ** sqlite3changeset_start_strm()).
171810 */
171811 struct SessionInput {
171812  int bNoDiscard; /* If true, discard no data */
171813  int iCurrent; /* Offset in aData[] of current change */
171814  int iNext; /* Offset in aData[] of next change */
171815  u8 *aData; /* Pointer to buffer containing changeset */
171816  int nData; /* Number of bytes in aData */
171817 
171818  SessionBuffer buf; /* Current read buffer */
171819  int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
171820  void *pIn; /* First argument to xInput */
171821  int bEof; /* Set to true after xInput finished */
171822 };
171823 
171824 /*
171825 ** Structure for changeset iterators.
171826 */
171827 struct sqlite3_changeset_iter {
171828  SessionInput in; /* Input buffer or stream */
171829  SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
171830  int bPatchset; /* True if this is a patchset */
171831  int rc; /* Iterator error code */
171832  sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
171833  char *zTab; /* Current table */
171834  int nCol; /* Number of columns in zTab */
171835  int op; /* Current operation */
171836  int bIndirect; /* True if current change was indirect */
171837  u8 *abPK; /* Primary key array */
171838  sqlite3_value **apValue; /* old.* and new.* values */
171839 };
171840 
171841 /*
171842 ** Each session object maintains a set of the following structures, one
171843 ** for each table the session object is monitoring. The structures are
171844 ** stored in a linked list starting at sqlite3_session.pTable.
171845 **
171846 ** The keys of the SessionTable.aChange[] hash table are all rows that have
171847 ** been modified in any way since the session object was attached to the
171848 ** table.
171849 **
171850 ** The data associated with each hash-table entry is a structure containing
171851 ** a subset of the initial values that the modified row contained at the
171852 ** start of the session. Or no initial values if the row was inserted.
171853 */
171854 struct SessionTable {
171855  SessionTable *pNext;
171856  char *zName; /* Local name of table */
171857  int nCol; /* Number of columns in table zName */
171858  const char **azCol; /* Column names */
171859  u8 *abPK; /* Array of primary key flags */
171860  int nEntry; /* Total number of entries in hash table */
171861  int nChange; /* Size of apChange[] array */
171862  SessionChange **apChange; /* Hash table buckets */
171863 };
171864 
171865 /*
171866 ** RECORD FORMAT:
171867 **
171868 ** The following record format is similar to (but not compatible with) that
171869 ** used in SQLite database files. This format is used as part of the
171870 ** change-set binary format, and so must be architecture independent.
171871 **
171872 ** Unlike the SQLite database record format, each field is self-contained -
171873 ** there is no separation of header and data. Each field begins with a
171874 ** single byte describing its type, as follows:
171875 **
171876 ** 0x00: Undefined value.
171877 ** 0x01: Integer value.
171878 ** 0x02: Real value.
171879 ** 0x03: Text value.
171880 ** 0x04: Blob value.
171881 ** 0x05: SQL NULL value.
171882 **
171883 ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
171884 ** and so on in sqlite3.h. For undefined and NULL values, the field consists
171885 ** only of the single type byte. For other types of values, the type byte
171886 ** is followed by:
171887 **
171888 ** Text values:
171889 ** A varint containing the number of bytes in the value (encoded using
171890 ** UTF-8). Followed by a buffer containing the UTF-8 representation
171891 ** of the text value. There is no nul terminator.
171892 **
171893 ** Blob values:
171894 ** A varint containing the number of bytes in the value, followed by
171895 ** a buffer containing the value itself.
171896 **
171897 ** Integer values:
171898 ** An 8-byte big-endian integer value.
171899 **
171900 ** Real values:
171901 ** An 8-byte big-endian IEEE 754-2008 real value.
171902 **
171903 ** Varint values are encoded in the same way as varints in the SQLite
171904 ** record format.
171905 **
171906 ** CHANGESET FORMAT:
171907 **
171908 ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
171909 ** one or more tables. Operations on a single table are grouped together,
171910 ** but may occur in any order (i.e. deletes, updates and inserts are all
171911 ** mixed together).
171912 **
171913 ** Each group of changes begins with a table header:
171914 **
171915 ** 1 byte: Constant 0x54 (capital 'T')
171916 ** Varint: Number of columns in the table.
171917 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
171918 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
171919 **
171920 ** Followed by one or more changes to the table.
171921 **
171922 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
171923 ** 1 byte: The "indirect-change" flag.
171924 ** old.* record: (delete and update only)
171925 ** new.* record: (insert and update only)
171926 **
171927 ** The "old.*" and "new.*" records, if present, are N field records in the
171928 ** format described above under "RECORD FORMAT", where N is the number of
171929 ** columns in the table. The i'th field of each record is associated with
171930 ** the i'th column of the table, counting from left to right in the order
171931 ** in which columns were declared in the CREATE TABLE statement.
171932 **
171933 ** The new.* record that is part of each INSERT change contains the values
171934 ** that make up the new row. Similarly, the old.* record that is part of each
171935 ** DELETE change contains the values that made up the row that was deleted
171936 ** from the database. In the changeset format, the records that are part
171937 ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
171938 ** fields.
171939 **
171940 ** Within the old.* record associated with an UPDATE change, all fields
171941 ** associated with table columns that are not PRIMARY KEY columns and are
171942 ** not modified by the UPDATE change are set to "undefined". Other fields
171943 ** are set to the values that made up the row before the UPDATE that the
171944 ** change records took place. Within the new.* record, fields associated
171945 ** with table columns modified by the UPDATE change contain the new
171946 ** values. Fields associated with table columns that are not modified
171947 ** are set to "undefined".
171948 **
171949 ** PATCHSET FORMAT:
171950 **
171951 ** A patchset is also a collection of changes. It is similar to a changeset,
171952 ** but leaves undefined those fields that are not useful if no conflict
171953 ** resolution is required when applying the changeset.
171954 **
171955 ** Each group of changes begins with a table header:
171956 **
171957 ** 1 byte: Constant 0x50 (capital 'P')
171958 ** Varint: Number of columns in the table.
171959 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
171960 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
171961 **
171962 ** Followed by one or more changes to the table.
171963 **
171964 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
171965 ** 1 byte: The "indirect-change" flag.
171966 ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
171967 ** full record for INSERT).
171968 **
171969 ** As in the changeset format, each field of the single record that is part
171970 ** of a patchset change is associated with the correspondingly positioned
171971 ** table column, counting from left to right within the CREATE TABLE
171972 ** statement.
171973 **
171974 ** For a DELETE change, all fields within the record except those associated
171975 ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
171976 ** contain the values identifying the row to delete.
171977 **
171978 ** For an UPDATE change, all fields except those associated with PRIMARY KEY
171979 ** columns and columns that are modified by the UPDATE are set to "undefined".
171980 ** PRIMARY KEY fields contain the values identifying the table row to update,
171981 ** and fields associated with modified columns contain the new column values.
171982 **
171983 ** The records associated with INSERT changes are in the same format as for
171984 ** changesets. It is not possible for a record associated with an INSERT
171985 ** change to contain a field set to "undefined".
171986 */
171987 
171988 /*
171989 ** For each row modified during a session, there exists a single instance of
171990 ** this structure stored in a SessionTable.aChange[] hash table.
171991 */
171992 struct SessionChange {
171993  int op; /* One of UPDATE, DELETE, INSERT */
171994  int bIndirect; /* True if this change is "indirect" */
171995  int nRecord; /* Number of bytes in buffer aRecord[] */
171996  u8 *aRecord; /* Buffer containing old.* record */
171997  SessionChange *pNext; /* For hash-table collisions */
171998 };
171999 
172000 /*
172001 ** Write a varint with value iVal into the buffer at aBuf. Return the
172002 ** number of bytes written.
172003 */
172004 static int sessionVarintPut(u8 *aBuf, int iVal){
172005  return putVarint32(aBuf, iVal);
172006 }
172007 
172008 /*
172009 ** Return the number of bytes required to store value iVal as a varint.
172010 */
172011 static int sessionVarintLen(int iVal){
172012  return sqlite3VarintLen(iVal);
172013 }
172014 
172015 /*
172016 ** Read a varint value from aBuf[] into *piVal. Return the number of
172017 ** bytes read.
172018 */
172019 static int sessionVarintGet(u8 *aBuf, int *piVal){
172020  return getVarint32(aBuf, *piVal);
172021 }
172022 
172023 /* Load an unaligned and unsigned 32-bit integer */
172024 #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
172025 
172026 /*
172027 ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
172028 ** the value read.
172029 */
172030 static sqlite3_int64 sessionGetI64(u8 *aRec){
172031  u64 x = SESSION_UINT32(aRec);
172032  u32 y = SESSION_UINT32(aRec+4);
172033  x = (x<<32) + y;
172034  return (sqlite3_int64)x;
172035 }
172036 
172037 /*
172038 ** Write a 64-bit big-endian integer value to the buffer aBuf[].
172039 */
172040 static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
172041  aBuf[0] = (i>>56) & 0xFF;
172042  aBuf[1] = (i>>48) & 0xFF;
172043  aBuf[2] = (i>>40) & 0xFF;
172044  aBuf[3] = (i>>32) & 0xFF;
172045  aBuf[4] = (i>>24) & 0xFF;
172046  aBuf[5] = (i>>16) & 0xFF;
172047  aBuf[6] = (i>> 8) & 0xFF;
172048  aBuf[7] = (i>> 0) & 0xFF;
172049 }
172050 
172051 /*
172052 ** This function is used to serialize the contents of value pValue (see
172053 ** comment titled "RECORD FORMAT" above).
172054 **
172055 ** If it is non-NULL, the serialized form of the value is written to
172056 ** buffer aBuf. *pnWrite is set to the number of bytes written before
172057 ** returning. Or, if aBuf is NULL, the only thing this function does is
172058 ** set *pnWrite.
172059 **
172060 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
172061 ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
172062 ** SQLITE_NOMEM is returned.
172063 */
172064 static int sessionSerializeValue(
172065  u8 *aBuf, /* If non-NULL, write serialized value here */
172066  sqlite3_value *pValue, /* Value to serialize */
172067  int *pnWrite /* IN/OUT: Increment by bytes written */
172068 ){
172069  int nByte; /* Size of serialized value in bytes */
172070 
172071  if( pValue ){
172072  int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
172073 
172074  eType = sqlite3_value_type(pValue);
172075  if( aBuf ) aBuf[0] = eType;
172076 
172077  switch( eType ){
172078  case SQLITE_NULL:
172079  nByte = 1;
172080  break;
172081 
172082  case SQLITE_INTEGER:
172083  case SQLITE_FLOAT:
172084  if( aBuf ){
172085  /* TODO: SQLite does something special to deal with mixed-endian
172086  ** floating point values (e.g. ARM7). This code probably should
172087  ** too. */
172088  u64 i;
172089  if( eType==SQLITE_INTEGER ){
172090  i = (u64)sqlite3_value_int64(pValue);
172091  }else{
172092  double r;
172093  assert( sizeof(double)==8 && sizeof(u64)==8 );
172094  r = sqlite3_value_double(pValue);
172095  memcpy(&i, &r, 8);
172096  }
172097  sessionPutI64(&aBuf[1], i);
172098  }
172099  nByte = 9;
172100  break;
172101 
172102  default: {
172103  u8 *z;
172104  int n;
172105  int nVarint;
172106 
172107  assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
172108  if( eType==SQLITE_TEXT ){
172109  z = (u8 *)sqlite3_value_text(pValue);
172110  }else{
172111  z = (u8 *)sqlite3_value_blob(pValue);
172112  }
172113  n = sqlite3_value_bytes(pValue);
172114  if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
172115  nVarint = sessionVarintLen(n);
172116 
172117  if( aBuf ){
172118  sessionVarintPut(&aBuf[1], n);
172119  memcpy(&aBuf[nVarint + 1], eType==SQLITE_TEXT ?
172120  sqlite3_value_text(pValue) : sqlite3_value_blob(pValue), n
172121  );
172122  }
172123 
172124  nByte = 1 + nVarint + n;
172125  break;
172126  }
172127  }
172128  }else{
172129  nByte = 1;
172130  if( aBuf ) aBuf[0] = '\0';
172131  }
172132 
172133  if( pnWrite ) *pnWrite += nByte;
172134  return SQLITE_OK;
172135 }
172136 
172137 
172138 /*
172139 ** This macro is used to calculate hash key values for data structures. In
172140 ** order to use this macro, the entire data structure must be represented
172141 ** as a series of unsigned integers. In order to calculate a hash-key value
172142 ** for a data structure represented as three such integers, the macro may
172143 ** then be used as follows:
172144 **
172145 ** int hash_key_value;
172146 ** hash_key_value = HASH_APPEND(0, <value 1>);
172147 ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
172148 ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
172149 **
172150 ** In practice, the data structures this macro is used for are the primary
172151 ** key values of modified rows.
172152 */
172153 #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
172154 
172155 /*
172156 ** Append the hash of the 64-bit integer passed as the second argument to the
172157 ** hash-key value passed as the first. Return the new hash-key value.
172158 */
172159 static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
172160  h = HASH_APPEND(h, i & 0xFFFFFFFF);
172161  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
172162 }
172163 
172164 /*
172165 ** Append the hash of the blob passed via the second and third arguments to
172166 ** the hash-key value passed as the first. Return the new hash-key value.
172167 */
172168 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
172169  int i;
172170  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
172171  return h;
172172 }
172173 
172174 /*
172175 ** Append the hash of the data type passed as the second argument to the
172176 ** hash-key value passed as the first. Return the new hash-key value.
172177 */
172178 static unsigned int sessionHashAppendType(unsigned int h, int eType){
172179  return HASH_APPEND(h, eType);
172180 }
172181 
172182 /*
172183 ** This function may only be called from within a pre-update callback.
172184 ** It calculates a hash based on the primary key values of the old.* or
172185 ** new.* row currently available and, assuming no error occurs, writes it to
172186 ** *piHash before returning. If the primary key contains one or more NULL
172187 ** values, *pbNullPK is set to true before returning.
172188 **
172189 ** If an error occurs, an SQLite error code is returned and the final values
172190 ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
172191 ** and the output variables are set as described above.
172192 */
172193 static int sessionPreupdateHash(
172194  sqlite3_session *pSession, /* Session object that owns pTab */
172195  SessionTable *pTab, /* Session table handle */
172196  int bNew, /* True to hash the new.* PK */
172197  int *piHash, /* OUT: Hash value */
172198  int *pbNullPK /* OUT: True if there are NULL values in PK */
172199 ){
172200  unsigned int h = 0; /* Hash value to return */
172201  int i; /* Used to iterate through columns */
172202 
172203  assert( *pbNullPK==0 );
172204  assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
172205  for(i=0; i<pTab->nCol; i++){
172206  if( pTab->abPK[i] ){
172207  int rc;
172208  int eType;
172209  sqlite3_value *pVal;
172210 
172211  if( bNew ){
172212  rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
172213  }else{
172214  rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
172215  }
172216  if( rc!=SQLITE_OK ) return rc;
172217 
172218  eType = sqlite3_value_type(pVal);
172219  h = sessionHashAppendType(h, eType);
172220  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172221  i64 iVal;
172222  if( eType==SQLITE_INTEGER ){
172223  iVal = sqlite3_value_int64(pVal);
172224  }else{
172225  double rVal = sqlite3_value_double(pVal);
172226  assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
172227  memcpy(&iVal, &rVal, 8);
172228  }
172229  h = sessionHashAppendI64(h, iVal);
172230  }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172231  const u8 *z;
172232  int n;
172233  if( eType==SQLITE_TEXT ){
172234  z = (const u8 *)sqlite3_value_text(pVal);
172235  }else{
172236  z = (const u8 *)sqlite3_value_blob(pVal);
172237  }
172238  n = sqlite3_value_bytes(pVal);
172239  if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
172240  h = sessionHashAppendBlob(h, n, z);
172241  }else{
172242  assert( eType==SQLITE_NULL );
172243  *pbNullPK = 1;
172244  }
172245  }
172246  }
172247 
172248  *piHash = (h % pTab->nChange);
172249  return SQLITE_OK;
172250 }
172251 
172252 /*
172253 ** The buffer that the argument points to contains a serialized SQL value.
172254 ** Return the number of bytes of space occupied by the value (including
172255 ** the type byte).
172256 */
172257 static int sessionSerialLen(u8 *a){
172258  int e = *a;
172259  int n;
172260  if( e==0 ) return 1;
172261  if( e==SQLITE_NULL ) return 1;
172262  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
172263  return sessionVarintGet(&a[1], &n) + 1 + n;
172264 }
172265 
172266 /*
172267 ** Based on the primary key values stored in change aRecord, calculate a
172268 ** hash key. Assume the has table has nBucket buckets. The hash keys
172269 ** calculated by this function are compatible with those calculated by
172270 ** sessionPreupdateHash().
172271 **
172272 ** The bPkOnly argument is non-zero if the record at aRecord[] is from
172273 ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
172274 */
172275 static unsigned int sessionChangeHash(
172276  SessionTable *pTab, /* Table handle */
172277  int bPkOnly, /* Record consists of PK fields only */
172278  u8 *aRecord, /* Change record */
172279  int nBucket /* Assume this many buckets in hash table */
172280 ){
172281  unsigned int h = 0; /* Value to return */
172282  int i; /* Used to iterate through columns */
172283  u8 *a = aRecord; /* Used to iterate through change record */
172284 
172285  for(i=0; i<pTab->nCol; i++){
172286  int eType = *a;
172287  int isPK = pTab->abPK[i];
172288  if( bPkOnly && isPK==0 ) continue;
172289 
172290  /* It is not possible for eType to be SQLITE_NULL here. The session
172291  ** module does not record changes for rows with NULL values stored in
172292  ** primary key columns. */
172293  assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
172294  || eType==SQLITE_TEXT || eType==SQLITE_BLOB
172295  || eType==SQLITE_NULL || eType==0
172296  );
172297  assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
172298 
172299  if( isPK ){
172300  a++;
172301  h = sessionHashAppendType(h, eType);
172302  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172303  h = sessionHashAppendI64(h, sessionGetI64(a));
172304  a += 8;
172305  }else{
172306  int n;
172307  a += sessionVarintGet(a, &n);
172308  h = sessionHashAppendBlob(h, n, a);
172309  a += n;
172310  }
172311  }else{
172312  a += sessionSerialLen(a);
172313  }
172314  }
172315  return (h % nBucket);
172316 }
172317 
172318 /*
172319 ** Arguments aLeft and aRight are pointers to change records for table pTab.
172320 ** This function returns true if the two records apply to the same row (i.e.
172321 ** have the same values stored in the primary key columns), or false
172322 ** otherwise.
172323 */
172324 static int sessionChangeEqual(
172325  SessionTable *pTab, /* Table used for PK definition */
172326  int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
172327  u8 *aLeft, /* Change record */
172328  int bRightPkOnly, /* True if aRight[] contains PK fields only */
172329  u8 *aRight /* Change record */
172330 ){
172331  u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
172332  u8 *a2 = aRight; /* Cursor to iterate through aRight */
172333  int iCol; /* Used to iterate through table columns */
172334 
172335  for(iCol=0; iCol<pTab->nCol; iCol++){
172336  if( pTab->abPK[iCol] ){
172337  int n1 = sessionSerialLen(a1);
172338  int n2 = sessionSerialLen(a2);
172339 
172340  if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
172341  return 0;
172342  }
172343  a1 += n1;
172344  a2 += n2;
172345  }else{
172346  if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
172347  if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
172348  }
172349  }
172350 
172351  return 1;
172352 }
172353 
172354 /*
172355 ** Arguments aLeft and aRight both point to buffers containing change
172356 ** records with nCol columns. This function "merges" the two records into
172357 ** a single records which is written to the buffer at *paOut. *paOut is
172358 ** then set to point to one byte after the last byte written before
172359 ** returning.
172360 **
172361 ** The merging of records is done as follows: For each column, if the
172362 ** aRight record contains a value for the column, copy the value from
172363 ** their. Otherwise, if aLeft contains a value, copy it. If neither
172364 ** record contains a value for a given column, then neither does the
172365 ** output record.
172366 */
172367 static void sessionMergeRecord(
172368  u8 **paOut,
172369  int nCol,
172370  u8 *aLeft,
172371  u8 *aRight
172372 ){
172373  u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
172374  u8 *a2 = aRight; /* Cursor used to iterate through aRight */
172375  u8 *aOut = *paOut; /* Output cursor */
172376  int iCol; /* Used to iterate from 0 to nCol */
172377 
172378  for(iCol=0; iCol<nCol; iCol++){
172379  int n1 = sessionSerialLen(a1);
172380  int n2 = sessionSerialLen(a2);
172381  if( *a2 ){
172382  memcpy(aOut, a2, n2);
172383  aOut += n2;
172384  }else{
172385  memcpy(aOut, a1, n1);
172386  aOut += n1;
172387  }
172388  a1 += n1;
172389  a2 += n2;
172390  }
172391 
172392  *paOut = aOut;
172393 }
172394 
172395 /*
172396 ** This is a helper function used by sessionMergeUpdate().
172397 **
172398 ** When this function is called, both *paOne and *paTwo point to a value
172399 ** within a change record. Before it returns, both have been advanced so
172400 ** as to point to the next value in the record.
172401 **
172402 ** If, when this function is called, *paTwo points to a valid value (i.e.
172403 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
172404 ** pointer is returned and *pnVal is set to the number of bytes in the
172405 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
172406 ** set to the number of bytes in the value at *paOne. If *paOne points
172407 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
172408 **
172409 ** if( *paTwo is valid ) return *paTwo;
172410 ** return *paOne;
172411 **
172412 */
172413 static u8 *sessionMergeValue(
172414  u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
172415  u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
172416  int *pnVal /* OUT: Bytes in returned value */
172417 ){
172418  u8 *a1 = *paOne;
172419  u8 *a2 = *paTwo;
172420  u8 *pRet = 0;
172421  int n1;
172422 
172423  assert( a1 );
172424  if( a2 ){
172425  int n2 = sessionSerialLen(a2);
172426  if( *a2 ){
172427  *pnVal = n2;
172428  pRet = a2;
172429  }
172430  *paTwo = &a2[n2];
172431  }
172432 
172433  n1 = sessionSerialLen(a1);
172434  if( pRet==0 ){
172435  *pnVal = n1;
172436  pRet = a1;
172437  }
172438  *paOne = &a1[n1];
172439 
172440  return pRet;
172441 }
172442 
172443 /*
172444 ** This function is used by changeset_concat() to merge two UPDATE changes
172445 ** on the same row.
172446 */
172447 static int sessionMergeUpdate(
172448  u8 **paOut, /* IN/OUT: Pointer to output buffer */
172449  SessionTable *pTab, /* Table change pertains to */
172450  int bPatchset, /* True if records are patchset records */
172451  u8 *aOldRecord1, /* old.* record for first change */
172452  u8 *aOldRecord2, /* old.* record for second change */
172453  u8 *aNewRecord1, /* new.* record for first change */
172454  u8 *aNewRecord2 /* new.* record for second change */
172455 ){
172456  u8 *aOld1 = aOldRecord1;
172457  u8 *aOld2 = aOldRecord2;
172458  u8 *aNew1 = aNewRecord1;
172459  u8 *aNew2 = aNewRecord2;
172460 
172461  u8 *aOut = *paOut;
172462  int i;
172463 
172464  if( bPatchset==0 ){
172465  int bRequired = 0;
172466 
172467  assert( aOldRecord1 && aNewRecord1 );
172468 
172469  /* Write the old.* vector first. */
172470  for(i=0; i<pTab->nCol; i++){
172471  int nOld;
172472  u8 *aOld;
172473  int nNew;
172474  u8 *aNew;
172475 
172476  aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
172477  aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
172478  if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
172479  if( pTab->abPK[i]==0 ) bRequired = 1;
172480  memcpy(aOut, aOld, nOld);
172481  aOut += nOld;
172482  }else{
172483  *(aOut++) = '\0';
172484  }
172485  }
172486 
172487  if( !bRequired ) return 0;
172488  }
172489 
172490  /* Write the new.* vector */
172491  aOld1 = aOldRecord1;
172492  aOld2 = aOldRecord2;
172493  aNew1 = aNewRecord1;
172494  aNew2 = aNewRecord2;
172495  for(i=0; i<pTab->nCol; i++){
172496  int nOld;
172497  u8 *aOld;
172498  int nNew;
172499  u8 *aNew;
172500 
172501  aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
172502  aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
172503  if( bPatchset==0
172504  && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
172505  ){
172506  *(aOut++) = '\0';
172507  }else{
172508  memcpy(aOut, aNew, nNew);
172509  aOut += nNew;
172510  }
172511  }
172512 
172513  *paOut = aOut;
172514  return 1;
172515 }
172516 
172517 /*
172518 ** This function is only called from within a pre-update-hook callback.
172519 ** It determines if the current pre-update-hook change affects the same row
172520 ** as the change stored in argument pChange. If so, it returns true. Otherwise
172521 ** if the pre-update-hook does not affect the same row as pChange, it returns
172522 ** false.
172523 */
172524 static int sessionPreupdateEqual(
172525  sqlite3_session *pSession, /* Session object that owns SessionTable */
172526  SessionTable *pTab, /* Table associated with change */
172527  SessionChange *pChange, /* Change to compare to */
172528  int op /* Current pre-update operation */
172529 ){
172530  int iCol; /* Used to iterate through columns */
172531  u8 *a = pChange->aRecord; /* Cursor used to scan change record */
172532 
172533  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
172534  for(iCol=0; iCol<pTab->nCol; iCol++){
172535  if( !pTab->abPK[iCol] ){
172536  a += sessionSerialLen(a);
172537  }else{
172538  sqlite3_value *pVal; /* Value returned by preupdate_new/old */
172539  int rc; /* Error code from preupdate_new/old */
172540  int eType = *a++; /* Type of value from change record */
172541 
172542  /* The following calls to preupdate_new() and preupdate_old() can not
172543  ** fail. This is because they cache their return values, and by the
172544  ** time control flows to here they have already been called once from
172545  ** within sessionPreupdateHash(). The first two asserts below verify
172546  ** this (that the method has already been called). */
172547  if( op==SQLITE_INSERT ){
172548  /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
172549  rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
172550  }else{
172551  /* assert( db->pPreUpdate->pUnpacked ); */
172552  rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
172553  }
172554  assert( rc==SQLITE_OK );
172555  if( sqlite3_value_type(pVal)!=eType ) return 0;
172556 
172557  /* A SessionChange object never has a NULL value in a PK column */
172558  assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
172559  || eType==SQLITE_BLOB || eType==SQLITE_TEXT
172560  );
172561 
172562  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172563  i64 iVal = sessionGetI64(a);
172564  a += 8;
172565  if( eType==SQLITE_INTEGER ){
172566  if( sqlite3_value_int64(pVal)!=iVal ) return 0;
172567  }else{
172568  double rVal;
172569  assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
172570  memcpy(&rVal, &iVal, 8);
172571  if( sqlite3_value_double(pVal)!=rVal ) return 0;
172572  }
172573  }else{
172574  int n;
172575  const u8 *z;
172576  a += sessionVarintGet(a, &n);
172577  if( sqlite3_value_bytes(pVal)!=n ) return 0;
172578  if( eType==SQLITE_TEXT ){
172579  z = sqlite3_value_text(pVal);
172580  }else{
172581  z = sqlite3_value_blob(pVal);
172582  }
172583  if( memcmp(a, z, n) ) return 0;
172584  a += n;
172585  break;
172586  }
172587  }
172588  }
172589 
172590  return 1;
172591 }
172592 
172593 /*
172594 ** If required, grow the hash table used to store changes on table pTab
172595 ** (part of the session pSession). If a fatal OOM error occurs, set the
172596 ** session object to failed and return SQLITE_ERROR. Otherwise, return
172597 ** SQLITE_OK.
172598 **
172599 ** It is possible that a non-fatal OOM error occurs in this function. In
172600 ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
172601 ** Growing the hash table in this case is a performance optimization only,
172602 ** it is not required for correct operation.
172603 */
172604 static int sessionGrowHash(int bPatchset, SessionTable *pTab){
172605  if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
172606  int i;
172607  SessionChange **apNew;
172608  int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
172609 
172610  apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
172611  if( apNew==0 ){
172612  if( pTab->nChange==0 ){
172613  return SQLITE_ERROR;
172614  }
172615  return SQLITE_OK;
172616  }
172617  memset(apNew, 0, sizeof(SessionChange *) * nNew);
172618 
172619  for(i=0; i<pTab->nChange; i++){
172620  SessionChange *p;
172621  SessionChange *pNext;
172622  for(p=pTab->apChange[i]; p; p=pNext){
172623  int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
172624  int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
172625  pNext = p->pNext;
172626  p->pNext = apNew[iHash];
172627  apNew[iHash] = p;
172628  }
172629  }
172630 
172631  sqlite3_free(pTab->apChange);
172632  pTab->nChange = nNew;
172633  pTab->apChange = apNew;
172634  }
172635 
172636  return SQLITE_OK;
172637 }
172638 
172639 /*
172640 ** This function queries the database for the names of the columns of table
172641 ** zThis, in schema zDb. It is expected that the table has nCol columns. If
172642 ** not, SQLITE_SCHEMA is returned and none of the output variables are
172643 ** populated.
172644 **
172645 ** Otherwise, if they are not NULL, variable *pnCol is set to the number
172646 ** of columns in the database table and variable *pzTab is set to point to a
172647 ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
172648 ** point to an array of pointers to column names. And *pabPK (again, if not
172649 ** NULL) is set to point to an array of booleans - true if the corresponding
172650 ** column is part of the primary key.
172651 **
172652 ** For example, if the table is declared as:
172653 **
172654 ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
172655 **
172656 ** Then the four output variables are populated as follows:
172657 **
172658 ** *pnCol = 4
172659 ** *pzTab = "tbl1"
172660 ** *pazCol = {"w", "x", "y", "z"}
172661 ** *pabPK = {1, 0, 0, 1}
172662 **
172663 ** All returned buffers are part of the same single allocation, which must
172664 ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
172665 ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
172666 ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
172667 */
172668 static int sessionTableInfo(
172669  sqlite3 *db, /* Database connection */
172670  const char *zDb, /* Name of attached database (e.g. "main") */
172671  const char *zThis, /* Table name */
172672  int *pnCol, /* OUT: number of columns */
172673  const char **pzTab, /* OUT: Copy of zThis */
172674  const char ***pazCol, /* OUT: Array of column names for table */
172675  u8 **pabPK /* OUT: Array of booleans - true for PK col */
172676 ){
172677  char *zPragma;
172678  sqlite3_stmt *pStmt;
172679  int rc;
172680  int nByte;
172681  int nDbCol = 0;
172682  int nThis;
172683  int i;
172684  u8 *pAlloc = 0;
172685  char **azCol = 0;
172686  u8 *abPK = 0;
172687 
172688  assert( pazCol && pabPK );
172689 
172690  nThis = sqlite3Strlen30(zThis);
172691  zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
172692  if( !zPragma ) return SQLITE_NOMEM;
172693 
172694  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
172695  sqlite3_free(zPragma);
172696  if( rc!=SQLITE_OK ) return rc;
172697 
172698  nByte = nThis + 1;
172699  while( SQLITE_ROW==sqlite3_step(pStmt) ){
172700  nByte += sqlite3_column_bytes(pStmt, 1);
172701  nDbCol++;
172702  }
172703  rc = sqlite3_reset(pStmt);
172704 
172705  if( rc==SQLITE_OK ){
172706  nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
172707  pAlloc = sqlite3_malloc(nByte);
172708  if( pAlloc==0 ){
172709  rc = SQLITE_NOMEM;
172710  }
172711  }
172712  if( rc==SQLITE_OK ){
172713  azCol = (char **)pAlloc;
172714  pAlloc = (u8 *)&azCol[nDbCol];
172715  abPK = (u8 *)pAlloc;
172716  pAlloc = &abPK[nDbCol];
172717  if( pzTab ){
172718  memcpy(pAlloc, zThis, nThis+1);
172719  *pzTab = (char *)pAlloc;
172720  pAlloc += nThis+1;
172721  }
172722 
172723  i = 0;
172724  while( SQLITE_ROW==sqlite3_step(pStmt) ){
172725  int nName = sqlite3_column_bytes(pStmt, 1);
172726  const unsigned char *zName = sqlite3_column_text(pStmt, 1);
172727  if( zName==0 ) break;
172728  memcpy(pAlloc, zName, nName+1);
172729  azCol[i] = (char *)pAlloc;
172730  pAlloc += nName+1;
172731  abPK[i] = sqlite3_column_int(pStmt, 5);
172732  i++;
172733  }
172734  rc = sqlite3_reset(pStmt);
172735 
172736  }
172737 
172738  /* If successful, populate the output variables. Otherwise, zero them and
172739  ** free any allocation made. An error code will be returned in this case.
172740  */
172741  if( rc==SQLITE_OK ){
172742  *pazCol = (const char **)azCol;
172743  *pabPK = abPK;
172744  *pnCol = nDbCol;
172745  }else{
172746  *pazCol = 0;
172747  *pabPK = 0;
172748  *pnCol = 0;
172749  if( pzTab ) *pzTab = 0;
172750  sqlite3_free(azCol);
172751  }
172752  sqlite3_finalize(pStmt);
172753  return rc;
172754 }
172755 
172756 /*
172757 ** This function is only called from within a pre-update handler for a
172758 ** write to table pTab, part of session pSession. If this is the first
172759 ** write to this table, initalize the SessionTable.nCol, azCol[] and
172760 ** abPK[] arrays accordingly.
172761 **
172762 ** If an error occurs, an error code is stored in sqlite3_session.rc and
172763 ** non-zero returned. Or, if no error occurs but the table has no primary
172764 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
172765 ** indicate that updates on this table should be ignored. SessionTable.abPK
172766 ** is set to NULL in this case.
172767 */
172768 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
172769  if( pTab->nCol==0 ){
172770  u8 *abPK;
172771  assert( pTab->azCol==0 || pTab->abPK==0 );
172772  pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
172773  pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
172774  );
172775  if( pSession->rc==SQLITE_OK ){
172776  int i;
172777  for(i=0; i<pTab->nCol; i++){
172778  if( abPK[i] ){
172779  pTab->abPK = abPK;
172780  break;
172781  }
172782  }
172783  }
172784  }
172785  return (pSession->rc || pTab->abPK==0);
172786 }
172787 
172788 /*
172789 ** This function is only called from with a pre-update-hook reporting a
172790 ** change on table pTab (attached to session pSession). The type of change
172791 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
172792 **
172793 ** Unless one is already present or an error occurs, an entry is added
172794 ** to the changed-rows hash table associated with table pTab.
172795 */
172796 static void sessionPreupdateOneChange(
172797  int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
172798  sqlite3_session *pSession, /* Session object pTab is attached to */
172799  SessionTable *pTab /* Table that change applies to */
172800 ){
172801  int iHash;
172802  int bNull = 0;
172803  int rc = SQLITE_OK;
172804 
172805  if( pSession->rc ) return;
172806 
172807  /* Load table details if required */
172808  if( sessionInitTable(pSession, pTab) ) return;
172809 
172810  /* Check the number of columns in this xPreUpdate call matches the
172811  ** number of columns in the table. */
172812  if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
172813  pSession->rc = SQLITE_SCHEMA;
172814  return;
172815  }
172816 
172817  /* Grow the hash table if required */
172818  if( sessionGrowHash(0, pTab) ){
172819  pSession->rc = SQLITE_NOMEM;
172820  return;
172821  }
172822 
172823  /* Calculate the hash-key for this change. If the primary key of the row
172824  ** includes a NULL value, exit early. Such changes are ignored by the
172825  ** session module. */
172826  rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
172827  if( rc!=SQLITE_OK ) goto error_out;
172828 
172829  if( bNull==0 ){
172830  /* Search the hash table for an existing record for this row. */
172831  SessionChange *pC;
172832  for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
172833  if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
172834  }
172835 
172836  if( pC==0 ){
172837  /* Create a new change object containing all the old values (if
172838  ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
172839  ** values (if this is an INSERT). */
172840  SessionChange *pChange; /* New change object */
172841  int nByte; /* Number of bytes to allocate */
172842  int i; /* Used to iterate through columns */
172843 
172844  assert( rc==SQLITE_OK );
172845  pTab->nEntry++;
172846 
172847  /* Figure out how large an allocation is required */
172848  nByte = sizeof(SessionChange);
172849  for(i=0; i<pTab->nCol; i++){
172850  sqlite3_value *p = 0;
172851  if( op!=SQLITE_INSERT ){
172852  TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
172853  assert( trc==SQLITE_OK );
172854  }else if( pTab->abPK[i] ){
172855  TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
172856  assert( trc==SQLITE_OK );
172857  }
172858 
172859  /* This may fail if SQLite value p contains a utf-16 string that must
172860  ** be converted to utf-8 and an OOM error occurs while doing so. */
172861  rc = sessionSerializeValue(0, p, &nByte);
172862  if( rc!=SQLITE_OK ) goto error_out;
172863  }
172864 
172865  /* Allocate the change object */
172866  pChange = (SessionChange *)sqlite3_malloc(nByte);
172867  if( !pChange ){
172868  rc = SQLITE_NOMEM;
172869  goto error_out;
172870  }else{
172871  memset(pChange, 0, sizeof(SessionChange));
172872  pChange->aRecord = (u8 *)&pChange[1];
172873  }
172874 
172875  /* Populate the change object. None of the preupdate_old(),
172876  ** preupdate_new() or SerializeValue() calls below may fail as all
172877  ** required values and encodings have already been cached in memory.
172878  ** It is not possible for an OOM to occur in this block. */
172879  nByte = 0;
172880  for(i=0; i<pTab->nCol; i++){
172881  sqlite3_value *p = 0;
172882  if( op!=SQLITE_INSERT ){
172883  pSession->hook.xOld(pSession->hook.pCtx, i, &p);
172884  }else if( pTab->abPK[i] ){
172885  pSession->hook.xNew(pSession->hook.pCtx, i, &p);
172886  }
172887  sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
172888  }
172889 
172890  /* Add the change to the hash-table */
172891  if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
172892  pChange->bIndirect = 1;
172893  }
172894  pChange->nRecord = nByte;
172895  pChange->op = op;
172896  pChange->pNext = pTab->apChange[iHash];
172897  pTab->apChange[iHash] = pChange;
172898 
172899  }else if( pC->bIndirect ){
172900  /* If the existing change is considered "indirect", but this current
172901  ** change is "direct", mark the change object as direct. */
172902  if( pSession->hook.xDepth(pSession->hook.pCtx)==0
172903  && pSession->bIndirect==0
172904  ){
172905  pC->bIndirect = 0;
172906  }
172907  }
172908  }
172909 
172910  /* If an error has occurred, mark the session object as failed. */
172911  error_out:
172912  if( rc!=SQLITE_OK ){
172913  pSession->rc = rc;
172914  }
172915 }
172916 
172917 static int sessionFindTable(
172918  sqlite3_session *pSession,
172919  const char *zName,
172920  SessionTable **ppTab
172921 ){
172922  int rc = SQLITE_OK;
172923  int nName = sqlite3Strlen30(zName);
172924  SessionTable *pRet;
172925 
172926  /* Search for an existing table */
172927  for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
172928  if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
172929  }
172930 
172931  if( pRet==0 && pSession->bAutoAttach ){
172932  /* If there is a table-filter configured, invoke it. If it returns 0,
172933  ** do not automatically add the new table. */
172934  if( pSession->xTableFilter==0
172935  || pSession->xTableFilter(pSession->pFilterCtx, zName)
172936  ){
172937  rc = sqlite3session_attach(pSession, zName);
172938  if( rc==SQLITE_OK ){
172939  for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
172940  assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
172941  }
172942  }
172943  }
172944 
172945  assert( rc==SQLITE_OK || pRet==0 );
172946  *ppTab = pRet;
172947  return rc;
172948 }
172949 
172950 /*
172951 ** The 'pre-update' hook registered by this module with SQLite databases.
172952 */
172953 static void xPreUpdate(
172954  void *pCtx, /* Copy of third arg to preupdate_hook() */
172955  sqlite3 *db, /* Database handle */
172956  int op, /* SQLITE_UPDATE, DELETE or INSERT */
172957  char const *zDb, /* Database name */
172958  char const *zName, /* Table name */
172959  sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
172960  sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
172961 ){
172962  sqlite3_session *pSession;
172963  int nDb = sqlite3Strlen30(zDb);
172964 
172965  assert( sqlite3_mutex_held(db->mutex) );
172966 
172967  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
172968  SessionTable *pTab;
172969 
172970  /* If this session is attached to a different database ("main", "temp"
172971  ** etc.), or if it is not currently enabled, there is nothing to do. Skip
172972  ** to the next session object attached to this database. */
172973  if( pSession->bEnable==0 ) continue;
172974  if( pSession->rc ) continue;
172975  if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
172976 
172977  pSession->rc = sessionFindTable(pSession, zName, &pTab);
172978  if( pTab ){
172979  assert( pSession->rc==SQLITE_OK );
172980  sessionPreupdateOneChange(op, pSession, pTab);
172981  if( op==SQLITE_UPDATE ){
172982  sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
172983  }
172984  }
172985  }
172986 }
172987 
172988 /*
172989 ** The pre-update hook implementations.
172990 */
172991 static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
172992  return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
172993 }
172994 static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
172995  return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
172996 }
172997 static int sessionPreupdateCount(void *pCtx){
172998  return sqlite3_preupdate_count((sqlite3*)pCtx);
172999 }
173000 static int sessionPreupdateDepth(void *pCtx){
173001  return sqlite3_preupdate_depth((sqlite3*)pCtx);
173002 }
173003 
173004 /*
173005 ** Install the pre-update hooks on the session object passed as the only
173006 ** argument.
173007 */
173008 static void sessionPreupdateHooks(
173009  sqlite3_session *pSession
173010 ){
173011  pSession->hook.pCtx = (void*)pSession->db;
173012  pSession->hook.xOld = sessionPreupdateOld;
173013  pSession->hook.xNew = sessionPreupdateNew;
173014  pSession->hook.xCount = sessionPreupdateCount;
173015  pSession->hook.xDepth = sessionPreupdateDepth;
173016 }
173017 
173018 typedef struct SessionDiffCtx SessionDiffCtx;
173019 struct SessionDiffCtx {
173020  sqlite3_stmt *pStmt;
173021  int nOldOff;
173022 };
173023 
173024 /*
173025 ** The diff hook implementations.
173026 */
173027 static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
173028  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
173029  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
173030  return SQLITE_OK;
173031 }
173032 static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
173033  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
173034  *ppVal = sqlite3_column_value(p->pStmt, iVal);
173035  return SQLITE_OK;
173036 }
173037 static int sessionDiffCount(void *pCtx){
173038  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
173039  return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
173040 }
173041 static int sessionDiffDepth(void *pCtx){
173042  return 0;
173043 }
173044 
173045 /*
173046 ** Install the diff hooks on the session object passed as the only
173047 ** argument.
173048 */
173049 static void sessionDiffHooks(
173050  sqlite3_session *pSession,
173051  SessionDiffCtx *pDiffCtx
173052 ){
173053  pSession->hook.pCtx = (void*)pDiffCtx;
173054  pSession->hook.xOld = sessionDiffOld;
173055  pSession->hook.xNew = sessionDiffNew;
173056  pSession->hook.xCount = sessionDiffCount;
173057  pSession->hook.xDepth = sessionDiffDepth;
173058 }
173059 
173060 static char *sessionExprComparePK(
173061  int nCol,
173062  const char *zDb1, const char *zDb2,
173063  const char *zTab,
173064  const char **azCol, u8 *abPK
173065 ){
173066  int i;
173067  const char *zSep = "";
173068  char *zRet = 0;
173069 
173070  for(i=0; i<nCol; i++){
173071  if( abPK[i] ){
173072  zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
173073  zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
173074  );
173075  zSep = " AND ";
173076  if( zRet==0 ) break;
173077  }
173078  }
173079 
173080  return zRet;
173081 }
173082 
173083 static char *sessionExprCompareOther(
173084  int nCol,
173085  const char *zDb1, const char *zDb2,
173086  const char *zTab,
173087  const char **azCol, u8 *abPK
173088 ){
173089  int i;
173090  const char *zSep = "";
173091  char *zRet = 0;
173092  int bHave = 0;
173093 
173094  for(i=0; i<nCol; i++){
173095  if( abPK[i]==0 ){
173096  bHave = 1;
173097  zRet = sqlite3_mprintf(
173098  "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
173099  zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
173100  );
173101  zSep = " OR ";
173102  if( zRet==0 ) break;
173103  }
173104  }
173105 
173106  if( bHave==0 ){
173107  assert( zRet==0 );
173108  zRet = sqlite3_mprintf("0");
173109  }
173110 
173111  return zRet;
173112 }
173113 
173114 static char *sessionSelectFindNew(
173115  int nCol,
173116  const char *zDb1, /* Pick rows in this db only */
173117  const char *zDb2, /* But not in this one */
173118  const char *zTbl, /* Table name */
173119  const char *zExpr
173120 ){
173121  char *zRet = sqlite3_mprintf(
173122  "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
173123  " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
173124  ")",
173125  zDb1, zTbl, zDb2, zTbl, zExpr
173126  );
173127  return zRet;
173128 }
173129 
173130 static int sessionDiffFindNew(
173131  int op,
173132  sqlite3_session *pSession,
173133  SessionTable *pTab,
173134  const char *zDb1,
173135  const char *zDb2,
173136  char *zExpr
173137 ){
173138  int rc = SQLITE_OK;
173139  char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
173140 
173141  if( zStmt==0 ){
173142  rc = SQLITE_NOMEM;
173143  }else{
173144  sqlite3_stmt *pStmt;
173145  rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
173146  if( rc==SQLITE_OK ){
173147  SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
173148  pDiffCtx->pStmt = pStmt;
173149  pDiffCtx->nOldOff = 0;
173150  while( SQLITE_ROW==sqlite3_step(pStmt) ){
173151  sessionPreupdateOneChange(op, pSession, pTab);
173152  }
173153  rc = sqlite3_finalize(pStmt);
173154  }
173155  sqlite3_free(zStmt);
173156  }
173157 
173158  return rc;
173159 }
173160 
173161 static int sessionDiffFindModified(
173162  sqlite3_session *pSession,
173163  SessionTable *pTab,
173164  const char *zFrom,
173165  const char *zExpr
173166 ){
173167  int rc = SQLITE_OK;
173168 
173169  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
173170  pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
173171  );
173172  if( zExpr2==0 ){
173173  rc = SQLITE_NOMEM;
173174  }else{
173175  char *zStmt = sqlite3_mprintf(
173176  "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
173177  pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
173178  );
173179  if( zStmt==0 ){
173180  rc = SQLITE_NOMEM;
173181  }else{
173182  sqlite3_stmt *pStmt;
173183  rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
173184 
173185  if( rc==SQLITE_OK ){
173186  SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
173187  pDiffCtx->pStmt = pStmt;
173188  pDiffCtx->nOldOff = pTab->nCol;
173189  while( SQLITE_ROW==sqlite3_step(pStmt) ){
173190  sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
173191  }
173192  rc = sqlite3_finalize(pStmt);
173193  }
173194  sqlite3_free(zStmt);
173195  }
173196  }
173197 
173198  return rc;
173199 }
173200 
173201 SQLITE_API int sqlite3session_diff(
173202  sqlite3_session *pSession,
173203  const char *zFrom,
173204  const char *zTbl,
173205  char **pzErrMsg
173206 ){
173207  const char *zDb = pSession->zDb;
173208  int rc = pSession->rc;
173209  SessionDiffCtx d;
173210 
173211  memset(&d, 0, sizeof(d));
173212  sessionDiffHooks(pSession, &d);
173213 
173214  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
173215  if( pzErrMsg ) *pzErrMsg = 0;
173216  if( rc==SQLITE_OK ){
173217  char *zExpr = 0;
173218  sqlite3 *db = pSession->db;
173219  SessionTable *pTo; /* Table zTbl */
173220 
173221  /* Locate and if necessary initialize the target table object */
173222  rc = sessionFindTable(pSession, zTbl, &pTo);
173223  if( pTo==0 ) goto diff_out;
173224  if( sessionInitTable(pSession, pTo) ){
173225  rc = pSession->rc;
173226  goto diff_out;
173227  }
173228 
173229  /* Check the table schemas match */
173230  if( rc==SQLITE_OK ){
173231  int bHasPk = 0;
173232  int bMismatch = 0;
173233  int nCol; /* Columns in zFrom.zTbl */
173234  u8 *abPK;
173235  const char **azCol = 0;
173236  rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
173237  if( rc==SQLITE_OK ){
173238  if( pTo->nCol!=nCol ){
173239  bMismatch = 1;
173240  }else{
173241  int i;
173242  for(i=0; i<nCol; i++){
173243  if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
173244  if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
173245  if( abPK[i] ) bHasPk = 1;
173246  }
173247  }
173248 
173249  }
173250  sqlite3_free((char*)azCol);
173251  if( bMismatch ){
173252  *pzErrMsg = sqlite3_mprintf("table schemas do not match");
173253  rc = SQLITE_SCHEMA;
173254  }
173255  if( bHasPk==0 ){
173256  /* Ignore tables with no primary keys */
173257  goto diff_out;
173258  }
173259  }
173260 
173261  if( rc==SQLITE_OK ){
173262  zExpr = sessionExprComparePK(pTo->nCol,
173263  zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
173264  );
173265  }
173266 
173267  /* Find new rows */
173268  if( rc==SQLITE_OK ){
173269  rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
173270  }
173271 
173272  /* Find old rows */
173273  if( rc==SQLITE_OK ){
173274  rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
173275  }
173276 
173277  /* Find modified rows */
173278  if( rc==SQLITE_OK ){
173279  rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
173280  }
173281 
173282  sqlite3_free(zExpr);
173283  }
173284 
173285  diff_out:
173286  sessionPreupdateHooks(pSession);
173287  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
173288  return rc;
173289 }
173290 
173291 /*
173292 ** Create a session object. This session object will record changes to
173293 ** database zDb attached to connection db.
173294 */
173295 SQLITE_API int sqlite3session_create(
173296  sqlite3 *db, /* Database handle */
173297  const char *zDb, /* Name of db (e.g. "main") */
173298  sqlite3_session **ppSession /* OUT: New session object */
173299 ){
173300  sqlite3_session *pNew; /* Newly allocated session object */
173301  sqlite3_session *pOld; /* Session object already attached to db */
173302  int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
173303 
173304  /* Zero the output value in case an error occurs. */
173305  *ppSession = 0;
173306 
173307  /* Allocate and populate the new session object. */
173308  pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
173309  if( !pNew ) return SQLITE_NOMEM;
173310  memset(pNew, 0, sizeof(sqlite3_session));
173311  pNew->db = db;
173312  pNew->zDb = (char *)&pNew[1];
173313  pNew->bEnable = 1;
173314  memcpy(pNew->zDb, zDb, nDb+1);
173315  sessionPreupdateHooks(pNew);
173316 
173317  /* Add the new session object to the linked list of session objects
173318  ** attached to database handle $db. Do this under the cover of the db
173319  ** handle mutex. */
173320  sqlite3_mutex_enter(sqlite3_db_mutex(db));
173321  pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
173322  pNew->pNext = pOld;
173323  sqlite3_mutex_leave(sqlite3_db_mutex(db));
173324 
173325  *ppSession = pNew;
173326  return SQLITE_OK;
173327 }
173328 
173329 /*
173330 ** Free the list of table objects passed as the first argument. The contents
173331 ** of the changed-rows hash tables are also deleted.
173332 */
173333 static void sessionDeleteTable(SessionTable *pList){
173334  SessionTable *pNext;
173335  SessionTable *pTab;
173336 
173337  for(pTab=pList; pTab; pTab=pNext){
173338  int i;
173339  pNext = pTab->pNext;
173340  for(i=0; i<pTab->nChange; i++){
173341  SessionChange *p;
173342  SessionChange *pNextChange;
173343  for(p=pTab->apChange[i]; p; p=pNextChange){
173344  pNextChange = p->pNext;
173345  sqlite3_free(p);
173346  }
173347  }
173348  sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
173349  sqlite3_free(pTab->apChange);
173350  sqlite3_free(pTab);
173351  }
173352 }
173353 
173354 /*
173355 ** Delete a session object previously allocated using sqlite3session_create().
173356 */
173357 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
173358  sqlite3 *db = pSession->db;
173359  sqlite3_session *pHead;
173360  sqlite3_session **pp;
173361 
173362  /* Unlink the session from the linked list of sessions attached to the
173363  ** database handle. Hold the db mutex while doing so. */
173364  sqlite3_mutex_enter(sqlite3_db_mutex(db));
173365  pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
173366  for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
173367  if( (*pp)==pSession ){
173368  *pp = (*pp)->pNext;
173369  if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
173370  break;
173371  }
173372  }
173373  sqlite3_mutex_leave(sqlite3_db_mutex(db));
173374 
173375  /* Delete all attached table objects. And the contents of their
173376  ** associated hash-tables. */
173377  sessionDeleteTable(pSession->pTable);
173378 
173379  /* Free the session object itself. */
173380  sqlite3_free(pSession);
173381 }
173382 
173383 /*
173384 ** Set a table filter on a Session Object.
173385 */
173386 SQLITE_API void sqlite3session_table_filter(
173387  sqlite3_session *pSession,
173388  int(*xFilter)(void*, const char*),
173389  void *pCtx /* First argument passed to xFilter */
173390 ){
173391  pSession->bAutoAttach = 1;
173392  pSession->pFilterCtx = pCtx;
173393  pSession->xTableFilter = xFilter;
173394 }
173395 
173396 /*
173397 ** Attach a table to a session. All subsequent changes made to the table
173398 ** while the session object is enabled will be recorded.
173399 **
173400 ** Only tables that have a PRIMARY KEY defined may be attached. It does
173401 ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
173402 ** or not.
173403 */
173404 SQLITE_API int sqlite3session_attach(
173405  sqlite3_session *pSession, /* Session object */
173406  const char *zName /* Table name */
173407 ){
173408  int rc = SQLITE_OK;
173409  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
173410 
173411  if( !zName ){
173412  pSession->bAutoAttach = 1;
173413  }else{
173414  SessionTable *pTab; /* New table object (if required) */
173415  int nName; /* Number of bytes in string zName */
173416 
173417  /* First search for an existing entry. If one is found, this call is
173418  ** a no-op. Return early. */
173419  nName = sqlite3Strlen30(zName);
173420  for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
173421  if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
173422  }
173423 
173424  if( !pTab ){
173425  /* Allocate new SessionTable object. */
173426  pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
173427  if( !pTab ){
173428  rc = SQLITE_NOMEM;
173429  }else{
173430  /* Populate the new SessionTable object and link it into the list.
173431  ** The new object must be linked onto the end of the list, not
173432  ** simply added to the start of it in order to ensure that tables
173433  ** appear in the correct order when a changeset or patchset is
173434  ** eventually generated. */
173435  SessionTable **ppTab;
173436  memset(pTab, 0, sizeof(SessionTable));
173437  pTab->zName = (char *)&pTab[1];
173438  memcpy(pTab->zName, zName, nName+1);
173439  for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
173440  *ppTab = pTab;
173441  }
173442  }
173443  }
173444 
173445  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
173446  return rc;
173447 }
173448 
173449 /*
173450 ** Ensure that there is room in the buffer to append nByte bytes of data.
173451 ** If not, use sqlite3_realloc() to grow the buffer so that there is.
173452 **
173453 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
173454 ** set *pRc to SQLITE_NOMEM and return non-zero.
173455 */
173456 static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
173457  if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
173458  u8 *aNew;
173459  int nNew = p->nAlloc ? p->nAlloc : 128;
173460  do {
173461  nNew = nNew*2;
173462  }while( nNew<(p->nBuf+nByte) );
173463 
173464  aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
173465  if( 0==aNew ){
173466  *pRc = SQLITE_NOMEM;
173467  }else{
173468  p->aBuf = aNew;
173469  p->nAlloc = nNew;
173470  }
173471  }
173472  return (*pRc!=SQLITE_OK);
173473 }
173474 
173475 /*
173476 ** Append the value passed as the second argument to the buffer passed
173477 ** as the first.
173478 **
173479 ** This function is a no-op if *pRc is non-zero when it is called.
173480 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
173481 ** before returning.
173482 */
173483 static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
173484  int rc = *pRc;
173485  if( rc==SQLITE_OK ){
173486  int nByte = 0;
173487  rc = sessionSerializeValue(0, pVal, &nByte);
173488  sessionBufferGrow(p, nByte, &rc);
173489  if( rc==SQLITE_OK ){
173490  rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
173491  p->nBuf += nByte;
173492  }else{
173493  *pRc = rc;
173494  }
173495  }
173496 }
173497 
173498 /*
173499 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173500 ** called. Otherwise, append a single byte to the buffer.
173501 **
173502 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173503 ** returning.
173504 */
173505 static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
173506  if( 0==sessionBufferGrow(p, 1, pRc) ){
173507  p->aBuf[p->nBuf++] = v;
173508  }
173509 }
173510 
173511 /*
173512 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173513 ** called. Otherwise, append a single varint to the buffer.
173514 **
173515 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173516 ** returning.
173517 */
173518 static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
173519  if( 0==sessionBufferGrow(p, 9, pRc) ){
173520  p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
173521  }
173522 }
173523 
173524 /*
173525 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173526 ** called. Otherwise, append a blob of data to the buffer.
173527 **
173528 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173529 ** returning.
173530 */
173531 static void sessionAppendBlob(
173532  SessionBuffer *p,
173533  const u8 *aBlob,
173534  int nBlob,
173535  int *pRc
173536 ){
173537  if( 0==sessionBufferGrow(p, nBlob, pRc) ){
173538  memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
173539  p->nBuf += nBlob;
173540  }
173541 }
173542 
173543 /*
173544 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173545 ** called. Otherwise, append a string to the buffer. All bytes in the string
173546 ** up to (but not including) the nul-terminator are written to the buffer.
173547 **
173548 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173549 ** returning.
173550 */
173551 static void sessionAppendStr(
173552  SessionBuffer *p,
173553  const char *zStr,
173554  int *pRc
173555 ){
173556  int nStr = sqlite3Strlen30(zStr);
173557  if( 0==sessionBufferGrow(p, nStr, pRc) ){
173558  memcpy(&p->aBuf[p->nBuf], zStr, nStr);
173559  p->nBuf += nStr;
173560  }
173561 }
173562 
173563 /*
173564 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173565 ** called. Otherwise, append the string representation of integer iVal
173566 ** to the buffer. No nul-terminator is written.
173567 **
173568 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173569 ** returning.
173570 */
173571 static void sessionAppendInteger(
173572  SessionBuffer *p, /* Buffer to append to */
173573  int iVal, /* Value to write the string rep. of */
173574  int *pRc /* IN/OUT: Error code */
173575 ){
173576  char aBuf[24];
173577  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
173578  sessionAppendStr(p, aBuf, pRc);
173579 }
173580 
173581 /*
173582 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173583 ** called. Otherwise, append the string zStr enclosed in quotes (") and
173584 ** with any embedded quote characters escaped to the buffer. No
173585 ** nul-terminator byte is written.
173586 **
173587 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173588 ** returning.
173589 */
173590 static void sessionAppendIdent(
173591  SessionBuffer *p, /* Buffer to a append to */
173592  const char *zStr, /* String to quote, escape and append */
173593  int *pRc /* IN/OUT: Error code */
173594 ){
173595  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
173596  if( 0==sessionBufferGrow(p, nStr, pRc) ){
173597  char *zOut = (char *)&p->aBuf[p->nBuf];
173598  const char *zIn = zStr;
173599  *zOut++ = '"';
173600  while( *zIn ){
173601  if( *zIn=='"' ) *zOut++ = '"';
173602  *zOut++ = *(zIn++);
173603  }
173604  *zOut++ = '"';
173605  p->nBuf = (int)((u8 *)zOut - p->aBuf);
173606  }
173607 }
173608 
173609 /*
173610 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173611 ** called. Otherwse, it appends the serialized version of the value stored
173612 ** in column iCol of the row that SQL statement pStmt currently points
173613 ** to to the buffer.
173614 */
173615 static void sessionAppendCol(
173616  SessionBuffer *p, /* Buffer to append to */
173617  sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
173618  int iCol, /* Column to read value from */
173619  int *pRc /* IN/OUT: Error code */
173620 ){
173621  if( *pRc==SQLITE_OK ){
173622  int eType = sqlite3_column_type(pStmt, iCol);
173623  sessionAppendByte(p, (u8)eType, pRc);
173624  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
173625  sqlite3_int64 i;
173626  u8 aBuf[8];
173627  if( eType==SQLITE_INTEGER ){
173628  i = sqlite3_column_int64(pStmt, iCol);
173629  }else{
173630  double r = sqlite3_column_double(pStmt, iCol);
173631  memcpy(&i, &r, 8);
173632  }
173633  sessionPutI64(aBuf, i);
173634  sessionAppendBlob(p, aBuf, 8, pRc);
173635  }
173636  if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
173637  u8 *z;
173638  int nByte;
173639  if( eType==SQLITE_BLOB ){
173640  z = (u8 *)sqlite3_column_blob(pStmt, iCol);
173641  }else{
173642  z = (u8 *)sqlite3_column_text(pStmt, iCol);
173643  }
173644  nByte = sqlite3_column_bytes(pStmt, iCol);
173645  if( z || (eType==SQLITE_BLOB && nByte==0) ){
173646  sessionAppendVarint(p, nByte, pRc);
173647  sessionAppendBlob(p, z, nByte, pRc);
173648  }else{
173649  *pRc = SQLITE_NOMEM;
173650  }
173651  }
173652  }
173653 }
173654 
173655 /*
173656 **
173657 ** This function appends an update change to the buffer (see the comments
173658 ** under "CHANGESET FORMAT" at the top of the file). An update change
173659 ** consists of:
173660 **
173661 ** 1 byte: SQLITE_UPDATE (0x17)
173662 ** n bytes: old.* record (see RECORD FORMAT)
173663 ** m bytes: new.* record (see RECORD FORMAT)
173664 **
173665 ** The SessionChange object passed as the third argument contains the
173666 ** values that were stored in the row when the session began (the old.*
173667 ** values). The statement handle passed as the second argument points
173668 ** at the current version of the row (the new.* values).
173669 **
173670 ** If all of the old.* values are equal to their corresponding new.* value
173671 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
173672 **
173673 ** Otherwise, the old.* record contains all primary key values and the
173674 ** original values of any fields that have been modified. The new.* record
173675 ** contains the new values of only those fields that have been modified.
173676 */
173677 static int sessionAppendUpdate(
173678  SessionBuffer *pBuf, /* Buffer to append to */
173679  int bPatchset, /* True for "patchset", 0 for "changeset" */
173680  sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
173681  SessionChange *p, /* Object containing old values */
173682  u8 *abPK /* Boolean array - true for PK columns */
173683 ){
173684  int rc = SQLITE_OK;
173685  SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
173686  int bNoop = 1; /* Set to zero if any values are modified */
173687  int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
173688  int i; /* Used to iterate through columns */
173689  u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
173690 
173691  sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
173692  sessionAppendByte(pBuf, p->bIndirect, &rc);
173693  for(i=0; i<sqlite3_column_count(pStmt); i++){
173694  int bChanged = 0;
173695  int nAdvance;
173696  int eType = *pCsr;
173697  switch( eType ){
173698  case SQLITE_NULL:
173699  nAdvance = 1;
173700  if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
173701  bChanged = 1;
173702  }
173703  break;
173704 
173705  case SQLITE_FLOAT:
173706  case SQLITE_INTEGER: {
173707  nAdvance = 9;
173708  if( eType==sqlite3_column_type(pStmt, i) ){
173709  sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
173710  if( eType==SQLITE_INTEGER ){
173711  if( iVal==sqlite3_column_int64(pStmt, i) ) break;
173712  }else{
173713  double dVal;
173714  memcpy(&dVal, &iVal, 8);
173715  if( dVal==sqlite3_column_double(pStmt, i) ) break;
173716  }
173717  }
173718  bChanged = 1;
173719  break;
173720  }
173721 
173722  default: {
173723  int nByte;
173724  int nHdr = 1 + sessionVarintGet(&pCsr[1], &nByte);
173725  assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
173726  nAdvance = nHdr + nByte;
173727  if( eType==sqlite3_column_type(pStmt, i)
173728  && nByte==sqlite3_column_bytes(pStmt, i)
173729  && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
173730  ){
173731  break;
173732  }
173733  bChanged = 1;
173734  }
173735  }
173736 
173737  /* If at least one field has been modified, this is not a no-op. */
173738  if( bChanged ) bNoop = 0;
173739 
173740  /* Add a field to the old.* record. This is omitted if this modules is
173741  ** currently generating a patchset. */
173742  if( bPatchset==0 ){
173743  if( bChanged || abPK[i] ){
173744  sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
173745  }else{
173746  sessionAppendByte(pBuf, 0, &rc);
173747  }
173748  }
173749 
173750  /* Add a field to the new.* record. Or the only record if currently
173751  ** generating a patchset. */
173752  if( bChanged || (bPatchset && abPK[i]) ){
173753  sessionAppendCol(&buf2, pStmt, i, &rc);
173754  }else{
173755  sessionAppendByte(&buf2, 0, &rc);
173756  }
173757 
173758  pCsr += nAdvance;
173759  }
173760 
173761  if( bNoop ){
173762  pBuf->nBuf = nRewind;
173763  }else{
173764  sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
173765  }
173766  sqlite3_free(buf2.aBuf);
173767 
173768  return rc;
173769 }
173770 
173771 /*
173772 ** Append a DELETE change to the buffer passed as the first argument. Use
173773 ** the changeset format if argument bPatchset is zero, or the patchset
173774 ** format otherwise.
173775 */
173776 static int sessionAppendDelete(
173777  SessionBuffer *pBuf, /* Buffer to append to */
173778  int bPatchset, /* True for "patchset", 0 for "changeset" */
173779  SessionChange *p, /* Object containing old values */
173780  int nCol, /* Number of columns in table */
173781  u8 *abPK /* Boolean array - true for PK columns */
173782 ){
173783  int rc = SQLITE_OK;
173784 
173785  sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
173786  sessionAppendByte(pBuf, p->bIndirect, &rc);
173787 
173788  if( bPatchset==0 ){
173789  sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
173790  }else{
173791  int i;
173792  u8 *a = p->aRecord;
173793  for(i=0; i<nCol; i++){
173794  u8 *pStart = a;
173795  int eType = *a++;
173796 
173797  switch( eType ){
173798  case 0:
173799  case SQLITE_NULL:
173800  assert( abPK[i]==0 );
173801  break;
173802 
173803  case SQLITE_FLOAT:
173804  case SQLITE_INTEGER:
173805  a += 8;
173806  break;
173807 
173808  default: {
173809  int n;
173810  a += sessionVarintGet(a, &n);
173811  a += n;
173812  break;
173813  }
173814  }
173815  if( abPK[i] ){
173816  sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
173817  }
173818  }
173819  assert( (a - p->aRecord)==p->nRecord );
173820  }
173821 
173822  return rc;
173823 }
173824 
173825 /*
173826 ** Formulate and prepare a SELECT statement to retrieve a row from table
173827 ** zTab in database zDb based on its primary key. i.e.
173828 **
173829 ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
173830 */
173831 static int sessionSelectStmt(
173832  sqlite3 *db, /* Database handle */
173833  const char *zDb, /* Database name */
173834  const char *zTab, /* Table name */
173835  int nCol, /* Number of columns in table */
173836  const char **azCol, /* Names of table columns */
173837  u8 *abPK, /* PRIMARY KEY array */
173838  sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
173839 ){
173840  int rc = SQLITE_OK;
173841  int i;
173842  const char *zSep = "";
173843  SessionBuffer buf = {0, 0, 0};
173844 
173845  sessionAppendStr(&buf, "SELECT * FROM ", &rc);
173846  sessionAppendIdent(&buf, zDb, &rc);
173847  sessionAppendStr(&buf, ".", &rc);
173848  sessionAppendIdent(&buf, zTab, &rc);
173849  sessionAppendStr(&buf, " WHERE ", &rc);
173850  for(i=0; i<nCol; i++){
173851  if( abPK[i] ){
173852  sessionAppendStr(&buf, zSep, &rc);
173853  sessionAppendIdent(&buf, azCol[i], &rc);
173854  sessionAppendStr(&buf, " = ?", &rc);
173855  sessionAppendInteger(&buf, i+1, &rc);
173856  zSep = " AND ";
173857  }
173858  }
173859  if( rc==SQLITE_OK ){
173860  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
173861  }
173862  sqlite3_free(buf.aBuf);
173863  return rc;
173864 }
173865 
173866 /*
173867 ** Bind the PRIMARY KEY values from the change passed in argument pChange
173868 ** to the SELECT statement passed as the first argument. The SELECT statement
173869 ** is as prepared by function sessionSelectStmt().
173870 **
173871 ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
173872 ** error code (e.g. SQLITE_NOMEM) otherwise.
173873 */
173874 static int sessionSelectBind(
173875  sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
173876  int nCol, /* Number of columns in table */
173877  u8 *abPK, /* PRIMARY KEY array */
173878  SessionChange *pChange /* Change structure */
173879 ){
173880  int i;
173881  int rc = SQLITE_OK;
173882  u8 *a = pChange->aRecord;
173883 
173884  for(i=0; i<nCol && rc==SQLITE_OK; i++){
173885  int eType = *a++;
173886 
173887  switch( eType ){
173888  case 0:
173889  case SQLITE_NULL:
173890  assert( abPK[i]==0 );
173891  break;
173892 
173893  case SQLITE_INTEGER: {
173894  if( abPK[i] ){
173895  i64 iVal = sessionGetI64(a);
173896  rc = sqlite3_bind_int64(pSelect, i+1, iVal);
173897  }
173898  a += 8;
173899  break;
173900  }
173901 
173902  case SQLITE_FLOAT: {
173903  if( abPK[i] ){
173904  double rVal;
173905  i64 iVal = sessionGetI64(a);
173906  memcpy(&rVal, &iVal, 8);
173907  rc = sqlite3_bind_double(pSelect, i+1, rVal);
173908  }
173909  a += 8;
173910  break;
173911  }
173912 
173913  case SQLITE_TEXT: {
173914  int n;
173915  a += sessionVarintGet(a, &n);
173916  if( abPK[i] ){
173917  rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
173918  }
173919  a += n;
173920  break;
173921  }
173922 
173923  default: {
173924  int n;
173925  assert( eType==SQLITE_BLOB );
173926  a += sessionVarintGet(a, &n);
173927  if( abPK[i] ){
173928  rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
173929  }
173930  a += n;
173931  break;
173932  }
173933  }
173934  }
173935 
173936  return rc;
173937 }
173938 
173939 /*
173940 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
173941 ** is called. Otherwise, append a serialized table header (part of the binary
173942 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
173943 ** SQLite error code before returning.
173944 */
173945 static void sessionAppendTableHdr(
173946  SessionBuffer *pBuf, /* Append header to this buffer */
173947  int bPatchset, /* Use the patchset format if true */
173948  SessionTable *pTab, /* Table object to append header for */
173949  int *pRc /* IN/OUT: Error code */
173950 ){
173951  /* Write a table header */
173952  sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
173953  sessionAppendVarint(pBuf, pTab->nCol, pRc);
173954  sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
173955  sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
173956 }
173957 
173958 /*
173959 ** Generate either a changeset (if argument bPatchset is zero) or a patchset
173960 ** (if it is non-zero) based on the current contents of the session object
173961 ** passed as the first argument.
173962 **
173963 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
173964 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
173965 ** occurs, an SQLite error code is returned and both output variables set
173966 ** to 0.
173967 */
173968 static int sessionGenerateChangeset(
173969  sqlite3_session *pSession, /* Session object */
173970  int bPatchset, /* True for patchset, false for changeset */
173971  int (*xOutput)(void *pOut, const void *pData, int nData),
173972  void *pOut, /* First argument for xOutput */
173973  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
173974  void **ppChangeset /* OUT: Buffer containing changeset */
173975 ){
173976  sqlite3 *db = pSession->db; /* Source database handle */
173977  SessionTable *pTab; /* Used to iterate through attached tables */
173978  SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
173979  int rc; /* Return code */
173980 
173981  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
173982 
173983  /* Zero the output variables in case an error occurs. If this session
173984  ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
173985  ** this call will be a no-op. */
173986  if( xOutput==0 ){
173987  *pnChangeset = 0;
173988  *ppChangeset = 0;
173989  }
173990 
173991  if( pSession->rc ) return pSession->rc;
173992  rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
173993  if( rc!=SQLITE_OK ) return rc;
173994 
173995  sqlite3_mutex_enter(sqlite3_db_mutex(db));
173996 
173997  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
173998  if( pTab->nEntry ){
173999  const char *zName = pTab->zName;
174000  int nCol; /* Number of columns in table */
174001  u8 *abPK; /* Primary key array */
174002  const char **azCol = 0; /* Table columns */
174003  int i; /* Used to iterate through hash buckets */
174004  sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
174005  int nRewind = buf.nBuf; /* Initial size of write buffer */
174006  int nNoop; /* Size of buffer after writing tbl header */
174007 
174008  /* Check the table schema is still Ok. */
174009  rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
174010  if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
174011  rc = SQLITE_SCHEMA;
174012  }
174013 
174014  /* Write a table header */
174015  sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
174016 
174017  /* Build and compile a statement to execute: */
174018  if( rc==SQLITE_OK ){
174019  rc = sessionSelectStmt(
174020  db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
174021  }
174022 
174023  nNoop = buf.nBuf;
174024  for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
174025  SessionChange *p; /* Used to iterate through changes */
174026 
174027  for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
174028  rc = sessionSelectBind(pSel, nCol, abPK, p);
174029  if( rc!=SQLITE_OK ) continue;
174030  if( sqlite3_step(pSel)==SQLITE_ROW ){
174031  if( p->op==SQLITE_INSERT ){
174032  int iCol;
174033  sessionAppendByte(&buf, SQLITE_INSERT, &rc);
174034  sessionAppendByte(&buf, p->bIndirect, &rc);
174035  for(iCol=0; iCol<nCol; iCol++){
174036  sessionAppendCol(&buf, pSel, iCol, &rc);
174037  }
174038  }else{
174039  rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
174040  }
174041  }else if( p->op!=SQLITE_INSERT ){
174042  rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
174043  }
174044  if( rc==SQLITE_OK ){
174045  rc = sqlite3_reset(pSel);
174046  }
174047 
174048  /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
174049  ** its contents to the xOutput() callback. */
174050  if( xOutput
174051  && rc==SQLITE_OK
174052  && buf.nBuf>nNoop
174053  && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
174054  ){
174055  rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
174056  nNoop = -1;
174057  buf.nBuf = 0;
174058  }
174059 
174060  }
174061  }
174062 
174063  sqlite3_finalize(pSel);
174064  if( buf.nBuf==nNoop ){
174065  buf.nBuf = nRewind;
174066  }
174067  sqlite3_free((char*)azCol); /* cast works around VC++ bug */
174068  }
174069  }
174070 
174071  if( rc==SQLITE_OK ){
174072  if( xOutput==0 ){
174073  *pnChangeset = buf.nBuf;
174074  *ppChangeset = buf.aBuf;
174075  buf.aBuf = 0;
174076  }else if( buf.nBuf>0 ){
174077  rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
174078  }
174079  }
174080 
174081  sqlite3_free(buf.aBuf);
174082  sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
174083  sqlite3_mutex_leave(sqlite3_db_mutex(db));
174084  return rc;
174085 }
174086 
174087 /*
174088 ** Obtain a changeset object containing all changes recorded by the
174089 ** session object passed as the first argument.
174090 **
174091 ** It is the responsibility of the caller to eventually free the buffer
174092 ** using sqlite3_free().
174093 */
174094 SQLITE_API int sqlite3session_changeset(
174095  sqlite3_session *pSession, /* Session object */
174096  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
174097  void **ppChangeset /* OUT: Buffer containing changeset */
174098 ){
174099  return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
174100 }
174101 
174102 /*
174103 ** Streaming version of sqlite3session_changeset().
174104 */
174105 SQLITE_API int sqlite3session_changeset_strm(
174106  sqlite3_session *pSession,
174107  int (*xOutput)(void *pOut, const void *pData, int nData),
174108  void *pOut
174109 ){
174110  return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
174111 }
174112 
174113 /*
174114 ** Streaming version of sqlite3session_patchset().
174115 */
174116 SQLITE_API int sqlite3session_patchset_strm(
174117  sqlite3_session *pSession,
174118  int (*xOutput)(void *pOut, const void *pData, int nData),
174119  void *pOut
174120 ){
174121  return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
174122 }
174123 
174124 /*
174125 ** Obtain a patchset object containing all changes recorded by the
174126 ** session object passed as the first argument.
174127 **
174128 ** It is the responsibility of the caller to eventually free the buffer
174129 ** using sqlite3_free().
174130 */
174131 SQLITE_API int sqlite3session_patchset(
174132  sqlite3_session *pSession, /* Session object */
174133  int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
174134  void **ppPatchset /* OUT: Buffer containing changeset */
174135 ){
174136  return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
174137 }
174138 
174139 /*
174140 ** Enable or disable the session object passed as the first argument.
174141 */
174142 SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
174143  int ret;
174144  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
174145  if( bEnable>=0 ){
174146  pSession->bEnable = bEnable;
174147  }
174148  ret = pSession->bEnable;
174149  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
174150  return ret;
174151 }
174152 
174153 /*
174154 ** Enable or disable the session object passed as the first argument.
174155 */
174156 SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
174157  int ret;
174158  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
174159  if( bIndirect>=0 ){
174160  pSession->bIndirect = bIndirect;
174161  }
174162  ret = pSession->bIndirect;
174163  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
174164  return ret;
174165 }
174166 
174167 /*
174168 ** Return true if there have been no changes to monitored tables recorded
174169 ** by the session object passed as the only argument.
174170 */
174171 SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
174172  int ret = 0;
174173  SessionTable *pTab;
174174 
174175  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
174176  for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
174177  ret = (pTab->nEntry>0);
174178  }
174179  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
174180 
174181  return (ret==0);
174182 }
174183 
174184 /*
174185 ** Do the work for either sqlite3changeset_start() or start_strm().
174186 */
174187 static int sessionChangesetStart(
174188  sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
174189  int (*xInput)(void *pIn, void *pData, int *pnData),
174190  void *pIn,
174191  int nChangeset, /* Size of buffer pChangeset in bytes */
174192  void *pChangeset /* Pointer to buffer containing changeset */
174193 ){
174194  sqlite3_changeset_iter *pRet; /* Iterator to return */
174195  int nByte; /* Number of bytes to allocate for iterator */
174196 
174197  assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
174198 
174199  /* Zero the output variable in case an error occurs. */
174200  *pp = 0;
174201 
174202  /* Allocate and initialize the iterator structure. */
174203  nByte = sizeof(sqlite3_changeset_iter);
174204  pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
174205  if( !pRet ) return SQLITE_NOMEM;
174206  memset(pRet, 0, sizeof(sqlite3_changeset_iter));
174207  pRet->in.aData = (u8 *)pChangeset;
174208  pRet->in.nData = nChangeset;
174209  pRet->in.xInput = xInput;
174210  pRet->in.pIn = pIn;
174211  pRet->in.bEof = (xInput ? 0 : 1);
174212 
174213  /* Populate the output variable and return success. */
174214  *pp = pRet;
174215  return SQLITE_OK;
174216 }
174217 
174218 /*
174219 ** Create an iterator used to iterate through the contents of a changeset.
174220 */
174221 SQLITE_API int sqlite3changeset_start(
174222  sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
174223  int nChangeset, /* Size of buffer pChangeset in bytes */
174224  void *pChangeset /* Pointer to buffer containing changeset */
174225 ){
174226  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
174227 }
174228 
174229 /*
174230 ** Streaming version of sqlite3changeset_start().
174231 */
174232 SQLITE_API int sqlite3changeset_start_strm(
174233  sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
174234  int (*xInput)(void *pIn, void *pData, int *pnData),
174235  void *pIn
174236 ){
174237  return sessionChangesetStart(pp, xInput, pIn, 0, 0);
174238 }
174239 
174240 /*
174241 ** If the SessionInput object passed as the only argument is a streaming
174242 ** object and the buffer is full, discard some data to free up space.
174243 */
174244 static void sessionDiscardData(SessionInput *pIn){
174245  if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
174246  int nMove = pIn->buf.nBuf - pIn->iNext;
174247  assert( nMove>=0 );
174248  if( nMove>0 ){
174249  memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
174250  }
174251  pIn->buf.nBuf -= pIn->iNext;
174252  pIn->iNext = 0;
174253  pIn->nData = pIn->buf.nBuf;
174254  }
174255 }
174256 
174257 /*
174258 ** Ensure that there are at least nByte bytes available in the buffer. Or,
174259 ** if there are not nByte bytes remaining in the input, that all available
174260 ** data is in the buffer.
174261 **
174262 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
174263 */
174264 static int sessionInputBuffer(SessionInput *pIn, int nByte){
174265  int rc = SQLITE_OK;
174266  if( pIn->xInput ){
174267  while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
174268  int nNew = SESSIONS_STRM_CHUNK_SIZE;
174269 
174270  if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
174271  if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
174272  rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
174273  if( nNew==0 ){
174274  pIn->bEof = 1;
174275  }else{
174276  pIn->buf.nBuf += nNew;
174277  }
174278  }
174279 
174280  pIn->aData = pIn->buf.aBuf;
174281  pIn->nData = pIn->buf.nBuf;
174282  }
174283  }
174284  return rc;
174285 }
174286 
174287 /*
174288 ** When this function is called, *ppRec points to the start of a record
174289 ** that contains nCol values. This function advances the pointer *ppRec
174290 ** until it points to the byte immediately following that record.
174291 */
174292 static void sessionSkipRecord(
174293  u8 **ppRec, /* IN/OUT: Record pointer */
174294  int nCol /* Number of values in record */
174295 ){
174296  u8 *aRec = *ppRec;
174297  int i;
174298  for(i=0; i<nCol; i++){
174299  int eType = *aRec++;
174300  if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
174301  int nByte;
174302  aRec += sessionVarintGet((u8*)aRec, &nByte);
174303  aRec += nByte;
174304  }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
174305  aRec += 8;
174306  }
174307  }
174308 
174309  *ppRec = aRec;
174310 }
174311 
174312 /*
174313 ** This function sets the value of the sqlite3_value object passed as the
174314 ** first argument to a copy of the string or blob held in the aData[]
174315 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
174316 ** error occurs.
174317 */
174318 static int sessionValueSetStr(
174319  sqlite3_value *pVal, /* Set the value of this object */
174320  u8 *aData, /* Buffer containing string or blob data */
174321  int nData, /* Size of buffer aData[] in bytes */
174322  u8 enc /* String encoding (0 for blobs) */
174323 ){
174324  /* In theory this code could just pass SQLITE_TRANSIENT as the final
174325  ** argument to sqlite3ValueSetStr() and have the copy created
174326  ** automatically. But doing so makes it difficult to detect any OOM
174327  ** error. Hence the code to create the copy externally. */
174328  u8 *aCopy = sqlite3_malloc(nData+1);
174329  if( aCopy==0 ) return SQLITE_NOMEM;
174330  memcpy(aCopy, aData, nData);
174331  sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
174332  return SQLITE_OK;
174333 }
174334 
174335 /*
174336 ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
174337 ** for details.
174338 **
174339 ** When this function is called, *paChange points to the start of the record
174340 ** to deserialize. Assuming no error occurs, *paChange is set to point to
174341 ** one byte after the end of the same record before this function returns.
174342 ** If the argument abPK is NULL, then the record contains nCol values. Or,
174343 ** if abPK is other than NULL, then the record contains only the PK fields
174344 ** (in other words, it is a patchset DELETE record).
174345 **
174346 ** If successful, each element of the apOut[] array (allocated by the caller)
174347 ** is set to point to an sqlite3_value object containing the value read
174348 ** from the corresponding position in the record. If that value is not
174349 ** included in the record (i.e. because the record is part of an UPDATE change
174350 ** and the field was not modified), the corresponding element of apOut[] is
174351 ** set to NULL.
174352 **
174353 ** It is the responsibility of the caller to free all sqlite_value structures
174354 ** using sqlite3_free().
174355 **
174356 ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
174357 ** The apOut[] array may have been partially populated in this case.
174358 */
174359 static int sessionReadRecord(
174360  SessionInput *pIn, /* Input data */
174361  int nCol, /* Number of values in record */
174362  u8 *abPK, /* Array of primary key flags, or NULL */
174363  sqlite3_value **apOut /* Write values to this array */
174364 ){
174365  int i; /* Used to iterate through columns */
174366  int rc = SQLITE_OK;
174367 
174368  for(i=0; i<nCol && rc==SQLITE_OK; i++){
174369  int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
174370  if( abPK && abPK[i]==0 ) continue;
174371  rc = sessionInputBuffer(pIn, 9);
174372  if( rc==SQLITE_OK ){
174373  eType = pIn->aData[pIn->iNext++];
174374  }
174375 
174376  assert( apOut[i]==0 );
174377  if( eType ){
174378  apOut[i] = sqlite3ValueNew(0);
174379  if( !apOut[i] ) rc = SQLITE_NOMEM;
174380  }
174381 
174382  if( rc==SQLITE_OK ){
174383  u8 *aVal = &pIn->aData[pIn->iNext];
174384  if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
174385  int nByte;
174386  pIn->iNext += sessionVarintGet(aVal, &nByte);
174387  rc = sessionInputBuffer(pIn, nByte);
174388  if( rc==SQLITE_OK ){
174389  u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
174390  rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
174391  }
174392  pIn->iNext += nByte;
174393  }
174394  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
174395  sqlite3_int64 v = sessionGetI64(aVal);
174396  if( eType==SQLITE_INTEGER ){
174397  sqlite3VdbeMemSetInt64(apOut[i], v);
174398  }else{
174399  double d;
174400  memcpy(&d, &v, 8);
174401  sqlite3VdbeMemSetDouble(apOut[i], d);
174402  }
174403  pIn->iNext += 8;
174404  }
174405  }
174406  }
174407 
174408  return rc;
174409 }
174410 
174411 /*
174412 ** The input pointer currently points to the second byte of a table-header.
174413 ** Specifically, to the following:
174414 **
174415 ** + number of columns in table (varint)
174416 ** + array of PK flags (1 byte per column),
174417 ** + table name (nul terminated).
174418 **
174419 ** This function ensures that all of the above is present in the input
174420 ** buffer (i.e. that it can be accessed without any calls to xInput()).
174421 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
174422 ** The input pointer is not moved.
174423 */
174424 static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
174425  int rc = SQLITE_OK;
174426  int nCol = 0;
174427  int nRead = 0;
174428 
174429  rc = sessionInputBuffer(pIn, 9);
174430  if( rc==SQLITE_OK ){
174431  nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
174432  rc = sessionInputBuffer(pIn, nRead+nCol+100);
174433  nRead += nCol;
174434  }
174435 
174436  while( rc==SQLITE_OK ){
174437  while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
174438  nRead++;
174439  }
174440  if( (pIn->iNext + nRead)<pIn->nData ) break;
174441  rc = sessionInputBuffer(pIn, nRead + 100);
174442  }
174443  *pnByte = nRead+1;
174444  return rc;
174445 }
174446 
174447 /*
174448 ** The input pointer currently points to the first byte of the first field
174449 ** of a record consisting of nCol columns. This function ensures the entire
174450 ** record is buffered. It does not move the input pointer.
174451 **
174452 ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
174453 ** the record in bytes. Otherwise, an SQLite error code is returned. The
174454 ** final value of *pnByte is undefined in this case.
174455 */
174456 static int sessionChangesetBufferRecord(
174457  SessionInput *pIn, /* Input data */
174458  int nCol, /* Number of columns in record */
174459  int *pnByte /* OUT: Size of record in bytes */
174460 ){
174461  int rc = SQLITE_OK;
174462  int nByte = 0;
174463  int i;
174464  for(i=0; rc==SQLITE_OK && i<nCol; i++){
174465  int eType;
174466  rc = sessionInputBuffer(pIn, nByte + 10);
174467  if( rc==SQLITE_OK ){
174468  eType = pIn->aData[pIn->iNext + nByte++];
174469  if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
174470  int n;
174471  nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
174472  nByte += n;
174473  rc = sessionInputBuffer(pIn, nByte);
174474  }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
174475  nByte += 8;
174476  }
174477  }
174478  }
174479  *pnByte = nByte;
174480  return rc;
174481 }
174482 
174483 /*
174484 ** The input pointer currently points to the second byte of a table-header.
174485 ** Specifically, to the following:
174486 **
174487 ** + number of columns in table (varint)
174488 ** + array of PK flags (1 byte per column),
174489 ** + table name (nul terminated).
174490 **
174491 ** This function decodes the table-header and populates the p->nCol,
174492 ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
174493 ** also allocated or resized according to the new value of p->nCol. The
174494 ** input pointer is left pointing to the byte following the table header.
174495 **
174496 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
174497 ** is returned and the final values of the various fields enumerated above
174498 ** are undefined.
174499 */
174500 static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
174501  int rc;
174502  int nCopy;
174503  assert( p->rc==SQLITE_OK );
174504 
174505  rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
174506  if( rc==SQLITE_OK ){
174507  int nByte;
174508  int nVarint;
174509  nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
174510  nCopy -= nVarint;
174511  p->in.iNext += nVarint;
174512  nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
174513  p->tblhdr.nBuf = 0;
174514  sessionBufferGrow(&p->tblhdr, nByte, &rc);
174515  }
174516 
174517  if( rc==SQLITE_OK ){
174518  int iPK = sizeof(sqlite3_value*)*p->nCol*2;
174519  memset(p->tblhdr.aBuf, 0, iPK);
174520  memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
174521  p->in.iNext += nCopy;
174522  }
174523 
174524  p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
174525  p->abPK = (u8*)&p->apValue[p->nCol*2];
174526  p->zTab = (char*)&p->abPK[p->nCol];
174527  return (p->rc = rc);
174528 }
174529 
174530 /*
174531 ** Advance the changeset iterator to the next change.
174532 **
174533 ** If both paRec and pnRec are NULL, then this function works like the public
174534 ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
174535 ** sqlite3changeset_new() and old() APIs may be used to query for values.
174536 **
174537 ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
174538 ** record is written to *paRec before returning and the number of bytes in
174539 ** the record to *pnRec.
174540 **
174541 ** Either way, this function returns SQLITE_ROW if the iterator is
174542 ** successfully advanced to the next change in the changeset, an SQLite
174543 ** error code if an error occurs, or SQLITE_DONE if there are no further
174544 ** changes in the changeset.
174545 */
174546 static int sessionChangesetNext(
174547  sqlite3_changeset_iter *p, /* Changeset iterator */
174548  u8 **paRec, /* If non-NULL, store record pointer here */
174549  int *pnRec /* If non-NULL, store size of record here */
174550 ){
174551  int i;
174552  u8 op;
174553 
174554  assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
174555 
174556  /* If the iterator is in the error-state, return immediately. */
174557  if( p->rc!=SQLITE_OK ) return p->rc;
174558 
174559  /* Free the current contents of p->apValue[], if any. */
174560  if( p->apValue ){
174561  for(i=0; i<p->nCol*2; i++){
174562  sqlite3ValueFree(p->apValue[i]);
174563  }
174564  memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
174565  }
174566 
174567  /* Make sure the buffer contains at least 10 bytes of input data, or all
174568  ** remaining data if there are less than 10 bytes available. This is
174569  ** sufficient either for the 'T' or 'P' byte and the varint that follows
174570  ** it, or for the two single byte values otherwise. */
174571  p->rc = sessionInputBuffer(&p->in, 2);
174572  if( p->rc!=SQLITE_OK ) return p->rc;
174573 
174574  /* If the iterator is already at the end of the changeset, return DONE. */
174575  if( p->in.iNext>=p->in.nData ){
174576  return SQLITE_DONE;
174577  }
174578 
174579  sessionDiscardData(&p->in);
174580  p->in.iCurrent = p->in.iNext;
174581 
174582  op = p->in.aData[p->in.iNext++];
174583  if( op=='T' || op=='P' ){
174584  p->bPatchset = (op=='P');
174585  if( sessionChangesetReadTblhdr(p) ) return p->rc;
174586  if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
174587  p->in.iCurrent = p->in.iNext;
174588  op = p->in.aData[p->in.iNext++];
174589  }
174590 
174591  p->op = op;
174592  p->bIndirect = p->in.aData[p->in.iNext++];
174593  if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
174594  return (p->rc = SQLITE_CORRUPT_BKPT);
174595  }
174596 
174597  if( paRec ){
174598  int nVal; /* Number of values to buffer */
174599  if( p->bPatchset==0 && op==SQLITE_UPDATE ){
174600  nVal = p->nCol * 2;
174601  }else if( p->bPatchset && op==SQLITE_DELETE ){
174602  nVal = 0;
174603  for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
174604  }else{
174605  nVal = p->nCol;
174606  }
174607  p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
174608  if( p->rc!=SQLITE_OK ) return p->rc;
174609  *paRec = &p->in.aData[p->in.iNext];
174610  p->in.iNext += *pnRec;
174611  }else{
174612 
174613  /* If this is an UPDATE or DELETE, read the old.* record. */
174614  if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
174615  u8 *abPK = p->bPatchset ? p->abPK : 0;
174616  p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
174617  if( p->rc!=SQLITE_OK ) return p->rc;
174618  }
174619 
174620  /* If this is an INSERT or UPDATE, read the new.* record. */
174621  if( p->op!=SQLITE_DELETE ){
174622  p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
174623  if( p->rc!=SQLITE_OK ) return p->rc;
174624  }
174625 
174626  if( p->bPatchset && p->op==SQLITE_UPDATE ){
174627  /* If this is an UPDATE that is part of a patchset, then all PK and
174628  ** modified fields are present in the new.* record. The old.* record
174629  ** is currently completely empty. This block shifts the PK fields from
174630  ** new.* to old.*, to accommodate the code that reads these arrays. */
174631  for(i=0; i<p->nCol; i++){
174632  assert( p->apValue[i]==0 );
174633  assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
174634  if( p->abPK[i] ){
174635  p->apValue[i] = p->apValue[i+p->nCol];
174636  p->apValue[i+p->nCol] = 0;
174637  }
174638  }
174639  }
174640  }
174641 
174642  return SQLITE_ROW;
174643 }
174644 
174645 /*
174646 ** Advance an iterator created by sqlite3changeset_start() to the next
174647 ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
174648 ** or SQLITE_CORRUPT.
174649 **
174650 ** This function may not be called on iterators passed to a conflict handler
174651 ** callback by changeset_apply().
174652 */
174653 SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
174654  return sessionChangesetNext(p, 0, 0);
174655 }
174656 
174657 /*
174658 ** The following function extracts information on the current change
174659 ** from a changeset iterator. It may only be called after changeset_next()
174660 ** has returned SQLITE_ROW.
174661 */
174662 SQLITE_API int sqlite3changeset_op(
174663  sqlite3_changeset_iter *pIter, /* Iterator handle */
174664  const char **pzTab, /* OUT: Pointer to table name */
174665  int *pnCol, /* OUT: Number of columns in table */
174666  int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
174667  int *pbIndirect /* OUT: True if change is indirect */
174668 ){
174669  *pOp = pIter->op;
174670  *pnCol = pIter->nCol;
174671  *pzTab = pIter->zTab;
174672  if( pbIndirect ) *pbIndirect = pIter->bIndirect;
174673  return SQLITE_OK;
174674 }
174675 
174676 /*
174677 ** Return information regarding the PRIMARY KEY and number of columns in
174678 ** the database table affected by the change that pIter currently points
174679 ** to. This function may only be called after changeset_next() returns
174680 ** SQLITE_ROW.
174681 */
174682 SQLITE_API int sqlite3changeset_pk(
174683  sqlite3_changeset_iter *pIter, /* Iterator object */
174684  unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
174685  int *pnCol /* OUT: Number of entries in output array */
174686 ){
174687  *pabPK = pIter->abPK;
174688  if( pnCol ) *pnCol = pIter->nCol;
174689  return SQLITE_OK;
174690 }
174691 
174692 /*
174693 ** This function may only be called while the iterator is pointing to an
174694 ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
174695 ** Otherwise, SQLITE_MISUSE is returned.
174696 **
174697 ** It sets *ppValue to point to an sqlite3_value structure containing the
174698 ** iVal'th value in the old.* record. Or, if that particular value is not
174699 ** included in the record (because the change is an UPDATE and the field
174700 ** was not modified and is not a PK column), set *ppValue to NULL.
174701 **
174702 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
174703 ** not modified. Otherwise, SQLITE_OK.
174704 */
174705 SQLITE_API int sqlite3changeset_old(
174706  sqlite3_changeset_iter *pIter, /* Changeset iterator */
174707  int iVal, /* Index of old.* value to retrieve */
174708  sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
174709 ){
174710  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
174711  return SQLITE_MISUSE;
174712  }
174713  if( iVal<0 || iVal>=pIter->nCol ){
174714  return SQLITE_RANGE;
174715  }
174716  *ppValue = pIter->apValue[iVal];
174717  return SQLITE_OK;
174718 }
174719 
174720 /*
174721 ** This function may only be called while the iterator is pointing to an
174722 ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
174723 ** Otherwise, SQLITE_MISUSE is returned.
174724 **
174725 ** It sets *ppValue to point to an sqlite3_value structure containing the
174726 ** iVal'th value in the new.* record. Or, if that particular value is not
174727 ** included in the record (because the change is an UPDATE and the field
174728 ** was not modified), set *ppValue to NULL.
174729 **
174730 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
174731 ** not modified. Otherwise, SQLITE_OK.
174732 */
174733 SQLITE_API int sqlite3changeset_new(
174734  sqlite3_changeset_iter *pIter, /* Changeset iterator */
174735  int iVal, /* Index of new.* value to retrieve */
174736  sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
174737 ){
174738  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
174739  return SQLITE_MISUSE;
174740  }
174741  if( iVal<0 || iVal>=pIter->nCol ){
174742  return SQLITE_RANGE;
174743  }
174744  *ppValue = pIter->apValue[pIter->nCol+iVal];
174745  return SQLITE_OK;
174746 }
174747 
174748 /*
174749 ** The following two macros are used internally. They are similar to the
174750 ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
174751 ** they omit all error checking and return a pointer to the requested value.
174752 */
174753 #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
174754 #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
174755 
174756 /*
174757 ** This function may only be called with a changeset iterator that has been
174758 ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
174759 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
174760 **
174761 ** If successful, *ppValue is set to point to an sqlite3_value structure
174762 ** containing the iVal'th value of the conflicting record.
174763 **
174764 ** If value iVal is out-of-range or some other error occurs, an SQLite error
174765 ** code is returned. Otherwise, SQLITE_OK.
174766 */
174767 SQLITE_API int sqlite3changeset_conflict(
174768  sqlite3_changeset_iter *pIter, /* Changeset iterator */
174769  int iVal, /* Index of conflict record value to fetch */
174770  sqlite3_value **ppValue /* OUT: Value from conflicting row */
174771 ){
174772  if( !pIter->pConflict ){
174773  return SQLITE_MISUSE;
174774  }
174775  if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){
174776  return SQLITE_RANGE;
174777  }
174778  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
174779  return SQLITE_OK;
174780 }
174781 
174782 /*
174783 ** This function may only be called with an iterator passed to an
174784 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
174785 ** it sets the output variable to the total number of known foreign key
174786 ** violations in the destination database and returns SQLITE_OK.
174787 **
174788 ** In all other cases this function returns SQLITE_MISUSE.
174789 */
174790 SQLITE_API int sqlite3changeset_fk_conflicts(
174791  sqlite3_changeset_iter *pIter, /* Changeset iterator */
174792  int *pnOut /* OUT: Number of FK violations */
174793 ){
174794  if( pIter->pConflict || pIter->apValue ){
174795  return SQLITE_MISUSE;
174796  }
174797  *pnOut = pIter->nCol;
174798  return SQLITE_OK;
174799 }
174800 
174801 
174802 /*
174803 ** Finalize an iterator allocated with sqlite3changeset_start().
174804 **
174805 ** This function may not be called on iterators passed to a conflict handler
174806 ** callback by changeset_apply().
174807 */
174808 SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
174809  int rc = SQLITE_OK;
174810  if( p ){
174811  int i; /* Used to iterate through p->apValue[] */
174812  rc = p->rc;
174813  if( p->apValue ){
174814  for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
174815  }
174816  sqlite3_free(p->tblhdr.aBuf);
174817  sqlite3_free(p->in.buf.aBuf);
174818  sqlite3_free(p);
174819  }
174820  return rc;
174821 }
174822 
174823 static int sessionChangesetInvert(
174824  SessionInput *pInput, /* Input changeset */
174825  int (*xOutput)(void *pOut, const void *pData, int nData),
174826  void *pOut,
174827  int *pnInverted, /* OUT: Number of bytes in output changeset */
174828  void **ppInverted /* OUT: Inverse of pChangeset */
174829 ){
174830  int rc = SQLITE_OK; /* Return value */
174831  SessionBuffer sOut; /* Output buffer */
174832  int nCol = 0; /* Number of cols in current table */
174833  u8 *abPK = 0; /* PK array for current table */
174834  sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
174835  SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
174836 
174837  /* Initialize the output buffer */
174838  memset(&sOut, 0, sizeof(SessionBuffer));
174839 
174840  /* Zero the output variables in case an error occurs. */
174841  if( ppInverted ){
174842  *ppInverted = 0;
174843  *pnInverted = 0;
174844  }
174845 
174846  while( 1 ){
174847  u8 eType;
174848 
174849  /* Test for EOF. */
174850  if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
174851  if( pInput->iNext>=pInput->nData ) break;
174852  eType = pInput->aData[pInput->iNext];
174853 
174854  switch( eType ){
174855  case 'T': {
174856  /* A 'table' record consists of:
174857  **
174858  ** * A constant 'T' character,
174859  ** * Number of columns in said table (a varint),
174860  ** * An array of nCol bytes (sPK),
174861  ** * A nul-terminated table name.
174862  */
174863  int nByte;
174864  int nVar;
174865  pInput->iNext++;
174866  if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
174867  goto finished_invert;
174868  }
174869  nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
174870  sPK.nBuf = 0;
174871  sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
174872  sessionAppendByte(&sOut, eType, &rc);
174873  sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
174874  if( rc ) goto finished_invert;
174875 
174876  pInput->iNext += nByte;
174877  sqlite3_free(apVal);
174878  apVal = 0;
174879  abPK = sPK.aBuf;
174880  break;
174881  }
174882 
174883  case SQLITE_INSERT:
174884  case SQLITE_DELETE: {
174885  int nByte;
174886  int bIndirect = pInput->aData[pInput->iNext+1];
174887  int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
174888  pInput->iNext += 2;
174889  assert( rc==SQLITE_OK );
174890  rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
174891  sessionAppendByte(&sOut, eType2, &rc);
174892  sessionAppendByte(&sOut, bIndirect, &rc);
174893  sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
174894  pInput->iNext += nByte;
174895  if( rc ) goto finished_invert;
174896  break;
174897  }
174898 
174899  case SQLITE_UPDATE: {
174900  int iCol;
174901 
174902  if( 0==apVal ){
174903  apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
174904  if( 0==apVal ){
174905  rc = SQLITE_NOMEM;
174906  goto finished_invert;
174907  }
174908  memset(apVal, 0, sizeof(apVal[0])*nCol*2);
174909  }
174910 
174911  /* Write the header for the new UPDATE change. Same as the original. */
174912  sessionAppendByte(&sOut, eType, &rc);
174913  sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
174914 
174915  /* Read the old.* and new.* records for the update change. */
174916  pInput->iNext += 2;
174917  rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
174918  if( rc==SQLITE_OK ){
174919  rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
174920  }
174921 
174922  /* Write the new old.* record. Consists of the PK columns from the
174923  ** original old.* record, and the other values from the original
174924  ** new.* record. */
174925  for(iCol=0; iCol<nCol; iCol++){
174926  sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
174927  sessionAppendValue(&sOut, pVal, &rc);
174928  }
174929 
174930  /* Write the new new.* record. Consists of a copy of all values
174931  ** from the original old.* record, except for the PK columns, which
174932  ** are set to "undefined". */
174933  for(iCol=0; iCol<nCol; iCol++){
174934  sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
174935  sessionAppendValue(&sOut, pVal, &rc);
174936  }
174937 
174938  for(iCol=0; iCol<nCol*2; iCol++){
174939  sqlite3ValueFree(apVal[iCol]);
174940  }
174941  memset(apVal, 0, sizeof(apVal[0])*nCol*2);
174942  if( rc!=SQLITE_OK ){
174943  goto finished_invert;
174944  }
174945 
174946  break;
174947  }
174948 
174949  default:
174950  rc = SQLITE_CORRUPT_BKPT;
174951  goto finished_invert;
174952  }
174953 
174954  assert( rc==SQLITE_OK );
174955  if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
174956  rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
174957  sOut.nBuf = 0;
174958  if( rc!=SQLITE_OK ) goto finished_invert;
174959  }
174960  }
174961 
174962  assert( rc==SQLITE_OK );
174963  if( pnInverted ){
174964  *pnInverted = sOut.nBuf;
174965  *ppInverted = sOut.aBuf;
174966  sOut.aBuf = 0;
174967  }else if( sOut.nBuf>0 ){
174968  rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
174969  }
174970 
174971  finished_invert:
174972  sqlite3_free(sOut.aBuf);
174973  sqlite3_free(apVal);
174974  sqlite3_free(sPK.aBuf);
174975  return rc;
174976 }
174977 
174978 
174979 /*
174980 ** Invert a changeset object.
174981 */
174982 SQLITE_API int sqlite3changeset_invert(
174983  int nChangeset, /* Number of bytes in input */
174984  const void *pChangeset, /* Input changeset */
174985  int *pnInverted, /* OUT: Number of bytes in output changeset */
174986  void **ppInverted /* OUT: Inverse of pChangeset */
174987 ){
174988  SessionInput sInput;
174989 
174990  /* Set up the input stream */
174991  memset(&sInput, 0, sizeof(SessionInput));
174992  sInput.nData = nChangeset;
174993  sInput.aData = (u8*)pChangeset;
174994 
174995  return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
174996 }
174997 
174998 /*
174999 ** Streaming version of sqlite3changeset_invert().
175000 */
175001 SQLITE_API int sqlite3changeset_invert_strm(
175002  int (*xInput)(void *pIn, void *pData, int *pnData),
175003  void *pIn,
175004  int (*xOutput)(void *pOut, const void *pData, int nData),
175005  void *pOut
175006 ){
175007  SessionInput sInput;
175008  int rc;
175009 
175010  /* Set up the input stream */
175011  memset(&sInput, 0, sizeof(SessionInput));
175012  sInput.xInput = xInput;
175013  sInput.pIn = pIn;
175014 
175015  rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
175016  sqlite3_free(sInput.buf.aBuf);
175017  return rc;
175018 }
175019 
175020 typedef struct SessionApplyCtx SessionApplyCtx;
175021 struct SessionApplyCtx {
175022  sqlite3 *db;
175023  sqlite3_stmt *pDelete; /* DELETE statement */
175024  sqlite3_stmt *pUpdate; /* UPDATE statement */
175025  sqlite3_stmt *pInsert; /* INSERT statement */
175026  sqlite3_stmt *pSelect; /* SELECT statement */
175027  int nCol; /* Size of azCol[] and abPK[] arrays */
175028  const char **azCol; /* Array of column names */
175029  u8 *abPK; /* Boolean array - true if column is in PK */
175030 
175031  int bDeferConstraints; /* True to defer constraints */
175032  SessionBuffer constraints; /* Deferred constraints are stored here */
175033 };
175034 
175035 /*
175036 ** Formulate a statement to DELETE a row from database db. Assuming a table
175037 ** structure like this:
175038 **
175039 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
175040 **
175041 ** The DELETE statement looks like this:
175042 **
175043 ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
175044 **
175045 ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
175046 ** matching b and d values, or 1 otherwise. The second case comes up if the
175047 ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
175048 **
175049 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
175050 ** pointing to the prepared version of the SQL statement.
175051 */
175052 static int sessionDeleteRow(
175053  sqlite3 *db, /* Database handle */
175054  const char *zTab, /* Table name */
175055  SessionApplyCtx *p /* Session changeset-apply context */
175056 ){
175057  int i;
175058  const char *zSep = "";
175059  int rc = SQLITE_OK;
175060  SessionBuffer buf = {0, 0, 0};
175061  int nPk = 0;
175062 
175063  sessionAppendStr(&buf, "DELETE FROM ", &rc);
175064  sessionAppendIdent(&buf, zTab, &rc);
175065  sessionAppendStr(&buf, " WHERE ", &rc);
175066 
175067  for(i=0; i<p->nCol; i++){
175068  if( p->abPK[i] ){
175069  nPk++;
175070  sessionAppendStr(&buf, zSep, &rc);
175071  sessionAppendIdent(&buf, p->azCol[i], &rc);
175072  sessionAppendStr(&buf, " = ?", &rc);
175073  sessionAppendInteger(&buf, i+1, &rc);
175074  zSep = " AND ";
175075  }
175076  }
175077 
175078  if( nPk<p->nCol ){
175079  sessionAppendStr(&buf, " AND (?", &rc);
175080  sessionAppendInteger(&buf, p->nCol+1, &rc);
175081  sessionAppendStr(&buf, " OR ", &rc);
175082 
175083  zSep = "";
175084  for(i=0; i<p->nCol; i++){
175085  if( !p->abPK[i] ){
175086  sessionAppendStr(&buf, zSep, &rc);
175087  sessionAppendIdent(&buf, p->azCol[i], &rc);
175088  sessionAppendStr(&buf, " IS ?", &rc);
175089  sessionAppendInteger(&buf, i+1, &rc);
175090  zSep = "AND ";
175091  }
175092  }
175093  sessionAppendStr(&buf, ")", &rc);
175094  }
175095 
175096  if( rc==SQLITE_OK ){
175097  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
175098  }
175099  sqlite3_free(buf.aBuf);
175100 
175101  return rc;
175102 }
175103 
175104 /*
175105 ** Formulate and prepare a statement to UPDATE a row from database db.
175106 ** Assuming a table structure like this:
175107 **
175108 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
175109 **
175110 ** The UPDATE statement looks like this:
175111 **
175112 ** UPDATE x SET
175113 ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
175114 ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
175115 ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
175116 ** d = CASE WHEN ?11 THEN ?12 ELSE d END
175117 ** WHERE a = ?1 AND c = ?7 AND (?13 OR
175118 ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
175119 ** )
175120 **
175121 ** For each column in the table, there are three variables to bind:
175122 **
175123 ** ?(i*3+1) The old.* value of the column, if any.
175124 ** ?(i*3+2) A boolean flag indicating that the value is being modified.
175125 ** ?(i*3+3) The new.* value of the column, if any.
175126 **
175127 ** Also, a boolean flag that, if set to true, causes the statement to update
175128 ** a row even if the non-PK values do not match. This is required if the
175129 ** conflict-handler is invoked with CHANGESET_DATA and returns
175130 ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
175131 **
175132 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
175133 ** pointing to the prepared version of the SQL statement.
175134 */
175135 static int sessionUpdateRow(
175136  sqlite3 *db, /* Database handle */
175137  const char *zTab, /* Table name */
175138  SessionApplyCtx *p /* Session changeset-apply context */
175139 ){
175140  int rc = SQLITE_OK;
175141  int i;
175142  const char *zSep = "";
175143  SessionBuffer buf = {0, 0, 0};
175144 
175145  /* Append "UPDATE tbl SET " */
175146  sessionAppendStr(&buf, "UPDATE ", &rc);
175147  sessionAppendIdent(&buf, zTab, &rc);
175148  sessionAppendStr(&buf, " SET ", &rc);
175149 
175150  /* Append the assignments */
175151  for(i=0; i<p->nCol; i++){
175152  sessionAppendStr(&buf, zSep, &rc);
175153  sessionAppendIdent(&buf, p->azCol[i], &rc);
175154  sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
175155  sessionAppendInteger(&buf, i*3+2, &rc);
175156  sessionAppendStr(&buf, " THEN ?", &rc);
175157  sessionAppendInteger(&buf, i*3+3, &rc);
175158  sessionAppendStr(&buf, " ELSE ", &rc);
175159  sessionAppendIdent(&buf, p->azCol[i], &rc);
175160  sessionAppendStr(&buf, " END", &rc);
175161  zSep = ", ";
175162  }
175163 
175164  /* Append the PK part of the WHERE clause */
175165  sessionAppendStr(&buf, " WHERE ", &rc);
175166  for(i=0; i<p->nCol; i++){
175167  if( p->abPK[i] ){
175168  sessionAppendIdent(&buf, p->azCol[i], &rc);
175169  sessionAppendStr(&buf, " = ?", &rc);
175170  sessionAppendInteger(&buf, i*3+1, &rc);
175171  sessionAppendStr(&buf, " AND ", &rc);
175172  }
175173  }
175174 
175175  /* Append the non-PK part of the WHERE clause */
175176  sessionAppendStr(&buf, " (?", &rc);
175177  sessionAppendInteger(&buf, p->nCol*3+1, &rc);
175178  sessionAppendStr(&buf, " OR 1", &rc);
175179  for(i=0; i<p->nCol; i++){
175180  if( !p->abPK[i] ){
175181  sessionAppendStr(&buf, " AND (?", &rc);
175182  sessionAppendInteger(&buf, i*3+2, &rc);
175183  sessionAppendStr(&buf, "=0 OR ", &rc);
175184  sessionAppendIdent(&buf, p->azCol[i], &rc);
175185  sessionAppendStr(&buf, " IS ?", &rc);
175186  sessionAppendInteger(&buf, i*3+1, &rc);
175187  sessionAppendStr(&buf, ")", &rc);
175188  }
175189  }
175190  sessionAppendStr(&buf, ")", &rc);
175191 
175192  if( rc==SQLITE_OK ){
175193  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
175194  }
175195  sqlite3_free(buf.aBuf);
175196 
175197  return rc;
175198 }
175199 
175200 /*
175201 ** Formulate and prepare an SQL statement to query table zTab by primary
175202 ** key. Assuming the following table structure:
175203 **
175204 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
175205 **
175206 ** The SELECT statement looks like this:
175207 **
175208 ** SELECT * FROM x WHERE a = ?1 AND c = ?3
175209 **
175210 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
175211 ** pointing to the prepared version of the SQL statement.
175212 */
175213 static int sessionSelectRow(
175214  sqlite3 *db, /* Database handle */
175215  const char *zTab, /* Table name */
175216  SessionApplyCtx *p /* Session changeset-apply context */
175217 ){
175218  return sessionSelectStmt(
175219  db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
175220 }
175221 
175222 /*
175223 ** Formulate and prepare an INSERT statement to add a record to table zTab.
175224 ** For example:
175225 **
175226 ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
175227 **
175228 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
175229 ** pointing to the prepared version of the SQL statement.
175230 */
175231 static int sessionInsertRow(
175232  sqlite3 *db, /* Database handle */
175233  const char *zTab, /* Table name */
175234  SessionApplyCtx *p /* Session changeset-apply context */
175235 ){
175236  int rc = SQLITE_OK;
175237  int i;
175238  SessionBuffer buf = {0, 0, 0};
175239 
175240  sessionAppendStr(&buf, "INSERT INTO main.", &rc);
175241  sessionAppendIdent(&buf, zTab, &rc);
175242  sessionAppendStr(&buf, " VALUES(?", &rc);
175243  for(i=1; i<p->nCol; i++){
175244  sessionAppendStr(&buf, ", ?", &rc);
175245  }
175246  sessionAppendStr(&buf, ")", &rc);
175247 
175248  if( rc==SQLITE_OK ){
175249  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
175250  }
175251  sqlite3_free(buf.aBuf);
175252  return rc;
175253 }
175254 
175255 /*
175256 ** A wrapper around sqlite3_bind_value() that detects an extra problem.
175257 ** See comments in the body of this function for details.
175258 */
175259 static int sessionBindValue(
175260  sqlite3_stmt *pStmt, /* Statement to bind value to */
175261  int i, /* Parameter number to bind to */
175262  sqlite3_value *pVal /* Value to bind */
175263 ){
175264  int eType = sqlite3_value_type(pVal);
175265  /* COVERAGE: The (pVal->z==0) branch is never true using current versions
175266  ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
175267  ** the (pVal->z) variable remains as it was or the type of the value is
175268  ** set to SQLITE_NULL. */
175269  if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
175270  /* This condition occurs when an earlier OOM in a call to
175271  ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
175272  ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
175273  return SQLITE_NOMEM;
175274  }
175275  return sqlite3_bind_value(pStmt, i, pVal);
175276 }
175277 
175278 /*
175279 ** Iterator pIter must point to an SQLITE_INSERT entry. This function
175280 ** transfers new.* values from the current iterator entry to statement
175281 ** pStmt. The table being inserted into has nCol columns.
175282 **
175283 ** New.* value $i from the iterator is bound to variable ($i+1) of
175284 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
175285 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
175286 ** to an array nCol elements in size. In this case only those values for
175287 ** which abPK[$i] is true are read from the iterator and bound to the
175288 ** statement.
175289 **
175290 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
175291 */
175292 static int sessionBindRow(
175293  sqlite3_changeset_iter *pIter, /* Iterator to read values from */
175294  int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
175295  int nCol, /* Number of columns */
175296  u8 *abPK, /* If not NULL, bind only if true */
175297  sqlite3_stmt *pStmt /* Bind values to this statement */
175298 ){
175299  int i;
175300  int rc = SQLITE_OK;
175301 
175302  /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
175303  ** argument iterator points to a suitable entry. Make sure that xValue
175304  ** is one of these to guarantee that it is safe to ignore the return
175305  ** in the code below. */
175306  assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
175307 
175308  for(i=0; rc==SQLITE_OK && i<nCol; i++){
175309  if( !abPK || abPK[i] ){
175310  sqlite3_value *pVal;
175311  (void)xValue(pIter, i, &pVal);
175312  rc = sessionBindValue(pStmt, i+1, pVal);
175313  }
175314  }
175315  return rc;
175316 }
175317 
175318 /*
175319 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
175320 ** This function binds the primary key values from the change that changeset
175321 ** iterator pIter points to to the SELECT and attempts to seek to the table
175322 ** entry. If a row is found, the SELECT statement left pointing at the row
175323 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
175324 ** has occured, the statement is reset and SQLITE_OK is returned. If an
175325 ** error occurs, the statement is reset and an SQLite error code is returned.
175326 **
175327 ** If this function returns SQLITE_ROW, the caller must eventually reset()
175328 ** statement pSelect. If any other value is returned, the statement does
175329 ** not require a reset().
175330 **
175331 ** If the iterator currently points to an INSERT record, bind values from the
175332 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
175333 ** UPDATE, bind values from the old.* record.
175334 */
175335 static int sessionSeekToRow(
175336  sqlite3 *db, /* Database handle */
175337  sqlite3_changeset_iter *pIter, /* Changeset iterator */
175338  u8 *abPK, /* Primary key flags array */
175339  sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
175340 ){
175341  int rc; /* Return code */
175342  int nCol; /* Number of columns in table */
175343  int op; /* Changset operation (SQLITE_UPDATE etc.) */
175344  const char *zDummy; /* Unused */
175345 
175346  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
175347  rc = sessionBindRow(pIter,
175348  op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
175349  nCol, abPK, pSelect
175350  );
175351 
175352  if( rc==SQLITE_OK ){
175353  rc = sqlite3_step(pSelect);
175354  if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
175355  }
175356 
175357  return rc;
175358 }
175359 
175360 /*
175361 ** Invoke the conflict handler for the change that the changeset iterator
175362 ** currently points to.
175363 **
175364 ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
175365 ** If argument pbReplace is NULL, then the type of conflict handler invoked
175366 ** depends solely on eType, as follows:
175367 **
175368 ** eType value Value passed to xConflict
175369 ** -------------------------------------------------
175370 ** CHANGESET_DATA CHANGESET_NOTFOUND
175371 ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
175372 **
175373 ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
175374 ** record with the same primary key as the record about to be deleted, updated
175375 ** or inserted. If such a record can be found, it is available to the conflict
175376 ** handler as the "conflicting" record. In this case the type of conflict
175377 ** handler invoked is as follows:
175378 **
175379 ** eType value PK Record found? Value passed to xConflict
175380 ** ----------------------------------------------------------------
175381 ** CHANGESET_DATA Yes CHANGESET_DATA
175382 ** CHANGESET_DATA No CHANGESET_NOTFOUND
175383 ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
175384 ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
175385 **
175386 ** If pbReplace is not NULL, and a record with a matching PK is found, and
175387 ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
175388 ** is set to non-zero before returning SQLITE_OK.
175389 **
175390 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
175391 ** returned. Or, if the conflict handler returns an invalid value,
175392 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
175393 ** this function returns SQLITE_OK.
175394 */
175395 static int sessionConflictHandler(
175396  int eType, /* Either CHANGESET_DATA or CONFLICT */
175397  SessionApplyCtx *p, /* changeset_apply() context */
175398  sqlite3_changeset_iter *pIter, /* Changeset iterator */
175399  int(*xConflict)(void *, int, sqlite3_changeset_iter*),
175400  void *pCtx, /* First argument for conflict handler */
175401  int *pbReplace /* OUT: Set to true if PK row is found */
175402 ){
175403  int res = 0; /* Value returned by conflict handler */
175404  int rc;
175405  int nCol;
175406  int op;
175407  const char *zDummy;
175408 
175409  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
175410 
175411  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
175412  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
175413  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
175414 
175415  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
175416  if( pbReplace ){
175417  rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
175418  }else{
175419  rc = SQLITE_OK;
175420  }
175421 
175422  if( rc==SQLITE_ROW ){
175423  /* There exists another row with the new.* primary key. */
175424  pIter->pConflict = p->pSelect;
175425  res = xConflict(pCtx, eType, pIter);
175426  pIter->pConflict = 0;
175427  rc = sqlite3_reset(p->pSelect);
175428  }else if( rc==SQLITE_OK ){
175429  if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
175430  /* Instead of invoking the conflict handler, append the change blob
175431  ** to the SessionApplyCtx.constraints buffer. */
175432  u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
175433  int nBlob = pIter->in.iNext - pIter->in.iCurrent;
175434  sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
175435  res = SQLITE_CHANGESET_OMIT;
175436  }else{
175437  /* No other row with the new.* primary key. */
175438  res = xConflict(pCtx, eType+1, pIter);
175439  if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
175440  }
175441  }
175442 
175443  if( rc==SQLITE_OK ){
175444  switch( res ){
175445  case SQLITE_CHANGESET_REPLACE:
175446  assert( pbReplace );
175447  *pbReplace = 1;
175448  break;
175449 
175450  case SQLITE_CHANGESET_OMIT:
175451  break;
175452 
175453  case SQLITE_CHANGESET_ABORT:
175454  rc = SQLITE_ABORT;
175455  break;
175456 
175457  default:
175458  rc = SQLITE_MISUSE;
175459  break;
175460  }
175461  }
175462 
175463  return rc;
175464 }
175465 
175466 /*
175467 ** Attempt to apply the change that the iterator passed as the first argument
175468 ** currently points to to the database. If a conflict is encountered, invoke
175469 ** the conflict handler callback.
175470 **
175471 ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
175472 ** one is encountered, update or delete the row with the matching primary key
175473 ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
175474 ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
175475 ** to true before returning. In this case the caller will invoke this function
175476 ** again, this time with pbRetry set to NULL.
175477 **
175478 ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
175479 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
175480 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
175481 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
175482 ** before retrying. In this case the caller attempts to remove the conflicting
175483 ** row before invoking this function again, this time with pbReplace set
175484 ** to NULL.
175485 **
175486 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
175487 ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
175488 ** returned.
175489 */
175490 static int sessionApplyOneOp(
175491  sqlite3_changeset_iter *pIter, /* Changeset iterator */
175492  SessionApplyCtx *p, /* changeset_apply() context */
175493  int(*xConflict)(void *, int, sqlite3_changeset_iter *),
175494  void *pCtx, /* First argument for the conflict handler */
175495  int *pbReplace, /* OUT: True to remove PK row and retry */
175496  int *pbRetry /* OUT: True to retry. */
175497 ){
175498  const char *zDummy;
175499  int op;
175500  int nCol;
175501  int rc = SQLITE_OK;
175502 
175503  assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
175504  assert( p->azCol && p->abPK );
175505  assert( !pbReplace || *pbReplace==0 );
175506 
175507  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
175508 
175509  if( op==SQLITE_DELETE ){
175510 
175511  /* Bind values to the DELETE statement. If conflict handling is required,
175512  ** bind values for all columns and set bound variable (nCol+1) to true.
175513  ** Or, if conflict handling is not required, bind just the PK column
175514  ** values and, if it exists, set (nCol+1) to false. Conflict handling
175515  ** is not required if:
175516  **
175517  ** * this is a patchset, or
175518  ** * (pbRetry==0), or
175519  ** * all columns of the table are PK columns (in this case there is
175520  ** no (nCol+1) variable to bind to).
175521  */
175522  u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
175523  rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
175524  if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
175525  rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
175526  }
175527  if( rc!=SQLITE_OK ) return rc;
175528 
175529  sqlite3_step(p->pDelete);
175530  rc = sqlite3_reset(p->pDelete);
175531  if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
175532  rc = sessionConflictHandler(
175533  SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
175534  );
175535  }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
175536  rc = sessionConflictHandler(
175537  SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
175538  );
175539  }
175540 
175541  }else if( op==SQLITE_UPDATE ){
175542  int i;
175543 
175544  /* Bind values to the UPDATE statement. */
175545  for(i=0; rc==SQLITE_OK && i<nCol; i++){
175546  sqlite3_value *pOld = sessionChangesetOld(pIter, i);
175547  sqlite3_value *pNew = sessionChangesetNew(pIter, i);
175548 
175549  sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
175550  if( pOld ){
175551  rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
175552  }
175553  if( rc==SQLITE_OK && pNew ){
175554  rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
175555  }
175556  }
175557  if( rc==SQLITE_OK ){
175558  sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
175559  }
175560  if( rc!=SQLITE_OK ) return rc;
175561 
175562  /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
175563  ** the result will be SQLITE_OK with 0 rows modified. */
175564  sqlite3_step(p->pUpdate);
175565  rc = sqlite3_reset(p->pUpdate);
175566 
175567  if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
175568  /* A NOTFOUND or DATA error. Search the table to see if it contains
175569  ** a row with a matching primary key. If so, this is a DATA conflict.
175570  ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
175571 
175572  rc = sessionConflictHandler(
175573  SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
175574  );
175575 
175576  }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
175577  /* This is always a CONSTRAINT conflict. */
175578  rc = sessionConflictHandler(
175579  SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
175580  );
175581  }
175582 
175583  }else{
175584  assert( op==SQLITE_INSERT );
175585  rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
175586  if( rc!=SQLITE_OK ) return rc;
175587 
175588  sqlite3_step(p->pInsert);
175589  rc = sqlite3_reset(p->pInsert);
175590  if( (rc&0xff)==SQLITE_CONSTRAINT ){
175591  rc = sessionConflictHandler(
175592  SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
175593  );
175594  }
175595  }
175596 
175597  return rc;
175598 }
175599 
175600 /*
175601 ** Attempt to apply the change that the iterator passed as the first argument
175602 ** currently points to to the database. If a conflict is encountered, invoke
175603 ** the conflict handler callback.
175604 **
175605 ** The difference between this function and sessionApplyOne() is that this
175606 ** function handles the case where the conflict-handler is invoked and
175607 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
175608 ** retried in some manner.
175609 */
175610 static int sessionApplyOneWithRetry(
175611  sqlite3 *db, /* Apply change to "main" db of this handle */
175612  sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
175613  SessionApplyCtx *pApply, /* Apply context */
175614  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
175615  void *pCtx /* First argument passed to xConflict */
175616 ){
175617  int bReplace = 0;
175618  int bRetry = 0;
175619  int rc;
175620 
175621  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
175622  assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
175623 
175624  /* If the bRetry flag is set, the change has not been applied due to an
175625  ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
175626  ** a row with the correct PK is present in the db, but one or more other
175627  ** fields do not contain the expected values) and the conflict handler
175628  ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
175629  ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
175630  ** the SQLITE_CHANGESET_DATA problem. */
175631  if( bRetry ){
175632  assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
175633  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
175634  }
175635 
175636  /* If the bReplace flag is set, the change is an INSERT that has not
175637  ** been performed because the database already contains a row with the
175638  ** specified primary key and the conflict handler returned
175639  ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
175640  ** before reattempting the INSERT. */
175641  else if( bReplace ){
175642  assert( pIter->op==SQLITE_INSERT );
175643  rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
175644  if( rc==SQLITE_OK ){
175645  rc = sessionBindRow(pIter,
175646  sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
175647  sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
175648  }
175649  if( rc==SQLITE_OK ){
175650  sqlite3_step(pApply->pDelete);
175651  rc = sqlite3_reset(pApply->pDelete);
175652  }
175653  if( rc==SQLITE_OK ){
175654  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
175655  }
175656  if( rc==SQLITE_OK ){
175657  rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
175658  }
175659  }
175660 
175661  return rc;
175662 }
175663 
175664 /*
175665 ** Retry the changes accumulated in the pApply->constraints buffer.
175666 */
175667 static int sessionRetryConstraints(
175668  sqlite3 *db,
175669  int bPatchset,
175670  const char *zTab,
175671  SessionApplyCtx *pApply,
175672  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
175673  void *pCtx /* First argument passed to xConflict */
175674 ){
175675  int rc = SQLITE_OK;
175676 
175677  while( pApply->constraints.nBuf ){
175678  sqlite3_changeset_iter *pIter2 = 0;
175679  SessionBuffer cons = pApply->constraints;
175680  memset(&pApply->constraints, 0, sizeof(SessionBuffer));
175681 
175682  rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
175683  if( rc==SQLITE_OK ){
175684  int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
175685  int rc2;
175686  pIter2->bPatchset = bPatchset;
175687  pIter2->zTab = (char*)zTab;
175688  pIter2->nCol = pApply->nCol;
175689  pIter2->abPK = pApply->abPK;
175690  sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
175691  pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
175692  if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
175693 
175694  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
175695  rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
175696  }
175697 
175698  rc2 = sqlite3changeset_finalize(pIter2);
175699  if( rc==SQLITE_OK ) rc = rc2;
175700  }
175701  assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
175702 
175703  sqlite3_free(cons.aBuf);
175704  if( rc!=SQLITE_OK ) break;
175705  if( pApply->constraints.nBuf>=cons.nBuf ){
175706  /* No progress was made on the last round. */
175707  pApply->bDeferConstraints = 0;
175708  }
175709  }
175710 
175711  return rc;
175712 }
175713 
175714 /*
175715 ** Argument pIter is a changeset iterator that has been initialized, but
175716 ** not yet passed to sqlite3changeset_next(). This function applies the
175717 ** changeset to the main database attached to handle "db". The supplied
175718 ** conflict handler callback is invoked to resolve any conflicts encountered
175719 ** while applying the change.
175720 */
175721 static int sessionChangesetApply(
175722  sqlite3 *db, /* Apply change to "main" db of this handle */
175723  sqlite3_changeset_iter *pIter, /* Changeset to apply */
175724  int(*xFilter)(
175725  void *pCtx, /* Copy of sixth arg to _apply() */
175726  const char *zTab /* Table name */
175727  ),
175728  int(*xConflict)(
175729  void *pCtx, /* Copy of fifth arg to _apply() */
175730  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
175731  sqlite3_changeset_iter *p /* Handle describing change and conflict */
175732  ),
175733  void *pCtx /* First argument passed to xConflict */
175734 ){
175735  int schemaMismatch = 0;
175736  int rc; /* Return code */
175737  const char *zTab = 0; /* Name of current table */
175738  int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
175739  SessionApplyCtx sApply; /* changeset_apply() context object */
175740  int bPatchset;
175741 
175742  assert( xConflict!=0 );
175743 
175744  pIter->in.bNoDiscard = 1;
175745  memset(&sApply, 0, sizeof(sApply));
175746  sqlite3_mutex_enter(sqlite3_db_mutex(db));
175747  rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
175748  if( rc==SQLITE_OK ){
175749  rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
175750  }
175751  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
175752  int nCol;
175753  int op;
175754  const char *zNew;
175755 
175756  sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
175757 
175758  if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
175759  u8 *abPK;
175760 
175761  rc = sessionRetryConstraints(
175762  db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
175763  );
175764  if( rc!=SQLITE_OK ) break;
175765 
175766  sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
175767  sqlite3_finalize(sApply.pDelete);
175768  sqlite3_finalize(sApply.pUpdate);
175769  sqlite3_finalize(sApply.pInsert);
175770  sqlite3_finalize(sApply.pSelect);
175771  memset(&sApply, 0, sizeof(sApply));
175772  sApply.db = db;
175773  sApply.bDeferConstraints = 1;
175774 
175775  /* If an xFilter() callback was specified, invoke it now. If the
175776  ** xFilter callback returns zero, skip this table. If it returns
175777  ** non-zero, proceed. */
175778  schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
175779  if( schemaMismatch ){
175780  zTab = sqlite3_mprintf("%s", zNew);
175781  if( zTab==0 ){
175782  rc = SQLITE_NOMEM;
175783  break;
175784  }
175785  nTab = (int)strlen(zTab);
175786  sApply.azCol = (const char **)zTab;
175787  }else{
175788  sqlite3changeset_pk(pIter, &abPK, 0);
175789  rc = sessionTableInfo(
175790  db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
175791  );
175792  if( rc!=SQLITE_OK ) break;
175793 
175794  if( sApply.nCol==0 ){
175795  schemaMismatch = 1;
175796  sqlite3_log(SQLITE_SCHEMA,
175797  "sqlite3changeset_apply(): no such table: %s", zTab
175798  );
175799  }
175800  else if( sApply.nCol!=nCol ){
175801  schemaMismatch = 1;
175802  sqlite3_log(SQLITE_SCHEMA,
175803  "sqlite3changeset_apply(): table %s has %d columns, expected %d",
175804  zTab, sApply.nCol, nCol
175805  );
175806  }
175807  else if( memcmp(sApply.abPK, abPK, nCol)!=0 ){
175808  schemaMismatch = 1;
175809  sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
175810  "primary key mismatch for table %s", zTab
175811  );
175812  }
175813  else if(
175814  (rc = sessionSelectRow(db, zTab, &sApply))
175815  || (rc = sessionUpdateRow(db, zTab, &sApply))
175816  || (rc = sessionDeleteRow(db, zTab, &sApply))
175817  || (rc = sessionInsertRow(db, zTab, &sApply))
175818  ){
175819  break;
175820  }
175821  nTab = sqlite3Strlen30(zTab);
175822  }
175823  }
175824 
175825  /* If there is a schema mismatch on the current table, proceed to the
175826  ** next change. A log message has already been issued. */
175827  if( schemaMismatch ) continue;
175828 
175829  rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
175830  }
175831 
175832  bPatchset = pIter->bPatchset;
175833  if( rc==SQLITE_OK ){
175834  rc = sqlite3changeset_finalize(pIter);
175835  }else{
175836  sqlite3changeset_finalize(pIter);
175837  }
175838 
175839  if( rc==SQLITE_OK ){
175840  rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
175841  }
175842 
175843  if( rc==SQLITE_OK ){
175844  int nFk, notUsed;
175845  sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
175846  if( nFk!=0 ){
175847  int res = SQLITE_CHANGESET_ABORT;
175848  sqlite3_changeset_iter sIter;
175849  memset(&sIter, 0, sizeof(sIter));
175850  sIter.nCol = nFk;
175851  res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
175852  if( res!=SQLITE_CHANGESET_OMIT ){
175853  rc = SQLITE_CONSTRAINT;
175854  }
175855  }
175856  }
175857  sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
175858 
175859  if( rc==SQLITE_OK ){
175860  rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
175861  }else{
175862  sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
175863  sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
175864  }
175865 
175866  sqlite3_finalize(sApply.pInsert);
175867  sqlite3_finalize(sApply.pDelete);
175868  sqlite3_finalize(sApply.pUpdate);
175869  sqlite3_finalize(sApply.pSelect);
175870  sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
175871  sqlite3_free((char*)sApply.constraints.aBuf);
175872  sqlite3_mutex_leave(sqlite3_db_mutex(db));
175873  return rc;
175874 }
175875 
175876 /*
175877 ** Apply the changeset passed via pChangeset/nChangeset to the main database
175878 ** attached to handle "db". Invoke the supplied conflict handler callback
175879 ** to resolve any conflicts encountered while applying the change.
175880 */
175881 SQLITE_API int sqlite3changeset_apply(
175882  sqlite3 *db, /* Apply change to "main" db of this handle */
175883  int nChangeset, /* Size of changeset in bytes */
175884  void *pChangeset, /* Changeset blob */
175885  int(*xFilter)(
175886  void *pCtx, /* Copy of sixth arg to _apply() */
175887  const char *zTab /* Table name */
175888  ),
175889  int(*xConflict)(
175890  void *pCtx, /* Copy of fifth arg to _apply() */
175891  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
175892  sqlite3_changeset_iter *p /* Handle describing change and conflict */
175893  ),
175894  void *pCtx /* First argument passed to xConflict */
175895 ){
175896  sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
175897  int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
175898  if( rc==SQLITE_OK ){
175899  rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
175900  }
175901  return rc;
175902 }
175903 
175904 /*
175905 ** Apply the changeset passed via xInput/pIn to the main database
175906 ** attached to handle "db". Invoke the supplied conflict handler callback
175907 ** to resolve any conflicts encountered while applying the change.
175908 */
175909 SQLITE_API int sqlite3changeset_apply_strm(
175910  sqlite3 *db, /* Apply change to "main" db of this handle */
175911  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
175912  void *pIn, /* First arg for xInput */
175913  int(*xFilter)(
175914  void *pCtx, /* Copy of sixth arg to _apply() */
175915  const char *zTab /* Table name */
175916  ),
175917  int(*xConflict)(
175918  void *pCtx, /* Copy of sixth arg to _apply() */
175919  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
175920  sqlite3_changeset_iter *p /* Handle describing change and conflict */
175921  ),
175922  void *pCtx /* First argument passed to xConflict */
175923 ){
175924  sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
175925  int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
175926  if( rc==SQLITE_OK ){
175927  rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
175928  }
175929  return rc;
175930 }
175931 
175932 /*
175933 ** sqlite3_changegroup handle.
175934 */
175935 struct sqlite3_changegroup {
175936  int rc; /* Error code */
175937  int bPatch; /* True to accumulate patchsets */
175938  SessionTable *pList; /* List of tables in current patch */
175939 };
175940 
175941 /*
175942 ** This function is called to merge two changes to the same row together as
175943 ** part of an sqlite3changeset_concat() operation. A new change object is
175944 ** allocated and a pointer to it stored in *ppNew.
175945 */
175946 static int sessionChangeMerge(
175947  SessionTable *pTab, /* Table structure */
175948  int bPatchset, /* True for patchsets */
175949  SessionChange *pExist, /* Existing change */
175950  int op2, /* Second change operation */
175951  int bIndirect, /* True if second change is indirect */
175952  u8 *aRec, /* Second change record */
175953  int nRec, /* Number of bytes in aRec */
175954  SessionChange **ppNew /* OUT: Merged change */
175955 ){
175956  SessionChange *pNew = 0;
175957 
175958  if( !pExist ){
175959  pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
175960  if( !pNew ){
175961  return SQLITE_NOMEM;
175962  }
175963  memset(pNew, 0, sizeof(SessionChange));
175964  pNew->op = op2;
175965  pNew->bIndirect = bIndirect;
175966  pNew->nRecord = nRec;
175967  pNew->aRecord = (u8*)&pNew[1];
175968  memcpy(pNew->aRecord, aRec, nRec);
175969  }else{
175970  int op1 = pExist->op;
175971 
175972  /*
175973  ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
175974  ** op1=INSERT, op2=UPDATE -> INSERT.
175975  ** op1=INSERT, op2=DELETE -> (none)
175976  **
175977  ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
175978  ** op1=UPDATE, op2=UPDATE -> UPDATE.
175979  ** op1=UPDATE, op2=DELETE -> DELETE.
175980  **
175981  ** op1=DELETE, op2=INSERT -> UPDATE.
175982  ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
175983  ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
175984  */
175985  if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
175986  || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
175987  || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
175988  || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
175989  ){
175990  pNew = pExist;
175991  }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
175992  sqlite3_free(pExist);
175993  assert( pNew==0 );
175994  }else{
175995  u8 *aExist = pExist->aRecord;
175996  int nByte;
175997  u8 *aCsr;
175998 
175999  /* Allocate a new SessionChange object. Ensure that the aRecord[]
176000  ** buffer of the new object is large enough to hold any record that
176001  ** may be generated by combining the input records. */
176002  nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
176003  pNew = (SessionChange *)sqlite3_malloc(nByte);
176004  if( !pNew ){
176005  sqlite3_free(pExist);
176006  return SQLITE_NOMEM;
176007  }
176008  memset(pNew, 0, sizeof(SessionChange));
176009  pNew->bIndirect = (bIndirect && pExist->bIndirect);
176010  aCsr = pNew->aRecord = (u8 *)&pNew[1];
176011 
176012  if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
176013  u8 *a1 = aRec;
176014  assert( op2==SQLITE_UPDATE );
176015  pNew->op = SQLITE_INSERT;
176016  if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
176017  sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
176018  }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
176019  assert( op2==SQLITE_INSERT );
176020  pNew->op = SQLITE_UPDATE;
176021  if( bPatchset ){
176022  memcpy(aCsr, aRec, nRec);
176023  aCsr += nRec;
176024  }else{
176025  if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
176026  sqlite3_free(pNew);
176027  pNew = 0;
176028  }
176029  }
176030  }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
176031  u8 *a1 = aExist;
176032  u8 *a2 = aRec;
176033  assert( op1==SQLITE_UPDATE );
176034  if( bPatchset==0 ){
176035  sessionSkipRecord(&a1, pTab->nCol);
176036  sessionSkipRecord(&a2, pTab->nCol);
176037  }
176038  pNew->op = SQLITE_UPDATE;
176039  if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
176040  sqlite3_free(pNew);
176041  pNew = 0;
176042  }
176043  }else{ /* UPDATE + DELETE */
176044  assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
176045  pNew->op = SQLITE_DELETE;
176046  if( bPatchset ){
176047  memcpy(aCsr, aRec, nRec);
176048  aCsr += nRec;
176049  }else{
176050  sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
176051  }
176052  }
176053 
176054  if( pNew ){
176055  pNew->nRecord = (int)(aCsr - pNew->aRecord);
176056  }
176057  sqlite3_free(pExist);
176058  }
176059  }
176060 
176061  *ppNew = pNew;
176062  return SQLITE_OK;
176063 }
176064 
176065 /*
176066 ** Add all changes in the changeset traversed by the iterator passed as
176067 ** the first argument to the changegroup hash tables.
176068 */
176069 static int sessionChangesetToHash(
176070  sqlite3_changeset_iter *pIter, /* Iterator to read from */
176071  sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
176072 ){
176073  u8 *aRec;
176074  int nRec;
176075  int rc = SQLITE_OK;
176076  SessionTable *pTab = 0;
176077 
176078 
176079  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
176080  const char *zNew;
176081  int nCol;
176082  int op;
176083  int iHash;
176084  int bIndirect;
176085  SessionChange *pChange;
176086  SessionChange *pExist = 0;
176087  SessionChange **pp;
176088 
176089  if( pGrp->pList==0 ){
176090  pGrp->bPatch = pIter->bPatchset;
176091  }else if( pIter->bPatchset!=pGrp->bPatch ){
176092  rc = SQLITE_ERROR;
176093  break;
176094  }
176095 
176096  sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
176097  if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
176098  /* Search the list for a matching table */
176099  int nNew = (int)strlen(zNew);
176100  u8 *abPK;
176101 
176102  sqlite3changeset_pk(pIter, &abPK, 0);
176103  for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
176104  if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
176105  }
176106  if( !pTab ){
176107  SessionTable **ppTab;
176108 
176109  pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
176110  if( !pTab ){
176111  rc = SQLITE_NOMEM;
176112  break;
176113  }
176114  memset(pTab, 0, sizeof(SessionTable));
176115  pTab->nCol = nCol;
176116  pTab->abPK = (u8*)&pTab[1];
176117  memcpy(pTab->abPK, abPK, nCol);
176118  pTab->zName = (char*)&pTab->abPK[nCol];
176119  memcpy(pTab->zName, zNew, nNew+1);
176120 
176121  /* The new object must be linked on to the end of the list, not
176122  ** simply added to the start of it. This is to ensure that the
176123  ** tables within the output of sqlite3changegroup_output() are in
176124  ** the right order. */
176125  for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
176126  *ppTab = pTab;
176127  }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
176128  rc = SQLITE_SCHEMA;
176129  break;
176130  }
176131  }
176132 
176133  if( sessionGrowHash(pIter->bPatchset, pTab) ){
176134  rc = SQLITE_NOMEM;
176135  break;
176136  }
176137  iHash = sessionChangeHash(
176138  pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
176139  );
176140 
176141  /* Search for existing entry. If found, remove it from the hash table.
176142  ** Code below may link it back in.
176143  */
176144  for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
176145  int bPkOnly1 = 0;
176146  int bPkOnly2 = 0;
176147  if( pIter->bPatchset ){
176148  bPkOnly1 = (*pp)->op==SQLITE_DELETE;
176149  bPkOnly2 = op==SQLITE_DELETE;
176150  }
176151  if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
176152  pExist = *pp;
176153  *pp = (*pp)->pNext;
176154  pTab->nEntry--;
176155  break;
176156  }
176157  }
176158 
176159  rc = sessionChangeMerge(pTab,
176160  pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
176161  );
176162  if( rc ) break;
176163  if( pChange ){
176164  pChange->pNext = pTab->apChange[iHash];
176165  pTab->apChange[iHash] = pChange;
176166  pTab->nEntry++;
176167  }
176168  }
176169 
176170  if( rc==SQLITE_OK ) rc = pIter->rc;
176171  return rc;
176172 }
176173 
176174 /*
176175 ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
176176 ** added to the changegroup object passed as the first argument.
176177 **
176178 ** If xOutput is not NULL, then the changeset/patchset is returned to the
176179 ** user via one or more calls to xOutput, as with the other streaming
176180 ** interfaces.
176181 **
176182 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
176183 ** buffer containing the output changeset before this function returns. In
176184 ** this case (*pnOut) is set to the size of the output buffer in bytes. It
176185 ** is the responsibility of the caller to free the output buffer using
176186 ** sqlite3_free() when it is no longer required.
176187 **
176188 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
176189 ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
176190 ** are both set to 0 before returning.
176191 */
176192 static int sessionChangegroupOutput(
176193  sqlite3_changegroup *pGrp,
176194  int (*xOutput)(void *pOut, const void *pData, int nData),
176195  void *pOut,
176196  int *pnOut,
176197  void **ppOut
176198 ){
176199  int rc = SQLITE_OK;
176200  SessionBuffer buf = {0, 0, 0};
176201  SessionTable *pTab;
176202  assert( xOutput==0 || (ppOut==0 && pnOut==0) );
176203 
176204  /* Create the serialized output changeset based on the contents of the
176205  ** hash tables attached to the SessionTable objects in list p->pList.
176206  */
176207  for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
176208  int i;
176209  if( pTab->nEntry==0 ) continue;
176210 
176211  sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
176212  for(i=0; i<pTab->nChange; i++){
176213  SessionChange *p;
176214  for(p=pTab->apChange[i]; p; p=p->pNext){
176215  sessionAppendByte(&buf, p->op, &rc);
176216  sessionAppendByte(&buf, p->bIndirect, &rc);
176217  sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
176218  }
176219  }
176220 
176221  if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
176222  rc = xOutput(pOut, buf.aBuf, buf.nBuf);
176223  buf.nBuf = 0;
176224  }
176225  }
176226 
176227  if( rc==SQLITE_OK ){
176228  if( xOutput ){
176229  if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
176230  }else{
176231  *ppOut = buf.aBuf;
176232  *pnOut = buf.nBuf;
176233  buf.aBuf = 0;
176234  }
176235  }
176236  sqlite3_free(buf.aBuf);
176237 
176238  return rc;
176239 }
176240 
176241 /*
176242 ** Allocate a new, empty, sqlite3_changegroup.
176243 */
176244 SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
176245  int rc = SQLITE_OK; /* Return code */
176246  sqlite3_changegroup *p; /* New object */
176247  p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
176248  if( p==0 ){
176249  rc = SQLITE_NOMEM;
176250  }else{
176251  memset(p, 0, sizeof(sqlite3_changegroup));
176252  }
176253  *pp = p;
176254  return rc;
176255 }
176256 
176257 /*
176258 ** Add the changeset currently stored in buffer pData, size nData bytes,
176259 ** to changeset-group p.
176260 */
176261 SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
176262  sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
176263  int rc; /* Return code */
176264 
176265  rc = sqlite3changeset_start(&pIter, nData, pData);
176266  if( rc==SQLITE_OK ){
176267  rc = sessionChangesetToHash(pIter, pGrp);
176268  }
176269  sqlite3changeset_finalize(pIter);
176270  return rc;
176271 }
176272 
176273 /*
176274 ** Obtain a buffer containing a changeset representing the concatenation
176275 ** of all changesets added to the group so far.
176276 */
176277 SQLITE_API int sqlite3changegroup_output(
176278  sqlite3_changegroup *pGrp,
176279  int *pnData,
176280  void **ppData
176281 ){
176282  return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
176283 }
176284 
176285 /*
176286 ** Streaming versions of changegroup_add().
176287 */
176288 SQLITE_API int sqlite3changegroup_add_strm(
176289  sqlite3_changegroup *pGrp,
176290  int (*xInput)(void *pIn, void *pData, int *pnData),
176291  void *pIn
176292 ){
176293  sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
176294  int rc; /* Return code */
176295 
176296  rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
176297  if( rc==SQLITE_OK ){
176298  rc = sessionChangesetToHash(pIter, pGrp);
176299  }
176300  sqlite3changeset_finalize(pIter);
176301  return rc;
176302 }
176303 
176304 /*
176305 ** Streaming versions of changegroup_output().
176306 */
176307 SQLITE_API int sqlite3changegroup_output_strm(
176308  sqlite3_changegroup *pGrp,
176309  int (*xOutput)(void *pOut, const void *pData, int nData),
176310  void *pOut
176311 ){
176312  return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
176313 }
176314 
176315 /*
176316 ** Delete a changegroup object.
176317 */
176318 SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
176319  if( pGrp ){
176320  sessionDeleteTable(pGrp->pList);
176321  sqlite3_free(pGrp);
176322  }
176323 }
176324 
176325 /*
176326 ** Combine two changesets together.
176327 */
176328 SQLITE_API int sqlite3changeset_concat(
176329  int nLeft, /* Number of bytes in lhs input */
176330  void *pLeft, /* Lhs input changeset */
176331  int nRight /* Number of bytes in rhs input */,
176332  void *pRight, /* Rhs input changeset */
176333  int *pnOut, /* OUT: Number of bytes in output changeset */
176334  void **ppOut /* OUT: changeset (left <concat> right) */
176335 ){
176336  sqlite3_changegroup *pGrp;
176337  int rc;
176338 
176339  rc = sqlite3changegroup_new(&pGrp);
176340  if( rc==SQLITE_OK ){
176341  rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
176342  }
176343  if( rc==SQLITE_OK ){
176344  rc = sqlite3changegroup_add(pGrp, nRight, pRight);
176345  }
176346  if( rc==SQLITE_OK ){
176347  rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
176348  }
176349  sqlite3changegroup_delete(pGrp);
176350 
176351  return rc;
176352 }
176353 
176354 /*
176355 ** Streaming version of sqlite3changeset_concat().
176356 */
176357 SQLITE_API int sqlite3changeset_concat_strm(
176358  int (*xInputA)(void *pIn, void *pData, int *pnData),
176359  void *pInA,
176360  int (*xInputB)(void *pIn, void *pData, int *pnData),
176361  void *pInB,
176362  int (*xOutput)(void *pOut, const void *pData, int nData),
176363  void *pOut
176364 ){
176365  sqlite3_changegroup *pGrp;
176366  int rc;
176367 
176368  rc = sqlite3changegroup_new(&pGrp);
176369  if( rc==SQLITE_OK ){
176370  rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
176371  }
176372  if( rc==SQLITE_OK ){
176373  rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
176374  }
176375  if( rc==SQLITE_OK ){
176376  rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
176377  }
176378  sqlite3changegroup_delete(pGrp);
176379 
176380  return rc;
176381 }
176382 
176383 #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
176384 
176385 /************** End of sqlite3session.c **************************************/
176386 /************** Begin file json1.c *******************************************/
176387 /*
176388 ** 2015-08-12
176389 **
176390 ** The author disclaims copyright to this source code. In place of
176391 ** a legal notice, here is a blessing:
176392 **
176393 ** May you do good and not evil.
176394 ** May you find forgiveness for yourself and forgive others.
176395 ** May you share freely, never taking more than you give.
176396 **
176397 ******************************************************************************
176398 **
176399 ** This SQLite extension implements JSON functions. The interface is
176400 ** modeled after MySQL JSON functions:
176401 **
176402 ** https://dev.mysql.com/doc/refman/5.7/en/json.html
176403 **
176404 ** For the time being, all JSON is stored as pure text. (We might add
176405 ** a JSONB type in the future which stores a binary encoding of JSON in
176406 ** a BLOB, but there is no support for JSONB in the current implementation.
176407 ** This implementation parses JSON text at 250 MB/s, so it is hard to see
176408 ** how JSONB might improve on that.)
176409 */
176410 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
176411 #if !defined(_SQLITEINT_H_)
176412 /* #include "sqlite3ext.h" */
176413 #endif
176414 SQLITE_EXTENSION_INIT1
176415 /* #include <assert.h> */
176416 /* #include <string.h> */
176417 /* #include <stdlib.h> */
176418 /* #include <stdarg.h> */
176419 
176420 /* Mark a function parameter as unused, to suppress nuisance compiler
176421 ** warnings. */
176422 #ifndef UNUSED_PARAM
176423 # define UNUSED_PARAM(X) (void)(X)
176424 #endif
176425 
176426 #ifndef LARGEST_INT64
176427 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
176428 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
176429 #endif
176430 
176431 /*
176432 ** Versions of isspace(), isalnum() and isdigit() to which it is safe
176433 ** to pass signed char values.
176434 */
176435 #ifdef sqlite3Isdigit
176436  /* Use the SQLite core versions if this routine is part of the
176437  ** SQLite amalgamation */
176438 # define safe_isdigit(x) sqlite3Isdigit(x)
176439 # define safe_isalnum(x) sqlite3Isalnum(x)
176440 #else
176441  /* Use the standard library for separate compilation */
176442 #include <ctype.h> /* amalgamator: keep */
176443 # define safe_isdigit(x) isdigit((unsigned char)(x))
176444 # define safe_isalnum(x) isalnum((unsigned char)(x))
176445 #endif
176446 
176447 /*
176448 ** Growing our own isspace() routine this way is twice as fast as
176449 ** the library isspace() function, resulting in a 7% overall performance
176450 ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
176451 */
176452 static const char jsonIsSpace[] = {
176453  0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
176454  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176455  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176456  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176457  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176458  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176459  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176460  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176461  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176462  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176463  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176464  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176465  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176466  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176467  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176468  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176469 };
176470 #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
176471 
176472 #ifndef SQLITE_AMALGAMATION
176473  /* Unsigned integer types. These are already defined in the sqliteInt.h,
176474  ** but the definitions need to be repeated for separate compilation. */
176475  typedef sqlite3_uint64 u64;
176476  typedef unsigned int u32;
176477  typedef unsigned char u8;
176478 #endif
176479 
176480 /* Objects */
176481 typedef struct JsonString JsonString;
176482 typedef struct JsonNode JsonNode;
176483 typedef struct JsonParse JsonParse;
176484 
176485 /* An instance of this object represents a JSON string
176486 ** under construction. Really, this is a generic string accumulator
176487 ** that can be and is used to create strings other than JSON.
176488 */
176489 struct JsonString {
176490  sqlite3_context *pCtx; /* Function context - put error messages here */
176491  char *zBuf; /* Append JSON content here */
176492  u64 nAlloc; /* Bytes of storage available in zBuf[] */
176493  u64 nUsed; /* Bytes of zBuf[] currently used */
176494  u8 bStatic; /* True if zBuf is static space */
176495  u8 bErr; /* True if an error has been encountered */
176496  char zSpace[100]; /* Initial static space */
176497 };
176498 
176499 /* JSON type values
176500 */
176501 #define JSON_NULL 0
176502 #define JSON_TRUE 1
176503 #define JSON_FALSE 2
176504 #define JSON_INT 3
176505 #define JSON_REAL 4
176506 #define JSON_STRING 5
176507 #define JSON_ARRAY 6
176508 #define JSON_OBJECT 7
176509 
176510 /* The "subtype" set for JSON values */
176511 #define JSON_SUBTYPE 74 /* Ascii for "J" */
176512 
176513 /*
176514 ** Names of the various JSON types:
176515 */
176516 static const char * const jsonType[] = {
176517  "null", "true", "false", "integer", "real", "text", "array", "object"
176518 };
176519 
176520 /* Bit values for the JsonNode.jnFlag field
176521 */
176522 #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
176523 #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
176524 #define JNODE_REMOVE 0x04 /* Do not output */
176525 #define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
176526 #define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
176527 #define JNODE_LABEL 0x20 /* Is a label of an object */
176528 
176529 
176530 /* A single node of parsed JSON
176531 */
176532 struct JsonNode {
176533  u8 eType; /* One of the JSON_ type values */
176534  u8 jnFlags; /* JNODE flags */
176535  u8 iVal; /* Replacement value when JNODE_REPLACE */
176536  u32 n; /* Bytes of content, or number of sub-nodes */
176537  union {
176538  const char *zJContent; /* Content for INT, REAL, and STRING */
176539  u32 iAppend; /* More terms for ARRAY and OBJECT */
176540  u32 iKey; /* Key for ARRAY objects in json_tree() */
176541  } u;
176542 };
176543 
176544 /* A completely parsed JSON string
176545 */
176546 struct JsonParse {
176547  u32 nNode; /* Number of slots of aNode[] used */
176548  u32 nAlloc; /* Number of slots of aNode[] allocated */
176549  JsonNode *aNode; /* Array of nodes containing the parse */
176550  const char *zJson; /* Original JSON string */
176551  u32 *aUp; /* Index of parent of each node */
176552  u8 oom; /* Set to true if out of memory */
176553  u8 nErr; /* Number of errors seen */
176554 };
176555 
176556 /**************************************************************************
176557 ** Utility routines for dealing with JsonString objects
176558 **************************************************************************/
176559 
176560 /* Set the JsonString object to an empty string
176561 */
176562 static void jsonZero(JsonString *p){
176563  p->zBuf = p->zSpace;
176564  p->nAlloc = sizeof(p->zSpace);
176565  p->nUsed = 0;
176566  p->bStatic = 1;
176567 }
176568 
176569 /* Initialize the JsonString object
176570 */
176571 static void jsonInit(JsonString *p, sqlite3_context *pCtx){
176572  p->pCtx = pCtx;
176573  p->bErr = 0;
176574  jsonZero(p);
176575 }
176576 
176577 
176578 /* Free all allocated memory and reset the JsonString object back to its
176579 ** initial state.
176580 */
176581 static void jsonReset(JsonString *p){
176582  if( !p->bStatic ) sqlite3_free(p->zBuf);
176583  jsonZero(p);
176584 }
176585 
176586 
176587 /* Report an out-of-memory (OOM) condition
176588 */
176589 static void jsonOom(JsonString *p){
176590  p->bErr = 1;
176591  sqlite3_result_error_nomem(p->pCtx);
176592  jsonReset(p);
176593 }
176594 
176595 /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
176596 ** Return zero on success. Return non-zero on an OOM error
176597 */
176598 static int jsonGrow(JsonString *p, u32 N){
176599  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
176600  char *zNew;
176601  if( p->bStatic ){
176602  if( p->bErr ) return 1;
176603  zNew = sqlite3_malloc64(nTotal);
176604  if( zNew==0 ){
176605  jsonOom(p);
176606  return SQLITE_NOMEM;
176607  }
176608  memcpy(zNew, p->zBuf, (size_t)p->nUsed);
176609  p->zBuf = zNew;
176610  p->bStatic = 0;
176611  }else{
176612  zNew = sqlite3_realloc64(p->zBuf, nTotal);
176613  if( zNew==0 ){
176614  jsonOom(p);
176615  return SQLITE_NOMEM;
176616  }
176617  p->zBuf = zNew;
176618  }
176619  p->nAlloc = nTotal;
176620  return SQLITE_OK;
176621 }
176622 
176623 /* Append N bytes from zIn onto the end of the JsonString string.
176624 */
176625 static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
176626  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
176627  memcpy(p->zBuf+p->nUsed, zIn, N);
176628  p->nUsed += N;
176629 }
176630 
176631 /* Append formatted text (not to exceed N bytes) to the JsonString.
176632 */
176633 static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
176634  va_list ap;
176635  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
176636  va_start(ap, zFormat);
176637  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
176638  va_end(ap);
176639  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
176640 }
176641 
176642 /* Append a single character
176643 */
176644 static void jsonAppendChar(JsonString *p, char c){
176645  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
176646  p->zBuf[p->nUsed++] = c;
176647 }
176648 
176649 /* Append a comma separator to the output buffer, if the previous
176650 ** character is not '[' or '{'.
176651 */
176652 static void jsonAppendSeparator(JsonString *p){
176653  char c;
176654  if( p->nUsed==0 ) return;
176655  c = p->zBuf[p->nUsed-1];
176656  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
176657 }
176658 
176659 /* Append the N-byte string in zIn to the end of the JsonString string
176660 ** under construction. Enclose the string in "..." and escape
176661 ** any double-quotes or backslash characters contained within the
176662 ** string.
176663 */
176664 static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
176665  u32 i;
176666  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
176667  p->zBuf[p->nUsed++] = '"';
176668  for(i=0; i<N; i++){
176669  unsigned char c = ((unsigned const char*)zIn)[i];
176670  if( c=='"' || c=='\\' ){
176671  json_simple_escape:
176672  if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
176673  p->zBuf[p->nUsed++] = '\\';
176674  }else if( c<=0x1f ){
176675  static const char aSpecial[] = {
176676  0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
176677  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
176678  };
176679  assert( sizeof(aSpecial)==32 );
176680  assert( aSpecial['\b']=='b' );
176681  assert( aSpecial['\f']=='f' );
176682  assert( aSpecial['\n']=='n' );
176683  assert( aSpecial['\r']=='r' );
176684  assert( aSpecial['\t']=='t' );
176685  if( aSpecial[c] ){
176686  c = aSpecial[c];
176687  goto json_simple_escape;
176688  }
176689  if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
176690  p->zBuf[p->nUsed++] = '\\';
176691  p->zBuf[p->nUsed++] = 'u';
176692  p->zBuf[p->nUsed++] = '0';
176693  p->zBuf[p->nUsed++] = '0';
176694  p->zBuf[p->nUsed++] = '0' + (c>>4);
176695  c = "0123456789abcdef"[c&0xf];
176696  }
176697  p->zBuf[p->nUsed++] = c;
176698  }
176699  p->zBuf[p->nUsed++] = '"';
176700  assert( p->nUsed<p->nAlloc );
176701 }
176702 
176703 /*
176704 ** Append a function parameter value to the JSON string under
176705 ** construction.
176706 */
176707 static void jsonAppendValue(
176708  JsonString *p, /* Append to this JSON string */
176709  sqlite3_value *pValue /* Value to append */
176710 ){
176711  switch( sqlite3_value_type(pValue) ){
176712  case SQLITE_NULL: {
176713  jsonAppendRaw(p, "null", 4);
176714  break;
176715  }
176716  case SQLITE_INTEGER:
176717  case SQLITE_FLOAT: {
176718  const char *z = (const char*)sqlite3_value_text(pValue);
176719  u32 n = (u32)sqlite3_value_bytes(pValue);
176720  jsonAppendRaw(p, z, n);
176721  break;
176722  }
176723  case SQLITE_TEXT: {
176724  const char *z = (const char*)sqlite3_value_text(pValue);
176725  u32 n = (u32)sqlite3_value_bytes(pValue);
176726  if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
176727  jsonAppendRaw(p, z, n);
176728  }else{
176729  jsonAppendString(p, z, n);
176730  }
176731  break;
176732  }
176733  default: {
176734  if( p->bErr==0 ){
176735  sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
176736  p->bErr = 2;
176737  jsonReset(p);
176738  }
176739  break;
176740  }
176741  }
176742 }
176743 
176744 
176745 /* Make the JSON in p the result of the SQL function.
176746 */
176747 static void jsonResult(JsonString *p){
176748  if( p->bErr==0 ){
176749  sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
176750  p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
176751  SQLITE_UTF8);
176752  jsonZero(p);
176753  }
176754  assert( p->bStatic );
176755 }
176756 
176757 /**************************************************************************
176758 ** Utility routines for dealing with JsonNode and JsonParse objects
176759 **************************************************************************/
176760 
176761 /*
176762 ** Return the number of consecutive JsonNode slots need to represent
176763 ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
176764 ** OBJECT types, the number might be larger.
176765 **
176766 ** Appended elements are not counted. The value returned is the number
176767 ** by which the JsonNode counter should increment in order to go to the
176768 ** next peer value.
176769 */
176770 static u32 jsonNodeSize(JsonNode *pNode){
176771  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
176772 }
176773 
176774 /*
176775 ** Reclaim all memory allocated by a JsonParse object. But do not
176776 ** delete the JsonParse object itself.
176777 */
176778 static void jsonParseReset(JsonParse *pParse){
176779  sqlite3_free(pParse->aNode);
176780  pParse->aNode = 0;
176781  pParse->nNode = 0;
176782  pParse->nAlloc = 0;
176783  sqlite3_free(pParse->aUp);
176784  pParse->aUp = 0;
176785 }
176786 
176787 /*
176788 ** Convert the JsonNode pNode into a pure JSON string and
176789 ** append to pOut. Subsubstructure is also included. Return
176790 ** the number of JsonNode objects that are encoded.
176791 */
176792 static void jsonRenderNode(
176793  JsonNode *pNode, /* The node to render */
176794  JsonString *pOut, /* Write JSON here */
176795  sqlite3_value **aReplace /* Replacement values */
176796 ){
176797  switch( pNode->eType ){
176798  default: {
176799  assert( pNode->eType==JSON_NULL );
176800  jsonAppendRaw(pOut, "null", 4);
176801  break;
176802  }
176803  case JSON_TRUE: {
176804  jsonAppendRaw(pOut, "true", 4);
176805  break;
176806  }
176807  case JSON_FALSE: {
176808  jsonAppendRaw(pOut, "false", 5);
176809  break;
176810  }
176811  case JSON_STRING: {
176812  if( pNode->jnFlags & JNODE_RAW ){
176813  jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
176814  break;
176815  }
176816  /* Fall through into the next case */
176817  }
176818  case JSON_REAL:
176819  case JSON_INT: {
176820  jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
176821  break;
176822  }
176823  case JSON_ARRAY: {
176824  u32 j = 1;
176825  jsonAppendChar(pOut, '[');
176826  for(;;){
176827  while( j<=pNode->n ){
176828  if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
176829  if( pNode[j].jnFlags & JNODE_REPLACE ){
176830  jsonAppendSeparator(pOut);
176831  jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
176832  }
176833  }else{
176834  jsonAppendSeparator(pOut);
176835  jsonRenderNode(&pNode[j], pOut, aReplace);
176836  }
176837  j += jsonNodeSize(&pNode[j]);
176838  }
176839  if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
176840  pNode = &pNode[pNode->u.iAppend];
176841  j = 1;
176842  }
176843  jsonAppendChar(pOut, ']');
176844  break;
176845  }
176846  case JSON_OBJECT: {
176847  u32 j = 1;
176848  jsonAppendChar(pOut, '{');
176849  for(;;){
176850  while( j<=pNode->n ){
176851  if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
176852  jsonAppendSeparator(pOut);
176853  jsonRenderNode(&pNode[j], pOut, aReplace);
176854  jsonAppendChar(pOut, ':');
176855  if( pNode[j+1].jnFlags & JNODE_REPLACE ){
176856  jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
176857  }else{
176858  jsonRenderNode(&pNode[j+1], pOut, aReplace);
176859  }
176860  }
176861  j += 1 + jsonNodeSize(&pNode[j+1]);
176862  }
176863  if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
176864  pNode = &pNode[pNode->u.iAppend];
176865  j = 1;
176866  }
176867  jsonAppendChar(pOut, '}');
176868  break;
176869  }
176870  }
176871 }
176872 
176873 /*
176874 ** Return a JsonNode and all its descendents as a JSON string.
176875 */
176876 static void jsonReturnJson(
176877  JsonNode *pNode, /* Node to return */
176878  sqlite3_context *pCtx, /* Return value for this function */
176879  sqlite3_value **aReplace /* Array of replacement values */
176880 ){
176881  JsonString s;
176882  jsonInit(&s, pCtx);
176883  jsonRenderNode(pNode, &s, aReplace);
176884  jsonResult(&s);
176885  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
176886 }
176887 
176888 /*
176889 ** Make the JsonNode the return value of the function.
176890 */
176891 static void jsonReturn(
176892  JsonNode *pNode, /* Node to return */
176893  sqlite3_context *pCtx, /* Return value for this function */
176894  sqlite3_value **aReplace /* Array of replacement values */
176895 ){
176896  switch( pNode->eType ){
176897  default: {
176898  assert( pNode->eType==JSON_NULL );
176899  sqlite3_result_null(pCtx);
176900  break;
176901  }
176902  case JSON_TRUE: {
176903  sqlite3_result_int(pCtx, 1);
176904  break;
176905  }
176906  case JSON_FALSE: {
176907  sqlite3_result_int(pCtx, 0);
176908  break;
176909  }
176910  case JSON_INT: {
176911  sqlite3_int64 i = 0;
176912  const char *z = pNode->u.zJContent;
176913  if( z[0]=='-' ){ z++; }
176914  while( z[0]>='0' && z[0]<='9' ){
176915  unsigned v = *(z++) - '0';
176916  if( i>=LARGEST_INT64/10 ){
176917  if( i>LARGEST_INT64/10 ) goto int_as_real;
176918  if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
176919  if( v==9 ) goto int_as_real;
176920  if( v==8 ){
176921  if( pNode->u.zJContent[0]=='-' ){
176922  sqlite3_result_int64(pCtx, SMALLEST_INT64);
176923  goto int_done;
176924  }else{
176925  goto int_as_real;
176926  }
176927  }
176928  }
176929  i = i*10 + v;
176930  }
176931  if( pNode->u.zJContent[0]=='-' ){ i = -i; }
176932  sqlite3_result_int64(pCtx, i);
176933  int_done:
176934  break;
176935  int_as_real: /* fall through to real */;
176936  }
176937  case JSON_REAL: {
176938  double r;
176939 #ifdef SQLITE_AMALGAMATION
176940  const char *z = pNode->u.zJContent;
176941  sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
176942 #else
176943  r = strtod(pNode->u.zJContent, 0);
176944 #endif
176945  sqlite3_result_double(pCtx, r);
176946  break;
176947  }
176948  case JSON_STRING: {
176949 #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
176950  ** json_insert() and json_replace() and those routines do not
176951  ** call jsonReturn() */
176952  if( pNode->jnFlags & JNODE_RAW ){
176953  sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
176954  SQLITE_TRANSIENT);
176955  }else
176956 #endif
176957  assert( (pNode->jnFlags & JNODE_RAW)==0 );
176958  if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
176959  /* JSON formatted without any backslash-escapes */
176960  sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
176961  SQLITE_TRANSIENT);
176962  }else{
176963  /* Translate JSON formatted string into raw text */
176964  u32 i;
176965  u32 n = pNode->n;
176966  const char *z = pNode->u.zJContent;
176967  char *zOut;
176968  u32 j;
176969  zOut = sqlite3_malloc( n+1 );
176970  if( zOut==0 ){
176971  sqlite3_result_error_nomem(pCtx);
176972  break;
176973  }
176974  for(i=1, j=0; i<n-1; i++){
176975  char c = z[i];
176976  if( c!='\\' ){
176977  zOut[j++] = c;
176978  }else{
176979  c = z[++i];
176980  if( c=='u' ){
176981  u32 v = 0, k;
176982  for(k=0; k<4 && i<n-2; i++, k++){
176983  c = z[i+1];
176984  if( c>='0' && c<='9' ) v = v*16 + c - '0';
176985  else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
176986  else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
176987  else break;
176988  }
176989  if( v==0 ) break;
176990  if( v<=0x7f ){
176991  zOut[j++] = (char)v;
176992  }else if( v<=0x7ff ){
176993  zOut[j++] = (char)(0xc0 | (v>>6));
176994  zOut[j++] = 0x80 | (v&0x3f);
176995  }else{
176996  zOut[j++] = (char)(0xe0 | (v>>12));
176997  zOut[j++] = 0x80 | ((v>>6)&0x3f);
176998  zOut[j++] = 0x80 | (v&0x3f);
176999  }
177000  }else{
177001  if( c=='b' ){
177002  c = '\b';
177003  }else if( c=='f' ){
177004  c = '\f';
177005  }else if( c=='n' ){
177006  c = '\n';
177007  }else if( c=='r' ){
177008  c = '\r';
177009  }else if( c=='t' ){
177010  c = '\t';
177011  }
177012  zOut[j++] = c;
177013  }
177014  }
177015  }
177016  zOut[j] = 0;
177017  sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
177018  }
177019  break;
177020  }
177021  case JSON_ARRAY:
177022  case JSON_OBJECT: {
177023  jsonReturnJson(pNode, pCtx, aReplace);
177024  break;
177025  }
177026  }
177027 }
177028 
177029 /* Forward reference */
177030 static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
177031 
177032 /*
177033 ** A macro to hint to the compiler that a function should not be
177034 ** inlined.
177035 */
177036 #if defined(__GNUC__)
177037 # define JSON_NOINLINE __attribute__((noinline))
177038 #elif defined(_MSC_VER) && _MSC_VER>=1310
177039 # define JSON_NOINLINE __declspec(noinline)
177040 #else
177041 # define JSON_NOINLINE
177042 #endif
177043 
177044 
177045 static JSON_NOINLINE int jsonParseAddNodeExpand(
177046  JsonParse *pParse, /* Append the node to this object */
177047  u32 eType, /* Node type */
177048  u32 n, /* Content size or sub-node count */
177049  const char *zContent /* Content */
177050 ){
177051  u32 nNew;
177052  JsonNode *pNew;
177053  assert( pParse->nNode>=pParse->nAlloc );
177054  if( pParse->oom ) return -1;
177055  nNew = pParse->nAlloc*2 + 10;
177056  pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
177057  if( pNew==0 ){
177058  pParse->oom = 1;
177059  return -1;
177060  }
177061  pParse->nAlloc = nNew;
177062  pParse->aNode = pNew;
177063  assert( pParse->nNode<pParse->nAlloc );
177064  return jsonParseAddNode(pParse, eType, n, zContent);
177065 }
177066 
177067 /*
177068 ** Create a new JsonNode instance based on the arguments and append that
177069 ** instance to the JsonParse. Return the index in pParse->aNode[] of the
177070 ** new node, or -1 if a memory allocation fails.
177071 */
177072 static int jsonParseAddNode(
177073  JsonParse *pParse, /* Append the node to this object */
177074  u32 eType, /* Node type */
177075  u32 n, /* Content size or sub-node count */
177076  const char *zContent /* Content */
177077 ){
177078  JsonNode *p;
177079  if( pParse->nNode>=pParse->nAlloc ){
177080  return jsonParseAddNodeExpand(pParse, eType, n, zContent);
177081  }
177082  p = &pParse->aNode[pParse->nNode];
177083  p->eType = (u8)eType;
177084  p->jnFlags = 0;
177085  p->iVal = 0;
177086  p->n = n;
177087  p->u.zJContent = zContent;
177088  return pParse->nNode++;
177089 }
177090 
177091 /*
177092 ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
177093 ** index of the first character past the end of the value parsed.
177094 **
177095 ** Return negative for a syntax error. Special cases: return -2 if the
177096 ** first non-whitespace character is '}' and return -3 if the first
177097 ** non-whitespace character is ']'.
177098 */
177099 static int jsonParseValue(JsonParse *pParse, u32 i){
177100  char c;
177101  u32 j;
177102  int iThis;
177103  int x;
177104  JsonNode *pNode;
177105  while( safe_isspace(pParse->zJson[i]) ){ i++; }
177106  if( (c = pParse->zJson[i])=='{' ){
177107  /* Parse object */
177108  iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
177109  if( iThis<0 ) return -1;
177110  for(j=i+1;;j++){
177111  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177112  x = jsonParseValue(pParse, j);
177113  if( x<0 ){
177114  if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
177115  return -1;
177116  }
177117  if( pParse->oom ) return -1;
177118  pNode = &pParse->aNode[pParse->nNode-1];
177119  if( pNode->eType!=JSON_STRING ) return -1;
177120  pNode->jnFlags |= JNODE_LABEL;
177121  j = x;
177122  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177123  if( pParse->zJson[j]!=':' ) return -1;
177124  j++;
177125  x = jsonParseValue(pParse, j);
177126  if( x<0 ) return -1;
177127  j = x;
177128  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177129  c = pParse->zJson[j];
177130  if( c==',' ) continue;
177131  if( c!='}' ) return -1;
177132  break;
177133  }
177134  pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
177135  return j+1;
177136  }else if( c=='[' ){
177137  /* Parse array */
177138  iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
177139  if( iThis<0 ) return -1;
177140  for(j=i+1;;j++){
177141  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177142  x = jsonParseValue(pParse, j);
177143  if( x<0 ){
177144  if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
177145  return -1;
177146  }
177147  j = x;
177148  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177149  c = pParse->zJson[j];
177150  if( c==',' ) continue;
177151  if( c!=']' ) return -1;
177152  break;
177153  }
177154  pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
177155  return j+1;
177156  }else if( c=='"' ){
177157  /* Parse string */
177158  u8 jnFlags = 0;
177159  j = i+1;
177160  for(;;){
177161  c = pParse->zJson[j];
177162  if( c==0 ) return -1;
177163  if( c=='\\' ){
177164  c = pParse->zJson[++j];
177165  if( c==0 ) return -1;
177166  jnFlags = JNODE_ESCAPE;
177167  }else if( c=='"' ){
177168  break;
177169  }
177170  j++;
177171  }
177172  jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
177173  if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
177174  return j+1;
177175  }else if( c=='n'
177176  && strncmp(pParse->zJson+i,"null",4)==0
177177  && !safe_isalnum(pParse->zJson[i+4]) ){
177178  jsonParseAddNode(pParse, JSON_NULL, 0, 0);
177179  return i+4;
177180  }else if( c=='t'
177181  && strncmp(pParse->zJson+i,"true",4)==0
177182  && !safe_isalnum(pParse->zJson[i+4]) ){
177183  jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
177184  return i+4;
177185  }else if( c=='f'
177186  && strncmp(pParse->zJson+i,"false",5)==0
177187  && !safe_isalnum(pParse->zJson[i+5]) ){
177188  jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
177189  return i+5;
177190  }else if( c=='-' || (c>='0' && c<='9') ){
177191  /* Parse number */
177192  u8 seenDP = 0;
177193  u8 seenE = 0;
177194  j = i+1;
177195  for(;; j++){
177196  c = pParse->zJson[j];
177197  if( c>='0' && c<='9' ) continue;
177198  if( c=='.' ){
177199  if( pParse->zJson[j-1]=='-' ) return -1;
177200  if( seenDP ) return -1;
177201  seenDP = 1;
177202  continue;
177203  }
177204  if( c=='e' || c=='E' ){
177205  if( pParse->zJson[j-1]<'0' ) return -1;
177206  if( seenE ) return -1;
177207  seenDP = seenE = 1;
177208  c = pParse->zJson[j+1];
177209  if( c=='+' || c=='-' ){
177210  j++;
177211  c = pParse->zJson[j+1];
177212  }
177213  if( c<'0' || c>'9' ) return -1;
177214  continue;
177215  }
177216  break;
177217  }
177218  if( pParse->zJson[j-1]<'0' ) return -1;
177219  jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
177220  j - i, &pParse->zJson[i]);
177221  return j;
177222  }else if( c=='}' ){
177223  return -2; /* End of {...} */
177224  }else if( c==']' ){
177225  return -3; /* End of [...] */
177226  }else if( c==0 ){
177227  return 0; /* End of file */
177228  }else{
177229  return -1; /* Syntax error */
177230  }
177231 }
177232 
177233 /*
177234 ** Parse a complete JSON string. Return 0 on success or non-zero if there
177235 ** are any errors. If an error occurs, free all memory associated with
177236 ** pParse.
177237 **
177238 ** pParse is uninitialized when this routine is called.
177239 */
177240 static int jsonParse(
177241  JsonParse *pParse, /* Initialize and fill this JsonParse object */
177242  sqlite3_context *pCtx, /* Report errors here */
177243  const char *zJson /* Input JSON text to be parsed */
177244 ){
177245  int i;
177246  memset(pParse, 0, sizeof(*pParse));
177247  if( zJson==0 ) return 1;
177248  pParse->zJson = zJson;
177249  i = jsonParseValue(pParse, 0);
177250  if( pParse->oom ) i = -1;
177251  if( i>0 ){
177252  while( safe_isspace(zJson[i]) ) i++;
177253  if( zJson[i] ) i = -1;
177254  }
177255  if( i<=0 ){
177256  if( pCtx!=0 ){
177257  if( pParse->oom ){
177258  sqlite3_result_error_nomem(pCtx);
177259  }else{
177260  sqlite3_result_error(pCtx, "malformed JSON", -1);
177261  }
177262  }
177263  jsonParseReset(pParse);
177264  return 1;
177265  }
177266  return 0;
177267 }
177268 
177269 /* Mark node i of pParse as being a child of iParent. Call recursively
177270 ** to fill in all the descendants of node i.
177271 */
177272 static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
177273  JsonNode *pNode = &pParse->aNode[i];
177274  u32 j;
177275  pParse->aUp[i] = iParent;
177276  switch( pNode->eType ){
177277  case JSON_ARRAY: {
177278  for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
177279  jsonParseFillInParentage(pParse, i+j, i);
177280  }
177281  break;
177282  }
177283  case JSON_OBJECT: {
177284  for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
177285  pParse->aUp[i+j] = i;
177286  jsonParseFillInParentage(pParse, i+j+1, i);
177287  }
177288  break;
177289  }
177290  default: {
177291  break;
177292  }
177293  }
177294 }
177295 
177296 /*
177297 ** Compute the parentage of all nodes in a completed parse.
177298 */
177299 static int jsonParseFindParents(JsonParse *pParse){
177300  u32 *aUp;
177301  assert( pParse->aUp==0 );
177302  aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
177303  if( aUp==0 ){
177304  pParse->oom = 1;
177305  return SQLITE_NOMEM;
177306  }
177307  jsonParseFillInParentage(pParse, 0, 0);
177308  return SQLITE_OK;
177309 }
177310 
177311 /*
177312 ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
177313 ** a match.
177314 */
177315 static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
177316  if( pNode->jnFlags & JNODE_RAW ){
177317  if( pNode->n!=nKey ) return 0;
177318  return strncmp(pNode->u.zJContent, zKey, nKey)==0;
177319  }else{
177320  if( pNode->n!=nKey+2 ) return 0;
177321  return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
177322  }
177323 }
177324 
177325 /* forward declaration */
177326 static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
177327 
177328 /*
177329 ** Search along zPath to find the node specified. Return a pointer
177330 ** to that node, or NULL if zPath is malformed or if there is no such
177331 ** node.
177332 **
177333 ** If pApnd!=0, then try to append new nodes to complete zPath if it is
177334 ** possible to do so and if no existing node corresponds to zPath. If
177335 ** new nodes are appended *pApnd is set to 1.
177336 */
177337 static JsonNode *jsonLookupStep(
177338  JsonParse *pParse, /* The JSON to search */
177339  u32 iRoot, /* Begin the search at this node */
177340  const char *zPath, /* The path to search */
177341  int *pApnd, /* Append nodes to complete path if not NULL */
177342  const char **pzErr /* Make *pzErr point to any syntax error in zPath */
177343 ){
177344  u32 i, j, nKey;
177345  const char *zKey;
177346  JsonNode *pRoot = &pParse->aNode[iRoot];
177347  if( zPath[0]==0 ) return pRoot;
177348  if( zPath[0]=='.' ){
177349  if( pRoot->eType!=JSON_OBJECT ) return 0;
177350  zPath++;
177351  if( zPath[0]=='"' ){
177352  zKey = zPath + 1;
177353  for(i=1; zPath[i] && zPath[i]!='"'; i++){}
177354  nKey = i-1;
177355  if( zPath[i] ){
177356  i++;
177357  }else{
177358  *pzErr = zPath;
177359  return 0;
177360  }
177361  }else{
177362  zKey = zPath;
177363  for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
177364  nKey = i;
177365  }
177366  if( nKey==0 ){
177367  *pzErr = zPath;
177368  return 0;
177369  }
177370  j = 1;
177371  for(;;){
177372  while( j<=pRoot->n ){
177373  if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
177374  return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
177375  }
177376  j++;
177377  j += jsonNodeSize(&pRoot[j]);
177378  }
177379  if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
177380  iRoot += pRoot->u.iAppend;
177381  pRoot = &pParse->aNode[iRoot];
177382  j = 1;
177383  }
177384  if( pApnd ){
177385  u32 iStart, iLabel;
177386  JsonNode *pNode;
177387  iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
177388  iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
177389  zPath += i;
177390  pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
177391  if( pParse->oom ) return 0;
177392  if( pNode ){
177393  pRoot = &pParse->aNode[iRoot];
177394  pRoot->u.iAppend = iStart - iRoot;
177395  pRoot->jnFlags |= JNODE_APPEND;
177396  pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
177397  }
177398  return pNode;
177399  }
177400  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
177401  if( pRoot->eType!=JSON_ARRAY ) return 0;
177402  i = 0;
177403  j = 1;
177404  while( safe_isdigit(zPath[j]) ){
177405  i = i*10 + zPath[j] - '0';
177406  j++;
177407  }
177408  if( zPath[j]!=']' ){
177409  *pzErr = zPath;
177410  return 0;
177411  }
177412  zPath += j + 1;
177413  j = 1;
177414  for(;;){
177415  while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
177416  if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
177417  j += jsonNodeSize(&pRoot[j]);
177418  }
177419  if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
177420  iRoot += pRoot->u.iAppend;
177421  pRoot = &pParse->aNode[iRoot];
177422  j = 1;
177423  }
177424  if( j<=pRoot->n ){
177425  return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
177426  }
177427  if( i==0 && pApnd ){
177428  u32 iStart;
177429  JsonNode *pNode;
177430  iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
177431  pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
177432  if( pParse->oom ) return 0;
177433  if( pNode ){
177434  pRoot = &pParse->aNode[iRoot];
177435  pRoot->u.iAppend = iStart - iRoot;
177436  pRoot->jnFlags |= JNODE_APPEND;
177437  }
177438  return pNode;
177439  }
177440  }else{
177441  *pzErr = zPath;
177442  }
177443  return 0;
177444 }
177445 
177446 /*
177447 ** Append content to pParse that will complete zPath. Return a pointer
177448 ** to the inserted node, or return NULL if the append fails.
177449 */
177450 static JsonNode *jsonLookupAppend(
177451  JsonParse *pParse, /* Append content to the JSON parse */
177452  const char *zPath, /* Description of content to append */
177453  int *pApnd, /* Set this flag to 1 */
177454  const char **pzErr /* Make this point to any syntax error */
177455 ){
177456  *pApnd = 1;
177457  if( zPath[0]==0 ){
177458  jsonParseAddNode(pParse, JSON_NULL, 0, 0);
177459  return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
177460  }
177461  if( zPath[0]=='.' ){
177462  jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
177463  }else if( strncmp(zPath,"[0]",3)==0 ){
177464  jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
177465  }else{
177466  return 0;
177467  }
177468  if( pParse->oom ) return 0;
177469  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
177470 }
177471 
177472 /*
177473 ** Return the text of a syntax error message on a JSON path. Space is
177474 ** obtained from sqlite3_malloc().
177475 */
177476 static char *jsonPathSyntaxError(const char *zErr){
177477  return sqlite3_mprintf("JSON path error near '%q'", zErr);
177478 }
177479 
177480 /*
177481 ** Do a node lookup using zPath. Return a pointer to the node on success.
177482 ** Return NULL if not found or if there is an error.
177483 **
177484 ** On an error, write an error message into pCtx and increment the
177485 ** pParse->nErr counter.
177486 **
177487 ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
177488 ** nodes are appended.
177489 */
177490 static JsonNode *jsonLookup(
177491  JsonParse *pParse, /* The JSON to search */
177492  const char *zPath, /* The path to search */
177493  int *pApnd, /* Append nodes to complete path if not NULL */
177494  sqlite3_context *pCtx /* Report errors here, if not NULL */
177495 ){
177496  const char *zErr = 0;
177497  JsonNode *pNode = 0;
177498  char *zMsg;
177499 
177500  if( zPath==0 ) return 0;
177501  if( zPath[0]!='$' ){
177502  zErr = zPath;
177503  goto lookup_err;
177504  }
177505  zPath++;
177506  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
177507  if( zErr==0 ) return pNode;
177508 
177509 lookup_err:
177510  pParse->nErr++;
177511  assert( zErr!=0 && pCtx!=0 );
177512  zMsg = jsonPathSyntaxError(zErr);
177513  if( zMsg ){
177514  sqlite3_result_error(pCtx, zMsg, -1);
177515  sqlite3_free(zMsg);
177516  }else{
177517  sqlite3_result_error_nomem(pCtx);
177518  }
177519  return 0;
177520 }
177521 
177522 
177523 /*
177524 ** Report the wrong number of arguments for json_insert(), json_replace()
177525 ** or json_set().
177526 */
177527 static void jsonWrongNumArgs(
177528  sqlite3_context *pCtx,
177529  const char *zFuncName
177530 ){
177531  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
177532  zFuncName);
177533  sqlite3_result_error(pCtx, zMsg, -1);
177534  sqlite3_free(zMsg);
177535 }
177536 
177537 
177538 /****************************************************************************
177539 ** SQL functions used for testing and debugging
177540 ****************************************************************************/
177541 
177542 #ifdef SQLITE_DEBUG
177543 /*
177544 ** The json_parse(JSON) function returns a string which describes
177545 ** a parse of the JSON provided. Or it returns NULL if JSON is not
177546 ** well-formed.
177547 */
177548 static void jsonParseFunc(
177549  sqlite3_context *ctx,
177550  int argc,
177551  sqlite3_value **argv
177552 ){
177553  JsonString s; /* Output string - not real JSON */
177554  JsonParse x; /* The parse */
177555  u32 i;
177556 
177557  assert( argc==1 );
177558  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177559  jsonParseFindParents(&x);
177560  jsonInit(&s, ctx);
177561  for(i=0; i<x.nNode; i++){
177562  const char *zType;
177563  if( x.aNode[i].jnFlags & JNODE_LABEL ){
177564  assert( x.aNode[i].eType==JSON_STRING );
177565  zType = "label";
177566  }else{
177567  zType = jsonType[x.aNode[i].eType];
177568  }
177569  jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
177570  i, zType, x.aNode[i].n, x.aUp[i]);
177571  if( x.aNode[i].u.zJContent!=0 ){
177572  jsonAppendRaw(&s, " ", 1);
177573  jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
177574  }
177575  jsonAppendRaw(&s, "\n", 1);
177576  }
177577  jsonParseReset(&x);
177578  jsonResult(&s);
177579 }
177580 
177581 /*
177582 ** The json_test1(JSON) function return true (1) if the input is JSON
177583 ** text generated by another json function. It returns (0) if the input
177584 ** is not known to be JSON.
177585 */
177586 static void jsonTest1Func(
177587  sqlite3_context *ctx,
177588  int argc,
177589  sqlite3_value **argv
177590 ){
177591  UNUSED_PARAM(argc);
177592  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
177593 }
177594 #endif /* SQLITE_DEBUG */
177595 
177596 /****************************************************************************
177597 ** Scalar SQL function implementations
177598 ****************************************************************************/
177599 
177600 /*
177601 ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
177602 ** corresponding to the SQL value input. Mostly this means putting
177603 ** double-quotes around strings and returning the unquoted string "null"
177604 ** when given a NULL input.
177605 */
177606 static void jsonQuoteFunc(
177607  sqlite3_context *ctx,
177608  int argc,
177609  sqlite3_value **argv
177610 ){
177611  JsonString jx;
177612  UNUSED_PARAM(argc);
177613 
177614  jsonInit(&jx, ctx);
177615  jsonAppendValue(&jx, argv[0]);
177616  jsonResult(&jx);
177617  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
177618 }
177619 
177620 /*
177621 ** Implementation of the json_array(VALUE,...) function. Return a JSON
177622 ** array that contains all values given in arguments. Or if any argument
177623 ** is a BLOB, throw an error.
177624 */
177625 static void jsonArrayFunc(
177626  sqlite3_context *ctx,
177627  int argc,
177628  sqlite3_value **argv
177629 ){
177630  int i;
177631  JsonString jx;
177632 
177633  jsonInit(&jx, ctx);
177634  jsonAppendChar(&jx, '[');
177635  for(i=0; i<argc; i++){
177636  jsonAppendSeparator(&jx);
177637  jsonAppendValue(&jx, argv[i]);
177638  }
177639  jsonAppendChar(&jx, ']');
177640  jsonResult(&jx);
177641  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
177642 }
177643 
177644 
177645 /*
177646 ** json_array_length(JSON)
177647 ** json_array_length(JSON, PATH)
177648 **
177649 ** Return the number of elements in the top-level JSON array.
177650 ** Return 0 if the input is not a well-formed JSON array.
177651 */
177652 static void jsonArrayLengthFunc(
177653  sqlite3_context *ctx,
177654  int argc,
177655  sqlite3_value **argv
177656 ){
177657  JsonParse x; /* The parse */
177658  sqlite3_int64 n = 0;
177659  u32 i;
177660  JsonNode *pNode;
177661 
177662  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177663  assert( x.nNode );
177664  if( argc==2 ){
177665  const char *zPath = (const char*)sqlite3_value_text(argv[1]);
177666  pNode = jsonLookup(&x, zPath, 0, ctx);
177667  }else{
177668  pNode = x.aNode;
177669  }
177670  if( pNode==0 ){
177671  x.nErr = 1;
177672  }else if( pNode->eType==JSON_ARRAY ){
177673  assert( (pNode->jnFlags & JNODE_APPEND)==0 );
177674  for(i=1; i<=pNode->n; n++){
177675  i += jsonNodeSize(&pNode[i]);
177676  }
177677  }
177678  if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
177679  jsonParseReset(&x);
177680 }
177681 
177682 /*
177683 ** json_extract(JSON, PATH, ...)
177684 **
177685 ** Return the element described by PATH. Return NULL if there is no
177686 ** PATH element. If there are multiple PATHs, then return a JSON array
177687 ** with the result from each path. Throw an error if the JSON or any PATH
177688 ** is malformed.
177689 */
177690 static void jsonExtractFunc(
177691  sqlite3_context *ctx,
177692  int argc,
177693  sqlite3_value **argv
177694 ){
177695  JsonParse x; /* The parse */
177696  JsonNode *pNode;
177697  const char *zPath;
177698  JsonString jx;
177699  int i;
177700 
177701  if( argc<2 ) return;
177702  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177703  jsonInit(&jx, ctx);
177704  jsonAppendChar(&jx, '[');
177705  for(i=1; i<argc; i++){
177706  zPath = (const char*)sqlite3_value_text(argv[i]);
177707  pNode = jsonLookup(&x, zPath, 0, ctx);
177708  if( x.nErr ) break;
177709  if( argc>2 ){
177710  jsonAppendSeparator(&jx);
177711  if( pNode ){
177712  jsonRenderNode(pNode, &jx, 0);
177713  }else{
177714  jsonAppendRaw(&jx, "null", 4);
177715  }
177716  }else if( pNode ){
177717  jsonReturn(pNode, ctx, 0);
177718  }
177719  }
177720  if( argc>2 && i==argc ){
177721  jsonAppendChar(&jx, ']');
177722  jsonResult(&jx);
177723  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
177724  }
177725  jsonReset(&jx);
177726  jsonParseReset(&x);
177727 }
177728 
177729 /*
177730 ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
177731 ** object that contains all name/value given in arguments. Or if any name
177732 ** is not a string or if any value is a BLOB, throw an error.
177733 */
177734 static void jsonObjectFunc(
177735  sqlite3_context *ctx,
177736  int argc,
177737  sqlite3_value **argv
177738 ){
177739  int i;
177740  JsonString jx;
177741  const char *z;
177742  u32 n;
177743 
177744  if( argc&1 ){
177745  sqlite3_result_error(ctx, "json_object() requires an even number "
177746  "of arguments", -1);
177747  return;
177748  }
177749  jsonInit(&jx, ctx);
177750  jsonAppendChar(&jx, '{');
177751  for(i=0; i<argc; i+=2){
177752  if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
177753  sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
177754  jsonReset(&jx);
177755  return;
177756  }
177757  jsonAppendSeparator(&jx);
177758  z = (const char*)sqlite3_value_text(argv[i]);
177759  n = (u32)sqlite3_value_bytes(argv[i]);
177760  jsonAppendString(&jx, z, n);
177761  jsonAppendChar(&jx, ':');
177762  jsonAppendValue(&jx, argv[i+1]);
177763  }
177764  jsonAppendChar(&jx, '}');
177765  jsonResult(&jx);
177766  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
177767 }
177768 
177769 
177770 /*
177771 ** json_remove(JSON, PATH, ...)
177772 **
177773 ** Remove the named elements from JSON and return the result. malformed
177774 ** JSON or PATH arguments result in an error.
177775 */
177776 static void jsonRemoveFunc(
177777  sqlite3_context *ctx,
177778  int argc,
177779  sqlite3_value **argv
177780 ){
177781  JsonParse x; /* The parse */
177782  JsonNode *pNode;
177783  const char *zPath;
177784  u32 i;
177785 
177786  if( argc<1 ) return;
177787  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177788  assert( x.nNode );
177789  for(i=1; i<(u32)argc; i++){
177790  zPath = (const char*)sqlite3_value_text(argv[i]);
177791  if( zPath==0 ) goto remove_done;
177792  pNode = jsonLookup(&x, zPath, 0, ctx);
177793  if( x.nErr ) goto remove_done;
177794  if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
177795  }
177796  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
177797  jsonReturnJson(x.aNode, ctx, 0);
177798  }
177799 remove_done:
177800  jsonParseReset(&x);
177801 }
177802 
177803 /*
177804 ** json_replace(JSON, PATH, VALUE, ...)
177805 **
177806 ** Replace the value at PATH with VALUE. If PATH does not already exist,
177807 ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
177808 */
177809 static void jsonReplaceFunc(
177810  sqlite3_context *ctx,
177811  int argc,
177812  sqlite3_value **argv
177813 ){
177814  JsonParse x; /* The parse */
177815  JsonNode *pNode;
177816  const char *zPath;
177817  u32 i;
177818 
177819  if( argc<1 ) return;
177820  if( (argc&1)==0 ) {
177821  jsonWrongNumArgs(ctx, "replace");
177822  return;
177823  }
177824  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177825  assert( x.nNode );
177826  for(i=1; i<(u32)argc; i+=2){
177827  zPath = (const char*)sqlite3_value_text(argv[i]);
177828  pNode = jsonLookup(&x, zPath, 0, ctx);
177829  if( x.nErr ) goto replace_err;
177830  if( pNode ){
177831  pNode->jnFlags |= (u8)JNODE_REPLACE;
177832  pNode->iVal = (u8)(i+1);
177833  }
177834  }
177835  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
177836  sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
177837  }else{
177838  jsonReturnJson(x.aNode, ctx, argv);
177839  }
177840 replace_err:
177841  jsonParseReset(&x);
177842 }
177843 
177844 /*
177845 ** json_set(JSON, PATH, VALUE, ...)
177846 **
177847 ** Set the value at PATH to VALUE. Create the PATH if it does not already
177848 ** exist. Overwrite existing values that do exist.
177849 ** If JSON or PATH is malformed, throw an error.
177850 **
177851 ** json_insert(JSON, PATH, VALUE, ...)
177852 **
177853 ** Create PATH and initialize it to VALUE. If PATH already exists, this
177854 ** routine is a no-op. If JSON or PATH is malformed, throw an error.
177855 */
177856 static void jsonSetFunc(
177857  sqlite3_context *ctx,
177858  int argc,
177859  sqlite3_value **argv
177860 ){
177861  JsonParse x; /* The parse */
177862  JsonNode *pNode;
177863  const char *zPath;
177864  u32 i;
177865  int bApnd;
177866  int bIsSet = *(int*)sqlite3_user_data(ctx);
177867 
177868  if( argc<1 ) return;
177869  if( (argc&1)==0 ) {
177870  jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
177871  return;
177872  }
177873  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177874  assert( x.nNode );
177875  for(i=1; i<(u32)argc; i+=2){
177876  zPath = (const char*)sqlite3_value_text(argv[i]);
177877  bApnd = 0;
177878  pNode = jsonLookup(&x, zPath, &bApnd, ctx);
177879  if( x.oom ){
177880  sqlite3_result_error_nomem(ctx);
177881  goto jsonSetDone;
177882  }else if( x.nErr ){
177883  goto jsonSetDone;
177884  }else if( pNode && (bApnd || bIsSet) ){
177885  pNode->jnFlags |= (u8)JNODE_REPLACE;
177886  pNode->iVal = (u8)(i+1);
177887  }
177888  }
177889  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
177890  sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
177891  }else{
177892  jsonReturnJson(x.aNode, ctx, argv);
177893  }
177894 jsonSetDone:
177895  jsonParseReset(&x);
177896 }
177897 
177898 /*
177899 ** json_type(JSON)
177900 ** json_type(JSON, PATH)
177901 **
177902 ** Return the top-level "type" of a JSON string. Throw an error if
177903 ** either the JSON or PATH inputs are not well-formed.
177904 */
177905 static void jsonTypeFunc(
177906  sqlite3_context *ctx,
177907  int argc,
177908  sqlite3_value **argv
177909 ){
177910  JsonParse x; /* The parse */
177911  const char *zPath;
177912  JsonNode *pNode;
177913 
177914  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177915  assert( x.nNode );
177916  if( argc==2 ){
177917  zPath = (const char*)sqlite3_value_text(argv[1]);
177918  pNode = jsonLookup(&x, zPath, 0, ctx);
177919  }else{
177920  pNode = x.aNode;
177921  }
177922  if( pNode ){
177923  sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
177924  }
177925  jsonParseReset(&x);
177926 }
177927 
177928 /*
177929 ** json_valid(JSON)
177930 **
177931 ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
177932 ** Return 0 otherwise.
177933 */
177934 static void jsonValidFunc(
177935  sqlite3_context *ctx,
177936  int argc,
177937  sqlite3_value **argv
177938 ){
177939  JsonParse x; /* The parse */
177940  int rc = 0;
177941 
177942  UNUSED_PARAM(argc);
177943  if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
177944  rc = 1;
177945  }
177946  jsonParseReset(&x);
177947  sqlite3_result_int(ctx, rc);
177948 }
177949 
177950 
177951 /****************************************************************************
177952 ** Aggregate SQL function implementations
177953 ****************************************************************************/
177954 /*
177955 ** json_group_array(VALUE)
177956 **
177957 ** Return a JSON array composed of all values in the aggregate.
177958 */
177959 static void jsonArrayStep(
177960  sqlite3_context *ctx,
177961  int argc,
177962  sqlite3_value **argv
177963 ){
177964  JsonString *pStr;
177965  UNUSED_PARAM(argc);
177966  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
177967  if( pStr ){
177968  if( pStr->zBuf==0 ){
177969  jsonInit(pStr, ctx);
177970  jsonAppendChar(pStr, '[');
177971  }else{
177972  jsonAppendChar(pStr, ',');
177973  pStr->pCtx = ctx;
177974  }
177975  jsonAppendValue(pStr, argv[0]);
177976  }
177977 }
177978 static void jsonArrayFinal(sqlite3_context *ctx){
177979  JsonString *pStr;
177980  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
177981  if( pStr ){
177982  pStr->pCtx = ctx;
177983  jsonAppendChar(pStr, ']');
177984  if( pStr->bErr ){
177985  if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
177986  assert( pStr->bStatic );
177987  }else{
177988  sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
177989  pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
177990  pStr->bStatic = 1;
177991  }
177992  }else{
177993  sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
177994  }
177995  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
177996 }
177997 
177998 /*
177999 ** json_group_obj(NAME,VALUE)
178000 **
178001 ** Return a JSON object composed of all names and values in the aggregate.
178002 */
178003 static void jsonObjectStep(
178004  sqlite3_context *ctx,
178005  int argc,
178006  sqlite3_value **argv
178007 ){
178008  JsonString *pStr;
178009  const char *z;
178010  u32 n;
178011  UNUSED_PARAM(argc);
178012  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
178013  if( pStr ){
178014  if( pStr->zBuf==0 ){
178015  jsonInit(pStr, ctx);
178016  jsonAppendChar(pStr, '{');
178017  }else{
178018  jsonAppendChar(pStr, ',');
178019  pStr->pCtx = ctx;
178020  }
178021  z = (const char*)sqlite3_value_text(argv[0]);
178022  n = (u32)sqlite3_value_bytes(argv[0]);
178023  jsonAppendString(pStr, z, n);
178024  jsonAppendChar(pStr, ':');
178025  jsonAppendValue(pStr, argv[1]);
178026  }
178027 }
178028 static void jsonObjectFinal(sqlite3_context *ctx){
178029  JsonString *pStr;
178030  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
178031  if( pStr ){
178032  jsonAppendChar(pStr, '}');
178033  if( pStr->bErr ){
178034  if( pStr->bErr==0 ) sqlite3_result_error_nomem(ctx);
178035  assert( pStr->bStatic );
178036  }else{
178037  sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
178038  pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
178039  pStr->bStatic = 1;
178040  }
178041  }else{
178042  sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
178043  }
178044  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
178045 }
178046 
178047 
178048 #ifndef SQLITE_OMIT_VIRTUALTABLE
178049 /****************************************************************************
178050 ** The json_each virtual table
178051 ****************************************************************************/
178052 typedef struct JsonEachCursor JsonEachCursor;
178053 struct JsonEachCursor {
178054  sqlite3_vtab_cursor base; /* Base class - must be first */
178055  u32 iRowid; /* The rowid */
178056  u32 iBegin; /* The first node of the scan */
178057  u32 i; /* Index in sParse.aNode[] of current row */
178058  u32 iEnd; /* EOF when i equals or exceeds this value */
178059  u8 eType; /* Type of top-level element */
178060  u8 bRecursive; /* True for json_tree(). False for json_each() */
178061  char *zJson; /* Input JSON */
178062  char *zRoot; /* Path by which to filter zJson */
178063  JsonParse sParse; /* Parse of the input JSON */
178064 };
178065 
178066 /* Constructor for the json_each virtual table */
178067 static int jsonEachConnect(
178068  sqlite3 *db,
178069  void *pAux,
178070  int argc, const char *const*argv,
178071  sqlite3_vtab **ppVtab,
178072  char **pzErr
178073 ){
178074  sqlite3_vtab *pNew;
178075  int rc;
178076 
178077 /* Column numbers */
178078 #define JEACH_KEY 0
178079 #define JEACH_VALUE 1
178080 #define JEACH_TYPE 2
178081 #define JEACH_ATOM 3
178082 #define JEACH_ID 4
178083 #define JEACH_PARENT 5
178084 #define JEACH_FULLKEY 6
178085 #define JEACH_PATH 7
178086 #define JEACH_JSON 8
178087 #define JEACH_ROOT 9
178088 
178089  UNUSED_PARAM(pzErr);
178090  UNUSED_PARAM(argv);
178091  UNUSED_PARAM(argc);
178092  UNUSED_PARAM(pAux);
178093  rc = sqlite3_declare_vtab(db,
178094  "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
178095  "json HIDDEN,root HIDDEN)");
178096  if( rc==SQLITE_OK ){
178097  pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
178098  if( pNew==0 ) return SQLITE_NOMEM;
178099  memset(pNew, 0, sizeof(*pNew));
178100  }
178101  return rc;
178102 }
178103 
178104 /* destructor for json_each virtual table */
178105 static int jsonEachDisconnect(sqlite3_vtab *pVtab){
178106  sqlite3_free(pVtab);
178107  return SQLITE_OK;
178108 }
178109 
178110 /* constructor for a JsonEachCursor object for json_each(). */
178111 static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
178112  JsonEachCursor *pCur;
178113 
178114  UNUSED_PARAM(p);
178115  pCur = sqlite3_malloc( sizeof(*pCur) );
178116  if( pCur==0 ) return SQLITE_NOMEM;
178117  memset(pCur, 0, sizeof(*pCur));
178118  *ppCursor = &pCur->base;
178119  return SQLITE_OK;
178120 }
178121 
178122 /* constructor for a JsonEachCursor object for json_tree(). */
178123 static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
178124  int rc = jsonEachOpenEach(p, ppCursor);
178125  if( rc==SQLITE_OK ){
178126  JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
178127  pCur->bRecursive = 1;
178128  }
178129  return rc;
178130 }
178131 
178132 /* Reset a JsonEachCursor back to its original state. Free any memory
178133 ** held. */
178134 static void jsonEachCursorReset(JsonEachCursor *p){
178135  sqlite3_free(p->zJson);
178136  sqlite3_free(p->zRoot);
178137  jsonParseReset(&p->sParse);
178138  p->iRowid = 0;
178139  p->i = 0;
178140  p->iEnd = 0;
178141  p->eType = 0;
178142  p->zJson = 0;
178143  p->zRoot = 0;
178144 }
178145 
178146 /* Destructor for a jsonEachCursor object */
178147 static int jsonEachClose(sqlite3_vtab_cursor *cur){
178148  JsonEachCursor *p = (JsonEachCursor*)cur;
178149  jsonEachCursorReset(p);
178150  sqlite3_free(cur);
178151  return SQLITE_OK;
178152 }
178153 
178154 /* Return TRUE if the jsonEachCursor object has been advanced off the end
178155 ** of the JSON object */
178156 static int jsonEachEof(sqlite3_vtab_cursor *cur){
178157  JsonEachCursor *p = (JsonEachCursor*)cur;
178158  return p->i >= p->iEnd;
178159 }
178160 
178161 /* Advance the cursor to the next element for json_tree() */
178162 static int jsonEachNext(sqlite3_vtab_cursor *cur){
178163  JsonEachCursor *p = (JsonEachCursor*)cur;
178164  if( p->bRecursive ){
178165  if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
178166  p->i++;
178167  p->iRowid++;
178168  if( p->i<p->iEnd ){
178169  u32 iUp = p->sParse.aUp[p->i];
178170  JsonNode *pUp = &p->sParse.aNode[iUp];
178171  p->eType = pUp->eType;
178172  if( pUp->eType==JSON_ARRAY ){
178173  if( iUp==p->i-1 ){
178174  pUp->u.iKey = 0;
178175  }else{
178176  pUp->u.iKey++;
178177  }
178178  }
178179  }
178180  }else{
178181  switch( p->eType ){
178182  case JSON_ARRAY: {
178183  p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
178184  p->iRowid++;
178185  break;
178186  }
178187  case JSON_OBJECT: {
178188  p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
178189  p->iRowid++;
178190  break;
178191  }
178192  default: {
178193  p->i = p->iEnd;
178194  break;
178195  }
178196  }
178197  }
178198  return SQLITE_OK;
178199 }
178200 
178201 /* Append the name of the path for element i to pStr
178202 */
178203 static void jsonEachComputePath(
178204  JsonEachCursor *p, /* The cursor */
178205  JsonString *pStr, /* Write the path here */
178206  u32 i /* Path to this element */
178207 ){
178208  JsonNode *pNode, *pUp;
178209  u32 iUp;
178210  if( i==0 ){
178211  jsonAppendChar(pStr, '$');
178212  return;
178213  }
178214  iUp = p->sParse.aUp[i];
178215  jsonEachComputePath(p, pStr, iUp);
178216  pNode = &p->sParse.aNode[i];
178217  pUp = &p->sParse.aNode[iUp];
178218  if( pUp->eType==JSON_ARRAY ){
178219  jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
178220  }else{
178221  assert( pUp->eType==JSON_OBJECT );
178222  if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
178223  assert( pNode->eType==JSON_STRING );
178224  assert( pNode->jnFlags & JNODE_LABEL );
178225  jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
178226  }
178227 }
178228 
178229 /* Return the value of a column */
178230 static int jsonEachColumn(
178231  sqlite3_vtab_cursor *cur, /* The cursor */
178232  sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
178233  int i /* Which column to return */
178234 ){
178235  JsonEachCursor *p = (JsonEachCursor*)cur;
178236  JsonNode *pThis = &p->sParse.aNode[p->i];
178237  switch( i ){
178238  case JEACH_KEY: {
178239  if( p->i==0 ) break;
178240  if( p->eType==JSON_OBJECT ){
178241  jsonReturn(pThis, ctx, 0);
178242  }else if( p->eType==JSON_ARRAY ){
178243  u32 iKey;
178244  if( p->bRecursive ){
178245  if( p->iRowid==0 ) break;
178246  iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
178247  }else{
178248  iKey = p->iRowid;
178249  }
178250  sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
178251  }
178252  break;
178253  }
178254  case JEACH_VALUE: {
178255  if( pThis->jnFlags & JNODE_LABEL ) pThis++;
178256  jsonReturn(pThis, ctx, 0);
178257  break;
178258  }
178259  case JEACH_TYPE: {
178260  if( pThis->jnFlags & JNODE_LABEL ) pThis++;
178261  sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
178262  break;
178263  }
178264  case JEACH_ATOM: {
178265  if( pThis->jnFlags & JNODE_LABEL ) pThis++;
178266  if( pThis->eType>=JSON_ARRAY ) break;
178267  jsonReturn(pThis, ctx, 0);
178268  break;
178269  }
178270  case JEACH_ID: {
178271  sqlite3_result_int64(ctx,
178272  (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
178273  break;
178274  }
178275  case JEACH_PARENT: {
178276  if( p->i>p->iBegin && p->bRecursive ){
178277  sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
178278  }
178279  break;
178280  }
178281  case JEACH_FULLKEY: {
178282  JsonString x;
178283  jsonInit(&x, ctx);
178284  if( p->bRecursive ){
178285  jsonEachComputePath(p, &x, p->i);
178286  }else{
178287  if( p->zRoot ){
178288  jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
178289  }else{
178290  jsonAppendChar(&x, '$');
178291  }
178292  if( p->eType==JSON_ARRAY ){
178293  jsonPrintf(30, &x, "[%d]", p->iRowid);
178294  }else{
178295  jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
178296  }
178297  }
178298  jsonResult(&x);
178299  break;
178300  }
178301  case JEACH_PATH: {
178302  if( p->bRecursive ){
178303  JsonString x;
178304  jsonInit(&x, ctx);
178305  jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
178306  jsonResult(&x);
178307  break;
178308  }
178309  /* For json_each() path and root are the same so fall through
178310  ** into the root case */
178311  }
178312  case JEACH_ROOT: {
178313  const char *zRoot = p->zRoot;
178314  if( zRoot==0 ) zRoot = "$";
178315  sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
178316  break;
178317  }
178318  case JEACH_JSON: {
178319  assert( i==JEACH_JSON );
178320  sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
178321  break;
178322  }
178323  }
178324  return SQLITE_OK;
178325 }
178326 
178327 /* Return the current rowid value */
178328 static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
178329  JsonEachCursor *p = (JsonEachCursor*)cur;
178330  *pRowid = p->iRowid;
178331  return SQLITE_OK;
178332 }
178333 
178334 /* The query strategy is to look for an equality constraint on the json
178335 ** column. Without such a constraint, the table cannot operate. idxNum is
178336 ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
178337 ** and 0 otherwise.
178338 */
178339 static int jsonEachBestIndex(
178340  sqlite3_vtab *tab,
178341  sqlite3_index_info *pIdxInfo
178342 ){
178343  int i;
178344  int jsonIdx = -1;
178345  int rootIdx = -1;
178346  const struct sqlite3_index_constraint *pConstraint;
178347 
178348  UNUSED_PARAM(tab);
178349  pConstraint = pIdxInfo->aConstraint;
178350  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
178351  if( pConstraint->usable==0 ) continue;
178352  if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
178353  switch( pConstraint->iColumn ){
178354  case JEACH_JSON: jsonIdx = i; break;
178355  case JEACH_ROOT: rootIdx = i; break;
178356  default: /* no-op */ break;
178357  }
178358  }
178359  if( jsonIdx<0 ){
178360  pIdxInfo->idxNum = 0;
178361  pIdxInfo->estimatedCost = 1e99;
178362  }else{
178363  pIdxInfo->estimatedCost = 1.0;
178364  pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
178365  pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
178366  if( rootIdx<0 ){
178367  pIdxInfo->idxNum = 1;
178368  }else{
178369  pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
178370  pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
178371  pIdxInfo->idxNum = 3;
178372  }
178373  }
178374  return SQLITE_OK;
178375 }
178376 
178377 /* Start a search on a new JSON string */
178378 static int jsonEachFilter(
178379  sqlite3_vtab_cursor *cur,
178380  int idxNum, const char *idxStr,
178381  int argc, sqlite3_value **argv
178382 ){
178383  JsonEachCursor *p = (JsonEachCursor*)cur;
178384  const char *z;
178385  const char *zRoot = 0;
178386  sqlite3_int64 n;
178387 
178388  UNUSED_PARAM(idxStr);
178389  UNUSED_PARAM(argc);
178390  jsonEachCursorReset(p);
178391  if( idxNum==0 ) return SQLITE_OK;
178392  z = (const char*)sqlite3_value_text(argv[0]);
178393  if( z==0 ) return SQLITE_OK;
178394  n = sqlite3_value_bytes(argv[0]);
178395  p->zJson = sqlite3_malloc64( n+1 );
178396  if( p->zJson==0 ) return SQLITE_NOMEM;
178397  memcpy(p->zJson, z, (size_t)n+1);
178398  if( jsonParse(&p->sParse, 0, p->zJson) ){
178399  int rc = SQLITE_NOMEM;
178400  if( p->sParse.oom==0 ){
178401  sqlite3_free(cur->pVtab->zErrMsg);
178402  cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
178403  if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
178404  }
178405  jsonEachCursorReset(p);
178406  return rc;
178407  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
178408  jsonEachCursorReset(p);
178409  return SQLITE_NOMEM;
178410  }else{
178411  JsonNode *pNode = 0;
178412  if( idxNum==3 ){
178413  const char *zErr = 0;
178414  zRoot = (const char*)sqlite3_value_text(argv[1]);
178415  if( zRoot==0 ) return SQLITE_OK;
178416  n = sqlite3_value_bytes(argv[1]);
178417  p->zRoot = sqlite3_malloc64( n+1 );
178418  if( p->zRoot==0 ) return SQLITE_NOMEM;
178419  memcpy(p->zRoot, zRoot, (size_t)n+1);
178420  if( zRoot[0]!='$' ){
178421  zErr = zRoot;
178422  }else{
178423  pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
178424  }
178425  if( zErr ){
178426  sqlite3_free(cur->pVtab->zErrMsg);
178427  cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
178428  jsonEachCursorReset(p);
178429  return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
178430  }else if( pNode==0 ){
178431  return SQLITE_OK;
178432  }
178433  }else{
178434  pNode = p->sParse.aNode;
178435  }
178436  p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
178437  p->eType = pNode->eType;
178438  if( p->eType>=JSON_ARRAY ){
178439  pNode->u.iKey = 0;
178440  p->iEnd = p->i + pNode->n + 1;
178441  if( p->bRecursive ){
178442  p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
178443  if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
178444  p->i--;
178445  }
178446  }else{
178447  p->i++;
178448  }
178449  }else{
178450  p->iEnd = p->i+1;
178451  }
178452  }
178453  return SQLITE_OK;
178454 }
178455 
178456 /* The methods of the json_each virtual table */
178457 static sqlite3_module jsonEachModule = {
178458  0, /* iVersion */
178459  0, /* xCreate */
178460  jsonEachConnect, /* xConnect */
178461  jsonEachBestIndex, /* xBestIndex */
178462  jsonEachDisconnect, /* xDisconnect */
178463  0, /* xDestroy */
178464  jsonEachOpenEach, /* xOpen - open a cursor */
178465  jsonEachClose, /* xClose - close a cursor */
178466  jsonEachFilter, /* xFilter - configure scan constraints */
178467  jsonEachNext, /* xNext - advance a cursor */
178468  jsonEachEof, /* xEof - check for end of scan */
178469  jsonEachColumn, /* xColumn - read data */
178470  jsonEachRowid, /* xRowid - read data */
178471  0, /* xUpdate */
178472  0, /* xBegin */
178473  0, /* xSync */
178474  0, /* xCommit */
178475  0, /* xRollback */
178476  0, /* xFindMethod */
178477  0, /* xRename */
178478  0, /* xSavepoint */
178479  0, /* xRelease */
178480  0 /* xRollbackTo */
178481 };
178482 
178483 /* The methods of the json_tree virtual table. */
178484 static sqlite3_module jsonTreeModule = {
178485  0, /* iVersion */
178486  0, /* xCreate */
178487  jsonEachConnect, /* xConnect */
178488  jsonEachBestIndex, /* xBestIndex */
178489  jsonEachDisconnect, /* xDisconnect */
178490  0, /* xDestroy */
178491  jsonEachOpenTree, /* xOpen - open a cursor */
178492  jsonEachClose, /* xClose - close a cursor */
178493  jsonEachFilter, /* xFilter - configure scan constraints */
178494  jsonEachNext, /* xNext - advance a cursor */
178495  jsonEachEof, /* xEof - check for end of scan */
178496  jsonEachColumn, /* xColumn - read data */
178497  jsonEachRowid, /* xRowid - read data */
178498  0, /* xUpdate */
178499  0, /* xBegin */
178500  0, /* xSync */
178501  0, /* xCommit */
178502  0, /* xRollback */
178503  0, /* xFindMethod */
178504  0, /* xRename */
178505  0, /* xSavepoint */
178506  0, /* xRelease */
178507  0 /* xRollbackTo */
178508 };
178509 #endif /* SQLITE_OMIT_VIRTUALTABLE */
178510 
178511 /****************************************************************************
178512 ** The following routines are the only publically visible identifiers in this
178513 ** file. Call the following routines in order to register the various SQL
178514 ** functions and the virtual table implemented by this file.
178515 ****************************************************************************/
178516 
178517 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
178518  int rc = SQLITE_OK;
178519  unsigned int i;
178520  static const struct {
178521  const char *zName;
178522  int nArg;
178523  int flag;
178524  void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
178525  } aFunc[] = {
178526  { "json", 1, 0, jsonRemoveFunc },
178527  { "json_array", -1, 0, jsonArrayFunc },
178528  { "json_array_length", 1, 0, jsonArrayLengthFunc },
178529  { "json_array_length", 2, 0, jsonArrayLengthFunc },
178530  { "json_extract", -1, 0, jsonExtractFunc },
178531  { "json_insert", -1, 0, jsonSetFunc },
178532  { "json_object", -1, 0, jsonObjectFunc },
178533  { "json_quote", 1, 0, jsonQuoteFunc },
178534  { "json_remove", -1, 0, jsonRemoveFunc },
178535  { "json_replace", -1, 0, jsonReplaceFunc },
178536  { "json_set", -1, 1, jsonSetFunc },
178537  { "json_type", 1, 0, jsonTypeFunc },
178538  { "json_type", 2, 0, jsonTypeFunc },
178539  { "json_valid", 1, 0, jsonValidFunc },
178540 
178541 #if SQLITE_DEBUG
178542  /* DEBUG and TESTING functions */
178543  { "json_parse", 1, 0, jsonParseFunc },
178544  { "json_test1", 1, 0, jsonTest1Func },
178545 #endif
178546  };
178547  static const struct {
178548  const char *zName;
178549  int nArg;
178550  void (*xStep)(sqlite3_context*,int,sqlite3_value**);
178551  void (*xFinal)(sqlite3_context*);
178552  } aAgg[] = {
178553  { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
178554  { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
178555  };
178556 #ifndef SQLITE_OMIT_VIRTUALTABLE
178557  static const struct {
178558  const char *zName;
178559  sqlite3_module *pModule;
178560  } aMod[] = {
178561  { "json_each", &jsonEachModule },
178562  { "json_tree", &jsonTreeModule },
178563  };
178564 #endif
178565  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
178566  rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
178567  SQLITE_UTF8 | SQLITE_DETERMINISTIC,
178568  (void*)&aFunc[i].flag,
178569  aFunc[i].xFunc, 0, 0);
178570  }
178571  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
178572  rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
178573  SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
178574  0, aAgg[i].xStep, aAgg[i].xFinal);
178575  }
178576 #ifndef SQLITE_OMIT_VIRTUALTABLE
178577  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
178578  rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
178579  }
178580 #endif
178581  return rc;
178582 }
178583 
178584 
178585 #ifndef SQLITE_CORE
178586 #ifdef _WIN32
178587 __declspec(dllexport)
178588 #endif
178589 SQLITE_API int sqlite3_json_init(
178590  sqlite3 *db,
178591  char **pzErrMsg,
178592  const sqlite3_api_routines *pApi
178593 ){
178594  SQLITE_EXTENSION_INIT2(pApi);
178595  (void)pzErrMsg; /* Unused parameter */
178596  return sqlite3Json1Init(db);
178597 }
178598 #endif
178599 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
178600 
178601 /************** End of json1.c ***********************************************/
178602 /************** Begin file fts5.c ********************************************/
178603 
178604 
178605 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
178606 
178607 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
178608 # define NDEBUG 1
178609 #endif
178610 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
178611 # undef NDEBUG
178612 #endif
178613 
178614 /*
178615 ** 2014 May 31
178616 **
178617 ** The author disclaims copyright to this source code. In place of
178618 ** a legal notice, here is a blessing:
178619 **
178620 ** May you do good and not evil.
178621 ** May you find forgiveness for yourself and forgive others.
178622 ** May you share freely, never taking more than you give.
178623 **
178624 ******************************************************************************
178625 **
178626 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
178627 ** FTS5 may be extended with:
178628 **
178629 ** * custom tokenizers, and
178630 ** * custom auxiliary functions.
178631 */
178632 
178633 
178634 #ifndef _FTS5_H
178635 #define _FTS5_H
178636 
178637 /* #include "sqlite3.h" */
178638 
178639 #if 0
178640 extern "C" {
178641 #endif
178642 
178643 /*************************************************************************
178644 ** CUSTOM AUXILIARY FUNCTIONS
178645 **
178646 ** Virtual table implementations may overload SQL functions by implementing
178647 ** the sqlite3_module.xFindFunction() method.
178648 */
178649 
178650 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
178651 typedef struct Fts5Context Fts5Context;
178652 typedef struct Fts5PhraseIter Fts5PhraseIter;
178653 
178654 typedef void (*fts5_extension_function)(
178655  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
178656  Fts5Context *pFts, /* First arg to pass to pApi functions */
178657  sqlite3_context *pCtx, /* Context for returning result/error */
178658  int nVal, /* Number of values in apVal[] array */
178659  sqlite3_value **apVal /* Array of trailing arguments */
178660 );
178661 
178662 struct Fts5PhraseIter {
178663  const unsigned char *a;
178664  const unsigned char *b;
178665 };
178666 
178667 /*
178668 ** EXTENSION API FUNCTIONS
178669 **
178670 ** xUserData(pFts):
178671 ** Return a copy of the context pointer the extension function was
178672 ** registered with.
178673 **
178674 ** xColumnTotalSize(pFts, iCol, pnToken):
178675 ** If parameter iCol is less than zero, set output variable *pnToken
178676 ** to the total number of tokens in the FTS5 table. Or, if iCol is
178677 ** non-negative but less than the number of columns in the table, return
178678 ** the total number of tokens in column iCol, considering all rows in
178679 ** the FTS5 table.
178680 **
178681 ** If parameter iCol is greater than or equal to the number of columns
178682 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
178683 ** an OOM condition or IO error), an appropriate SQLite error code is
178684 ** returned.
178685 **
178686 ** xColumnCount(pFts):
178687 ** Return the number of columns in the table.
178688 **
178689 ** xColumnSize(pFts, iCol, pnToken):
178690 ** If parameter iCol is less than zero, set output variable *pnToken
178691 ** to the total number of tokens in the current row. Or, if iCol is
178692 ** non-negative but less than the number of columns in the table, set
178693 ** *pnToken to the number of tokens in column iCol of the current row.
178694 **
178695 ** If parameter iCol is greater than or equal to the number of columns
178696 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
178697 ** an OOM condition or IO error), an appropriate SQLite error code is
178698 ** returned.
178699 **
178700 ** This function may be quite inefficient if used with an FTS5 table
178701 ** created with the "columnsize=0" option.
178702 **
178703 ** xColumnText:
178704 ** This function attempts to retrieve the text of column iCol of the
178705 ** current document. If successful, (*pz) is set to point to a buffer
178706 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
178707 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
178708 ** if an error occurs, an SQLite error code is returned and the final values
178709 ** of (*pz) and (*pn) are undefined.
178710 **
178711 ** xPhraseCount:
178712 ** Returns the number of phrases in the current query expression.
178713 **
178714 ** xPhraseSize:
178715 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
178716 ** are numbered starting from zero.
178717 **
178718 ** xInstCount:
178719 ** Set *pnInst to the total number of occurrences of all phrases within
178720 ** the query within the current row. Return SQLITE_OK if successful, or
178721 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
178722 **
178723 ** This API can be quite slow if used with an FTS5 table created with the
178724 ** "detail=none" or "detail=column" option. If the FTS5 table is created
178725 ** with either "detail=none" or "detail=column" and "content=" option
178726 ** (i.e. if it is a contentless table), then this API always returns 0.
178727 **
178728 ** xInst:
178729 ** Query for the details of phrase match iIdx within the current row.
178730 ** Phrase matches are numbered starting from zero, so the iIdx argument
178731 ** should be greater than or equal to zero and smaller than the value
178732 ** output by xInstCount().
178733 **
178734 ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
178735 ** to the column in which it occurs and *piOff the token offset of the
178736 ** first token of the phrase. The exception is if the table was created
178737 ** with the offsets=0 option specified. In this case *piOff is always
178738 ** set to -1.
178739 **
178740 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
178741 ** if an error occurs.
178742 **
178743 ** This API can be quite slow if used with an FTS5 table created with the
178744 ** "detail=none" or "detail=column" option.
178745 **
178746 ** xRowid:
178747 ** Returns the rowid of the current row.
178748 **
178749 ** xTokenize:
178750 ** Tokenize text using the tokenizer belonging to the FTS5 table.
178751 **
178752 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
178753 ** This API function is used to query the FTS table for phrase iPhrase
178754 ** of the current query. Specifically, a query equivalent to:
178755 **
178756 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
178757 **
178758 ** with $p set to a phrase equivalent to the phrase iPhrase of the
178759 ** current query is executed. Any column filter that applies to
178760 ** phrase iPhrase of the current query is included in $p. For each
178761 ** row visited, the callback function passed as the fourth argument
178762 ** is invoked. The context and API objects passed to the callback
178763 ** function may be used to access the properties of each matched row.
178764 ** Invoking Api.xUserData() returns a copy of the pointer passed as
178765 ** the third argument to pUserData.
178766 **
178767 ** If the callback function returns any value other than SQLITE_OK, the
178768 ** query is abandoned and the xQueryPhrase function returns immediately.
178769 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
178770 ** Otherwise, the error code is propagated upwards.
178771 **
178772 ** If the query runs to completion without incident, SQLITE_OK is returned.
178773 ** Or, if some error occurs before the query completes or is aborted by
178774 ** the callback, an SQLite error code is returned.
178775 **
178776 **
178777 ** xSetAuxdata(pFts5, pAux, xDelete)
178778 **
178779 ** Save the pointer passed as the second argument as the extension functions
178780 ** "auxiliary data". The pointer may then be retrieved by the current or any
178781 ** future invocation of the same fts5 extension function made as part of
178782 ** of the same MATCH query using the xGetAuxdata() API.
178783 **
178784 ** Each extension function is allocated a single auxiliary data slot for
178785 ** each FTS query (MATCH expression). If the extension function is invoked
178786 ** more than once for a single FTS query, then all invocations share a
178787 ** single auxiliary data context.
178788 **
178789 ** If there is already an auxiliary data pointer when this function is
178790 ** invoked, then it is replaced by the new pointer. If an xDelete callback
178791 ** was specified along with the original pointer, it is invoked at this
178792 ** point.
178793 **
178794 ** The xDelete callback, if one is specified, is also invoked on the
178795 ** auxiliary data pointer after the FTS5 query has finished.
178796 **
178797 ** If an error (e.g. an OOM condition) occurs within this function, an
178798 ** the auxiliary data is set to NULL and an error code returned. If the
178799 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
178800 ** pointer before returning.
178801 **
178802 **
178803 ** xGetAuxdata(pFts5, bClear)
178804 **
178805 ** Returns the current auxiliary data pointer for the fts5 extension
178806 ** function. See the xSetAuxdata() method for details.
178807 **
178808 ** If the bClear argument is non-zero, then the auxiliary data is cleared
178809 ** (set to NULL) before this function returns. In this case the xDelete,
178810 ** if any, is not invoked.
178811 **
178812 **
178813 ** xRowCount(pFts5, pnRow)
178814 **
178815 ** This function is used to retrieve the total number of rows in the table.
178816 ** In other words, the same value that would be returned by:
178817 **
178818 ** SELECT count(*) FROM ftstable;
178819 **
178820 ** xPhraseFirst()
178821 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
178822 ** method, to iterate through all instances of a single query phrase within
178823 ** the current row. This is the same information as is accessible via the
178824 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
178825 ** to use, this API may be faster under some circumstances. To iterate
178826 ** through instances of phrase iPhrase, use the following code:
178827 **
178828 ** Fts5PhraseIter iter;
178829 ** int iCol, iOff;
178830 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
178831 ** iCol>=0;
178832 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
178833 ** ){
178834 ** // An instance of phrase iPhrase at offset iOff of column iCol
178835 ** }
178836 **
178837 ** The Fts5PhraseIter structure is defined above. Applications should not
178838 ** modify this structure directly - it should only be used as shown above
178839 ** with the xPhraseFirst() and xPhraseNext() API methods (and by
178840 ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
178841 **
178842 ** This API can be quite slow if used with an FTS5 table created with the
178843 ** "detail=none" or "detail=column" option. If the FTS5 table is created
178844 ** with either "detail=none" or "detail=column" and "content=" option
178845 ** (i.e. if it is a contentless table), then this API always iterates
178846 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
178847 **
178848 ** xPhraseNext()
178849 ** See xPhraseFirst above.
178850 **
178851 ** xPhraseFirstColumn()
178852 ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
178853 ** and xPhraseNext() APIs described above. The difference is that instead
178854 ** of iterating through all instances of a phrase in the current row, these
178855 ** APIs are used to iterate through the set of columns in the current row
178856 ** that contain one or more instances of a specified phrase. For example:
178857 **
178858 ** Fts5PhraseIter iter;
178859 ** int iCol;
178860 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
178861 ** iCol>=0;
178862 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
178863 ** ){
178864 ** // Column iCol contains at least one instance of phrase iPhrase
178865 ** }
178866 **
178867 ** This API can be quite slow if used with an FTS5 table created with the
178868 ** "detail=none" option. If the FTS5 table is created with either
178869 ** "detail=none" "content=" option (i.e. if it is a contentless table),
178870 ** then this API always iterates through an empty set (all calls to
178871 ** xPhraseFirstColumn() set iCol to -1).
178872 **
178873 ** The information accessed using this API and its companion
178874 ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
178875 ** (or xInst/xInstCount). The chief advantage of this API is that it is
178876 ** significantly more efficient than those alternatives when used with
178877 ** "detail=column" tables.
178878 **
178879 ** xPhraseNextColumn()
178880 ** See xPhraseFirstColumn above.
178881 */
178882 struct Fts5ExtensionApi {
178883  int iVersion; /* Currently always set to 3 */
178884 
178885  void *(*xUserData)(Fts5Context*);
178886 
178887  int (*xColumnCount)(Fts5Context*);
178888  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
178889  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
178890 
178891  int (*xTokenize)(Fts5Context*,
178892  const char *pText, int nText, /* Text to tokenize */
178893  void *pCtx, /* Context passed to xToken() */
178894  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
178895  );
178896 
178897  int (*xPhraseCount)(Fts5Context*);
178898  int (*xPhraseSize)(Fts5Context*, int iPhrase);
178899 
178900  int (*xInstCount)(Fts5Context*, int *pnInst);
178901  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
178902 
178903  sqlite3_int64 (*xRowid)(Fts5Context*);
178904  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
178905  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
178906 
178907  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
178908  int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
178909  );
178910  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
178911  void *(*xGetAuxdata)(Fts5Context*, int bClear);
178912 
178913  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
178914  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
178915 
178916  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
178917  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
178918 };
178919 
178920 /*
178921 ** CUSTOM AUXILIARY FUNCTIONS
178922 *************************************************************************/
178923 
178924 /*************************************************************************
178925 ** CUSTOM TOKENIZERS
178926 **
178927 ** Applications may also register custom tokenizer types. A tokenizer
178928 ** is registered by providing fts5 with a populated instance of the
178929 ** following structure. All structure methods must be defined, setting
178930 ** any member of the fts5_tokenizer struct to NULL leads to undefined
178931 ** behaviour. The structure methods are expected to function as follows:
178932 **
178933 ** xCreate:
178934 ** This function is used to allocate and initialize a tokenizer instance.
178935 ** A tokenizer instance is required to actually tokenize text.
178936 **
178937 ** The first argument passed to this function is a copy of the (void*)
178938 ** pointer provided by the application when the fts5_tokenizer object
178939 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
178940 ** The second and third arguments are an array of nul-terminated strings
178941 ** containing the tokenizer arguments, if any, specified following the
178942 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
178943 ** to create the FTS5 table.
178944 **
178945 ** The final argument is an output variable. If successful, (*ppOut)
178946 ** should be set to point to the new tokenizer handle and SQLITE_OK
178947 ** returned. If an error occurs, some value other than SQLITE_OK should
178948 ** be returned. In this case, fts5 assumes that the final value of *ppOut
178949 ** is undefined.
178950 **
178951 ** xDelete:
178952 ** This function is invoked to delete a tokenizer handle previously
178953 ** allocated using xCreate(). Fts5 guarantees that this function will
178954 ** be invoked exactly once for each successful call to xCreate().
178955 **
178956 ** xTokenize:
178957 ** This function is expected to tokenize the nText byte string indicated
178958 ** by argument pText. pText may or may not be nul-terminated. The first
178959 ** argument passed to this function is a pointer to an Fts5Tokenizer object
178960 ** returned by an earlier call to xCreate().
178961 **
178962 ** The second argument indicates the reason that FTS5 is requesting
178963 ** tokenization of the supplied text. This is always one of the following
178964 ** four values:
178965 **
178966 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
178967 ** or removed from the FTS table. The tokenizer is being invoked to
178968 ** determine the set of tokens to add to (or delete from) the
178969 ** FTS index.
178970 **
178971 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
178972 ** against the FTS index. The tokenizer is being called to tokenize
178973 ** a bareword or quoted string specified as part of the query.
178974 **
178975 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
178976 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
178977 ** followed by a "*" character, indicating that the last token
178978 ** returned by the tokenizer will be treated as a token prefix.
178979 **
178980 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
178981 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
178982 ** function. Or an fts5_api.xColumnSize() request made by the same
178983 ** on a columnsize=0 database.
178984 ** </ul>
178985 **
178986 ** For each token in the input string, the supplied callback xToken() must
178987 ** be invoked. The first argument to it should be a copy of the pointer
178988 ** passed as the second argument to xTokenize(). The third and fourth
178989 ** arguments are a pointer to a buffer containing the token text, and the
178990 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
178991 ** of the first byte of and first byte immediately following the text from
178992 ** which the token is derived within the input.
178993 **
178994 ** The second argument passed to the xToken() callback ("tflags") should
178995 ** normally be set to 0. The exception is if the tokenizer supports
178996 ** synonyms. In this case see the discussion below for details.
178997 **
178998 ** FTS5 assumes the xToken() callback is invoked for each token in the
178999 ** order that they occur within the input text.
179000 **
179001 ** If an xToken() callback returns any value other than SQLITE_OK, then
179002 ** the tokenization should be abandoned and the xTokenize() method should
179003 ** immediately return a copy of the xToken() return value. Or, if the
179004 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
179005 ** if an error occurs with the xTokenize() implementation itself, it
179006 ** may abandon the tokenization and return any error code other than
179007 ** SQLITE_OK or SQLITE_DONE.
179008 **
179009 ** SYNONYM SUPPORT
179010 **
179011 ** Custom tokenizers may also support synonyms. Consider a case in which a
179012 ** user wishes to query for a phrase such as "first place". Using the
179013 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
179014 ** of "first place" within the document set, but not alternative forms
179015 ** such as "1st place". In some applications, it would be better to match
179016 ** all instances of "first place" or "1st place" regardless of which form
179017 ** the user specified in the MATCH query text.
179018 **
179019 ** There are several ways to approach this in FTS5:
179020 **
179021 ** <ol><li> By mapping all synonyms to a single token. In this case, the
179022 ** In the above example, this means that the tokenizer returns the
179023 ** same token for inputs "first" and "1st". Say that token is in
179024 ** fact "first", so that when the user inserts the document "I won
179025 ** 1st place" entries are added to the index for tokens "i", "won",
179026 ** "first" and "place". If the user then queries for '1st + place',
179027 ** the tokenizer substitutes "first" for "1st" and the query works
179028 ** as expected.
179029 **
179030 ** <li> By adding multiple synonyms for a single term to the FTS index.
179031 ** In this case, when tokenizing query text, the tokenizer may
179032 ** provide multiple synonyms for a single term within the document.
179033 ** FTS5 then queries the index for each synonym individually. For
179034 ** example, faced with the query:
179035 **
179036 ** <codeblock>
179037 ** ... MATCH 'first place'</codeblock>
179038 **
179039 ** the tokenizer offers both "1st" and "first" as synonyms for the
179040 ** first token in the MATCH query and FTS5 effectively runs a query
179041 ** similar to:
179042 **
179043 ** <codeblock>
179044 ** ... MATCH '(first OR 1st) place'</codeblock>
179045 **
179046 ** except that, for the purposes of auxiliary functions, the query
179047 ** still appears to contain just two phrases - "(first OR 1st)"
179048 ** being treated as a single phrase.
179049 **
179050 ** <li> By adding multiple synonyms for a single term to the FTS index.
179051 ** Using this method, when tokenizing document text, the tokenizer
179052 ** provides multiple synonyms for each token. So that when a
179053 ** document such as "I won first place" is tokenized, entries are
179054 ** added to the FTS index for "i", "won", "first", "1st" and
179055 ** "place".
179056 **
179057 ** This way, even if the tokenizer does not provide synonyms
179058 ** when tokenizing query text (it should not - to do would be
179059 ** inefficient), it doesn't matter if the user queries for
179060 ** 'first + place' or '1st + place', as there are entires in the
179061 ** FTS index corresponding to both forms of the first token.
179062 ** </ol>
179063 **
179064 ** Whether it is parsing document or query text, any call to xToken that
179065 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
179066 ** is considered to supply a synonym for the previous token. For example,
179067 ** when parsing the document "I won first place", a tokenizer that supports
179068 ** synonyms would call xToken() 5 times, as follows:
179069 **
179070 ** <codeblock>
179071 ** xToken(pCtx, 0, "i", 1, 0, 1);
179072 ** xToken(pCtx, 0, "won", 3, 2, 5);
179073 ** xToken(pCtx, 0, "first", 5, 6, 11);
179074 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
179075 ** xToken(pCtx, 0, "place", 5, 12, 17);
179076 **</codeblock>
179077 **
179078 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
179079 ** xToken() is called. Multiple synonyms may be specified for a single token
179080 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
179081 ** There is no limit to the number of synonyms that may be provided for a
179082 ** single token.
179083 **
179084 ** In many cases, method (1) above is the best approach. It does not add
179085 ** extra data to the FTS index or require FTS5 to query for multiple terms,
179086 ** so it is efficient in terms of disk space and query speed. However, it
179087 ** does not support prefix queries very well. If, as suggested above, the
179088 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
179089 **
179090 ** <codeblock>
179091 ** ... MATCH '1s*'</codeblock>
179092 **
179093 ** will not match documents that contain the token "1st" (as the tokenizer
179094 ** will probably not map "1s" to any prefix of "first").
179095 **
179096 ** For full prefix support, method (3) may be preferred. In this case,
179097 ** because the index contains entries for both "first" and "1st", prefix
179098 ** queries such as 'fi*' or '1s*' will match correctly. However, because
179099 ** extra entries are added to the FTS index, this method uses more space
179100 ** within the database.
179101 **
179102 ** Method (2) offers a midpoint between (1) and (3). Using this method,
179103 ** a query such as '1s*' will match documents that contain the literal
179104 ** token "1st", but not "first" (assuming the tokenizer is not able to
179105 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
179106 ** will match against "1st" and "first". This method does not require
179107 ** extra disk space, as no extra entries are added to the FTS index.
179108 ** On the other hand, it may require more CPU cycles to run MATCH queries,
179109 ** as separate queries of the FTS index are required for each synonym.
179110 **
179111 ** When using methods (2) or (3), it is important that the tokenizer only
179112 ** provide synonyms when tokenizing document text (method (2)) or query
179113 ** text (method (3)), not both. Doing so will not cause any errors, but is
179114 ** inefficient.
179115 */
179116 typedef struct Fts5Tokenizer Fts5Tokenizer;
179117 typedef struct fts5_tokenizer fts5_tokenizer;
179118 struct fts5_tokenizer {
179119  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
179120  void (*xDelete)(Fts5Tokenizer*);
179121  int (*xTokenize)(Fts5Tokenizer*,
179122  void *pCtx,
179123  int flags, /* Mask of FTS5_TOKENIZE_* flags */
179124  const char *pText, int nText,
179125  int (*xToken)(
179126  void *pCtx, /* Copy of 2nd argument to xTokenize() */
179127  int tflags, /* Mask of FTS5_TOKEN_* flags */
179128  const char *pToken, /* Pointer to buffer containing token */
179129  int nToken, /* Size of token in bytes */
179130  int iStart, /* Byte offset of token within input text */
179131  int iEnd /* Byte offset of end of token within input text */
179132  )
179133  );
179134 };
179135 
179136 /* Flags that may be passed as the third argument to xTokenize() */
179137 #define FTS5_TOKENIZE_QUERY 0x0001
179138 #define FTS5_TOKENIZE_PREFIX 0x0002
179139 #define FTS5_TOKENIZE_DOCUMENT 0x0004
179140 #define FTS5_TOKENIZE_AUX 0x0008
179141 
179142 /* Flags that may be passed by the tokenizer implementation back to FTS5
179143 ** as the third argument to the supplied xToken callback. */
179144 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
179145 
179146 /*
179147 ** END OF CUSTOM TOKENIZERS
179148 *************************************************************************/
179149 
179150 /*************************************************************************
179151 ** FTS5 EXTENSION REGISTRATION API
179152 */
179153 typedef struct fts5_api fts5_api;
179154 struct fts5_api {
179155  int iVersion; /* Currently always set to 2 */
179156 
179157  /* Create a new tokenizer */
179158  int (*xCreateTokenizer)(
179159  fts5_api *pApi,
179160  const char *zName,
179161  void *pContext,
179162  fts5_tokenizer *pTokenizer,
179163  void (*xDestroy)(void*)
179164  );
179165 
179166  /* Find an existing tokenizer */
179167  int (*xFindTokenizer)(
179168  fts5_api *pApi,
179169  const char *zName,
179170  void **ppContext,
179171  fts5_tokenizer *pTokenizer
179172  );
179173 
179174  /* Create a new auxiliary function */
179175  int (*xCreateFunction)(
179176  fts5_api *pApi,
179177  const char *zName,
179178  void *pContext,
179179  fts5_extension_function xFunction,
179180  void (*xDestroy)(void*)
179181  );
179182 };
179183 
179184 /*
179185 ** END OF REGISTRATION API
179186 *************************************************************************/
179187 
179188 #if 0
179189 } /* end of the 'extern "C"' block */
179190 #endif
179191 
179192 #endif /* _FTS5_H */
179193 
179194 /*
179195 ** 2014 May 31
179196 **
179197 ** The author disclaims copyright to this source code. In place of
179198 ** a legal notice, here is a blessing:
179199 **
179200 ** May you do good and not evil.
179201 ** May you find forgiveness for yourself and forgive others.
179202 ** May you share freely, never taking more than you give.
179203 **
179204 ******************************************************************************
179205 **
179206 */
179207 #ifndef _FTS5INT_H
179208 #define _FTS5INT_H
179209 
179210 /* #include "fts5.h" */
179211 /* #include "sqlite3ext.h" */
179212 SQLITE_EXTENSION_INIT1
179213 
179214 /* #include <string.h> */
179215 /* #include <assert.h> */
179216 
179217 #ifndef SQLITE_AMALGAMATION
179218 
179219 typedef unsigned char u8;
179220 typedef unsigned int u32;
179221 typedef unsigned short u16;
179222 typedef short i16;
179223 typedef sqlite3_int64 i64;
179224 typedef sqlite3_uint64 u64;
179225 
179226 #define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
179227 
179228 #define testcase(x)
179229 #define ALWAYS(x) 1
179230 #define NEVER(x) 0
179231 
179232 #define MIN(x,y) (((x) < (y)) ? (x) : (y))
179233 #define MAX(x,y) (((x) > (y)) ? (x) : (y))
179234 
179235 /*
179236 ** Constants for the largest and smallest possible 64-bit signed integers.
179237 */
179238 # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
179239 # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
179240 
179241 #endif
179242 
179243 /* Truncate very long tokens to this many bytes. Hard limit is
179244 ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
179245 ** field that occurs at the start of each leaf page (see fts5_index.c). */
179246 #define FTS5_MAX_TOKEN_SIZE 32768
179247 
179248 /*
179249 ** Maximum number of prefix indexes on single FTS5 table. This must be
179250 ** less than 32. If it is set to anything large than that, an #error
179251 ** directive in fts5_index.c will cause the build to fail.
179252 */
179253 #define FTS5_MAX_PREFIX_INDEXES 31
179254 
179255 #define FTS5_DEFAULT_NEARDIST 10
179256 #define FTS5_DEFAULT_RANK "bm25"
179257 
179258 /* Name of rank and rowid columns */
179259 #define FTS5_RANK_NAME "rank"
179260 #define FTS5_ROWID_NAME "rowid"
179261 
179262 #ifdef SQLITE_DEBUG
179263 # define FTS5_CORRUPT sqlite3Fts5Corrupt()
179264 static int sqlite3Fts5Corrupt(void);
179265 #else
179266 # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
179267 #endif
179268 
179269 /*
179270 ** The assert_nc() macro is similar to the assert() macro, except that it
179271 ** is used for assert() conditions that are true only if it can be
179272 ** guranteed that the database is not corrupt.
179273 */
179274 #ifdef SQLITE_DEBUG
179275 SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
179276 # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
179277 #else
179278 # define assert_nc(x) assert(x)
179279 #endif
179280 
179281 /* Mark a function parameter as unused, to suppress nuisance compiler
179282 ** warnings. */
179283 #ifndef UNUSED_PARAM
179284 # define UNUSED_PARAM(X) (void)(X)
179285 #endif
179286 
179287 #ifndef UNUSED_PARAM2
179288 # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
179289 #endif
179290 
179291 typedef struct Fts5Global Fts5Global;
179292 typedef struct Fts5Colset Fts5Colset;
179293 
179294 /* If a NEAR() clump or phrase may only match a specific set of columns,
179295 ** then an object of the following type is used to record the set of columns.
179296 ** Each entry in the aiCol[] array is a column that may be matched.
179297 **
179298 ** This object is used by fts5_expr.c and fts5_index.c.
179299 */
179300 struct Fts5Colset {
179301  int nCol;
179302  int aiCol[1];
179303 };
179304 
179305 
179306 
179307 /**************************************************************************
179308 ** Interface to code in fts5_config.c. fts5_config.c contains contains code
179309 ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
179310 */
179311 
179312 typedef struct Fts5Config Fts5Config;
179313 
179314 /*
179315 ** An instance of the following structure encodes all information that can
179316 ** be gleaned from the CREATE VIRTUAL TABLE statement.
179317 **
179318 ** And all information loaded from the %_config table.
179319 **
179320 ** nAutomerge:
179321 ** The minimum number of segments that an auto-merge operation should
179322 ** attempt to merge together. A value of 1 sets the object to use the
179323 ** compile time default. Zero disables auto-merge altogether.
179324 **
179325 ** zContent:
179326 **
179327 ** zContentRowid:
179328 ** The value of the content_rowid= option, if one was specified. Or
179329 ** the string "rowid" otherwise. This text is not quoted - if it is
179330 ** used as part of an SQL statement it needs to be quoted appropriately.
179331 **
179332 ** zContentExprlist:
179333 **
179334 ** pzErrmsg:
179335 ** This exists in order to allow the fts5_index.c module to return a
179336 ** decent error message if it encounters a file-format version it does
179337 ** not understand.
179338 **
179339 ** bColumnsize:
179340 ** True if the %_docsize table is created.
179341 **
179342 ** bPrefixIndex:
179343 ** This is only used for debugging. If set to false, any prefix indexes
179344 ** are ignored. This value is configured using:
179345 **
179346 ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
179347 **
179348 */
179349 struct Fts5Config {
179350  sqlite3 *db; /* Database handle */
179351  char *zDb; /* Database holding FTS index (e.g. "main") */
179352  char *zName; /* Name of FTS index */
179353  int nCol; /* Number of columns */
179354  char **azCol; /* Column names */
179355  u8 *abUnindexed; /* True for unindexed columns */
179356  int nPrefix; /* Number of prefix indexes */
179357  int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
179358  int eContent; /* An FTS5_CONTENT value */
179359  char *zContent; /* content table */
179360  char *zContentRowid; /* "content_rowid=" option value */
179361  int bColumnsize; /* "columnsize=" option value (dflt==1) */
179362  int eDetail; /* FTS5_DETAIL_XXX value */
179363  char *zContentExprlist;
179364  Fts5Tokenizer *pTok;
179365  fts5_tokenizer *pTokApi;
179366 
179367  /* Values loaded from the %_config table */
179368  int iCookie; /* Incremented when %_config is modified */
179369  int pgsz; /* Approximate page size used in %_data */
179370  int nAutomerge; /* 'automerge' setting */
179371  int nCrisisMerge; /* Maximum allowed segments per level */
179372  int nUsermerge; /* 'usermerge' setting */
179373  int nHashSize; /* Bytes of memory for in-memory hash */
179374  char *zRank; /* Name of rank function */
179375  char *zRankArgs; /* Arguments to rank function */
179376 
179377  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
179378  char **pzErrmsg;
179379 
179380 #ifdef SQLITE_DEBUG
179381  int bPrefixIndex; /* True to use prefix-indexes */
179382 #endif
179383 };
179384 
179385 /* Current expected value of %_config table 'version' field */
179386 #define FTS5_CURRENT_VERSION 4
179387 
179388 #define FTS5_CONTENT_NORMAL 0
179389 #define FTS5_CONTENT_NONE 1
179390 #define FTS5_CONTENT_EXTERNAL 2
179391 
179392 #define FTS5_DETAIL_FULL 0
179393 #define FTS5_DETAIL_NONE 1
179394 #define FTS5_DETAIL_COLUMNS 2
179395 
179396 
179397 
179398 static int sqlite3Fts5ConfigParse(
179399  Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
179400 );
179401 static void sqlite3Fts5ConfigFree(Fts5Config*);
179402 
179403 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
179404 
179405 static int sqlite3Fts5Tokenize(
179406  Fts5Config *pConfig, /* FTS5 Configuration object */
179407  int flags, /* FTS5_TOKENIZE_* flags */
179408  const char *pText, int nText, /* Text to tokenize */
179409  void *pCtx, /* Context passed to xToken() */
179410  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
179411 );
179412 
179413 static void sqlite3Fts5Dequote(char *z);
179414 
179415 /* Load the contents of the %_config table */
179416 static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
179417 
179418 /* Set the value of a single config attribute */
179419 static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
179420 
179421 static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
179422 
179423 /*
179424 ** End of interface to code in fts5_config.c.
179425 **************************************************************************/
179426 
179427 /**************************************************************************
179428 ** Interface to code in fts5_buffer.c.
179429 */
179430 
179431 /*
179432 ** Buffer object for the incremental building of string data.
179433 */
179434 typedef struct Fts5Buffer Fts5Buffer;
179435 struct Fts5Buffer {
179436  u8 *p;
179437  int n;
179438  int nSpace;
179439 };
179440 
179441 static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
179442 static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
179443 static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
179444 static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
179445 static void sqlite3Fts5BufferFree(Fts5Buffer*);
179446 static void sqlite3Fts5BufferZero(Fts5Buffer*);
179447 static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
179448 static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
179449 
179450 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
179451 
179452 #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
179453 #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
179454 #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
179455 #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
179456 #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
179457 
179458 #define fts5BufferGrow(pRc,pBuf,nn) ( \
179459  (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
179460  sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
179461 )
179462 
179463 /* Write and decode big-endian 32-bit integer values */
179464 static void sqlite3Fts5Put32(u8*, int);
179465 static int sqlite3Fts5Get32(const u8*);
179466 
179467 #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
179468 #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
179469 
179470 typedef struct Fts5PoslistReader Fts5PoslistReader;
179471 struct Fts5PoslistReader {
179472  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
179473  const u8 *a; /* Position list to iterate through */
179474  int n; /* Size of buffer at a[] in bytes */
179475  int i; /* Current offset in a[] */
179476 
179477  u8 bFlag; /* For client use (any custom purpose) */
179478 
179479  /* Output variables */
179480  u8 bEof; /* Set to true at EOF */
179481  i64 iPos; /* (iCol<<32) + iPos */
179482 };
179483 static int sqlite3Fts5PoslistReaderInit(
179484  const u8 *a, int n, /* Poslist buffer to iterate through */
179485  Fts5PoslistReader *pIter /* Iterator object to initialize */
179486 );
179487 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
179488 
179489 typedef struct Fts5PoslistWriter Fts5PoslistWriter;
179490 struct Fts5PoslistWriter {
179491  i64 iPrev;
179492 };
179493 static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
179494 static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
179495 
179496 static int sqlite3Fts5PoslistNext64(
179497  const u8 *a, int n, /* Buffer containing poslist */
179498  int *pi, /* IN/OUT: Offset within a[] */
179499  i64 *piOff /* IN/OUT: Current offset */
179500 );
179501 
179502 /* Malloc utility */
179503 static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
179504 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
179505 
179506 /* Character set tests (like isspace(), isalpha() etc.) */
179507 static int sqlite3Fts5IsBareword(char t);
179508 
179509 
179510 /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
179511 typedef struct Fts5Termset Fts5Termset;
179512 static int sqlite3Fts5TermsetNew(Fts5Termset**);
179513 static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
179514 static void sqlite3Fts5TermsetFree(Fts5Termset*);
179515 
179516 /*
179517 ** End of interface to code in fts5_buffer.c.
179518 **************************************************************************/
179519 
179520 /**************************************************************************
179521 ** Interface to code in fts5_index.c. fts5_index.c contains contains code
179522 ** to access the data stored in the %_data table.
179523 */
179524 
179525 typedef struct Fts5Index Fts5Index;
179526 typedef struct Fts5IndexIter Fts5IndexIter;
179527 
179528 struct Fts5IndexIter {
179529  i64 iRowid;
179530  const u8 *pData;
179531  int nData;
179532  u8 bEof;
179533 };
179534 
179535 #define sqlite3Fts5IterEof(x) ((x)->bEof)
179536 
179537 /*
179538 ** Values used as part of the flags argument passed to IndexQuery().
179539 */
179540 #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
179541 #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
179542 #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
179543 #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
179544 
179545 /* The following are used internally by the fts5_index.c module. They are
179546 ** defined here only to make it easier to avoid clashes with the flags
179547 ** above. */
179548 #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
179549 #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
179550 
179551 /*
179552 ** Create/destroy an Fts5Index object.
179553 */
179554 static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
179555 static int sqlite3Fts5IndexClose(Fts5Index *p);
179556 
179557 /*
179558 ** Return a simple checksum value based on the arguments.
179559 */
179560 static u64 sqlite3Fts5IndexEntryCksum(
179561  i64 iRowid,
179562  int iCol,
179563  int iPos,
179564  int iIdx,
179565  const char *pTerm,
179566  int nTerm
179567 );
179568 
179569 /*
179570 ** Argument p points to a buffer containing utf-8 text that is n bytes in
179571 ** size. Return the number of bytes in the nChar character prefix of the
179572 ** buffer, or 0 if there are less than nChar characters in total.
179573 */
179574 static int sqlite3Fts5IndexCharlenToBytelen(
179575  const char *p,
179576  int nByte,
179577  int nChar
179578 );
179579 
179580 /*
179581 ** Open a new iterator to iterate though all rowids that match the
179582 ** specified token or token prefix.
179583 */
179584 static int sqlite3Fts5IndexQuery(
179585  Fts5Index *p, /* FTS index to query */
179586  const char *pToken, int nToken, /* Token (or prefix) to query for */
179587  int flags, /* Mask of FTS5INDEX_QUERY_X flags */
179588  Fts5Colset *pColset, /* Match these columns only */
179589  Fts5IndexIter **ppIter /* OUT: New iterator object */
179590 );
179591 
179592 /*
179593 ** The various operations on open token or token prefix iterators opened
179594 ** using sqlite3Fts5IndexQuery().
179595 */
179596 static int sqlite3Fts5IterNext(Fts5IndexIter*);
179597 static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
179598 
179599 /*
179600 ** Close an iterator opened by sqlite3Fts5IndexQuery().
179601 */
179602 static void sqlite3Fts5IterClose(Fts5IndexIter*);
179603 
179604 /*
179605 ** This interface is used by the fts5vocab module.
179606 */
179607 static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
179608 static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
179609 
179610 
179611 /*
179612 ** Insert or remove data to or from the index. Each time a document is
179613 ** added to or removed from the index, this function is called one or more
179614 ** times.
179615 **
179616 ** For an insert, it must be called once for each token in the new document.
179617 ** If the operation is a delete, it must be called (at least) once for each
179618 ** unique token in the document with an iCol value less than zero. The iPos
179619 ** argument is ignored for a delete.
179620 */
179621 static int sqlite3Fts5IndexWrite(
179622  Fts5Index *p, /* Index to write to */
179623  int iCol, /* Column token appears in (-ve -> delete) */
179624  int iPos, /* Position of token within column */
179625  const char *pToken, int nToken /* Token to add or remove to or from index */
179626 );
179627 
179628 /*
179629 ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
179630 ** document iDocid.
179631 */
179632 static int sqlite3Fts5IndexBeginWrite(
179633  Fts5Index *p, /* Index to write to */
179634  int bDelete, /* True if current operation is a delete */
179635  i64 iDocid /* Docid to add or remove data from */
179636 );
179637 
179638 /*
179639 ** Flush any data stored in the in-memory hash tables to the database.
179640 ** If the bCommit flag is true, also close any open blob handles.
179641 */
179642 static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
179643 
179644 /*
179645 ** Discard any data stored in the in-memory hash tables. Do not write it
179646 ** to the database. Additionally, assume that the contents of the %_data
179647 ** table may have changed on disk. So any in-memory caches of %_data
179648 ** records must be invalidated.
179649 */
179650 static int sqlite3Fts5IndexRollback(Fts5Index *p);
179651 
179652 /*
179653 ** Get or set the "averages" values.
179654 */
179655 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
179656 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
179657 
179658 /*
179659 ** Functions called by the storage module as part of integrity-check.
179660 */
179661 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
179662 
179663 /*
179664 ** Called during virtual module initialization to register UDF
179665 ** fts5_decode() with SQLite
179666 */
179667 static int sqlite3Fts5IndexInit(sqlite3*);
179668 
179669 static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
179670 
179671 /*
179672 ** Return the total number of entries read from the %_data table by
179673 ** this connection since it was created.
179674 */
179675 static int sqlite3Fts5IndexReads(Fts5Index *p);
179676 
179677 static int sqlite3Fts5IndexReinit(Fts5Index *p);
179678 static int sqlite3Fts5IndexOptimize(Fts5Index *p);
179679 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
179680 static int sqlite3Fts5IndexReset(Fts5Index *p);
179681 
179682 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
179683 
179684 /*
179685 ** End of interface to code in fts5_index.c.
179686 **************************************************************************/
179687 
179688 /**************************************************************************
179689 ** Interface to code in fts5_varint.c.
179690 */
179691 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
179692 static int sqlite3Fts5GetVarintLen(u32 iVal);
179693 static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
179694 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
179695 
179696 #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
179697 #define fts5GetVarint sqlite3Fts5GetVarint
179698 
179699 #define fts5FastGetVarint32(a, iOff, nVal) { \
179700  nVal = (a)[iOff++]; \
179701  if( nVal & 0x80 ){ \
179702  iOff--; \
179703  iOff += fts5GetVarint32(&(a)[iOff], nVal); \
179704  } \
179705 }
179706 
179707 
179708 /*
179709 ** End of interface to code in fts5_varint.c.
179710 **************************************************************************/
179711 
179712 
179713 /**************************************************************************
179714 ** Interface to code in fts5.c.
179715 */
179716 
179717 static int sqlite3Fts5GetTokenizer(
179718  Fts5Global*,
179719  const char **azArg,
179720  int nArg,
179721  Fts5Tokenizer**,
179722  fts5_tokenizer**,
179723  char **pzErr
179724 );
179725 
179726 static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
179727 
179728 /*
179729 ** End of interface to code in fts5.c.
179730 **************************************************************************/
179731 
179732 /**************************************************************************
179733 ** Interface to code in fts5_hash.c.
179734 */
179735 typedef struct Fts5Hash Fts5Hash;
179736 
179737 /*
179738 ** Create a hash table, free a hash table.
179739 */
179740 static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
179741 static void sqlite3Fts5HashFree(Fts5Hash*);
179742 
179743 static int sqlite3Fts5HashWrite(
179744  Fts5Hash*,
179745  i64 iRowid, /* Rowid for this entry */
179746  int iCol, /* Column token appears in (-ve -> delete) */
179747  int iPos, /* Position of token within column */
179748  char bByte,
179749  const char *pToken, int nToken /* Token to add or remove to or from index */
179750 );
179751 
179752 /*
179753 ** Empty (but do not delete) a hash table.
179754 */
179755 static void sqlite3Fts5HashClear(Fts5Hash*);
179756 
179757 static int sqlite3Fts5HashQuery(
179758  Fts5Hash*, /* Hash table to query */
179759  const char *pTerm, int nTerm, /* Query term */
179760  const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
179761  int *pnDoclist /* OUT: Size of doclist in bytes */
179762 );
179763 
179764 static int sqlite3Fts5HashScanInit(
179765  Fts5Hash*, /* Hash table to query */
179766  const char *pTerm, int nTerm /* Query prefix */
179767 );
179768 static void sqlite3Fts5HashScanNext(Fts5Hash*);
179769 static int sqlite3Fts5HashScanEof(Fts5Hash*);
179770 static void sqlite3Fts5HashScanEntry(Fts5Hash *,
179771  const char **pzTerm, /* OUT: term (nul-terminated) */
179772  const u8 **ppDoclist, /* OUT: pointer to doclist */
179773  int *pnDoclist /* OUT: size of doclist in bytes */
179774 );
179775 
179776 
179777 /*
179778 ** End of interface to code in fts5_hash.c.
179779 **************************************************************************/
179780 
179781 /**************************************************************************
179782 ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
179783 ** code to access the data stored in the %_content and %_docsize tables.
179784 */
179785 
179786 #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
179787 #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
179788 #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
179789 
179790 typedef struct Fts5Storage Fts5Storage;
179791 
179792 static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
179793 static int sqlite3Fts5StorageClose(Fts5Storage *p);
179794 static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
179795 
179796 static int sqlite3Fts5DropAll(Fts5Config*);
179797 static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
179798 
179799 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
179800 static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
179801 static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
179802 
179803 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
179804 
179805 static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
179806 static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
179807 
179808 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
179809 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
179810 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
179811 
179812 static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
179813 static int sqlite3Fts5StorageRollback(Fts5Storage *p);
179814 
179815 static int sqlite3Fts5StorageConfigValue(
179816  Fts5Storage *p, const char*, sqlite3_value*, int
179817 );
179818 
179819 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
179820 static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
179821 static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
179822 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
179823 static int sqlite3Fts5StorageReset(Fts5Storage *p);
179824 
179825 /*
179826 ** End of interface to code in fts5_storage.c.
179827 **************************************************************************/
179828 
179829 
179830 /**************************************************************************
179831 ** Interface to code in fts5_expr.c.
179832 */
179833 typedef struct Fts5Expr Fts5Expr;
179834 typedef struct Fts5ExprNode Fts5ExprNode;
179835 typedef struct Fts5Parse Fts5Parse;
179836 typedef struct Fts5Token Fts5Token;
179837 typedef struct Fts5ExprPhrase Fts5ExprPhrase;
179838 typedef struct Fts5ExprNearset Fts5ExprNearset;
179839 
179840 struct Fts5Token {
179841  const char *p; /* Token text (not NULL terminated) */
179842  int n; /* Size of buffer p in bytes */
179843 };
179844 
179845 /* Parse a MATCH expression. */
179846 static int sqlite3Fts5ExprNew(
179847  Fts5Config *pConfig,
179848  const char *zExpr,
179849  Fts5Expr **ppNew,
179850  char **pzErr
179851 );
179852 
179853 /*
179854 ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
179855 ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
179856 ** rc = sqlite3Fts5ExprNext(pExpr)
179857 ** ){
179858 ** // The document with rowid iRowid matches the expression!
179859 ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
179860 ** }
179861 */
179862 static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
179863 static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
179864 static int sqlite3Fts5ExprEof(Fts5Expr*);
179865 static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
179866 
179867 static void sqlite3Fts5ExprFree(Fts5Expr*);
179868 
179869 /* Called during startup to register a UDF with SQLite */
179870 static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
179871 
179872 static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
179873 static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
179874 static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
179875 
179876 typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
179877 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
179878 static int sqlite3Fts5ExprPopulatePoslists(
179879  Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
179880 );
179881 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
179882 
179883 static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
179884 
179885 static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
179886 
179887 /*******************************************
179888 ** The fts5_expr.c API above this point is used by the other hand-written
179889 ** C code in this module. The interfaces below this point are called by
179890 ** the parser code in fts5parse.y. */
179891 
179892 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
179893 
179894 static Fts5ExprNode *sqlite3Fts5ParseNode(
179895  Fts5Parse *pParse,
179896  int eType,
179897  Fts5ExprNode *pLeft,
179898  Fts5ExprNode *pRight,
179899  Fts5ExprNearset *pNear
179900 );
179901 
179902 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
179903  Fts5Parse *pParse,
179904  Fts5ExprNode *pLeft,
179905  Fts5ExprNode *pRight
179906 );
179907 
179908 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
179909  Fts5Parse *pParse,
179910  Fts5ExprPhrase *pPhrase,
179911  Fts5Token *pToken,
179912  int bPrefix
179913 );
179914 
179915 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
179916  Fts5Parse*,
179917  Fts5ExprNearset*,
179918  Fts5ExprPhrase*
179919 );
179920 
179921 static Fts5Colset *sqlite3Fts5ParseColset(
179922  Fts5Parse*,
179923  Fts5Colset*,
179924  Fts5Token *
179925 );
179926 
179927 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
179928 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
179929 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
179930 
179931 static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
179932 static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
179933 static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
179934 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
179935 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
179936 
179937 /*
179938 ** End of interface to code in fts5_expr.c.
179939 **************************************************************************/
179940 
179941 
179942 
179943 /**************************************************************************
179944 ** Interface to code in fts5_aux.c.
179945 */
179946 
179947 static int sqlite3Fts5AuxInit(fts5_api*);
179948 /*
179949 ** End of interface to code in fts5_aux.c.
179950 **************************************************************************/
179951 
179952 /**************************************************************************
179953 ** Interface to code in fts5_tokenizer.c.
179954 */
179955 
179956 static int sqlite3Fts5TokenizerInit(fts5_api*);
179957 /*
179958 ** End of interface to code in fts5_tokenizer.c.
179959 **************************************************************************/
179960 
179961 /**************************************************************************
179962 ** Interface to code in fts5_vocab.c.
179963 */
179964 
179965 static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
179966 
179967 /*
179968 ** End of interface to code in fts5_vocab.c.
179969 **************************************************************************/
179970 
179971 
179972 /**************************************************************************
179973 ** Interface to automatically generated code in fts5_unicode2.c.
179974 */
179975 static int sqlite3Fts5UnicodeIsalnum(int c);
179976 static int sqlite3Fts5UnicodeIsdiacritic(int c);
179977 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
179978 /*
179979 ** End of interface to code in fts5_unicode2.c.
179980 **************************************************************************/
179981 
179982 #endif
179983 
179984 #define FTS5_OR 1
179985 #define FTS5_AND 2
179986 #define FTS5_NOT 3
179987 #define FTS5_TERM 4
179988 #define FTS5_COLON 5
179989 #define FTS5_LP 6
179990 #define FTS5_RP 7
179991 #define FTS5_MINUS 8
179992 #define FTS5_LCP 9
179993 #define FTS5_RCP 10
179994 #define FTS5_STRING 11
179995 #define FTS5_COMMA 12
179996 #define FTS5_PLUS 13
179997 #define FTS5_STAR 14
179998 
179999 /*
180000 ** 2000-05-29
180001 **
180002 ** The author disclaims copyright to this source code. In place of
180003 ** a legal notice, here is a blessing:
180004 **
180005 ** May you do good and not evil.
180006 ** May you find forgiveness for yourself and forgive others.
180007 ** May you share freely, never taking more than you give.
180008 **
180009 *************************************************************************
180010 ** Driver template for the LEMON parser generator.
180011 **
180012 ** The "lemon" program processes an LALR(1) input grammar file, then uses
180013 ** this template to construct a parser. The "lemon" program inserts text
180014 ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
180015 ** interstitial "-" characters) contained in this template is changed into
180016 ** the value of the %name directive from the grammar. Otherwise, the content
180017 ** of this template is copied straight through into the generate parser
180018 ** source file.
180019 **
180020 ** The following is the concatenation of all %include directives from the
180021 ** input grammar file:
180022 */
180023 /* #include <stdio.h> */
180024 /************ Begin %include sections from the grammar ************************/
180025 
180026 /* #include "fts5Int.h" */
180027 /* #include "fts5parse.h" */
180028 
180029 /*
180030 ** Disable all error recovery processing in the parser push-down
180031 ** automaton.
180032 */
180033 #define fts5YYNOERRORRECOVERY 1
180034 
180035 /*
180036 ** Make fts5yytestcase() the same as testcase()
180037 */
180038 #define fts5yytestcase(X) testcase(X)
180039 
180040 /*
180041 ** Indicate that sqlite3ParserFree() will never be called with a null
180042 ** pointer.
180043 */
180044 #define fts5YYPARSEFREENOTNULL 1
180045 
180046 /*
180047 ** Alternative datatype for the argument to the malloc() routine passed
180048 ** into sqlite3ParserAlloc(). The default is size_t.
180049 */
180050 #define fts5YYMALLOCARGTYPE u64
180051 
180052 /**************** End of %include directives **********************************/
180053 /* These constants specify the various numeric values for terminal symbols
180054 ** in a format understandable to "makeheaders". This section is blank unless
180055 ** "lemon" is run with the "-m" command-line option.
180056 ***************** Begin makeheaders token definitions *************************/
180057 /**************** End makeheaders token definitions ***************************/
180058 
180059 /* The next sections is a series of control #defines.
180060 ** various aspects of the generated parser.
180061 ** fts5YYCODETYPE is the data type used to store the integer codes
180062 ** that represent terminal and non-terminal symbols.
180063 ** "unsigned char" is used if there are fewer than
180064 ** 256 symbols. Larger types otherwise.
180065 ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
180066 ** any terminal or nonterminal symbol.
180067 ** fts5YYFALLBACK If defined, this indicates that one or more tokens
180068 ** (also known as: "terminal symbols") have fall-back
180069 ** values which should be used if the original symbol
180070 ** would not parse. This permits keywords to sometimes
180071 ** be used as identifiers, for example.
180072 ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
180073 ** that indicate what to do in response to the next
180074 ** token.
180075 ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
180076 ** symbols. Background: A "minor type" is a semantic
180077 ** value associated with a terminal or non-terminal
180078 ** symbols. For example, for an "ID" terminal symbol,
180079 ** the minor type might be the name of the identifier.
180080 ** Each non-terminal can have a different minor type.
180081 ** Terminal symbols all have the same minor type, though.
180082 ** This macros defines the minor type for terminal
180083 ** symbols.
180084 ** fts5YYMINORTYPE is the data type used for all minor types.
180085 ** This is typically a union of many types, one of
180086 ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
180087 ** for terminal symbols is called "fts5yy0".
180088 ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
180089 ** zero the stack is dynamically sized using realloc()
180090 ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
180091 ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
180092 ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
180093 ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
180094 ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
180095 ** defined, then do no error processing.
180096 ** fts5YYNSTATE the combined number of states.
180097 ** fts5YYNRULE the number of rules in the grammar
180098 ** fts5YY_MAX_SHIFT Maximum value for shift actions
180099 ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
180100 ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
180101 ** fts5YY_MIN_REDUCE Maximum value for reduce actions
180102 ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
180103 ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
180104 ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
180105 */
180106 #ifndef INTERFACE
180107 # define INTERFACE 1
180108 #endif
180109 /************* Begin control #defines *****************************************/
180110 #define fts5YYCODETYPE unsigned char
180111 #define fts5YYNOCODE 28
180112 #define fts5YYACTIONTYPE unsigned char
180113 #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
180114 typedef union {
180115  int fts5yyinit;
180116  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
180117  int fts5yy4;
180118  Fts5Colset* fts5yy11;
180119  Fts5ExprNode* fts5yy24;
180120  Fts5ExprNearset* fts5yy46;
180121  Fts5ExprPhrase* fts5yy53;
180122 } fts5YYMINORTYPE;
180123 #ifndef fts5YYSTACKDEPTH
180124 #define fts5YYSTACKDEPTH 100
180125 #endif
180126 #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
180127 #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
180128 #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
180129 #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
180130 #define fts5YYNSTATE 29
180131 #define fts5YYNRULE 26
180132 #define fts5YY_MAX_SHIFT 28
180133 #define fts5YY_MIN_SHIFTREDUCE 45
180134 #define fts5YY_MAX_SHIFTREDUCE 70
180135 #define fts5YY_MIN_REDUCE 71
180136 #define fts5YY_MAX_REDUCE 96
180137 #define fts5YY_ERROR_ACTION 97
180138 #define fts5YY_ACCEPT_ACTION 98
180139 #define fts5YY_NO_ACTION 99
180140 /************* End control #defines *******************************************/
180141 
180142 /* Define the fts5yytestcase() macro to be a no-op if is not already defined
180143 ** otherwise.
180144 **
180145 ** Applications can choose to define fts5yytestcase() in the %include section
180146 ** to a macro that can assist in verifying code coverage. For production
180147 ** code the fts5yytestcase() macro should be turned off. But it is useful
180148 ** for testing.
180149 */
180150 #ifndef fts5yytestcase
180151 # define fts5yytestcase(X)
180152 #endif
180153 
180154 
180155 /* Next are the tables used to determine what action to take based on the
180156 ** current state and lookahead token. These tables are used to implement
180157 ** functions that take a state number and lookahead value and return an
180158 ** action integer.
180159 **
180160 ** Suppose the action integer is N. Then the action is determined as
180161 ** follows
180162 **
180163 ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
180164 ** token onto the stack and goto state N.
180165 **
180166 ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
180167 ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
180168 **
180169 ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
180170 ** and fts5YY_MAX_REDUCE
180171 **
180172 ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
180173 **
180174 ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
180175 **
180176 ** N == fts5YY_NO_ACTION No such action. Denotes unused
180177 ** slots in the fts5yy_action[] table.
180178 **
180179 ** The action table is constructed as a single large table named fts5yy_action[].
180180 ** Given state S and lookahead X, the action is computed as either:
180181 **
180182 ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
180183 ** (B) N = fts5yy_default[S]
180184 **
180185 ** The (A) formula is preferred. The B formula is used instead if:
180186 ** (1) The fts5yy_shift_ofst[S]+X value is out of range, or
180187 ** (2) fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or
180188 ** (3) fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT.
180189 ** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that
180190 ** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
180191 ** Hence only tests (1) and (2) need to be evaluated.)
180192 **
180193 ** The formulas above are for computing the action when the lookahead is
180194 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
180195 ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
180196 ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
180197 ** fts5YY_SHIFT_USE_DFLT.
180198 **
180199 ** The following are the tables generated in this section:
180200 **
180201 ** fts5yy_action[] A single table containing all actions.
180202 ** fts5yy_lookahead[] A table containing the lookahead for each entry in
180203 ** fts5yy_action. Used to detect hash collisions.
180204 ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
180205 ** shifting terminals.
180206 ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
180207 ** shifting non-terminals after a reduce.
180208 ** fts5yy_default[] Default action for each state.
180209 **
180210 *********** Begin parsing tables **********************************************/
180211 #define fts5YY_ACTTAB_COUNT (85)
180212 static const fts5YYACTIONTYPE fts5yy_action[] = {
180213  /* 0 */ 98, 16, 51, 5, 53, 27, 83, 7, 26, 15,
180214  /* 10 */ 51, 5, 53, 27, 13, 69, 26, 48, 51, 5,
180215  /* 20 */ 53, 27, 19, 11, 26, 9, 20, 51, 5, 53,
180216  /* 30 */ 27, 13, 22, 26, 28, 51, 5, 53, 27, 68,
180217  /* 40 */ 1, 26, 19, 11, 17, 9, 52, 10, 53, 27,
180218  /* 50 */ 23, 24, 26, 54, 3, 4, 2, 26, 6, 21,
180219  /* 60 */ 49, 71, 3, 4, 2, 7, 56, 59, 55, 59,
180220  /* 70 */ 4, 2, 12, 69, 58, 60, 18, 67, 62, 69,
180221  /* 80 */ 25, 66, 8, 14, 2,
180222 };
180223 static const fts5YYCODETYPE fts5yy_lookahead[] = {
180224  /* 0 */ 16, 17, 18, 19, 20, 21, 5, 6, 24, 17,
180225  /* 10 */ 18, 19, 20, 21, 11, 14, 24, 17, 18, 19,
180226  /* 20 */ 20, 21, 8, 9, 24, 11, 17, 18, 19, 20,
180227  /* 30 */ 21, 11, 12, 24, 17, 18, 19, 20, 21, 26,
180228  /* 40 */ 6, 24, 8, 9, 22, 11, 18, 11, 20, 21,
180229  /* 50 */ 24, 25, 24, 20, 1, 2, 3, 24, 23, 24,
180230  /* 60 */ 7, 0, 1, 2, 3, 6, 10, 11, 10, 11,
180231  /* 70 */ 2, 3, 9, 14, 11, 11, 22, 26, 7, 14,
180232  /* 80 */ 13, 11, 5, 11, 3,
180233 };
180234 #define fts5YY_SHIFT_USE_DFLT (85)
180235 #define fts5YY_SHIFT_COUNT (28)
180236 #define fts5YY_SHIFT_MIN (0)
180237 #define fts5YY_SHIFT_MAX (81)
180238 static const unsigned char fts5yy_shift_ofst[] = {
180239  /* 0 */ 34, 34, 34, 34, 34, 14, 20, 3, 36, 1,
180240  /* 10 */ 59, 64, 64, 65, 65, 53, 61, 56, 58, 63,
180241  /* 20 */ 68, 67, 70, 67, 71, 72, 67, 77, 81,
180242 };
180243 #define fts5YY_REDUCE_USE_DFLT (-17)
180244 #define fts5YY_REDUCE_COUNT (14)
180245 #define fts5YY_REDUCE_MIN (-16)
180246 #define fts5YY_REDUCE_MAX (54)
180247 static const signed char fts5yy_reduce_ofst[] = {
180248  /* 0 */ -16, -8, 0, 9, 17, 28, 26, 35, 33, 13,
180249  /* 10 */ 13, 22, 54, 13, 51,
180250 };
180251 static const fts5YYACTIONTYPE fts5yy_default[] = {
180252  /* 0 */ 97, 97, 97, 97, 97, 76, 91, 97, 97, 96,
180253  /* 10 */ 96, 97, 97, 96, 96, 97, 97, 97, 97, 97,
180254  /* 20 */ 73, 89, 97, 90, 97, 97, 87, 97, 72,
180255 };
180256 /********** End of lemon-generated parsing tables *****************************/
180257 
180258 /* The next table maps tokens (terminal symbols) into fallback tokens.
180259 ** If a construct like the following:
180260 **
180261 ** %fallback ID X Y Z.
180262 **
180263 ** appears in the grammar, then ID becomes a fallback token for X, Y,
180264 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
180265 ** but it does not parse, the type of the token is changed to ID and
180266 ** the parse is retried before an error is thrown.
180267 **
180268 ** This feature can be used, for example, to cause some keywords in a language
180269 ** to revert to identifiers if they keyword does not apply in the context where
180270 ** it appears.
180271 */
180272 #ifdef fts5YYFALLBACK
180273 static const fts5YYCODETYPE fts5yyFallback[] = {
180274 };
180275 #endif /* fts5YYFALLBACK */
180276 
180277 /* The following structure represents a single element of the
180278 ** parser's stack. Information stored includes:
180279 **
180280 ** + The state number for the parser at this level of the stack.
180281 **
180282 ** + The value of the token stored at this level of the stack.
180283 ** (In other words, the "major" token.)
180284 **
180285 ** + The semantic value stored at this level of the stack. This is
180286 ** the information used by the action routines in the grammar.
180287 ** It is sometimes called the "minor" token.
180288 **
180289 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
180290 ** actually contains the reduce action for the second half of the
180291 ** SHIFTREDUCE.
180292 */
180293 struct fts5yyStackEntry {
180294  fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
180295  fts5YYCODETYPE major; /* The major token value. This is the code
180296  ** number for the token at this stack level */
180297  fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
180298  ** is the value of the token */
180299 };
180300 typedef struct fts5yyStackEntry fts5yyStackEntry;
180301 
180302 /* The state of the parser is completely contained in an instance of
180303 ** the following structure */
180304 struct fts5yyParser {
180305  fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
180306 #ifdef fts5YYTRACKMAXSTACKDEPTH
180307  int fts5yyhwm; /* High-water mark of the stack */
180308 #endif
180309 #ifndef fts5YYNOERRORRECOVERY
180310  int fts5yyerrcnt; /* Shifts left before out of the error */
180311 #endif
180312  sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
180313 #if fts5YYSTACKDEPTH<=0
180314  int fts5yystksz; /* Current side of the stack */
180315  fts5yyStackEntry *fts5yystack; /* The parser's stack */
180316  fts5yyStackEntry fts5yystk0; /* First stack entry */
180317 #else
180318  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
180319 #endif
180320 };
180321 typedef struct fts5yyParser fts5yyParser;
180322 
180323 #ifndef NDEBUG
180324 /* #include <stdio.h> */
180325 static FILE *fts5yyTraceFILE = 0;
180326 static char *fts5yyTracePrompt = 0;
180327 #endif /* NDEBUG */
180328 
180329 #ifndef NDEBUG
180330 /*
180331 ** Turn parser tracing on by giving a stream to which to write the trace
180332 ** and a prompt to preface each trace message. Tracing is turned off
180333 ** by making either argument NULL
180334 **
180335 ** Inputs:
180336 ** <ul>
180337 ** <li> A FILE* to which trace output should be written.
180338 ** If NULL, then tracing is turned off.
180339 ** <li> A prefix string written at the beginning of every
180340 ** line of trace output. If NULL, then tracing is
180341 ** turned off.
180342 ** </ul>
180343 **
180344 ** Outputs:
180345 ** None.
180346 */
180347 static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
180348  fts5yyTraceFILE = TraceFILE;
180349  fts5yyTracePrompt = zTracePrompt;
180350  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
180351  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
180352 }
180353 #endif /* NDEBUG */
180354 
180355 #ifndef NDEBUG
180356 /* For tracing shifts, the names of all terminals and nonterminals
180357 ** are required. The following table supplies these names */
180358 static const char *const fts5yyTokenName[] = {
180359  "$", "OR", "AND", "NOT",
180360  "TERM", "COLON", "LP", "RP",
180361  "MINUS", "LCP", "RCP", "STRING",
180362  "COMMA", "PLUS", "STAR", "error",
180363  "input", "expr", "cnearset", "exprlist",
180364  "nearset", "colset", "colsetlist", "nearphrases",
180365  "phrase", "neardist_opt", "star_opt",
180366 };
180367 #endif /* NDEBUG */
180368 
180369 #ifndef NDEBUG
180370 /* For tracing reduce actions, the names of all rules are required.
180371 */
180372 static const char *const fts5yyRuleName[] = {
180373  /* 0 */ "input ::= expr",
180374  /* 1 */ "expr ::= expr AND expr",
180375  /* 2 */ "expr ::= expr OR expr",
180376  /* 3 */ "expr ::= expr NOT expr",
180377  /* 4 */ "expr ::= LP expr RP",
180378  /* 5 */ "expr ::= exprlist",
180379  /* 6 */ "exprlist ::= cnearset",
180380  /* 7 */ "exprlist ::= exprlist cnearset",
180381  /* 8 */ "cnearset ::= nearset",
180382  /* 9 */ "cnearset ::= colset COLON nearset",
180383  /* 10 */ "colset ::= MINUS LCP colsetlist RCP",
180384  /* 11 */ "colset ::= LCP colsetlist RCP",
180385  /* 12 */ "colset ::= STRING",
180386  /* 13 */ "colset ::= MINUS STRING",
180387  /* 14 */ "colsetlist ::= colsetlist STRING",
180388  /* 15 */ "colsetlist ::= STRING",
180389  /* 16 */ "nearset ::= phrase",
180390  /* 17 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
180391  /* 18 */ "nearphrases ::= phrase",
180392  /* 19 */ "nearphrases ::= nearphrases phrase",
180393  /* 20 */ "neardist_opt ::=",
180394  /* 21 */ "neardist_opt ::= COMMA STRING",
180395  /* 22 */ "phrase ::= phrase PLUS STRING star_opt",
180396  /* 23 */ "phrase ::= STRING star_opt",
180397  /* 24 */ "star_opt ::= STAR",
180398  /* 25 */ "star_opt ::=",
180399 };
180400 #endif /* NDEBUG */
180401 
180402 
180403 #if fts5YYSTACKDEPTH<=0
180404 /*
180405 ** Try to increase the size of the parser stack. Return the number
180406 ** of errors. Return 0 on success.
180407 */
180408 static int fts5yyGrowStack(fts5yyParser *p){
180409  int newSize;
180410  int idx;
180411  fts5yyStackEntry *pNew;
180412 
180413  newSize = p->fts5yystksz*2 + 100;
180414  idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
180415  if( p->fts5yystack==&p->fts5yystk0 ){
180416  pNew = malloc(newSize*sizeof(pNew[0]));
180417  if( pNew ) pNew[0] = p->fts5yystk0;
180418  }else{
180419  pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
180420  }
180421  if( pNew ){
180422  p->fts5yystack = pNew;
180423  p->fts5yytos = &p->fts5yystack[idx];
180424 #ifndef NDEBUG
180425  if( fts5yyTraceFILE ){
180426  fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
180427  fts5yyTracePrompt, p->fts5yystksz, newSize);
180428  }
180429 #endif
180430  p->fts5yystksz = newSize;
180431  }
180432  return pNew==0;
180433 }
180434 #endif
180435 
180436 /* Datatype of the argument to the memory allocated passed as the
180437 ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
180438 ** putting an appropriate #define in the %include section of the input
180439 ** grammar.
180440 */
180441 #ifndef fts5YYMALLOCARGTYPE
180442 # define fts5YYMALLOCARGTYPE size_t
180443 #endif
180444 
180445 /*
180446 ** This function allocates a new parser.
180447 ** The only argument is a pointer to a function which works like
180448 ** malloc.
180449 **
180450 ** Inputs:
180451 ** A pointer to the function used to allocate memory.
180452 **
180453 ** Outputs:
180454 ** A pointer to a parser. This pointer is used in subsequent calls
180455 ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
180456 */
180457 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
180458  fts5yyParser *pParser;
180459  pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
180460  if( pParser ){
180461 #ifdef fts5YYTRACKMAXSTACKDEPTH
180462  pParser->fts5yyhwm = 0;
180463 #endif
180464 #if fts5YYSTACKDEPTH<=0
180465  pParser->fts5yytos = NULL;
180466  pParser->fts5yystack = NULL;
180467  pParser->fts5yystksz = 0;
180468  if( fts5yyGrowStack(pParser) ){
180469  pParser->fts5yystack = &pParser->fts5yystk0;
180470  pParser->fts5yystksz = 1;
180471  }
180472 #endif
180473 #ifndef fts5YYNOERRORRECOVERY
180474  pParser->fts5yyerrcnt = -1;
180475 #endif
180476  pParser->fts5yytos = pParser->fts5yystack;
180477  pParser->fts5yystack[0].stateno = 0;
180478  pParser->fts5yystack[0].major = 0;
180479  }
180480  return pParser;
180481 }
180482 
180483 /* The following function deletes the "minor type" or semantic value
180484 ** associated with a symbol. The symbol can be either a terminal
180485 ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
180486 ** a pointer to the value to be deleted. The code used to do the
180487 ** deletions is derived from the %destructor and/or %token_destructor
180488 ** directives of the input grammar.
180489 */
180490 static void fts5yy_destructor(
180491  fts5yyParser *fts5yypParser, /* The parser */
180492  fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
180493  fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
180494 ){
180495  sqlite3Fts5ParserARG_FETCH;
180496  switch( fts5yymajor ){
180497  /* Here is inserted the actions which take place when a
180498  ** terminal or non-terminal is destroyed. This can happen
180499  ** when the symbol is popped from the stack during a
180500  ** reduce or during error processing or when a parser is
180501  ** being destroyed before it is finished parsing.
180502  **
180503  ** Note: during a reduce, the only symbols destroyed are those
180504  ** which appear on the RHS of the rule, but which are *not* used
180505  ** inside the C code.
180506  */
180507 /********* Begin destructor definitions ***************************************/
180508  case 16: /* input */
180509 {
180510  (void)pParse;
180511 }
180512  break;
180513  case 17: /* expr */
180514  case 18: /* cnearset */
180515  case 19: /* exprlist */
180516 {
180517  sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
180518 }
180519  break;
180520  case 20: /* nearset */
180521  case 23: /* nearphrases */
180522 {
180523  sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
180524 }
180525  break;
180526  case 21: /* colset */
180527  case 22: /* colsetlist */
180528 {
180529  sqlite3_free((fts5yypminor->fts5yy11));
180530 }
180531  break;
180532  case 24: /* phrase */
180533 {
180534  sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
180535 }
180536  break;
180537 /********* End destructor definitions *****************************************/
180538  default: break; /* If no destructor action specified: do nothing */
180539  }
180540 }
180541 
180542 /*
180543 ** Pop the parser's stack once.
180544 **
180545 ** If there is a destructor routine associated with the token which
180546 ** is popped from the stack, then call it.
180547 */
180548 static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
180549  fts5yyStackEntry *fts5yytos;
180550  assert( pParser->fts5yytos!=0 );
180551  assert( pParser->fts5yytos > pParser->fts5yystack );
180552  fts5yytos = pParser->fts5yytos--;
180553 #ifndef NDEBUG
180554  if( fts5yyTraceFILE ){
180555  fprintf(fts5yyTraceFILE,"%sPopping %s\n",
180556  fts5yyTracePrompt,
180557  fts5yyTokenName[fts5yytos->major]);
180558  }
180559 #endif
180560  fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
180561 }
180562 
180563 /*
180564 ** Deallocate and destroy a parser. Destructors are called for
180565 ** all stack elements before shutting the parser down.
180566 **
180567 ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
180568 ** is defined in a %include section of the input grammar) then it is
180569 ** assumed that the input pointer is never NULL.
180570 */
180571 static void sqlite3Fts5ParserFree(
180572  void *p, /* The parser to be deleted */
180573  void (*freeProc)(void*) /* Function used to reclaim memory */
180574 ){
180575  fts5yyParser *pParser = (fts5yyParser*)p;
180576 #ifndef fts5YYPARSEFREENEVERNULL
180577  if( pParser==0 ) return;
180578 #endif
180579  while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
180580 #if fts5YYSTACKDEPTH<=0
180581  if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
180582 #endif
180583  (*freeProc)((void*)pParser);
180584 }
180585 
180586 /*
180587 ** Return the peak depth of the stack for a parser.
180588 */
180589 #ifdef fts5YYTRACKMAXSTACKDEPTH
180590 static int sqlite3Fts5ParserStackPeak(void *p){
180591  fts5yyParser *pParser = (fts5yyParser*)p;
180592  return pParser->fts5yyhwm;
180593 }
180594 #endif
180595 
180596 /*
180597 ** Find the appropriate action for a parser given the terminal
180598 ** look-ahead token iLookAhead.
180599 */
180600 static unsigned int fts5yy_find_shift_action(
180601  fts5yyParser *pParser, /* The parser */
180602  fts5YYCODETYPE iLookAhead /* The look-ahead token */
180603 ){
180604  int i;
180605  int stateno = pParser->fts5yytos->stateno;
180606 
180607  if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
180608  assert( stateno <= fts5YY_SHIFT_COUNT );
180609  do{
180610  i = fts5yy_shift_ofst[stateno];
180611  assert( iLookAhead!=fts5YYNOCODE );
180612  i += iLookAhead;
180613  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
180614 #ifdef fts5YYFALLBACK
180615  fts5YYCODETYPE iFallback; /* Fallback token */
180616  if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
180617  && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
180618 #ifndef NDEBUG
180619  if( fts5yyTraceFILE ){
180620  fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
180621  fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
180622  }
180623 #endif
180624  assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
180625  iLookAhead = iFallback;
180626  continue;
180627  }
180628 #endif
180629 #ifdef fts5YYWILDCARD
180630  {
180631  int j = i - iLookAhead + fts5YYWILDCARD;
180632  if(
180633 #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
180634  j>=0 &&
180635 #endif
180636 #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
180637  j<fts5YY_ACTTAB_COUNT &&
180638 #endif
180639  fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
180640  ){
180641 #ifndef NDEBUG
180642  if( fts5yyTraceFILE ){
180643  fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
180644  fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
180645  fts5yyTokenName[fts5YYWILDCARD]);
180646  }
180647 #endif /* NDEBUG */
180648  return fts5yy_action[j];
180649  }
180650  }
180651 #endif /* fts5YYWILDCARD */
180652  return fts5yy_default[stateno];
180653  }else{
180654  return fts5yy_action[i];
180655  }
180656  }while(1);
180657 }
180658 
180659 /*
180660 ** Find the appropriate action for a parser given the non-terminal
180661 ** look-ahead token iLookAhead.
180662 */
180663 static int fts5yy_find_reduce_action(
180664  int stateno, /* Current state number */
180665  fts5YYCODETYPE iLookAhead /* The look-ahead token */
180666 ){
180667  int i;
180668 #ifdef fts5YYERRORSYMBOL
180669  if( stateno>fts5YY_REDUCE_COUNT ){
180670  return fts5yy_default[stateno];
180671  }
180672 #else
180673  assert( stateno<=fts5YY_REDUCE_COUNT );
180674 #endif
180675  i = fts5yy_reduce_ofst[stateno];
180676  assert( i!=fts5YY_REDUCE_USE_DFLT );
180677  assert( iLookAhead!=fts5YYNOCODE );
180678  i += iLookAhead;
180679 #ifdef fts5YYERRORSYMBOL
180680  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
180681  return fts5yy_default[stateno];
180682  }
180683 #else
180684  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
180685  assert( fts5yy_lookahead[i]==iLookAhead );
180686 #endif
180687  return fts5yy_action[i];
180688 }
180689 
180690 /*
180691 ** The following routine is called if the stack overflows.
180692 */
180693 static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
180694  sqlite3Fts5ParserARG_FETCH;
180695  fts5yypParser->fts5yytos--;
180696 #ifndef NDEBUG
180697  if( fts5yyTraceFILE ){
180698  fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
180699  }
180700 #endif
180701  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
180702  /* Here code is inserted which will execute if the parser
180703  ** stack every overflows */
180704 /******** Begin %stack_overflow code ******************************************/
180705 
180706  sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
180707 /******** End %stack_overflow code ********************************************/
180708  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
180709 }
180710 
180711 /*
180712 ** Print tracing information for a SHIFT action
180713 */
180714 #ifndef NDEBUG
180715 static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
180716  if( fts5yyTraceFILE ){
180717  if( fts5yyNewState<fts5YYNSTATE ){
180718  fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
180719  fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
180720  fts5yyNewState);
180721  }else{
180722  fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
180723  fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
180724  }
180725  }
180726 }
180727 #else
180728 # define fts5yyTraceShift(X,Y)
180729 #endif
180730 
180731 /*
180732 ** Perform a shift action.
180733 */
180734 static void fts5yy_shift(
180735  fts5yyParser *fts5yypParser, /* The parser to be shifted */
180736  int fts5yyNewState, /* The new state to shift in */
180737  int fts5yyMajor, /* The major token to shift in */
180738  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
180739 ){
180740  fts5yyStackEntry *fts5yytos;
180741  fts5yypParser->fts5yytos++;
180742 #ifdef fts5YYTRACKMAXSTACKDEPTH
180743  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
180744  fts5yypParser->fts5yyhwm++;
180745  assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
180746  }
180747 #endif
180748 #if fts5YYSTACKDEPTH>0
180749  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){
180750  fts5yyStackOverflow(fts5yypParser);
180751  return;
180752  }
180753 #else
180754  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
180755  if( fts5yyGrowStack(fts5yypParser) ){
180756  fts5yyStackOverflow(fts5yypParser);
180757  return;
180758  }
180759  }
180760 #endif
180761  if( fts5yyNewState > fts5YY_MAX_SHIFT ){
180762  fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
180763  }
180764  fts5yytos = fts5yypParser->fts5yytos;
180765  fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
180766  fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
180767  fts5yytos->minor.fts5yy0 = fts5yyMinor;
180768  fts5yyTraceShift(fts5yypParser, fts5yyNewState);
180769 }
180770 
180771 /* The following table contains information about every rule that
180772 ** is used during the reduce.
180773 */
180774 static const struct {
180775  fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
180776  unsigned char nrhs; /* Number of right-hand side symbols in the rule */
180777 } fts5yyRuleInfo[] = {
180778  { 16, 1 },
180779  { 17, 3 },
180780  { 17, 3 },
180781  { 17, 3 },
180782  { 17, 3 },
180783  { 17, 1 },
180784  { 19, 1 },
180785  { 19, 2 },
180786  { 18, 1 },
180787  { 18, 3 },
180788  { 21, 4 },
180789  { 21, 3 },
180790  { 21, 1 },
180791  { 21, 2 },
180792  { 22, 2 },
180793  { 22, 1 },
180794  { 20, 1 },
180795  { 20, 5 },
180796  { 23, 1 },
180797  { 23, 2 },
180798  { 25, 0 },
180799  { 25, 2 },
180800  { 24, 4 },
180801  { 24, 2 },
180802  { 26, 1 },
180803  { 26, 0 },
180804 };
180805 
180806 static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
180807 
180808 /*
180809 ** Perform a reduce action and the shift that must immediately
180810 ** follow the reduce.
180811 */
180812 static void fts5yy_reduce(
180813  fts5yyParser *fts5yypParser, /* The parser */
180814  unsigned int fts5yyruleno /* Number of the rule by which to reduce */
180815 ){
180816  int fts5yygoto; /* The next state */
180817  int fts5yyact; /* The next action */
180818  fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
180819  int fts5yysize; /* Amount to pop the stack */
180820  sqlite3Fts5ParserARG_FETCH;
180821  fts5yymsp = fts5yypParser->fts5yytos;
180822 #ifndef NDEBUG
180823  if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
180824  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
180825  fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
180826  fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
180827  }
180828 #endif /* NDEBUG */
180829 
180830  /* Check that the stack is large enough to grow by a single entry
180831  ** if the RHS of the rule is empty. This ensures that there is room
180832  ** enough on the stack to push the LHS value */
180833  if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
180834 #ifdef fts5YYTRACKMAXSTACKDEPTH
180835  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
180836  fts5yypParser->fts5yyhwm++;
180837  assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
180838  }
180839 #endif
180840 #if fts5YYSTACKDEPTH>0
180841  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){
180842  fts5yyStackOverflow(fts5yypParser);
180843  return;
180844  }
180845 #else
180846  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
180847  if( fts5yyGrowStack(fts5yypParser) ){
180848  fts5yyStackOverflow(fts5yypParser);
180849  return;
180850  }
180851  fts5yymsp = fts5yypParser->fts5yytos;
180852  }
180853 #endif
180854  }
180855 
180856  switch( fts5yyruleno ){
180857  /* Beginning here are the reduction cases. A typical example
180858  ** follows:
180859  ** case 0:
180860  ** #line <lineno> <grammarfile>
180861  ** { ... } // User supplied code
180862  ** #line <lineno> <thisfile>
180863  ** break;
180864  */
180865 /********** Begin reduce actions **********************************************/
180866  fts5YYMINORTYPE fts5yylhsminor;
180867  case 0: /* input ::= expr */
180868 { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
180869  break;
180870  case 1: /* expr ::= expr AND expr */
180871 {
180872  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
180873 }
180874  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180875  break;
180876  case 2: /* expr ::= expr OR expr */
180877 {
180878  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
180879 }
180880  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180881  break;
180882  case 3: /* expr ::= expr NOT expr */
180883 {
180884  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
180885 }
180886  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180887  break;
180888  case 4: /* expr ::= LP expr RP */
180889 {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
180890  break;
180891  case 5: /* expr ::= exprlist */
180892  case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
180893 {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
180894  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180895  break;
180896  case 7: /* exprlist ::= exprlist cnearset */
180897 {
180898  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
180899 }
180900  fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180901  break;
180902  case 8: /* cnearset ::= nearset */
180903 {
180904  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
180905 }
180906  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180907  break;
180908  case 9: /* cnearset ::= colset COLON nearset */
180909 {
180910  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy46, fts5yymsp[-2].minor.fts5yy11);
180911  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
180912 }
180913  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180914  break;
180915  case 10: /* colset ::= MINUS LCP colsetlist RCP */
180916 {
180917  fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
180918 }
180919  break;
180920  case 11: /* colset ::= LCP colsetlist RCP */
180921 { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
180922  break;
180923  case 12: /* colset ::= STRING */
180924 {
180925  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
180926 }
180927  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
180928  break;
180929  case 13: /* colset ::= MINUS STRING */
180930 {
180931  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
180932  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
180933 }
180934  break;
180935  case 14: /* colsetlist ::= colsetlist STRING */
180936 {
180937  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
180938  fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
180939  break;
180940  case 15: /* colsetlist ::= STRING */
180941 {
180942  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
180943 }
180944  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
180945  break;
180946  case 16: /* nearset ::= phrase */
180947 { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
180948  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
180949  break;
180950  case 17: /* nearset ::= STRING LP nearphrases neardist_opt RP */
180951 {
180952  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
180953  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
180954  fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
180955 }
180956  fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
180957  break;
180958  case 18: /* nearphrases ::= phrase */
180959 {
180960  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
180961 }
180962  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
180963  break;
180964  case 19: /* nearphrases ::= nearphrases phrase */
180965 {
180966  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
180967 }
180968  fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
180969  break;
180970  case 20: /* neardist_opt ::= */
180971 { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
180972  break;
180973  case 21: /* neardist_opt ::= COMMA STRING */
180974 { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
180975  break;
180976  case 22: /* phrase ::= phrase PLUS STRING star_opt */
180977 {
180978  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
180979 }
180980  fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
180981  break;
180982  case 23: /* phrase ::= STRING star_opt */
180983 {
180984  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
180985 }
180986  fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
180987  break;
180988  case 24: /* star_opt ::= STAR */
180989 { fts5yymsp[0].minor.fts5yy4 = 1; }
180990  break;
180991  case 25: /* star_opt ::= */
180992 { fts5yymsp[1].minor.fts5yy4 = 0; }
180993  break;
180994  default:
180995  break;
180996 /********** End reduce actions ************************************************/
180997  };
180998  assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
180999  fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
181000  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
181001  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
181002  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
181003  if( fts5yyact>fts5YY_MAX_SHIFT ){
181004  fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
181005  }
181006  fts5yymsp -= fts5yysize-1;
181007  fts5yypParser->fts5yytos = fts5yymsp;
181008  fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
181009  fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
181010  fts5yyTraceShift(fts5yypParser, fts5yyact);
181011  }else{
181012  assert( fts5yyact == fts5YY_ACCEPT_ACTION );
181013  fts5yypParser->fts5yytos -= fts5yysize;
181014  fts5yy_accept(fts5yypParser);
181015  }
181016 }
181017 
181018 /*
181019 ** The following code executes when the parse fails
181020 */
181021 #ifndef fts5YYNOERRORRECOVERY
181022 static void fts5yy_parse_failed(
181023  fts5yyParser *fts5yypParser /* The parser */
181024 ){
181025  sqlite3Fts5ParserARG_FETCH;
181026 #ifndef NDEBUG
181027  if( fts5yyTraceFILE ){
181028  fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
181029  }
181030 #endif
181031  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
181032  /* Here code is inserted which will be executed whenever the
181033  ** parser fails */
181034 /************ Begin %parse_failure code ***************************************/
181035 /************ End %parse_failure code *****************************************/
181036  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
181037 }
181038 #endif /* fts5YYNOERRORRECOVERY */
181039 
181040 /*
181041 ** The following code executes when a syntax error first occurs.
181042 */
181043 static void fts5yy_syntax_error(
181044  fts5yyParser *fts5yypParser, /* The parser */
181045  int fts5yymajor, /* The major type of the error token */
181046  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
181047 ){
181048  sqlite3Fts5ParserARG_FETCH;
181049 #define FTS5TOKEN fts5yyminor
181050 /************ Begin %syntax_error code ****************************************/
181051 
181052  UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
181053  sqlite3Fts5ParseError(
181054  pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
181055  );
181056 /************ End %syntax_error code ******************************************/
181057  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
181058 }
181059 
181060 /*
181061 ** The following is executed when the parser accepts
181062 */
181063 static void fts5yy_accept(
181064  fts5yyParser *fts5yypParser /* The parser */
181065 ){
181066  sqlite3Fts5ParserARG_FETCH;
181067 #ifndef NDEBUG
181068  if( fts5yyTraceFILE ){
181069  fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
181070  }
181071 #endif
181072 #ifndef fts5YYNOERRORRECOVERY
181073  fts5yypParser->fts5yyerrcnt = -1;
181074 #endif
181075  assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
181076  /* Here code is inserted which will be executed whenever the
181077  ** parser accepts */
181078 /*********** Begin %parse_accept code *****************************************/
181079 /*********** End %parse_accept code *******************************************/
181080  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
181081 }
181082 
181083 /* The main parser program.
181084 ** The first argument is a pointer to a structure obtained from
181085 ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
181086 ** The second argument is the major token number. The third is
181087 ** the minor token. The fourth optional argument is whatever the
181088 ** user wants (and specified in the grammar) and is available for
181089 ** use by the action routines.
181090 **
181091 ** Inputs:
181092 ** <ul>
181093 ** <li> A pointer to the parser (an opaque structure.)
181094 ** <li> The major token number.
181095 ** <li> The minor token number.
181096 ** <li> An option argument of a grammar-specified type.
181097 ** </ul>
181098 **
181099 ** Outputs:
181100 ** None.
181101 */
181102 static void sqlite3Fts5Parser(
181103  void *fts5yyp, /* The parser */
181104  int fts5yymajor, /* The major token code number */
181105  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
181106  sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
181107 ){
181108  fts5YYMINORTYPE fts5yyminorunion;
181109  unsigned int fts5yyact; /* The parser action. */
181110 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
181111  int fts5yyendofinput; /* True if we are at the end of input */
181112 #endif
181113 #ifdef fts5YYERRORSYMBOL
181114  int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
181115 #endif
181116  fts5yyParser *fts5yypParser; /* The parser */
181117 
181118  fts5yypParser = (fts5yyParser*)fts5yyp;
181119  assert( fts5yypParser->fts5yytos!=0 );
181120 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
181121  fts5yyendofinput = (fts5yymajor==0);
181122 #endif
181123  sqlite3Fts5ParserARG_STORE;
181124 
181125 #ifndef NDEBUG
181126  if( fts5yyTraceFILE ){
181127  fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
181128  }
181129 #endif
181130 
181131  do{
181132  fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
181133  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
181134  fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
181135 #ifndef fts5YYNOERRORRECOVERY
181136  fts5yypParser->fts5yyerrcnt--;
181137 #endif
181138  fts5yymajor = fts5YYNOCODE;
181139  }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
181140  fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
181141  }else{
181142  assert( fts5yyact == fts5YY_ERROR_ACTION );
181143  fts5yyminorunion.fts5yy0 = fts5yyminor;
181144 #ifdef fts5YYERRORSYMBOL
181145  int fts5yymx;
181146 #endif
181147 #ifndef NDEBUG
181148  if( fts5yyTraceFILE ){
181149  fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
181150  }
181151 #endif
181152 #ifdef fts5YYERRORSYMBOL
181153  /* A syntax error has occurred.
181154  ** The response to an error depends upon whether or not the
181155  ** grammar defines an error token "ERROR".
181156  **
181157  ** This is what we do if the grammar does define ERROR:
181158  **
181159  ** * Call the %syntax_error function.
181160  **
181161  ** * Begin popping the stack until we enter a state where
181162  ** it is legal to shift the error symbol, then shift
181163  ** the error symbol.
181164  **
181165  ** * Set the error count to three.
181166  **
181167  ** * Begin accepting and shifting new tokens. No new error
181168  ** processing will occur until three tokens have been
181169  ** shifted successfully.
181170  **
181171  */
181172  if( fts5yypParser->fts5yyerrcnt<0 ){
181173  fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
181174  }
181175  fts5yymx = fts5yypParser->fts5yytos->major;
181176  if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
181177 #ifndef NDEBUG
181178  if( fts5yyTraceFILE ){
181179  fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
181180  fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
181181  }
181182 #endif
181183  fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
181184  fts5yymajor = fts5YYNOCODE;
181185  }else{
181186  while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
181187  && fts5yymx != fts5YYERRORSYMBOL
181188  && (fts5yyact = fts5yy_find_reduce_action(
181189  fts5yypParser->fts5yytos->stateno,
181190  fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
181191  ){
181192  fts5yy_pop_parser_stack(fts5yypParser);
181193  }
181194  if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
181195  fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
181196  fts5yy_parse_failed(fts5yypParser);
181197 #ifndef fts5YYNOERRORRECOVERY
181198  fts5yypParser->fts5yyerrcnt = -1;
181199 #endif
181200  fts5yymajor = fts5YYNOCODE;
181201  }else if( fts5yymx!=fts5YYERRORSYMBOL ){
181202  fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
181203  }
181204  }
181205  fts5yypParser->fts5yyerrcnt = 3;
181206  fts5yyerrorhit = 1;
181207 #elif defined(fts5YYNOERRORRECOVERY)
181208  /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
181209  ** do any kind of error recovery. Instead, simply invoke the syntax
181210  ** error routine and continue going as if nothing had happened.
181211  **
181212  ** Applications can set this macro (for example inside %include) if
181213  ** they intend to abandon the parse upon the first syntax error seen.
181214  */
181215  fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
181216  fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
181217  fts5yymajor = fts5YYNOCODE;
181218 
181219 #else /* fts5YYERRORSYMBOL is not defined */
181220  /* This is what we do if the grammar does not define ERROR:
181221  **
181222  ** * Report an error message, and throw away the input token.
181223  **
181224  ** * If the input token is $, then fail the parse.
181225  **
181226  ** As before, subsequent error messages are suppressed until
181227  ** three input tokens have been successfully shifted.
181228  */
181229  if( fts5yypParser->fts5yyerrcnt<=0 ){
181230  fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
181231  }
181232  fts5yypParser->fts5yyerrcnt = 3;
181233  fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
181234  if( fts5yyendofinput ){
181235  fts5yy_parse_failed(fts5yypParser);
181236 #ifndef fts5YYNOERRORRECOVERY
181237  fts5yypParser->fts5yyerrcnt = -1;
181238 #endif
181239  }
181240  fts5yymajor = fts5YYNOCODE;
181241 #endif
181242  }
181243  }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
181244 #ifndef NDEBUG
181245  if( fts5yyTraceFILE ){
181246  fts5yyStackEntry *i;
181247  char cDiv = '[';
181248  fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
181249  for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
181250  fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
181251  cDiv = ' ';
181252  }
181253  fprintf(fts5yyTraceFILE,"]\n");
181254  }
181255 #endif
181256  return;
181257 }
181258 
181259 /*
181260 ** 2014 May 31
181261 **
181262 ** The author disclaims copyright to this source code. In place of
181263 ** a legal notice, here is a blessing:
181264 **
181265 ** May you do good and not evil.
181266 ** May you find forgiveness for yourself and forgive others.
181267 ** May you share freely, never taking more than you give.
181268 **
181269 ******************************************************************************
181270 */
181271 
181272 
181273 /* #include "fts5Int.h" */
181274 #include <math.h> /* amalgamator: keep */
181275 
181276 /*
181277 ** Object used to iterate through all "coalesced phrase instances" in
181278 ** a single column of the current row. If the phrase instances in the
181279 ** column being considered do not overlap, this object simply iterates
181280 ** through them. Or, if they do overlap (share one or more tokens in
181281 ** common), each set of overlapping instances is treated as a single
181282 ** match. See documentation for the highlight() auxiliary function for
181283 ** details.
181284 **
181285 ** Usage is:
181286 **
181287 ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
181288 ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
181289 ** rc = fts5CInstIterNext(&iter)
181290 ** ){
181291 ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
181292 ** }
181293 **
181294 */
181295 typedef struct CInstIter CInstIter;
181296 struct CInstIter {
181297  const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
181298  Fts5Context *pFts; /* First arg to pass to pApi functions */
181299  int iCol; /* Column to search */
181300  int iInst; /* Next phrase instance index */
181301  int nInst; /* Total number of phrase instances */
181302 
181303  /* Output variables */
181304  int iStart; /* First token in coalesced phrase instance */
181305  int iEnd; /* Last token in coalesced phrase instance */
181306 };
181307 
181308 /*
181309 ** Advance the iterator to the next coalesced phrase instance. Return
181310 ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
181311 */
181312 static int fts5CInstIterNext(CInstIter *pIter){
181313  int rc = SQLITE_OK;
181314  pIter->iStart = -1;
181315  pIter->iEnd = -1;
181316 
181317  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
181318  int ip; int ic; int io;
181319  rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
181320  if( rc==SQLITE_OK ){
181321  if( ic==pIter->iCol ){
181322  int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
181323  if( pIter->iStart<0 ){
181324  pIter->iStart = io;
181325  pIter->iEnd = iEnd;
181326  }else if( io<=pIter->iEnd ){
181327  if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
181328  }else{
181329  break;
181330  }
181331  }
181332  pIter->iInst++;
181333  }
181334  }
181335 
181336  return rc;
181337 }
181338 
181339 /*
181340 ** Initialize the iterator object indicated by the final parameter to
181341 ** iterate through coalesced phrase instances in column iCol.
181342 */
181343 static int fts5CInstIterInit(
181344  const Fts5ExtensionApi *pApi,
181345  Fts5Context *pFts,
181346  int iCol,
181347  CInstIter *pIter
181348 ){
181349  int rc;
181350 
181351  memset(pIter, 0, sizeof(CInstIter));
181352  pIter->pApi = pApi;
181353  pIter->pFts = pFts;
181354  pIter->iCol = iCol;
181355  rc = pApi->xInstCount(pFts, &pIter->nInst);
181356 
181357  if( rc==SQLITE_OK ){
181358  rc = fts5CInstIterNext(pIter);
181359  }
181360 
181361  return rc;
181362 }
181363 
181364 
181365 
181366 /*************************************************************************
181367 ** Start of highlight() implementation.
181368 */
181369 typedef struct HighlightContext HighlightContext;
181370 struct HighlightContext {
181371  CInstIter iter; /* Coalesced Instance Iterator */
181372  int iPos; /* Current token offset in zIn[] */
181373  int iRangeStart; /* First token to include */
181374  int iRangeEnd; /* If non-zero, last token to include */
181375  const char *zOpen; /* Opening highlight */
181376  const char *zClose; /* Closing highlight */
181377  const char *zIn; /* Input text */
181378  int nIn; /* Size of input text in bytes */
181379  int iOff; /* Current offset within zIn[] */
181380  char *zOut; /* Output value */
181381 };
181382 
181383 /*
181384 ** Append text to the HighlightContext output string - p->zOut. Argument
181385 ** z points to a buffer containing n bytes of text to append. If n is
181386 ** negative, everything up until the first '\0' is appended to the output.
181387 **
181388 ** If *pRc is set to any value other than SQLITE_OK when this function is
181389 ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
181390 ** *pRc is set to an error code before returning.
181391 */
181392 static void fts5HighlightAppend(
181393  int *pRc,
181394  HighlightContext *p,
181395  const char *z, int n
181396 ){
181397  if( *pRc==SQLITE_OK ){
181398  if( n<0 ) n = (int)strlen(z);
181399  p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
181400  if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
181401  }
181402 }
181403 
181404 /*
181405 ** Tokenizer callback used by implementation of highlight() function.
181406 */
181407 static int fts5HighlightCb(
181408  void *pContext, /* Pointer to HighlightContext object */
181409  int tflags, /* Mask of FTS5_TOKEN_* flags */
181410  const char *pToken, /* Buffer containing token */
181411  int nToken, /* Size of token in bytes */
181412  int iStartOff, /* Start offset of token */
181413  int iEndOff /* End offset of token */
181414 ){
181415  HighlightContext *p = (HighlightContext*)pContext;
181416  int rc = SQLITE_OK;
181417  int iPos;
181418 
181419  UNUSED_PARAM2(pToken, nToken);
181420 
181421  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
181422  iPos = p->iPos++;
181423 
181424  if( p->iRangeEnd>0 ){
181425  if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
181426  if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
181427  }
181428 
181429  if( iPos==p->iter.iStart ){
181430  fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
181431  fts5HighlightAppend(&rc, p, p->zOpen, -1);
181432  p->iOff = iStartOff;
181433  }
181434 
181435  if( iPos==p->iter.iEnd ){
181436  if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
181437  fts5HighlightAppend(&rc, p, p->zOpen, -1);
181438  }
181439  fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
181440  fts5HighlightAppend(&rc, p, p->zClose, -1);
181441  p->iOff = iEndOff;
181442  if( rc==SQLITE_OK ){
181443  rc = fts5CInstIterNext(&p->iter);
181444  }
181445  }
181446 
181447  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
181448  fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
181449  p->iOff = iEndOff;
181450  if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
181451  fts5HighlightAppend(&rc, p, p->zClose, -1);
181452  }
181453  }
181454 
181455  return rc;
181456 }
181457 
181458 /*
181459 ** Implementation of highlight() function.
181460 */
181461 static void fts5HighlightFunction(
181462  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
181463  Fts5Context *pFts, /* First arg to pass to pApi functions */
181464  sqlite3_context *pCtx, /* Context for returning result/error */
181465  int nVal, /* Number of values in apVal[] array */
181466  sqlite3_value **apVal /* Array of trailing arguments */
181467 ){
181468  HighlightContext ctx;
181469  int rc;
181470  int iCol;
181471 
181472  if( nVal!=3 ){
181473  const char *zErr = "wrong number of arguments to function highlight()";
181474  sqlite3_result_error(pCtx, zErr, -1);
181475  return;
181476  }
181477 
181478  iCol = sqlite3_value_int(apVal[0]);
181479  memset(&ctx, 0, sizeof(HighlightContext));
181480  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
181481  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
181482  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
181483 
181484  if( ctx.zIn ){
181485  if( rc==SQLITE_OK ){
181486  rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
181487  }
181488 
181489  if( rc==SQLITE_OK ){
181490  rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
181491  }
181492  fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
181493 
181494  if( rc==SQLITE_OK ){
181495  sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
181496  }
181497  sqlite3_free(ctx.zOut);
181498  }
181499  if( rc!=SQLITE_OK ){
181500  sqlite3_result_error_code(pCtx, rc);
181501  }
181502 }
181503 /*
181504 ** End of highlight() implementation.
181505 **************************************************************************/
181506 
181507 /*
181508 ** Context object passed to the fts5SentenceFinderCb() function.
181509 */
181510 typedef struct Fts5SFinder Fts5SFinder;
181511 struct Fts5SFinder {
181512  int iPos; /* Current token position */
181513  int nFirstAlloc; /* Allocated size of aFirst[] */
181514  int nFirst; /* Number of entries in aFirst[] */
181515  int *aFirst; /* Array of first token in each sentence */
181516  const char *zDoc; /* Document being tokenized */
181517 };
181518 
181519 /*
181520 ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
181521 ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
181522 ** error occurs.
181523 */
181524 static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
181525  if( p->nFirstAlloc==p->nFirst ){
181526  int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
181527  int *aNew;
181528 
181529  aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
181530  if( aNew==0 ) return SQLITE_NOMEM;
181531  p->aFirst = aNew;
181532  p->nFirstAlloc = nNew;
181533  }
181534  p->aFirst[p->nFirst++] = iAdd;
181535  return SQLITE_OK;
181536 }
181537 
181538 /*
181539 ** This function is an xTokenize() callback used by the auxiliary snippet()
181540 ** function. Its job is to identify tokens that are the first in a sentence.
181541 ** For each such token, an entry is added to the SFinder.aFirst[] array.
181542 */
181543 static int fts5SentenceFinderCb(
181544  void *pContext, /* Pointer to HighlightContext object */
181545  int tflags, /* Mask of FTS5_TOKEN_* flags */
181546  const char *pToken, /* Buffer containing token */
181547  int nToken, /* Size of token in bytes */
181548  int iStartOff, /* Start offset of token */
181549  int iEndOff /* End offset of token */
181550 ){
181551  int rc = SQLITE_OK;
181552 
181553  UNUSED_PARAM2(pToken, nToken);
181554  UNUSED_PARAM(iEndOff);
181555 
181556  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
181557  Fts5SFinder *p = (Fts5SFinder*)pContext;
181558  if( p->iPos>0 ){
181559  int i;
181560  char c = 0;
181561  for(i=iStartOff-1; i>=0; i--){
181562  c = p->zDoc[i];
181563  if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
181564  }
181565  if( i!=iStartOff-1 && (c=='.' || c==':') ){
181566  rc = fts5SentenceFinderAdd(p, p->iPos);
181567  }
181568  }else{
181569  rc = fts5SentenceFinderAdd(p, 0);
181570  }
181571  p->iPos++;
181572  }
181573  return rc;
181574 }
181575 
181576 static int fts5SnippetScore(
181577  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
181578  Fts5Context *pFts, /* First arg to pass to pApi functions */
181579  int nDocsize, /* Size of column in tokens */
181580  unsigned char *aSeen, /* Array with one element per query phrase */
181581  int iCol, /* Column to score */
181582  int iPos, /* Starting offset to score */
181583  int nToken, /* Max tokens per snippet */
181584  int *pnScore, /* OUT: Score */
181585  int *piPos /* OUT: Adjusted offset */
181586 ){
181587  int rc;
181588  int i;
181589  int ip = 0;
181590  int ic = 0;
181591  int iOff = 0;
181592  int iFirst = -1;
181593  int nInst;
181594  int nScore = 0;
181595  int iLast = 0;
181596 
181597  rc = pApi->xInstCount(pFts, &nInst);
181598  for(i=0; i<nInst && rc==SQLITE_OK; i++){
181599  rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
181600  if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
181601  nScore += (aSeen[ip] ? 1 : 1000);
181602  aSeen[ip] = 1;
181603  if( iFirst<0 ) iFirst = iOff;
181604  iLast = iOff + pApi->xPhraseSize(pFts, ip);
181605  }
181606  }
181607 
181608  *pnScore = nScore;
181609  if( piPos ){
181610  int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
181611  if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
181612  if( iAdj<0 ) iAdj = 0;
181613  *piPos = iAdj;
181614  }
181615 
181616  return rc;
181617 }
181618 
181619 /*
181620 ** Implementation of snippet() function.
181621 */
181622 static void fts5SnippetFunction(
181623  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
181624  Fts5Context *pFts, /* First arg to pass to pApi functions */
181625  sqlite3_context *pCtx, /* Context for returning result/error */
181626  int nVal, /* Number of values in apVal[] array */
181627  sqlite3_value **apVal /* Array of trailing arguments */
181628 ){
181629  HighlightContext ctx;
181630  int rc = SQLITE_OK; /* Return code */
181631  int iCol; /* 1st argument to snippet() */
181632  const char *zEllips; /* 4th argument to snippet() */
181633  int nToken; /* 5th argument to snippet() */
181634  int nInst = 0; /* Number of instance matches this row */
181635  int i; /* Used to iterate through instances */
181636  int nPhrase; /* Number of phrases in query */
181637  unsigned char *aSeen; /* Array of "seen instance" flags */
181638  int iBestCol; /* Column containing best snippet */
181639  int iBestStart = 0; /* First token of best snippet */
181640  int nBestScore = 0; /* Score of best snippet */
181641  int nColSize = 0; /* Total size of iBestCol in tokens */
181642  Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
181643  int nCol;
181644 
181645  if( nVal!=5 ){
181646  const char *zErr = "wrong number of arguments to function snippet()";
181647  sqlite3_result_error(pCtx, zErr, -1);
181648  return;
181649  }
181650 
181651  nCol = pApi->xColumnCount(pFts);
181652  memset(&ctx, 0, sizeof(HighlightContext));
181653  iCol = sqlite3_value_int(apVal[0]);
181654  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
181655  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
181656  zEllips = (const char*)sqlite3_value_text(apVal[3]);
181657  nToken = sqlite3_value_int(apVal[4]);
181658 
181659  iBestCol = (iCol>=0 ? iCol : 0);
181660  nPhrase = pApi->xPhraseCount(pFts);
181661  aSeen = sqlite3_malloc(nPhrase);
181662  if( aSeen==0 ){
181663  rc = SQLITE_NOMEM;
181664  }
181665  if( rc==SQLITE_OK ){
181666  rc = pApi->xInstCount(pFts, &nInst);
181667  }
181668 
181669  memset(&sFinder, 0, sizeof(Fts5SFinder));
181670  for(i=0; i<nCol; i++){
181671  if( iCol<0 || iCol==i ){
181672  int nDoc;
181673  int nDocsize;
181674  int ii;
181675  sFinder.iPos = 0;
181676  sFinder.nFirst = 0;
181677  rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
181678  if( rc!=SQLITE_OK ) break;
181679  rc = pApi->xTokenize(pFts,
181680  sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
181681  );
181682  if( rc!=SQLITE_OK ) break;
181683  rc = pApi->xColumnSize(pFts, i, &nDocsize);
181684  if( rc!=SQLITE_OK ) break;
181685 
181686  for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
181687  int ip, ic, io;
181688  int iAdj;
181689  int nScore;
181690  int jj;
181691 
181692  rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
181693  if( ic!=i || rc!=SQLITE_OK ) continue;
181694  memset(aSeen, 0, nPhrase);
181695  rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
181696  io, nToken, &nScore, &iAdj
181697  );
181698  if( rc==SQLITE_OK && nScore>nBestScore ){
181699  nBestScore = nScore;
181700  iBestCol = i;
181701  iBestStart = iAdj;
181702  nColSize = nDocsize;
181703  }
181704 
181705  if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
181706  for(jj=0; jj<(sFinder.nFirst-1); jj++){
181707  if( sFinder.aFirst[jj+1]>io ) break;
181708  }
181709 
181710  if( sFinder.aFirst[jj]<io ){
181711  memset(aSeen, 0, nPhrase);
181712  rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
181713  sFinder.aFirst[jj], nToken, &nScore, 0
181714  );
181715 
181716  nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
181717  if( rc==SQLITE_OK && nScore>nBestScore ){
181718  nBestScore = nScore;
181719  iBestCol = i;
181720  iBestStart = sFinder.aFirst[jj];
181721  nColSize = nDocsize;
181722  }
181723  }
181724  }
181725  }
181726  }
181727  }
181728 
181729  if( rc==SQLITE_OK ){
181730  rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
181731  }
181732  if( rc==SQLITE_OK && nColSize==0 ){
181733  rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
181734  }
181735  if( ctx.zIn ){
181736  if( rc==SQLITE_OK ){
181737  rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
181738  }
181739 
181740  ctx.iRangeStart = iBestStart;
181741  ctx.iRangeEnd = iBestStart + nToken - 1;
181742 
181743  if( iBestStart>0 ){
181744  fts5HighlightAppend(&rc, &ctx, zEllips, -1);
181745  }
181746 
181747  /* Advance iterator ctx.iter so that it points to the first coalesced
181748  ** phrase instance at or following position iBestStart. */
181749  while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
181750  rc = fts5CInstIterNext(&ctx.iter);
181751  }
181752 
181753  if( rc==SQLITE_OK ){
181754  rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
181755  }
181756  if( ctx.iRangeEnd>=(nColSize-1) ){
181757  fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
181758  }else{
181759  fts5HighlightAppend(&rc, &ctx, zEllips, -1);
181760  }
181761  }
181762  if( rc==SQLITE_OK ){
181763  sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
181764  }else{
181765  sqlite3_result_error_code(pCtx, rc);
181766  }
181767  sqlite3_free(ctx.zOut);
181768  sqlite3_free(aSeen);
181769  sqlite3_free(sFinder.aFirst);
181770 }
181771 
181772 /************************************************************************/
181773 
181774 /*
181775 ** The first time the bm25() function is called for a query, an instance
181776 ** of the following structure is allocated and populated.
181777 */
181778 typedef struct Fts5Bm25Data Fts5Bm25Data;
181779 struct Fts5Bm25Data {
181780  int nPhrase; /* Number of phrases in query */
181781  double avgdl; /* Average number of tokens in each row */
181782  double *aIDF; /* IDF for each phrase */
181783  double *aFreq; /* Array used to calculate phrase freq. */
181784 };
181785 
181786 /*
181787 ** Callback used by fts5Bm25GetData() to count the number of rows in the
181788 ** table matched by each individual phrase within the query.
181789 */
181790 static int fts5CountCb(
181791  const Fts5ExtensionApi *pApi,
181792  Fts5Context *pFts,
181793  void *pUserData /* Pointer to sqlite3_int64 variable */
181794 ){
181795  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
181796  UNUSED_PARAM2(pApi, pFts);
181797  (*pn)++;
181798  return SQLITE_OK;
181799 }
181800 
181801 /*
181802 ** Set *ppData to point to the Fts5Bm25Data object for the current query.
181803 ** If the object has not already been allocated, allocate and populate it
181804 ** now.
181805 */
181806 static int fts5Bm25GetData(
181807  const Fts5ExtensionApi *pApi,
181808  Fts5Context *pFts,
181809  Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
181810 ){
181811  int rc = SQLITE_OK; /* Return code */
181812  Fts5Bm25Data *p; /* Object to return */
181813 
181814  p = pApi->xGetAuxdata(pFts, 0);
181815  if( p==0 ){
181816  int nPhrase; /* Number of phrases in query */
181817  sqlite3_int64 nRow = 0; /* Number of rows in table */
181818  sqlite3_int64 nToken = 0; /* Number of tokens in table */
181819  int nByte; /* Bytes of space to allocate */
181820  int i;
181821 
181822  /* Allocate the Fts5Bm25Data object */
181823  nPhrase = pApi->xPhraseCount(pFts);
181824  nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
181825  p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
181826  if( p==0 ){
181827  rc = SQLITE_NOMEM;
181828  }else{
181829  memset(p, 0, nByte);
181830  p->nPhrase = nPhrase;
181831  p->aIDF = (double*)&p[1];
181832  p->aFreq = &p->aIDF[nPhrase];
181833  }
181834 
181835  /* Calculate the average document length for this FTS5 table */
181836  if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
181837  if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
181838  if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
181839 
181840  /* Calculate an IDF for each phrase in the query */
181841  for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
181842  sqlite3_int64 nHit = 0;
181843  rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
181844  if( rc==SQLITE_OK ){
181845  /* Calculate the IDF (Inverse Document Frequency) for phrase i.
181846  ** This is done using the standard BM25 formula as found on wikipedia:
181847  **
181848  ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
181849  **
181850  ** where "N" is the total number of documents in the set and nHit
181851  ** is the number that contain at least one instance of the phrase
181852  ** under consideration.
181853  **
181854  ** The problem with this is that if (N < 2*nHit), the IDF is
181855  ** negative. Which is undesirable. So the mimimum allowable IDF is
181856  ** (1e-6) - roughly the same as a term that appears in just over
181857  ** half of set of 5,000,000 documents. */
181858  double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
181859  if( idf<=0.0 ) idf = 1e-6;
181860  p->aIDF[i] = idf;
181861  }
181862  }
181863 
181864  if( rc!=SQLITE_OK ){
181865  sqlite3_free(p);
181866  }else{
181867  rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
181868  }
181869  if( rc!=SQLITE_OK ) p = 0;
181870  }
181871  *ppData = p;
181872  return rc;
181873 }
181874 
181875 /*
181876 ** Implementation of bm25() function.
181877 */
181878 static void fts5Bm25Function(
181879  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
181880  Fts5Context *pFts, /* First arg to pass to pApi functions */
181881  sqlite3_context *pCtx, /* Context for returning result/error */
181882  int nVal, /* Number of values in apVal[] array */
181883  sqlite3_value **apVal /* Array of trailing arguments */
181884 ){
181885  const double k1 = 1.2; /* Constant "k1" from BM25 formula */
181886  const double b = 0.75; /* Constant "b" from BM25 formula */
181887  int rc = SQLITE_OK; /* Error code */
181888  double score = 0.0; /* SQL function return value */
181889  Fts5Bm25Data *pData; /* Values allocated/calculated once only */
181890  int i; /* Iterator variable */
181891  int nInst = 0; /* Value returned by xInstCount() */
181892  double D = 0.0; /* Total number of tokens in row */
181893  double *aFreq = 0; /* Array of phrase freq. for current row */
181894 
181895  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
181896  ** for each phrase in the query for the current row. */
181897  rc = fts5Bm25GetData(pApi, pFts, &pData);
181898  if( rc==SQLITE_OK ){
181899  aFreq = pData->aFreq;
181900  memset(aFreq, 0, sizeof(double) * pData->nPhrase);
181901  rc = pApi->xInstCount(pFts, &nInst);
181902  }
181903  for(i=0; rc==SQLITE_OK && i<nInst; i++){
181904  int ip; int ic; int io;
181905  rc = pApi->xInst(pFts, i, &ip, &ic, &io);
181906  if( rc==SQLITE_OK ){
181907  double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
181908  aFreq[ip] += w;
181909  }
181910  }
181911 
181912  /* Figure out the total size of the current row in tokens. */
181913  if( rc==SQLITE_OK ){
181914  int nTok;
181915  rc = pApi->xColumnSize(pFts, -1, &nTok);
181916  D = (double)nTok;
181917  }
181918 
181919  /* Determine the BM25 score for the current row. */
181920  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
181921  score += pData->aIDF[i] * (
181922  ( aFreq[i] * (k1 + 1.0) ) /
181923  ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
181924  );
181925  }
181926 
181927  /* If no error has occurred, return the calculated score. Otherwise,
181928  ** throw an SQL exception. */
181929  if( rc==SQLITE_OK ){
181930  sqlite3_result_double(pCtx, -1.0 * score);
181931  }else{
181932  sqlite3_result_error_code(pCtx, rc);
181933  }
181934 }
181935 
181936 static int sqlite3Fts5AuxInit(fts5_api *pApi){
181937  struct Builtin {
181938  const char *zFunc; /* Function name (nul-terminated) */
181939  void *pUserData; /* User-data pointer */
181940  fts5_extension_function xFunc;/* Callback function */
181941  void (*xDestroy)(void*); /* Destructor function */
181942  } aBuiltin [] = {
181943  { "snippet", 0, fts5SnippetFunction, 0 },
181944  { "highlight", 0, fts5HighlightFunction, 0 },
181945  { "bm25", 0, fts5Bm25Function, 0 },
181946  };
181947  int rc = SQLITE_OK; /* Return code */
181948  int i; /* To iterate through builtin functions */
181949 
181950  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
181951  rc = pApi->xCreateFunction(pApi,
181952  aBuiltin[i].zFunc,
181953  aBuiltin[i].pUserData,
181954  aBuiltin[i].xFunc,
181955  aBuiltin[i].xDestroy
181956  );
181957  }
181958 
181959  return rc;
181960 }
181961 
181962 
181963 
181964 /*
181965 ** 2014 May 31
181966 **
181967 ** The author disclaims copyright to this source code. In place of
181968 ** a legal notice, here is a blessing:
181969 **
181970 ** May you do good and not evil.
181971 ** May you find forgiveness for yourself and forgive others.
181972 ** May you share freely, never taking more than you give.
181973 **
181974 ******************************************************************************
181975 */
181976 
181977 
181978 
181979 /* #include "fts5Int.h" */
181980 
181981 static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
181982  if( (u32)pBuf->nSpace<nByte ){
181983  u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
181984  u8 *pNew;
181985  while( nNew<nByte ){
181986  nNew = nNew * 2;
181987  }
181988  pNew = sqlite3_realloc(pBuf->p, nNew);
181989  if( pNew==0 ){
181990  *pRc = SQLITE_NOMEM;
181991  return 1;
181992  }else{
181993  pBuf->nSpace = nNew;
181994  pBuf->p = pNew;
181995  }
181996  }
181997  return 0;
181998 }
181999 
182000 
182001 /*
182002 ** Encode value iVal as an SQLite varint and append it to the buffer object
182003 ** pBuf. If an OOM error occurs, set the error code in p.
182004 */
182005 static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
182006  if( fts5BufferGrow(pRc, pBuf, 9) ) return;
182007  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
182008 }
182009 
182010 static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
182011  aBuf[0] = (iVal>>24) & 0x00FF;
182012  aBuf[1] = (iVal>>16) & 0x00FF;
182013  aBuf[2] = (iVal>> 8) & 0x00FF;
182014  aBuf[3] = (iVal>> 0) & 0x00FF;
182015 }
182016 
182017 static int sqlite3Fts5Get32(const u8 *aBuf){
182018  return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
182019 }
182020 
182021 /*
182022 ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
182023 ** the error code in p. If an error has already occurred when this function
182024 ** is called, it is a no-op.
182025 */
182026 static void sqlite3Fts5BufferAppendBlob(
182027  int *pRc,
182028  Fts5Buffer *pBuf,
182029  u32 nData,
182030  const u8 *pData
182031 ){
182032  assert_nc( *pRc || nData>=0 );
182033  if( fts5BufferGrow(pRc, pBuf, nData) ) return;
182034  memcpy(&pBuf->p[pBuf->n], pData, nData);
182035  pBuf->n += nData;
182036 }
182037 
182038 /*
182039 ** Append the nul-terminated string zStr to the buffer pBuf. This function
182040 ** ensures that the byte following the buffer data is set to 0x00, even
182041 ** though this byte is not included in the pBuf->n count.
182042 */
182043 static void sqlite3Fts5BufferAppendString(
182044  int *pRc,
182045  Fts5Buffer *pBuf,
182046  const char *zStr
182047 ){
182048  int nStr = (int)strlen(zStr);
182049  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
182050  pBuf->n--;
182051 }
182052 
182053 /*
182054 ** Argument zFmt is a printf() style format string. This function performs
182055 ** the printf() style processing, then appends the results to buffer pBuf.
182056 **
182057 ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
182058 ** following the buffer data is set to 0x00, even though this byte is not
182059 ** included in the pBuf->n count.
182060 */
182061 static void sqlite3Fts5BufferAppendPrintf(
182062  int *pRc,
182063  Fts5Buffer *pBuf,
182064  char *zFmt, ...
182065 ){
182066  if( *pRc==SQLITE_OK ){
182067  char *zTmp;
182068  va_list ap;
182069  va_start(ap, zFmt);
182070  zTmp = sqlite3_vmprintf(zFmt, ap);
182071  va_end(ap);
182072 
182073  if( zTmp==0 ){
182074  *pRc = SQLITE_NOMEM;
182075  }else{
182076  sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
182077  sqlite3_free(zTmp);
182078  }
182079  }
182080 }
182081 
182082 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
182083  char *zRet = 0;
182084  if( *pRc==SQLITE_OK ){
182085  va_list ap;
182086  va_start(ap, zFmt);
182087  zRet = sqlite3_vmprintf(zFmt, ap);
182088  va_end(ap);
182089  if( zRet==0 ){
182090  *pRc = SQLITE_NOMEM;
182091  }
182092  }
182093  return zRet;
182094 }
182095 
182096 
182097 /*
182098 ** Free any buffer allocated by pBuf. Zero the structure before returning.
182099 */
182100 static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
182101  sqlite3_free(pBuf->p);
182102  memset(pBuf, 0, sizeof(Fts5Buffer));
182103 }
182104 
182105 /*
182106 ** Zero the contents of the buffer object. But do not free the associated
182107 ** memory allocation.
182108 */
182109 static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
182110  pBuf->n = 0;
182111 }
182112 
182113 /*
182114 ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
182115 ** the error code in p. If an error has already occurred when this function
182116 ** is called, it is a no-op.
182117 */
182118 static void sqlite3Fts5BufferSet(
182119  int *pRc,
182120  Fts5Buffer *pBuf,
182121  int nData,
182122  const u8 *pData
182123 ){
182124  pBuf->n = 0;
182125  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
182126 }
182127 
182128 static int sqlite3Fts5PoslistNext64(
182129  const u8 *a, int n, /* Buffer containing poslist */
182130  int *pi, /* IN/OUT: Offset within a[] */
182131  i64 *piOff /* IN/OUT: Current offset */
182132 ){
182133  int i = *pi;
182134  if( i>=n ){
182135  /* EOF */
182136  *piOff = -1;
182137  return 1;
182138  }else{
182139  i64 iOff = *piOff;
182140  int iVal;
182141  fts5FastGetVarint32(a, i, iVal);
182142  if( iVal==1 ){
182143  fts5FastGetVarint32(a, i, iVal);
182144  iOff = ((i64)iVal) << 32;
182145  fts5FastGetVarint32(a, i, iVal);
182146  }
182147  *piOff = iOff + (iVal-2);
182148  *pi = i;
182149  return 0;
182150  }
182151 }
182152 
182153 
182154 /*
182155 ** Advance the iterator object passed as the only argument. Return true
182156 ** if the iterator reaches EOF, or false otherwise.
182157 */
182158 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
182159  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
182160  pIter->bEof = 1;
182161  }
182162  return pIter->bEof;
182163 }
182164 
182165 static int sqlite3Fts5PoslistReaderInit(
182166  const u8 *a, int n, /* Poslist buffer to iterate through */
182167  Fts5PoslistReader *pIter /* Iterator object to initialize */
182168 ){
182169  memset(pIter, 0, sizeof(*pIter));
182170  pIter->a = a;
182171  pIter->n = n;
182172  sqlite3Fts5PoslistReaderNext(pIter);
182173  return pIter->bEof;
182174 }
182175 
182176 /*
182177 ** Append position iPos to the position list being accumulated in buffer
182178 ** pBuf, which must be already be large enough to hold the new data.
182179 ** The previous position written to this list is *piPrev. *piPrev is set
182180 ** to iPos before returning.
182181 */
182182 static void sqlite3Fts5PoslistSafeAppend(
182183  Fts5Buffer *pBuf,
182184  i64 *piPrev,
182185  i64 iPos
182186 ){
182187  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
182188  if( (iPos & colmask) != (*piPrev & colmask) ){
182189  pBuf->p[pBuf->n++] = 1;
182190  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
182191  *piPrev = (iPos & colmask);
182192  }
182193  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
182194  *piPrev = iPos;
182195 }
182196 
182197 static int sqlite3Fts5PoslistWriterAppend(
182198  Fts5Buffer *pBuf,
182199  Fts5PoslistWriter *pWriter,
182200  i64 iPos
182201 ){
182202  int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
182203  if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
182204  sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
182205  return SQLITE_OK;
182206 }
182207 
182208 static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
182209  void *pRet = 0;
182210  if( *pRc==SQLITE_OK ){
182211  pRet = sqlite3_malloc(nByte);
182212  if( pRet==0 && nByte>0 ){
182213  *pRc = SQLITE_NOMEM;
182214  }else{
182215  memset(pRet, 0, nByte);
182216  }
182217  }
182218  return pRet;
182219 }
182220 
182221 /*
182222 ** Return a nul-terminated copy of the string indicated by pIn. If nIn
182223 ** is non-negative, then it is the length of the string in bytes. Otherwise,
182224 ** the length of the string is determined using strlen().
182225 **
182226 ** It is the responsibility of the caller to eventually free the returned
182227 ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
182228 */
182229 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
182230  char *zRet = 0;
182231  if( *pRc==SQLITE_OK ){
182232  if( nIn<0 ){
182233  nIn = (int)strlen(pIn);
182234  }
182235  zRet = (char*)sqlite3_malloc(nIn+1);
182236  if( zRet ){
182237  memcpy(zRet, pIn, nIn);
182238  zRet[nIn] = '\0';
182239  }else{
182240  *pRc = SQLITE_NOMEM;
182241  }
182242  }
182243  return zRet;
182244 }
182245 
182246 
182247 /*
182248 ** Return true if character 't' may be part of an FTS5 bareword, or false
182249 ** otherwise. Characters that may be part of barewords:
182250 **
182251 ** * All non-ASCII characters,
182252 ** * The 52 upper and lower case ASCII characters, and
182253 ** * The 10 integer ASCII characters.
182254 ** * The underscore character "_" (0x5F).
182255 ** * The unicode "subsitute" character (0x1A).
182256 */
182257 static int sqlite3Fts5IsBareword(char t){
182258  u8 aBareword[128] = {
182259  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
182260  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
182261  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
182262  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
182263  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
182264  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
182265  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
182266  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
182267  };
182268 
182269  return (t & 0x80) || aBareword[(int)t];
182270 }
182271 
182272 
182273 /*************************************************************************
182274 */
182275 typedef struct Fts5TermsetEntry Fts5TermsetEntry;
182276 struct Fts5TermsetEntry {
182277  char *pTerm;
182278  int nTerm;
182279  int iIdx; /* Index (main or aPrefix[] entry) */
182280  Fts5TermsetEntry *pNext;
182281 };
182282 
182283 struct Fts5Termset {
182284  Fts5TermsetEntry *apHash[512];
182285 };
182286 
182287 static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
182288  int rc = SQLITE_OK;
182289  *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
182290  return rc;
182291 }
182292 
182293 static int sqlite3Fts5TermsetAdd(
182294  Fts5Termset *p,
182295  int iIdx,
182296  const char *pTerm, int nTerm,
182297  int *pbPresent
182298 ){
182299  int rc = SQLITE_OK;
182300  *pbPresent = 0;
182301  if( p ){
182302  int i;
182303  u32 hash = 13;
182304  Fts5TermsetEntry *pEntry;
182305 
182306  /* Calculate a hash value for this term. This is the same hash checksum
182307  ** used by the fts5_hash.c module. This is not important for correct
182308  ** operation of the module, but is necessary to ensure that some tests
182309  ** designed to produce hash table collisions really do work. */
182310  for(i=nTerm-1; i>=0; i--){
182311  hash = (hash << 3) ^ hash ^ pTerm[i];
182312  }
182313  hash = (hash << 3) ^ hash ^ iIdx;
182314  hash = hash % ArraySize(p->apHash);
182315 
182316  for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
182317  if( pEntry->iIdx==iIdx
182318  && pEntry->nTerm==nTerm
182319  && memcmp(pEntry->pTerm, pTerm, nTerm)==0
182320  ){
182321  *pbPresent = 1;
182322  break;
182323  }
182324  }
182325 
182326  if( pEntry==0 ){
182327  pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
182328  if( pEntry ){
182329  pEntry->pTerm = (char*)&pEntry[1];
182330  pEntry->nTerm = nTerm;
182331  pEntry->iIdx = iIdx;
182332  memcpy(pEntry->pTerm, pTerm, nTerm);
182333  pEntry->pNext = p->apHash[hash];
182334  p->apHash[hash] = pEntry;
182335  }
182336  }
182337  }
182338 
182339  return rc;
182340 }
182341 
182342 static void sqlite3Fts5TermsetFree(Fts5Termset *p){
182343  if( p ){
182344  u32 i;
182345  for(i=0; i<ArraySize(p->apHash); i++){
182346  Fts5TermsetEntry *pEntry = p->apHash[i];
182347  while( pEntry ){
182348  Fts5TermsetEntry *pDel = pEntry;
182349  pEntry = pEntry->pNext;
182350  sqlite3_free(pDel);
182351  }
182352  }
182353  sqlite3_free(p);
182354  }
182355 }
182356 
182357 /*
182358 ** 2014 Jun 09
182359 **
182360 ** The author disclaims copyright to this source code. In place of
182361 ** a legal notice, here is a blessing:
182362 **
182363 ** May you do good and not evil.
182364 ** May you find forgiveness for yourself and forgive others.
182365 ** May you share freely, never taking more than you give.
182366 **
182367 ******************************************************************************
182368 **
182369 ** This is an SQLite module implementing full-text search.
182370 */
182371 
182372 
182373 /* #include "fts5Int.h" */
182374 
182375 #define FTS5_DEFAULT_PAGE_SIZE 4050
182376 #define FTS5_DEFAULT_AUTOMERGE 4
182377 #define FTS5_DEFAULT_USERMERGE 4
182378 #define FTS5_DEFAULT_CRISISMERGE 16
182379 #define FTS5_DEFAULT_HASHSIZE (1024*1024)
182380 
182381 /* Maximum allowed page size */
182382 #define FTS5_MAX_PAGE_SIZE (128*1024)
182383 
182384 static int fts5_iswhitespace(char x){
182385  return (x==' ');
182386 }
182387 
182388 static int fts5_isopenquote(char x){
182389  return (x=='"' || x=='\'' || x=='[' || x=='`');
182390 }
182391 
182392 /*
182393 ** Argument pIn points to a character that is part of a nul-terminated
182394 ** string. Return a pointer to the first character following *pIn in
182395 ** the string that is not a white-space character.
182396 */
182397 static const char *fts5ConfigSkipWhitespace(const char *pIn){
182398  const char *p = pIn;
182399  if( p ){
182400  while( fts5_iswhitespace(*p) ){ p++; }
182401  }
182402  return p;
182403 }
182404 
182405 /*
182406 ** Argument pIn points to a character that is part of a nul-terminated
182407 ** string. Return a pointer to the first character following *pIn in
182408 ** the string that is not a "bareword" character.
182409 */
182410 static const char *fts5ConfigSkipBareword(const char *pIn){
182411  const char *p = pIn;
182412  while ( sqlite3Fts5IsBareword(*p) ) p++;
182413  if( p==pIn ) p = 0;
182414  return p;
182415 }
182416 
182417 static int fts5_isdigit(char a){
182418  return (a>='0' && a<='9');
182419 }
182420 
182421 
182422 
182423 static const char *fts5ConfigSkipLiteral(const char *pIn){
182424  const char *p = pIn;
182425  switch( *p ){
182426  case 'n': case 'N':
182427  if( sqlite3_strnicmp("null", p, 4)==0 ){
182428  p = &p[4];
182429  }else{
182430  p = 0;
182431  }
182432  break;
182433 
182434  case 'x': case 'X':
182435  p++;
182436  if( *p=='\'' ){
182437  p++;
182438  while( (*p>='a' && *p<='f')
182439  || (*p>='A' && *p<='F')
182440  || (*p>='0' && *p<='9')
182441  ){
182442  p++;
182443  }
182444  if( *p=='\'' && 0==((p-pIn)%2) ){
182445  p++;
182446  }else{
182447  p = 0;
182448  }
182449  }else{
182450  p = 0;
182451  }
182452  break;
182453 
182454  case '\'':
182455  p++;
182456  while( p ){
182457  if( *p=='\'' ){
182458  p++;
182459  if( *p!='\'' ) break;
182460  }
182461  p++;
182462  if( *p==0 ) p = 0;
182463  }
182464  break;
182465 
182466  default:
182467  /* maybe a number */
182468  if( *p=='+' || *p=='-' ) p++;
182469  while( fts5_isdigit(*p) ) p++;
182470 
182471  /* At this point, if the literal was an integer, the parse is
182472  ** finished. Or, if it is a floating point value, it may continue
182473  ** with either a decimal point or an 'E' character. */
182474  if( *p=='.' && fts5_isdigit(p[1]) ){
182475  p += 2;
182476  while( fts5_isdigit(*p) ) p++;
182477  }
182478  if( p==pIn ) p = 0;
182479 
182480  break;
182481  }
182482 
182483  return p;
182484 }
182485 
182486 /*
182487 ** The first character of the string pointed to by argument z is guaranteed
182488 ** to be an open-quote character (see function fts5_isopenquote()).
182489 **
182490 ** This function searches for the corresponding close-quote character within
182491 ** the string and, if found, dequotes the string in place and adds a new
182492 ** nul-terminator byte.
182493 **
182494 ** If the close-quote is found, the value returned is the byte offset of
182495 ** the character immediately following it. Or, if the close-quote is not
182496 ** found, -1 is returned. If -1 is returned, the buffer is left in an
182497 ** undefined state.
182498 */
182499 static int fts5Dequote(char *z){
182500  char q;
182501  int iIn = 1;
182502  int iOut = 0;
182503  q = z[0];
182504 
182505  /* Set stack variable q to the close-quote character */
182506  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
182507  if( q=='[' ) q = ']';
182508 
182509  while( ALWAYS(z[iIn]) ){
182510  if( z[iIn]==q ){
182511  if( z[iIn+1]!=q ){
182512  /* Character iIn was the close quote. */
182513  iIn++;
182514  break;
182515  }else{
182516  /* Character iIn and iIn+1 form an escaped quote character. Skip
182517  ** the input cursor past both and copy a single quote character
182518  ** to the output buffer. */
182519  iIn += 2;
182520  z[iOut++] = q;
182521  }
182522  }else{
182523  z[iOut++] = z[iIn++];
182524  }
182525  }
182526 
182527  z[iOut] = '\0';
182528  return iIn;
182529 }
182530 
182531 /*
182532 ** Convert an SQL-style quoted string into a normal string by removing
182533 ** the quote characters. The conversion is done in-place. If the
182534 ** input does not begin with a quote character, then this routine
182535 ** is a no-op.
182536 **
182537 ** Examples:
182538 **
182539 ** "abc" becomes abc
182540 ** 'xyz' becomes xyz
182541 ** [pqr] becomes pqr
182542 ** `mno` becomes mno
182543 */
182544 static void sqlite3Fts5Dequote(char *z){
182545  char quote; /* Quote character (if any ) */
182546 
182547  assert( 0==fts5_iswhitespace(z[0]) );
182548  quote = z[0];
182549  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
182550  fts5Dequote(z);
182551  }
182552 }
182553 
182554 
182555 struct Fts5Enum {
182556  const char *zName;
182557  int eVal;
182558 };
182559 typedef struct Fts5Enum Fts5Enum;
182560 
182561 static int fts5ConfigSetEnum(
182562  const Fts5Enum *aEnum,
182563  const char *zEnum,
182564  int *peVal
182565 ){
182566  int nEnum = (int)strlen(zEnum);
182567  int i;
182568  int iVal = -1;
182569 
182570  for(i=0; aEnum[i].zName; i++){
182571  if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
182572  if( iVal>=0 ) return SQLITE_ERROR;
182573  iVal = aEnum[i].eVal;
182574  }
182575  }
182576 
182577  *peVal = iVal;
182578  return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
182579 }
182580 
182581 /*
182582 ** Parse a "special" CREATE VIRTUAL TABLE directive and update
182583 ** configuration object pConfig as appropriate.
182584 **
182585 ** If successful, object pConfig is updated and SQLITE_OK returned. If
182586 ** an error occurs, an SQLite error code is returned and an error message
182587 ** may be left in *pzErr. It is the responsibility of the caller to
182588 ** eventually free any such error message using sqlite3_free().
182589 */
182590 static int fts5ConfigParseSpecial(
182591  Fts5Global *pGlobal,
182592  Fts5Config *pConfig, /* Configuration object to update */
182593  const char *zCmd, /* Special command to parse */
182594  const char *zArg, /* Argument to parse */
182595  char **pzErr /* OUT: Error message */
182596 ){
182597  int rc = SQLITE_OK;
182598  int nCmd = (int)strlen(zCmd);
182599  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
182600  const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
182601  const char *p;
182602  int bFirst = 1;
182603  if( pConfig->aPrefix==0 ){
182604  pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
182605  if( rc ) return rc;
182606  }
182607 
182608  p = zArg;
182609  while( 1 ){
182610  int nPre = 0;
182611 
182612  while( p[0]==' ' ) p++;
182613  if( bFirst==0 && p[0]==',' ){
182614  p++;
182615  while( p[0]==' ' ) p++;
182616  }else if( p[0]=='\0' ){
182617  break;
182618  }
182619  if( p[0]<'0' || p[0]>'9' ){
182620  *pzErr = sqlite3_mprintf("malformed prefix=... directive");
182621  rc = SQLITE_ERROR;
182622  break;
182623  }
182624 
182625  if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
182626  *pzErr = sqlite3_mprintf(
182627  "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
182628  );
182629  rc = SQLITE_ERROR;
182630  break;
182631  }
182632 
182633  while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
182634  nPre = nPre*10 + (p[0] - '0');
182635  p++;
182636  }
182637 
182638  if( nPre<=0 || nPre>=1000 ){
182639  *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
182640  rc = SQLITE_ERROR;
182641  break;
182642  }
182643 
182644  pConfig->aPrefix[pConfig->nPrefix] = nPre;
182645  pConfig->nPrefix++;
182646  bFirst = 0;
182647  }
182648  assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
182649  return rc;
182650  }
182651 
182652  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
182653  const char *p = (const char*)zArg;
182654  int nArg = (int)strlen(zArg) + 1;
182655  char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
182656  char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
182657  char *pSpace = pDel;
182658 
182659  if( azArg && pSpace ){
182660  if( pConfig->pTok ){
182661  *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
182662  rc = SQLITE_ERROR;
182663  }else{
182664  for(nArg=0; p && *p; nArg++){
182665  const char *p2 = fts5ConfigSkipWhitespace(p);
182666  if( *p2=='\'' ){
182667  p = fts5ConfigSkipLiteral(p2);
182668  }else{
182669  p = fts5ConfigSkipBareword(p2);
182670  }
182671  if( p ){
182672  memcpy(pSpace, p2, p-p2);
182673  azArg[nArg] = pSpace;
182674  sqlite3Fts5Dequote(pSpace);
182675  pSpace += (p - p2) + 1;
182676  p = fts5ConfigSkipWhitespace(p);
182677  }
182678  }
182679  if( p==0 ){
182680  *pzErr = sqlite3_mprintf("parse error in tokenize directive");
182681  rc = SQLITE_ERROR;
182682  }else{
182683  rc = sqlite3Fts5GetTokenizer(pGlobal,
182684  (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
182685  pzErr
182686  );
182687  }
182688  }
182689  }
182690 
182691  sqlite3_free(azArg);
182692  sqlite3_free(pDel);
182693  return rc;
182694  }
182695 
182696  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
182697  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
182698  *pzErr = sqlite3_mprintf("multiple content=... directives");
182699  rc = SQLITE_ERROR;
182700  }else{
182701  if( zArg[0] ){
182702  pConfig->eContent = FTS5_CONTENT_EXTERNAL;
182703  pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
182704  }else{
182705  pConfig->eContent = FTS5_CONTENT_NONE;
182706  }
182707  }
182708  return rc;
182709  }
182710 
182711  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
182712  if( pConfig->zContentRowid ){
182713  *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
182714  rc = SQLITE_ERROR;
182715  }else{
182716  pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
182717  }
182718  return rc;
182719  }
182720 
182721  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
182722  if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
182723  *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
182724  rc = SQLITE_ERROR;
182725  }else{
182726  pConfig->bColumnsize = (zArg[0]=='1');
182727  }
182728  return rc;
182729  }
182730 
182731  if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
182732  const Fts5Enum aDetail[] = {
182733  { "none", FTS5_DETAIL_NONE },
182734  { "full", FTS5_DETAIL_FULL },
182735  { "columns", FTS5_DETAIL_COLUMNS },
182736  { 0, 0 }
182737  };
182738 
182739  if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
182740  *pzErr = sqlite3_mprintf("malformed detail=... directive");
182741  }
182742  return rc;
182743  }
182744 
182745  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
182746  return SQLITE_ERROR;
182747 }
182748 
182749 /*
182750 ** Allocate an instance of the default tokenizer ("simple") at
182751 ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
182752 ** code if an error occurs.
182753 */
182754 static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
182755  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
182756  return sqlite3Fts5GetTokenizer(
182757  pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
182758  );
182759 }
182760 
182761 /*
182762 ** Gobble up the first bareword or quoted word from the input buffer zIn.
182763 ** Return a pointer to the character immediately following the last in
182764 ** the gobbled word if successful, or a NULL pointer otherwise (failed
182765 ** to find close-quote character).
182766 **
182767 ** Before returning, set pzOut to point to a new buffer containing a
182768 ** nul-terminated, dequoted copy of the gobbled word. If the word was
182769 ** quoted, *pbQuoted is also set to 1 before returning.
182770 **
182771 ** If *pRc is other than SQLITE_OK when this function is called, it is
182772 ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
182773 ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
182774 ** set if a parse error (failed to find close quote) occurs.
182775 */
182776 static const char *fts5ConfigGobbleWord(
182777  int *pRc, /* IN/OUT: Error code */
182778  const char *zIn, /* Buffer to gobble string/bareword from */
182779  char **pzOut, /* OUT: malloc'd buffer containing str/bw */
182780  int *pbQuoted /* OUT: Set to true if dequoting required */
182781 ){
182782  const char *zRet = 0;
182783 
182784  int nIn = (int)strlen(zIn);
182785  char *zOut = sqlite3_malloc(nIn+1);
182786 
182787  assert( *pRc==SQLITE_OK );
182788  *pbQuoted = 0;
182789  *pzOut = 0;
182790 
182791  if( zOut==0 ){
182792  *pRc = SQLITE_NOMEM;
182793  }else{
182794  memcpy(zOut, zIn, nIn+1);
182795  if( fts5_isopenquote(zOut[0]) ){
182796  int ii = fts5Dequote(zOut);
182797  zRet = &zIn[ii];
182798  *pbQuoted = 1;
182799  }else{
182800  zRet = fts5ConfigSkipBareword(zIn);
182801  if( zRet ){
182802  zOut[zRet-zIn] = '\0';
182803  }
182804  }
182805  }
182806 
182807  if( zRet==0 ){
182808  sqlite3_free(zOut);
182809  }else{
182810  *pzOut = zOut;
182811  }
182812 
182813  return zRet;
182814 }
182815 
182816 static int fts5ConfigParseColumn(
182817  Fts5Config *p,
182818  char *zCol,
182819  char *zArg,
182820  char **pzErr
182821 ){
182822  int rc = SQLITE_OK;
182823  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
182824  || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
182825  ){
182826  *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
182827  rc = SQLITE_ERROR;
182828  }else if( zArg ){
182829  if( 0==sqlite3_stricmp(zArg, "unindexed") ){
182830  p->abUnindexed[p->nCol] = 1;
182831  }else{
182832  *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
182833  rc = SQLITE_ERROR;
182834  }
182835  }
182836 
182837  p->azCol[p->nCol++] = zCol;
182838  return rc;
182839 }
182840 
182841 /*
182842 ** Populate the Fts5Config.zContentExprlist string.
182843 */
182844 static int fts5ConfigMakeExprlist(Fts5Config *p){
182845  int i;
182846  int rc = SQLITE_OK;
182847  Fts5Buffer buf = {0, 0, 0};
182848 
182849  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
182850  if( p->eContent!=FTS5_CONTENT_NONE ){
182851  for(i=0; i<p->nCol; i++){
182852  if( p->eContent==FTS5_CONTENT_EXTERNAL ){
182853  sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
182854  }else{
182855  sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
182856  }
182857  }
182858  }
182859 
182860  assert( p->zContentExprlist==0 );
182861  p->zContentExprlist = (char*)buf.p;
182862  return rc;
182863 }
182864 
182865 /*
182866 ** Arguments nArg/azArg contain the string arguments passed to the xCreate
182867 ** or xConnect method of the virtual table. This function attempts to
182868 ** allocate an instance of Fts5Config containing the results of parsing
182869 ** those arguments.
182870 **
182871 ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
182872 ** new Fts5Config object. If an error occurs, an SQLite error code is
182873 ** returned, *ppOut is set to NULL and an error message may be left in
182874 ** *pzErr. It is the responsibility of the caller to eventually free any
182875 ** such error message using sqlite3_free().
182876 */
182877 static int sqlite3Fts5ConfigParse(
182878  Fts5Global *pGlobal,
182879  sqlite3 *db,
182880  int nArg, /* Number of arguments */
182881  const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
182882  Fts5Config **ppOut, /* OUT: Results of parse */
182883  char **pzErr /* OUT: Error message */
182884 ){
182885  int rc = SQLITE_OK; /* Return code */
182886  Fts5Config *pRet; /* New object to return */
182887  int i;
182888  int nByte;
182889 
182890  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
182891  if( pRet==0 ) return SQLITE_NOMEM;
182892  memset(pRet, 0, sizeof(Fts5Config));
182893  pRet->db = db;
182894  pRet->iCookie = -1;
182895 
182896  nByte = nArg * (sizeof(char*) + sizeof(u8));
182897  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
182898  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
182899  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
182900  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
182901  pRet->bColumnsize = 1;
182902  pRet->eDetail = FTS5_DETAIL_FULL;
182903 #ifdef SQLITE_DEBUG
182904  pRet->bPrefixIndex = 1;
182905 #endif
182906  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
182907  *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
182908  rc = SQLITE_ERROR;
182909  }
182910 
182911  for(i=3; rc==SQLITE_OK && i<nArg; i++){
182912  const char *zOrig = azArg[i];
182913  const char *z;
182914  char *zOne = 0;
182915  char *zTwo = 0;
182916  int bOption = 0;
182917  int bMustBeCol = 0;
182918 
182919  z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
182920  z = fts5ConfigSkipWhitespace(z);
182921  if( z && *z=='=' ){
182922  bOption = 1;
182923  z++;
182924  if( bMustBeCol ) z = 0;
182925  }
182926  z = fts5ConfigSkipWhitespace(z);
182927  if( z && z[0] ){
182928  int bDummy;
182929  z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
182930  if( z && z[0] ) z = 0;
182931  }
182932 
182933  if( rc==SQLITE_OK ){
182934  if( z==0 ){
182935  *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
182936  rc = SQLITE_ERROR;
182937  }else{
182938  if( bOption ){
182939  rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
182940  }else{
182941  rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
182942  zOne = 0;
182943  }
182944  }
182945  }
182946 
182947  sqlite3_free(zOne);
182948  sqlite3_free(zTwo);
182949  }
182950 
182951  /* If a tokenizer= option was successfully parsed, the tokenizer has
182952  ** already been allocated. Otherwise, allocate an instance of the default
182953  ** tokenizer (unicode61) now. */
182954  if( rc==SQLITE_OK && pRet->pTok==0 ){
182955  rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
182956  }
182957 
182958  /* If no zContent option was specified, fill in the default values. */
182959  if( rc==SQLITE_OK && pRet->zContent==0 ){
182960  const char *zTail = 0;
182961  assert( pRet->eContent==FTS5_CONTENT_NORMAL
182962  || pRet->eContent==FTS5_CONTENT_NONE
182963  );
182964  if( pRet->eContent==FTS5_CONTENT_NORMAL ){
182965  zTail = "content";
182966  }else if( pRet->bColumnsize ){
182967  zTail = "docsize";
182968  }
182969 
182970  if( zTail ){
182971  pRet->zContent = sqlite3Fts5Mprintf(
182972  &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
182973  );
182974  }
182975  }
182976 
182977  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
182978  pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
182979  }
182980 
182981  /* Formulate the zContentExprlist text */
182982  if( rc==SQLITE_OK ){
182983  rc = fts5ConfigMakeExprlist(pRet);
182984  }
182985 
182986  if( rc!=SQLITE_OK ){
182987  sqlite3Fts5ConfigFree(pRet);
182988  *ppOut = 0;
182989  }
182990  return rc;
182991 }
182992 
182993 /*
182994 ** Free the configuration object passed as the only argument.
182995 */
182996 static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
182997  if( pConfig ){
182998  int i;
182999  if( pConfig->pTok ){
183000  pConfig->pTokApi->xDelete(pConfig->pTok);
183001  }
183002  sqlite3_free(pConfig->zDb);
183003  sqlite3_free(pConfig->zName);
183004  for(i=0; i<pConfig->nCol; i++){
183005  sqlite3_free(pConfig->azCol[i]);
183006  }
183007  sqlite3_free(pConfig->azCol);
183008  sqlite3_free(pConfig->aPrefix);
183009  sqlite3_free(pConfig->zRank);
183010  sqlite3_free(pConfig->zRankArgs);
183011  sqlite3_free(pConfig->zContent);
183012  sqlite3_free(pConfig->zContentRowid);
183013  sqlite3_free(pConfig->zContentExprlist);
183014  sqlite3_free(pConfig);
183015  }
183016 }
183017 
183018 /*
183019 ** Call sqlite3_declare_vtab() based on the contents of the configuration
183020 ** object passed as the only argument. Return SQLITE_OK if successful, or
183021 ** an SQLite error code if an error occurs.
183022 */
183023 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
183024  int i;
183025  int rc = SQLITE_OK;
183026  char *zSql;
183027 
183028  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
183029  for(i=0; zSql && i<pConfig->nCol; i++){
183030  const char *zSep = (i==0?"":", ");
183031  zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
183032  }
183033  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
183034  zSql, pConfig->zName, FTS5_RANK_NAME
183035  );
183036 
183037  assert( zSql || rc==SQLITE_NOMEM );
183038  if( zSql ){
183039  rc = sqlite3_declare_vtab(pConfig->db, zSql);
183040  sqlite3_free(zSql);
183041  }
183042 
183043  return rc;
183044 }
183045 
183046 /*
183047 ** Tokenize the text passed via the second and third arguments.
183048 **
183049 ** The callback is invoked once for each token in the input text. The
183050 ** arguments passed to it are, in order:
183051 **
183052 ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
183053 ** const char *pToken // Pointer to buffer containing token
183054 ** int nToken // Size of token in bytes
183055 ** int iStart // Byte offset of start of token within input text
183056 ** int iEnd // Byte offset of end of token within input text
183057 ** int iPos // Position of token in input (first token is 0)
183058 **
183059 ** If the callback returns a non-zero value the tokenization is abandoned
183060 ** and no further callbacks are issued.
183061 **
183062 ** This function returns SQLITE_OK if successful or an SQLite error code
183063 ** if an error occurs. If the tokenization was abandoned early because
183064 ** the callback returned SQLITE_DONE, this is not an error and this function
183065 ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
183066 ** because the callback returned another non-zero value, it is assumed
183067 ** to be an SQLite error code and returned to the caller.
183068 */
183069 static int sqlite3Fts5Tokenize(
183070  Fts5Config *pConfig, /* FTS5 Configuration object */
183071  int flags, /* FTS5_TOKENIZE_* flags */
183072  const char *pText, int nText, /* Text to tokenize */
183073  void *pCtx, /* Context passed to xToken() */
183074  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
183075 ){
183076  if( pText==0 ) return SQLITE_OK;
183077  return pConfig->pTokApi->xTokenize(
183078  pConfig->pTok, pCtx, flags, pText, nText, xToken
183079  );
183080 }
183081 
183082 /*
183083 ** Argument pIn points to the first character in what is expected to be
183084 ** a comma-separated list of SQL literals followed by a ')' character.
183085 ** If it actually is this, return a pointer to the ')'. Otherwise, return
183086 ** NULL to indicate a parse error.
183087 */
183088 static const char *fts5ConfigSkipArgs(const char *pIn){
183089  const char *p = pIn;
183090 
183091  while( 1 ){
183092  p = fts5ConfigSkipWhitespace(p);
183093  p = fts5ConfigSkipLiteral(p);
183094  p = fts5ConfigSkipWhitespace(p);
183095  if( p==0 || *p==')' ) break;
183096  if( *p!=',' ){
183097  p = 0;
183098  break;
183099  }
183100  p++;
183101  }
183102 
183103  return p;
183104 }
183105 
183106 /*
183107 ** Parameter zIn contains a rank() function specification. The format of
183108 ** this is:
183109 **
183110 ** + Bareword (function name)
183111 ** + Open parenthesis - "("
183112 ** + Zero or more SQL literals in a comma separated list
183113 ** + Close parenthesis - ")"
183114 */
183115 static int sqlite3Fts5ConfigParseRank(
183116  const char *zIn, /* Input string */
183117  char **pzRank, /* OUT: Rank function name */
183118  char **pzRankArgs /* OUT: Rank function arguments */
183119 ){
183120  const char *p = zIn;
183121  const char *pRank;
183122  char *zRank = 0;
183123  char *zRankArgs = 0;
183124  int rc = SQLITE_OK;
183125 
183126  *pzRank = 0;
183127  *pzRankArgs = 0;
183128 
183129  if( p==0 ){
183130  rc = SQLITE_ERROR;
183131  }else{
183132  p = fts5ConfigSkipWhitespace(p);
183133  pRank = p;
183134  p = fts5ConfigSkipBareword(p);
183135 
183136  if( p ){
183137  zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
183138  if( zRank ) memcpy(zRank, pRank, p-pRank);
183139  }else{
183140  rc = SQLITE_ERROR;
183141  }
183142 
183143  if( rc==SQLITE_OK ){
183144  p = fts5ConfigSkipWhitespace(p);
183145  if( *p!='(' ) rc = SQLITE_ERROR;
183146  p++;
183147  }
183148  if( rc==SQLITE_OK ){
183149  const char *pArgs;
183150  p = fts5ConfigSkipWhitespace(p);
183151  pArgs = p;
183152  if( *p!=')' ){
183153  p = fts5ConfigSkipArgs(p);
183154  if( p==0 ){
183155  rc = SQLITE_ERROR;
183156  }else{
183157  zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
183158  if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
183159  }
183160  }
183161  }
183162  }
183163 
183164  if( rc!=SQLITE_OK ){
183165  sqlite3_free(zRank);
183166  assert( zRankArgs==0 );
183167  }else{
183168  *pzRank = zRank;
183169  *pzRankArgs = zRankArgs;
183170  }
183171  return rc;
183172 }
183173 
183174 static int sqlite3Fts5ConfigSetValue(
183175  Fts5Config *pConfig,
183176  const char *zKey,
183177  sqlite3_value *pVal,
183178  int *pbBadkey
183179 ){
183180  int rc = SQLITE_OK;
183181 
183182  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
183183  int pgsz = 0;
183184  if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
183185  pgsz = sqlite3_value_int(pVal);
183186  }
183187  if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
183188  *pbBadkey = 1;
183189  }else{
183190  pConfig->pgsz = pgsz;
183191  }
183192  }
183193 
183194  else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
183195  int nHashSize = -1;
183196  if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
183197  nHashSize = sqlite3_value_int(pVal);
183198  }
183199  if( nHashSize<=0 ){
183200  *pbBadkey = 1;
183201  }else{
183202  pConfig->nHashSize = nHashSize;
183203  }
183204  }
183205 
183206  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
183207  int nAutomerge = -1;
183208  if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
183209  nAutomerge = sqlite3_value_int(pVal);
183210  }
183211  if( nAutomerge<0 || nAutomerge>64 ){
183212  *pbBadkey = 1;
183213  }else{
183214  if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
183215  pConfig->nAutomerge = nAutomerge;
183216  }
183217  }
183218 
183219  else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
183220  int nUsermerge = -1;
183221  if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
183222  nUsermerge = sqlite3_value_int(pVal);
183223  }
183224  if( nUsermerge<2 || nUsermerge>16 ){
183225  *pbBadkey = 1;
183226  }else{
183227  pConfig->nUsermerge = nUsermerge;
183228  }
183229  }
183230 
183231  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
183232  int nCrisisMerge = -1;
183233  if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
183234  nCrisisMerge = sqlite3_value_int(pVal);
183235  }
183236  if( nCrisisMerge<0 ){
183237  *pbBadkey = 1;
183238  }else{
183239  if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
183240  pConfig->nCrisisMerge = nCrisisMerge;
183241  }
183242  }
183243 
183244  else if( 0==sqlite3_stricmp(zKey, "rank") ){
183245  const char *zIn = (const char*)sqlite3_value_text(pVal);
183246  char *zRank;
183247  char *zRankArgs;
183248  rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
183249  if( rc==SQLITE_OK ){
183250  sqlite3_free(pConfig->zRank);
183251  sqlite3_free(pConfig->zRankArgs);
183252  pConfig->zRank = zRank;
183253  pConfig->zRankArgs = zRankArgs;
183254  }else if( rc==SQLITE_ERROR ){
183255  rc = SQLITE_OK;
183256  *pbBadkey = 1;
183257  }
183258  }else{
183259  *pbBadkey = 1;
183260  }
183261  return rc;
183262 }
183263 
183264 /*
183265 ** Load the contents of the %_config table into memory.
183266 */
183267 static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
183268  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
183269  char *zSql;
183270  sqlite3_stmt *p = 0;
183271  int rc = SQLITE_OK;
183272  int iVersion = 0;
183273 
183274  /* Set default values */
183275  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
183276  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
183277  pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
183278  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
183279  pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
183280 
183281  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
183282  if( zSql ){
183283  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
183284  sqlite3_free(zSql);
183285  }
183286 
183287  assert( rc==SQLITE_OK || p==0 );
183288  if( rc==SQLITE_OK ){
183289  while( SQLITE_ROW==sqlite3_step(p) ){
183290  const char *zK = (const char*)sqlite3_column_text(p, 0);
183291  sqlite3_value *pVal = sqlite3_column_value(p, 1);
183292  if( 0==sqlite3_stricmp(zK, "version") ){
183293  iVersion = sqlite3_value_int(pVal);
183294  }else{
183295  int bDummy = 0;
183296  sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
183297  }
183298  }
183299  rc = sqlite3_finalize(p);
183300  }
183301 
183302  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
183303  rc = SQLITE_ERROR;
183304  if( pConfig->pzErrmsg ){
183305  assert( 0==*pConfig->pzErrmsg );
183306  *pConfig->pzErrmsg = sqlite3_mprintf(
183307  "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
183308  iVersion, FTS5_CURRENT_VERSION
183309  );
183310  }
183311  }
183312 
183313  if( rc==SQLITE_OK ){
183314  pConfig->iCookie = iCookie;
183315  }
183316  return rc;
183317 }
183318 
183319 /*
183320 ** 2014 May 31
183321 **
183322 ** The author disclaims copyright to this source code. In place of
183323 ** a legal notice, here is a blessing:
183324 **
183325 ** May you do good and not evil.
183326 ** May you find forgiveness for yourself and forgive others.
183327 ** May you share freely, never taking more than you give.
183328 **
183329 ******************************************************************************
183330 **
183331 */
183332 
183333 
183334 
183335 /* #include "fts5Int.h" */
183336 /* #include "fts5parse.h" */
183337 
183338 /*
183339 ** All token types in the generated fts5parse.h file are greater than 0.
183340 */
183341 #define FTS5_EOF 0
183342 
183343 #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
183344 
183345 typedef struct Fts5ExprTerm Fts5ExprTerm;
183346 
183347 /*
183348 ** Functions generated by lemon from fts5parse.y.
183349 */
183350 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
183351 static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
183352 static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
183353 #ifndef NDEBUG
183354 /* #include <stdio.h> */
183355 static void sqlite3Fts5ParserTrace(FILE*, char*);
183356 #endif
183357 
183358 
183359 struct Fts5Expr {
183360  Fts5Index *pIndex;
183361  Fts5Config *pConfig;
183362  Fts5ExprNode *pRoot;
183363  int bDesc; /* Iterate in descending rowid order */
183364  int nPhrase; /* Number of phrases in expression */
183365  Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
183366 };
183367 
183368 /*
183369 ** eType:
183370 ** Expression node type. Always one of:
183371 **
183372 ** FTS5_AND (nChild, apChild valid)
183373 ** FTS5_OR (nChild, apChild valid)
183374 ** FTS5_NOT (nChild, apChild valid)
183375 ** FTS5_STRING (pNear valid)
183376 ** FTS5_TERM (pNear valid)
183377 */
183378 struct Fts5ExprNode {
183379  int eType; /* Node type */
183380  int bEof; /* True at EOF */
183381  int bNomatch; /* True if entry is not a match */
183382 
183383  /* Next method for this node. */
183384  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
183385 
183386  i64 iRowid; /* Current rowid */
183387  Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
183388 
183389  /* Child nodes. For a NOT node, this array always contains 2 entries. For
183390  ** AND or OR nodes, it contains 2 or more entries. */
183391  int nChild; /* Number of child nodes */
183392  Fts5ExprNode *apChild[1]; /* Array of child nodes */
183393 };
183394 
183395 #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
183396 
183397 /*
183398 ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
183399 ** used as if it has the same signature as the xNext() methods themselves.
183400 */
183401 #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
183402 
183403 /*
183404 ** An instance of the following structure represents a single search term
183405 ** or term prefix.
183406 */
183407 struct Fts5ExprTerm {
183408  int bPrefix; /* True for a prefix term */
183409  char *zTerm; /* nul-terminated term */
183410  Fts5IndexIter *pIter; /* Iterator for this term */
183411  Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
183412 };
183413 
183414 /*
183415 ** A phrase. One or more terms that must appear in a contiguous sequence
183416 ** within a document for it to match.
183417 */
183418 struct Fts5ExprPhrase {
183419  Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
183420  Fts5Buffer poslist; /* Current position list */
183421  int nTerm; /* Number of entries in aTerm[] */
183422  Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
183423 };
183424 
183425 /*
183426 ** One or more phrases that must appear within a certain token distance of
183427 ** each other within each matching document.
183428 */
183429 struct Fts5ExprNearset {
183430  int nNear; /* NEAR parameter */
183431  Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
183432  int nPhrase; /* Number of entries in aPhrase[] array */
183433  Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
183434 };
183435 
183436 
183437 /*
183438 ** Parse context.
183439 */
183440 struct Fts5Parse {
183441  Fts5Config *pConfig;
183442  char *zErr;
183443  int rc;
183444  int nPhrase; /* Size of apPhrase array */
183445  Fts5ExprPhrase **apPhrase; /* Array of all phrases */
183446  Fts5ExprNode *pExpr; /* Result of a successful parse */
183447 };
183448 
183449 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
183450  va_list ap;
183451  va_start(ap, zFmt);
183452  if( pParse->rc==SQLITE_OK ){
183453  pParse->zErr = sqlite3_vmprintf(zFmt, ap);
183454  pParse->rc = SQLITE_ERROR;
183455  }
183456  va_end(ap);
183457 }
183458 
183459 static int fts5ExprIsspace(char t){
183460  return t==' ' || t=='\t' || t=='\n' || t=='\r';
183461 }
183462 
183463 /*
183464 ** Read the first token from the nul-terminated string at *pz.
183465 */
183466 static int fts5ExprGetToken(
183467  Fts5Parse *pParse,
183468  const char **pz, /* IN/OUT: Pointer into buffer */
183469  Fts5Token *pToken
183470 ){
183471  const char *z = *pz;
183472  int tok;
183473 
183474  /* Skip past any whitespace */
183475  while( fts5ExprIsspace(*z) ) z++;
183476 
183477  pToken->p = z;
183478  pToken->n = 1;
183479  switch( *z ){
183480  case '(': tok = FTS5_LP; break;
183481  case ')': tok = FTS5_RP; break;
183482  case '{': tok = FTS5_LCP; break;
183483  case '}': tok = FTS5_RCP; break;
183484  case ':': tok = FTS5_COLON; break;
183485  case ',': tok = FTS5_COMMA; break;
183486  case '+': tok = FTS5_PLUS; break;
183487  case '*': tok = FTS5_STAR; break;
183488  case '-': tok = FTS5_MINUS; break;
183489  case '\0': tok = FTS5_EOF; break;
183490 
183491  case '"': {
183492  const char *z2;
183493  tok = FTS5_STRING;
183494 
183495  for(z2=&z[1]; 1; z2++){
183496  if( z2[0]=='"' ){
183497  z2++;
183498  if( z2[0]!='"' ) break;
183499  }
183500  if( z2[0]=='\0' ){
183501  sqlite3Fts5ParseError(pParse, "unterminated string");
183502  return FTS5_EOF;
183503  }
183504  }
183505  pToken->n = (z2 - z);
183506  break;
183507  }
183508 
183509  default: {
183510  const char *z2;
183511  if( sqlite3Fts5IsBareword(z[0])==0 ){
183512  sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
183513  return FTS5_EOF;
183514  }
183515  tok = FTS5_STRING;
183516  for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
183517  pToken->n = (z2 - z);
183518  if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
183519  if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
183520  if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
183521  break;
183522  }
183523  }
183524 
183525  *pz = &pToken->p[pToken->n];
183526  return tok;
183527 }
183528 
183529 static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
183530 static void fts5ParseFree(void *p){ sqlite3_free(p); }
183531 
183532 static int sqlite3Fts5ExprNew(
183533  Fts5Config *pConfig, /* FTS5 Configuration */
183534  const char *zExpr, /* Expression text */
183535  Fts5Expr **ppNew,
183536  char **pzErr
183537 ){
183538  Fts5Parse sParse;
183539  Fts5Token token;
183540  const char *z = zExpr;
183541  int t; /* Next token type */
183542  void *pEngine;
183543  Fts5Expr *pNew;
183544 
183545  *ppNew = 0;
183546  *pzErr = 0;
183547  memset(&sParse, 0, sizeof(sParse));
183548  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
183549  if( pEngine==0 ){ return SQLITE_NOMEM; }
183550  sParse.pConfig = pConfig;
183551 
183552  do {
183553  t = fts5ExprGetToken(&sParse, &z, &token);
183554  sqlite3Fts5Parser(pEngine, t, token, &sParse);
183555  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
183556  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
183557 
183558  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
183559  if( sParse.rc==SQLITE_OK ){
183560  *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
183561  if( pNew==0 ){
183562  sParse.rc = SQLITE_NOMEM;
183563  sqlite3Fts5ParseNodeFree(sParse.pExpr);
183564  }else{
183565  if( !sParse.pExpr ){
183566  const int nByte = sizeof(Fts5ExprNode);
183567  pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
183568  if( pNew->pRoot ){
183569  pNew->pRoot->bEof = 1;
183570  }
183571  }else{
183572  pNew->pRoot = sParse.pExpr;
183573  }
183574  pNew->pIndex = 0;
183575  pNew->pConfig = pConfig;
183576  pNew->apExprPhrase = sParse.apPhrase;
183577  pNew->nPhrase = sParse.nPhrase;
183578  sParse.apPhrase = 0;
183579  }
183580  }else{
183581  sqlite3Fts5ParseNodeFree(sParse.pExpr);
183582  }
183583 
183584  sqlite3_free(sParse.apPhrase);
183585  *pzErr = sParse.zErr;
183586  return sParse.rc;
183587 }
183588 
183589 /*
183590 ** Free the expression node object passed as the only argument.
183591 */
183592 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
183593  if( p ){
183594  int i;
183595  for(i=0; i<p->nChild; i++){
183596  sqlite3Fts5ParseNodeFree(p->apChild[i]);
183597  }
183598  sqlite3Fts5ParseNearsetFree(p->pNear);
183599  sqlite3_free(p);
183600  }
183601 }
183602 
183603 /*
183604 ** Free the expression object passed as the only argument.
183605 */
183606 static void sqlite3Fts5ExprFree(Fts5Expr *p){
183607  if( p ){
183608  sqlite3Fts5ParseNodeFree(p->pRoot);
183609  sqlite3_free(p->apExprPhrase);
183610  sqlite3_free(p);
183611  }
183612 }
183613 
183614 /*
183615 ** Argument pTerm must be a synonym iterator. Return the current rowid
183616 ** that it points to.
183617 */
183618 static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
183619  i64 iRet = 0;
183620  int bRetValid = 0;
183621  Fts5ExprTerm *p;
183622 
183623  assert( pTerm->pSynonym );
183624  assert( bDesc==0 || bDesc==1 );
183625  for(p=pTerm; p; p=p->pSynonym){
183626  if( 0==sqlite3Fts5IterEof(p->pIter) ){
183627  i64 iRowid = p->pIter->iRowid;
183628  if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
183629  iRet = iRowid;
183630  bRetValid = 1;
183631  }
183632  }
183633  }
183634 
183635  if( pbEof && bRetValid==0 ) *pbEof = 1;
183636  return iRet;
183637 }
183638 
183639 /*
183640 ** Argument pTerm must be a synonym iterator.
183641 */
183642 static int fts5ExprSynonymList(
183643  Fts5ExprTerm *pTerm,
183644  i64 iRowid,
183645  Fts5Buffer *pBuf, /* Use this buffer for space if required */
183646  u8 **pa, int *pn
183647 ){
183648  Fts5PoslistReader aStatic[4];
183649  Fts5PoslistReader *aIter = aStatic;
183650  int nIter = 0;
183651  int nAlloc = 4;
183652  int rc = SQLITE_OK;
183653  Fts5ExprTerm *p;
183654 
183655  assert( pTerm->pSynonym );
183656  for(p=pTerm; p; p=p->pSynonym){
183657  Fts5IndexIter *pIter = p->pIter;
183658  if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
183659  if( pIter->nData==0 ) continue;
183660  if( nIter==nAlloc ){
183661  int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
183662  Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
183663  if( aNew==0 ){
183664  rc = SQLITE_NOMEM;
183665  goto synonym_poslist_out;
183666  }
183667  memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
183668  nAlloc = nAlloc*2;
183669  if( aIter!=aStatic ) sqlite3_free(aIter);
183670  aIter = aNew;
183671  }
183672  sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
183673  assert( aIter[nIter].bEof==0 );
183674  nIter++;
183675  }
183676  }
183677 
183678  if( nIter==1 ){
183679  *pa = (u8*)aIter[0].a;
183680  *pn = aIter[0].n;
183681  }else{
183682  Fts5PoslistWriter writer = {0};
183683  i64 iPrev = -1;
183684  fts5BufferZero(pBuf);
183685  while( 1 ){
183686  int i;
183687  i64 iMin = FTS5_LARGEST_INT64;
183688  for(i=0; i<nIter; i++){
183689  if( aIter[i].bEof==0 ){
183690  if( aIter[i].iPos==iPrev ){
183691  if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
183692  }
183693  if( aIter[i].iPos<iMin ){
183694  iMin = aIter[i].iPos;
183695  }
183696  }
183697  }
183698  if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
183699  rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
183700  iPrev = iMin;
183701  }
183702  if( rc==SQLITE_OK ){
183703  *pa = pBuf->p;
183704  *pn = pBuf->n;
183705  }
183706  }
183707 
183708  synonym_poslist_out:
183709  if( aIter!=aStatic ) sqlite3_free(aIter);
183710  return rc;
183711 }
183712 
183713 
183714 /*
183715 ** All individual term iterators in pPhrase are guaranteed to be valid and
183716 ** pointing to the same rowid when this function is called. This function
183717 ** checks if the current rowid really is a match, and if so populates
183718 ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
183719 ** is set to true if this is really a match, or false otherwise.
183720 **
183721 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
183722 ** otherwise. It is not considered an error code if the current rowid is
183723 ** not a match.
183724 */
183725 static int fts5ExprPhraseIsMatch(
183726  Fts5ExprNode *pNode, /* Node pPhrase belongs to */
183727  Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
183728  int *pbMatch /* OUT: Set to true if really a match */
183729 ){
183730  Fts5PoslistWriter writer = {0};
183731  Fts5PoslistReader aStatic[4];
183732  Fts5PoslistReader *aIter = aStatic;
183733  int i;
183734  int rc = SQLITE_OK;
183735 
183736  fts5BufferZero(&pPhrase->poslist);
183737 
183738  /* If the aStatic[] array is not large enough, allocate a large array
183739  ** using sqlite3_malloc(). This approach could be improved upon. */
183740  if( pPhrase->nTerm>ArraySize(aStatic) ){
183741  int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
183742  aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
183743  if( !aIter ) return SQLITE_NOMEM;
183744  }
183745  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
183746 
183747  /* Initialize a term iterator for each term in the phrase */
183748  for(i=0; i<pPhrase->nTerm; i++){
183749  Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
183750  int n = 0;
183751  int bFlag = 0;
183752  u8 *a = 0;
183753  if( pTerm->pSynonym ){
183754  Fts5Buffer buf = {0, 0, 0};
183755  rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
183756  if( rc ){
183757  sqlite3_free(a);
183758  goto ismatch_out;
183759  }
183760  if( a==buf.p ) bFlag = 1;
183761  }else{
183762  a = (u8*)pTerm->pIter->pData;
183763  n = pTerm->pIter->nData;
183764  }
183765  sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
183766  aIter[i].bFlag = (u8)bFlag;
183767  if( aIter[i].bEof ) goto ismatch_out;
183768  }
183769 
183770  while( 1 ){
183771  int bMatch;
183772  i64 iPos = aIter[0].iPos;
183773  do {
183774  bMatch = 1;
183775  for(i=0; i<pPhrase->nTerm; i++){
183776  Fts5PoslistReader *pPos = &aIter[i];
183777  i64 iAdj = iPos + i;
183778  if( pPos->iPos!=iAdj ){
183779  bMatch = 0;
183780  while( pPos->iPos<iAdj ){
183781  if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
183782  }
183783  if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
183784  }
183785  }
183786  }while( bMatch==0 );
183787 
183788  /* Append position iPos to the output */
183789  rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
183790  if( rc!=SQLITE_OK ) goto ismatch_out;
183791 
183792  for(i=0; i<pPhrase->nTerm; i++){
183793  if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
183794  }
183795  }
183796 
183797  ismatch_out:
183798  *pbMatch = (pPhrase->poslist.n>0);
183799  for(i=0; i<pPhrase->nTerm; i++){
183800  if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
183801  }
183802  if( aIter!=aStatic ) sqlite3_free(aIter);
183803  return rc;
183804 }
183805 
183806 typedef struct Fts5LookaheadReader Fts5LookaheadReader;
183807 struct Fts5LookaheadReader {
183808  const u8 *a; /* Buffer containing position list */
183809  int n; /* Size of buffer a[] in bytes */
183810  int i; /* Current offset in position list */
183811  i64 iPos; /* Current position */
183812  i64 iLookahead; /* Next position */
183813 };
183814 
183815 #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
183816 
183817 static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
183818  p->iPos = p->iLookahead;
183819  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
183820  p->iLookahead = FTS5_LOOKAHEAD_EOF;
183821  }
183822  return (p->iPos==FTS5_LOOKAHEAD_EOF);
183823 }
183824 
183825 static int fts5LookaheadReaderInit(
183826  const u8 *a, int n, /* Buffer to read position list from */
183827  Fts5LookaheadReader *p /* Iterator object to initialize */
183828 ){
183829  memset(p, 0, sizeof(Fts5LookaheadReader));
183830  p->a = a;
183831  p->n = n;
183832  fts5LookaheadReaderNext(p);
183833  return fts5LookaheadReaderNext(p);
183834 }
183835 
183836 typedef struct Fts5NearTrimmer Fts5NearTrimmer;
183837 struct Fts5NearTrimmer {
183838  Fts5LookaheadReader reader; /* Input iterator */
183839  Fts5PoslistWriter writer; /* Writer context */
183840  Fts5Buffer *pOut; /* Output poslist */
183841 };
183842 
183843 /*
183844 ** The near-set object passed as the first argument contains more than
183845 ** one phrase. All phrases currently point to the same row. The
183846 ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
183847 ** tests if the current row contains instances of each phrase sufficiently
183848 ** close together to meet the NEAR constraint. Non-zero is returned if it
183849 ** does, or zero otherwise.
183850 **
183851 ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
183852 ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
183853 ** occurs within this function (*pRc) is set accordingly before returning.
183854 ** The return value is undefined in both these cases.
183855 **
183856 ** If no error occurs and non-zero (a match) is returned, the position-list
183857 ** of each phrase object is edited to contain only those entries that
183858 ** meet the constraint before returning.
183859 */
183860 static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
183861  Fts5NearTrimmer aStatic[4];
183862  Fts5NearTrimmer *a = aStatic;
183863  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
183864 
183865  int i;
183866  int rc = *pRc;
183867  int bMatch;
183868 
183869  assert( pNear->nPhrase>1 );
183870 
183871  /* If the aStatic[] array is not large enough, allocate a large array
183872  ** using sqlite3_malloc(). This approach could be improved upon. */
183873  if( pNear->nPhrase>ArraySize(aStatic) ){
183874  int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
183875  a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
183876  }else{
183877  memset(aStatic, 0, sizeof(aStatic));
183878  }
183879  if( rc!=SQLITE_OK ){
183880  *pRc = rc;
183881  return 0;
183882  }
183883 
183884  /* Initialize a lookahead iterator for each phrase. After passing the
183885  ** buffer and buffer size to the lookaside-reader init function, zero
183886  ** the phrase poslist buffer. The new poslist for the phrase (containing
183887  ** the same entries as the original with some entries removed on account
183888  ** of the NEAR constraint) is written over the original even as it is
183889  ** being read. This is safe as the entries for the new poslist are a
183890  ** subset of the old, so it is not possible for data yet to be read to
183891  ** be overwritten. */
183892  for(i=0; i<pNear->nPhrase; i++){
183893  Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
183894  fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
183895  pPoslist->n = 0;
183896  a[i].pOut = pPoslist;
183897  }
183898 
183899  while( 1 ){
183900  int iAdv;
183901  i64 iMin;
183902  i64 iMax;
183903 
183904  /* This block advances the phrase iterators until they point to a set of
183905  ** entries that together comprise a match. */
183906  iMax = a[0].reader.iPos;
183907  do {
183908  bMatch = 1;
183909  for(i=0; i<pNear->nPhrase; i++){
183910  Fts5LookaheadReader *pPos = &a[i].reader;
183911  iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
183912  if( pPos->iPos<iMin || pPos->iPos>iMax ){
183913  bMatch = 0;
183914  while( pPos->iPos<iMin ){
183915  if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
183916  }
183917  if( pPos->iPos>iMax ) iMax = pPos->iPos;
183918  }
183919  }
183920  }while( bMatch==0 );
183921 
183922  /* Add an entry to each output position list */
183923  for(i=0; i<pNear->nPhrase; i++){
183924  i64 iPos = a[i].reader.iPos;
183925  Fts5PoslistWriter *pWriter = &a[i].writer;
183926  if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
183927  sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
183928  }
183929  }
183930 
183931  iAdv = 0;
183932  iMin = a[0].reader.iLookahead;
183933  for(i=0; i<pNear->nPhrase; i++){
183934  if( a[i].reader.iLookahead < iMin ){
183935  iMin = a[i].reader.iLookahead;
183936  iAdv = i;
183937  }
183938  }
183939  if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
183940  }
183941 
183942  ismatch_out: {
183943  int bRet = a[0].pOut->n>0;
183944  *pRc = rc;
183945  if( a!=aStatic ) sqlite3_free(a);
183946  return bRet;
183947  }
183948 }
183949 
183950 /*
183951 ** Advance iterator pIter until it points to a value equal to or laster
183952 ** than the initial value of *piLast. If this means the iterator points
183953 ** to a value laster than *piLast, update *piLast to the new lastest value.
183954 **
183955 ** If the iterator reaches EOF, set *pbEof to true before returning. If
183956 ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
183957 ** are set, return a non-zero value. Otherwise, return zero.
183958 */
183959 static int fts5ExprAdvanceto(
183960  Fts5IndexIter *pIter, /* Iterator to advance */
183961  int bDesc, /* True if iterator is "rowid DESC" */
183962  i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
183963  int *pRc, /* OUT: Error code */
183964  int *pbEof /* OUT: Set to true if EOF */
183965 ){
183966  i64 iLast = *piLast;
183967  i64 iRowid;
183968 
183969  iRowid = pIter->iRowid;
183970  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
183971  int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
183972  if( rc || sqlite3Fts5IterEof(pIter) ){
183973  *pRc = rc;
183974  *pbEof = 1;
183975  return 1;
183976  }
183977  iRowid = pIter->iRowid;
183978  assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
183979  }
183980  *piLast = iRowid;
183981 
183982  return 0;
183983 }
183984 
183985 static int fts5ExprSynonymAdvanceto(
183986  Fts5ExprTerm *pTerm, /* Term iterator to advance */
183987  int bDesc, /* True if iterator is "rowid DESC" */
183988  i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
183989  int *pRc /* OUT: Error code */
183990 ){
183991  int rc = SQLITE_OK;
183992  i64 iLast = *piLast;
183993  Fts5ExprTerm *p;
183994  int bEof = 0;
183995 
183996  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
183997  if( sqlite3Fts5IterEof(p->pIter)==0 ){
183998  i64 iRowid = p->pIter->iRowid;
183999  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
184000  rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
184001  }
184002  }
184003  }
184004 
184005  if( rc!=SQLITE_OK ){
184006  *pRc = rc;
184007  bEof = 1;
184008  }else{
184009  *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
184010  }
184011  return bEof;
184012 }
184013 
184014 
184015 static int fts5ExprNearTest(
184016  int *pRc,
184017  Fts5Expr *pExpr, /* Expression that pNear is a part of */
184018  Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
184019 ){
184020  Fts5ExprNearset *pNear = pNode->pNear;
184021  int rc = *pRc;
184022 
184023  if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
184024  Fts5ExprTerm *pTerm;
184025  Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
184026  pPhrase->poslist.n = 0;
184027  for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
184028  Fts5IndexIter *pIter = pTerm->pIter;
184029  if( sqlite3Fts5IterEof(pIter)==0 ){
184030  if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
184031  pPhrase->poslist.n = 1;
184032  }
184033  }
184034  }
184035  return pPhrase->poslist.n;
184036  }else{
184037  int i;
184038 
184039  /* Check that each phrase in the nearset matches the current row.
184040  ** Populate the pPhrase->poslist buffers at the same time. If any
184041  ** phrase is not a match, break out of the loop early. */
184042  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
184043  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
184044  if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
184045  int bMatch = 0;
184046  rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
184047  if( bMatch==0 ) break;
184048  }else{
184049  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
184050  fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
184051  }
184052  }
184053 
184054  *pRc = rc;
184055  if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
184056  return 1;
184057  }
184058  return 0;
184059  }
184060 }
184061 
184062 
184063 /*
184064 ** Initialize all term iterators in the pNear object. If any term is found
184065 ** to match no documents at all, return immediately without initializing any
184066 ** further iterators.
184067 */
184068 static int fts5ExprNearInitAll(
184069  Fts5Expr *pExpr,
184070  Fts5ExprNode *pNode
184071 ){
184072  Fts5ExprNearset *pNear = pNode->pNear;
184073  int i, j;
184074  int rc = SQLITE_OK;
184075  int bEof = 1;
184076 
184077  assert( pNode->bNomatch==0 );
184078  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
184079  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
184080  for(j=0; j<pPhrase->nTerm; j++){
184081  Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
184082  Fts5ExprTerm *p;
184083 
184084  for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
184085  if( p->pIter ){
184086  sqlite3Fts5IterClose(p->pIter);
184087  p->pIter = 0;
184088  }
184089  rc = sqlite3Fts5IndexQuery(
184090  pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
184091  (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
184092  (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
184093  pNear->pColset,
184094  &p->pIter
184095  );
184096  assert( rc==SQLITE_OK || p->pIter==0 );
184097  if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
184098  bEof = 0;
184099  }
184100  }
184101 
184102  if( bEof ) break;
184103  }
184104  if( bEof ) break;
184105  }
184106 
184107  pNode->bEof = bEof;
184108  return rc;
184109 }
184110 
184111 /*
184112 ** If pExpr is an ASC iterator, this function returns a value with the
184113 ** same sign as:
184114 **
184115 ** (iLhs - iRhs)
184116 **
184117 ** Otherwise, if this is a DESC iterator, the opposite is returned:
184118 **
184119 ** (iRhs - iLhs)
184120 */
184121 static int fts5RowidCmp(
184122  Fts5Expr *pExpr,
184123  i64 iLhs,
184124  i64 iRhs
184125 ){
184126  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
184127  if( pExpr->bDesc==0 ){
184128  if( iLhs<iRhs ) return -1;
184129  return (iLhs > iRhs);
184130  }else{
184131  if( iLhs>iRhs ) return -1;
184132  return (iLhs < iRhs);
184133  }
184134 }
184135 
184136 static void fts5ExprSetEof(Fts5ExprNode *pNode){
184137  int i;
184138  pNode->bEof = 1;
184139  pNode->bNomatch = 0;
184140  for(i=0; i<pNode->nChild; i++){
184141  fts5ExprSetEof(pNode->apChild[i]);
184142  }
184143 }
184144 
184145 static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
184146  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
184147  Fts5ExprNearset *pNear = pNode->pNear;
184148  int i;
184149  for(i=0; i<pNear->nPhrase; i++){
184150  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
184151  pPhrase->poslist.n = 0;
184152  }
184153  }else{
184154  int i;
184155  for(i=0; i<pNode->nChild; i++){
184156  fts5ExprNodeZeroPoslist(pNode->apChild[i]);
184157  }
184158  }
184159 }
184160 
184161 
184162 
184163 /*
184164 ** Compare the values currently indicated by the two nodes as follows:
184165 **
184166 ** res = (*p1) - (*p2)
184167 **
184168 ** Nodes that point to values that come later in the iteration order are
184169 ** considered to be larger. Nodes at EOF are the largest of all.
184170 **
184171 ** This means that if the iteration order is ASC, then numerically larger
184172 ** rowids are considered larger. Or if it is the default DESC, numerically
184173 ** smaller rowids are larger.
184174 */
184175 static int fts5NodeCompare(
184176  Fts5Expr *pExpr,
184177  Fts5ExprNode *p1,
184178  Fts5ExprNode *p2
184179 ){
184180  if( p2->bEof ) return -1;
184181  if( p1->bEof ) return +1;
184182  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
184183 }
184184 
184185 /*
184186 ** All individual term iterators in pNear are guaranteed to be valid when
184187 ** this function is called. This function checks if all term iterators
184188 ** point to the same rowid, and if not, advances them until they do.
184189 ** If an EOF is reached before this happens, *pbEof is set to true before
184190 ** returning.
184191 **
184192 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
184193 ** otherwise. It is not considered an error code if an iterator reaches
184194 ** EOF.
184195 */
184196 static int fts5ExprNodeTest_STRING(
184197  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
184198  Fts5ExprNode *pNode
184199 ){
184200  Fts5ExprNearset *pNear = pNode->pNear;
184201  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
184202  int rc = SQLITE_OK;
184203  i64 iLast; /* Lastest rowid any iterator points to */
184204  int i, j; /* Phrase and token index, respectively */
184205  int bMatch; /* True if all terms are at the same rowid */
184206  const int bDesc = pExpr->bDesc;
184207 
184208  /* Check that this node should not be FTS5_TERM */
184209  assert( pNear->nPhrase>1
184210  || pNear->apPhrase[0]->nTerm>1
184211  || pNear->apPhrase[0]->aTerm[0].pSynonym
184212  );
184213 
184214  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
184215  ** iterator skips through rowids in the default ascending order, this means
184216  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
184217  ** means the minimum rowid. */
184218  if( pLeft->aTerm[0].pSynonym ){
184219  iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
184220  }else{
184221  iLast = pLeft->aTerm[0].pIter->iRowid;
184222  }
184223 
184224  do {
184225  bMatch = 1;
184226  for(i=0; i<pNear->nPhrase; i++){
184227  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
184228  for(j=0; j<pPhrase->nTerm; j++){
184229  Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
184230  if( pTerm->pSynonym ){
184231  i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
184232  if( iRowid==iLast ) continue;
184233  bMatch = 0;
184234  if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
184235  pNode->bNomatch = 0;
184236  pNode->bEof = 1;
184237  return rc;
184238  }
184239  }else{
184240  Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
184241  if( pIter->iRowid==iLast ) continue;
184242  bMatch = 0;
184243  if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
184244  return rc;
184245  }
184246  }
184247  }
184248  }
184249  }while( bMatch==0 );
184250 
184251  pNode->iRowid = iLast;
184252  pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
184253  assert( pNode->bEof==0 || pNode->bNomatch==0 );
184254 
184255  return rc;
184256 }
184257 
184258 /*
184259 ** Advance the first term iterator in the first phrase of pNear. Set output
184260 ** variable *pbEof to true if it reaches EOF or if an error occurs.
184261 **
184262 ** Return SQLITE_OK if successful, or an SQLite error code if an error
184263 ** occurs.
184264 */
184265 static int fts5ExprNodeNext_STRING(
184266  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
184267  Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
184268  int bFromValid,
184269  i64 iFrom
184270 ){
184271  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
184272  int rc = SQLITE_OK;
184273 
184274  pNode->bNomatch = 0;
184275  if( pTerm->pSynonym ){
184276  int bEof = 1;
184277  Fts5ExprTerm *p;
184278 
184279  /* Find the firstest rowid any synonym points to. */
184280  i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
184281 
184282  /* Advance each iterator that currently points to iRowid. Or, if iFrom
184283  ** is valid - each iterator that points to a rowid before iFrom. */
184284  for(p=pTerm; p; p=p->pSynonym){
184285  if( sqlite3Fts5IterEof(p->pIter)==0 ){
184286  i64 ii = p->pIter->iRowid;
184287  if( ii==iRowid
184288  || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
184289  ){
184290  if( bFromValid ){
184291  rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
184292  }else{
184293  rc = sqlite3Fts5IterNext(p->pIter);
184294  }
184295  if( rc!=SQLITE_OK ) break;
184296  if( sqlite3Fts5IterEof(p->pIter)==0 ){
184297  bEof = 0;
184298  }
184299  }else{
184300  bEof = 0;
184301  }
184302  }
184303  }
184304 
184305  /* Set the EOF flag if either all synonym iterators are at EOF or an
184306  ** error has occurred. */
184307  pNode->bEof = (rc || bEof);
184308  }else{
184309  Fts5IndexIter *pIter = pTerm->pIter;
184310 
184311  assert( Fts5NodeIsString(pNode) );
184312  if( bFromValid ){
184313  rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
184314  }else{
184315  rc = sqlite3Fts5IterNext(pIter);
184316  }
184317 
184318  pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
184319  }
184320 
184321  if( pNode->bEof==0 ){
184322  assert( rc==SQLITE_OK );
184323  rc = fts5ExprNodeTest_STRING(pExpr, pNode);
184324  }
184325 
184326  return rc;
184327 }
184328 
184329 
184330 static int fts5ExprNodeTest_TERM(
184331  Fts5Expr *pExpr, /* Expression that pNear is a part of */
184332  Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
184333 ){
184334  /* As this "NEAR" object is actually a single phrase that consists
184335  ** of a single term only, grab pointers into the poslist managed by the
184336  ** fts5_index.c iterator object. This is much faster than synthesizing
184337  ** a new poslist the way we have to for more complicated phrase or NEAR
184338  ** expressions. */
184339  Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
184340  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
184341 
184342  assert( pNode->eType==FTS5_TERM );
184343  assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
184344  assert( pPhrase->aTerm[0].pSynonym==0 );
184345 
184346  pPhrase->poslist.n = pIter->nData;
184347  if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
184348  pPhrase->poslist.p = (u8*)pIter->pData;
184349  }
184350  pNode->iRowid = pIter->iRowid;
184351  pNode->bNomatch = (pPhrase->poslist.n==0);
184352  return SQLITE_OK;
184353 }
184354 
184355 /*
184356 ** xNext() method for a node of type FTS5_TERM.
184357 */
184358 static int fts5ExprNodeNext_TERM(
184359  Fts5Expr *pExpr,
184360  Fts5ExprNode *pNode,
184361  int bFromValid,
184362  i64 iFrom
184363 ){
184364  int rc;
184365  Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
184366 
184367  assert( pNode->bEof==0 );
184368  if( bFromValid ){
184369  rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
184370  }else{
184371  rc = sqlite3Fts5IterNext(pIter);
184372  }
184373  if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
184374  rc = fts5ExprNodeTest_TERM(pExpr, pNode);
184375  }else{
184376  pNode->bEof = 1;
184377  pNode->bNomatch = 0;
184378  }
184379  return rc;
184380 }
184381 
184382 static void fts5ExprNodeTest_OR(
184383  Fts5Expr *pExpr, /* Expression of which pNode is a part */
184384  Fts5ExprNode *pNode /* Expression node to test */
184385 ){
184386  Fts5ExprNode *pNext = pNode->apChild[0];
184387  int i;
184388 
184389  for(i=1; i<pNode->nChild; i++){
184390  Fts5ExprNode *pChild = pNode->apChild[i];
184391  int cmp = fts5NodeCompare(pExpr, pNext, pChild);
184392  if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
184393  pNext = pChild;
184394  }
184395  }
184396  pNode->iRowid = pNext->iRowid;
184397  pNode->bEof = pNext->bEof;
184398  pNode->bNomatch = pNext->bNomatch;
184399 }
184400 
184401 static int fts5ExprNodeNext_OR(
184402  Fts5Expr *pExpr,
184403  Fts5ExprNode *pNode,
184404  int bFromValid,
184405  i64 iFrom
184406 ){
184407  int i;
184408  i64 iLast = pNode->iRowid;
184409 
184410  for(i=0; i<pNode->nChild; i++){
184411  Fts5ExprNode *p1 = pNode->apChild[i];
184412  assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
184413  if( p1->bEof==0 ){
184414  if( (p1->iRowid==iLast)
184415  || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
184416  ){
184417  int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
184418  if( rc!=SQLITE_OK ) return rc;
184419  }
184420  }
184421  }
184422 
184423  fts5ExprNodeTest_OR(pExpr, pNode);
184424  return SQLITE_OK;
184425 }
184426 
184427 /*
184428 ** Argument pNode is an FTS5_AND node.
184429 */
184430 static int fts5ExprNodeTest_AND(
184431  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
184432  Fts5ExprNode *pAnd /* FTS5_AND node to advance */
184433 ){
184434  int iChild;
184435  i64 iLast = pAnd->iRowid;
184436  int rc = SQLITE_OK;
184437  int bMatch;
184438 
184439  assert( pAnd->bEof==0 );
184440  do {
184441  pAnd->bNomatch = 0;
184442  bMatch = 1;
184443  for(iChild=0; iChild<pAnd->nChild; iChild++){
184444  Fts5ExprNode *pChild = pAnd->apChild[iChild];
184445  int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
184446  if( cmp>0 ){
184447  /* Advance pChild until it points to iLast or laster */
184448  rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
184449  if( rc!=SQLITE_OK ) return rc;
184450  }
184451 
184452  /* If the child node is now at EOF, so is the parent AND node. Otherwise,
184453  ** the child node is guaranteed to have advanced at least as far as
184454  ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
184455  ** new lastest rowid seen so far. */
184456  assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
184457  if( pChild->bEof ){
184458  fts5ExprSetEof(pAnd);
184459  bMatch = 1;
184460  break;
184461  }else if( iLast!=pChild->iRowid ){
184462  bMatch = 0;
184463  iLast = pChild->iRowid;
184464  }
184465 
184466  if( pChild->bNomatch ){
184467  pAnd->bNomatch = 1;
184468  }
184469  }
184470  }while( bMatch==0 );
184471 
184472  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
184473  fts5ExprNodeZeroPoslist(pAnd);
184474  }
184475  pAnd->iRowid = iLast;
184476  return SQLITE_OK;
184477 }
184478 
184479 static int fts5ExprNodeNext_AND(
184480  Fts5Expr *pExpr,
184481  Fts5ExprNode *pNode,
184482  int bFromValid,
184483  i64 iFrom
184484 ){
184485  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
184486  if( rc==SQLITE_OK ){
184487  rc = fts5ExprNodeTest_AND(pExpr, pNode);
184488  }
184489  return rc;
184490 }
184491 
184492 static int fts5ExprNodeTest_NOT(
184493  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
184494  Fts5ExprNode *pNode /* FTS5_NOT node to advance */
184495 ){
184496  int rc = SQLITE_OK;
184497  Fts5ExprNode *p1 = pNode->apChild[0];
184498  Fts5ExprNode *p2 = pNode->apChild[1];
184499  assert( pNode->nChild==2 );
184500 
184501  while( rc==SQLITE_OK && p1->bEof==0 ){
184502  int cmp = fts5NodeCompare(pExpr, p1, p2);
184503  if( cmp>0 ){
184504  rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
184505  cmp = fts5NodeCompare(pExpr, p1, p2);
184506  }
184507  assert( rc!=SQLITE_OK || cmp<=0 );
184508  if( cmp || p2->bNomatch ) break;
184509  rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
184510  }
184511  pNode->bEof = p1->bEof;
184512  pNode->bNomatch = p1->bNomatch;
184513  pNode->iRowid = p1->iRowid;
184514  if( p1->bEof ){
184515  fts5ExprNodeZeroPoslist(p2);
184516  }
184517  return rc;
184518 }
184519 
184520 static int fts5ExprNodeNext_NOT(
184521  Fts5Expr *pExpr,
184522  Fts5ExprNode *pNode,
184523  int bFromValid,
184524  i64 iFrom
184525 ){
184526  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
184527  if( rc==SQLITE_OK ){
184528  rc = fts5ExprNodeTest_NOT(pExpr, pNode);
184529  }
184530  return rc;
184531 }
184532 
184533 /*
184534 ** If pNode currently points to a match, this function returns SQLITE_OK
184535 ** without modifying it. Otherwise, pNode is advanced until it does point
184536 ** to a match or EOF is reached.
184537 */
184538 static int fts5ExprNodeTest(
184539  Fts5Expr *pExpr, /* Expression of which pNode is a part */
184540  Fts5ExprNode *pNode /* Expression node to test */
184541 ){
184542  int rc = SQLITE_OK;
184543  if( pNode->bEof==0 ){
184544  switch( pNode->eType ){
184545 
184546  case FTS5_STRING: {
184547  rc = fts5ExprNodeTest_STRING(pExpr, pNode);
184548  break;
184549  }
184550 
184551  case FTS5_TERM: {
184552  rc = fts5ExprNodeTest_TERM(pExpr, pNode);
184553  break;
184554  }
184555 
184556  case FTS5_AND: {
184557  rc = fts5ExprNodeTest_AND(pExpr, pNode);
184558  break;
184559  }
184560 
184561  case FTS5_OR: {
184562  fts5ExprNodeTest_OR(pExpr, pNode);
184563  break;
184564  }
184565 
184566  default: assert( pNode->eType==FTS5_NOT ); {
184567  rc = fts5ExprNodeTest_NOT(pExpr, pNode);
184568  break;
184569  }
184570  }
184571  }
184572  return rc;
184573 }
184574 
184575 
184576 /*
184577 ** Set node pNode, which is part of expression pExpr, to point to the first
184578 ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
184579 **
184580 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
184581 ** It is not an error if there are no matches.
184582 */
184583 static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
184584  int rc = SQLITE_OK;
184585  pNode->bEof = 0;
184586  pNode->bNomatch = 0;
184587 
184588  if( Fts5NodeIsString(pNode) ){
184589  /* Initialize all term iterators in the NEAR object. */
184590  rc = fts5ExprNearInitAll(pExpr, pNode);
184591  }else if( pNode->xNext==0 ){
184592  pNode->bEof = 1;
184593  }else{
184594  int i;
184595  int nEof = 0;
184596  for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
184597  Fts5ExprNode *pChild = pNode->apChild[i];
184598  rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
184599  assert( pChild->bEof==0 || pChild->bEof==1 );
184600  nEof += pChild->bEof;
184601  }
184602  pNode->iRowid = pNode->apChild[0]->iRowid;
184603 
184604  switch( pNode->eType ){
184605  case FTS5_AND:
184606  if( nEof>0 ) fts5ExprSetEof(pNode);
184607  break;
184608 
184609  case FTS5_OR:
184610  if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
184611  break;
184612 
184613  default:
184614  assert( pNode->eType==FTS5_NOT );
184615  pNode->bEof = pNode->apChild[0]->bEof;
184616  break;
184617  }
184618  }
184619 
184620  if( rc==SQLITE_OK ){
184621  rc = fts5ExprNodeTest(pExpr, pNode);
184622  }
184623  return rc;
184624 }
184625 
184626 
184627 /*
184628 ** Begin iterating through the set of documents in index pIdx matched by
184629 ** the MATCH expression passed as the first argument. If the "bDesc"
184630 ** parameter is passed a non-zero value, iteration is in descending rowid
184631 ** order. Or, if it is zero, in ascending order.
184632 **
184633 ** If iterating in ascending rowid order (bDesc==0), the first document
184634 ** visited is that with the smallest rowid that is larger than or equal
184635 ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
184636 ** then the first document visited must have a rowid smaller than or
184637 ** equal to iFirst.
184638 **
184639 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
184640 ** is not considered an error if the query does not match any documents.
184641 */
184642 static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
184643  Fts5ExprNode *pRoot = p->pRoot;
184644  int rc; /* Return code */
184645 
184646  p->pIndex = pIdx;
184647  p->bDesc = bDesc;
184648  rc = fts5ExprNodeFirst(p, pRoot);
184649 
184650  /* If not at EOF but the current rowid occurs earlier than iFirst in
184651  ** the iteration order, move to document iFirst or later. */
184652  if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
184653  rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
184654  }
184655 
184656  /* If the iterator is not at a real match, skip forward until it is. */
184657  while( pRoot->bNomatch ){
184658  assert( pRoot->bEof==0 && rc==SQLITE_OK );
184659  rc = fts5ExprNodeNext(p, pRoot, 0, 0);
184660  }
184661  return rc;
184662 }
184663 
184664 /*
184665 ** Move to the next document
184666 **
184667 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
184668 ** is not considered an error if the query does not match any documents.
184669 */
184670 static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
184671  int rc;
184672  Fts5ExprNode *pRoot = p->pRoot;
184673  assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
184674  do {
184675  rc = fts5ExprNodeNext(p, pRoot, 0, 0);
184676  assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
184677  }while( pRoot->bNomatch );
184678  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
184679  pRoot->bEof = 1;
184680  }
184681  return rc;
184682 }
184683 
184684 static int sqlite3Fts5ExprEof(Fts5Expr *p){
184685  return p->pRoot->bEof;
184686 }
184687 
184688 static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
184689  return p->pRoot->iRowid;
184690 }
184691 
184692 static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
184693  int rc = SQLITE_OK;
184694  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
184695  return rc;
184696 }
184697 
184698 /*
184699 ** Free the phrase object passed as the only argument.
184700 */
184701 static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
184702  if( pPhrase ){
184703  int i;
184704  for(i=0; i<pPhrase->nTerm; i++){
184705  Fts5ExprTerm *pSyn;
184706  Fts5ExprTerm *pNext;
184707  Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
184708  sqlite3_free(pTerm->zTerm);
184709  sqlite3Fts5IterClose(pTerm->pIter);
184710  for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
184711  pNext = pSyn->pSynonym;
184712  sqlite3Fts5IterClose(pSyn->pIter);
184713  fts5BufferFree((Fts5Buffer*)&pSyn[1]);
184714  sqlite3_free(pSyn);
184715  }
184716  }
184717  if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
184718  sqlite3_free(pPhrase);
184719  }
184720 }
184721 
184722 /*
184723 ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
184724 ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
184725 ** appended to it and the results returned.
184726 **
184727 ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
184728 ** NULL returned.
184729 */
184730 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
184731  Fts5Parse *pParse, /* Parse context */
184732  Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
184733  Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
184734 ){
184735  const int SZALLOC = 8;
184736  Fts5ExprNearset *pRet = 0;
184737 
184738  if( pParse->rc==SQLITE_OK ){
184739  if( pPhrase==0 ){
184740  return pNear;
184741  }
184742  if( pNear==0 ){
184743  int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
184744  pRet = sqlite3_malloc(nByte);
184745  if( pRet==0 ){
184746  pParse->rc = SQLITE_NOMEM;
184747  }else{
184748  memset(pRet, 0, nByte);
184749  }
184750  }else if( (pNear->nPhrase % SZALLOC)==0 ){
184751  int nNew = pNear->nPhrase + SZALLOC;
184752  int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
184753 
184754  pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
184755  if( pRet==0 ){
184756  pParse->rc = SQLITE_NOMEM;
184757  }
184758  }else{
184759  pRet = pNear;
184760  }
184761  }
184762 
184763  if( pRet==0 ){
184764  assert( pParse->rc!=SQLITE_OK );
184765  sqlite3Fts5ParseNearsetFree(pNear);
184766  sqlite3Fts5ParsePhraseFree(pPhrase);
184767  }else{
184768  if( pRet->nPhrase>0 ){
184769  Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
184770  assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
184771  if( pPhrase->nTerm==0 ){
184772  fts5ExprPhraseFree(pPhrase);
184773  pRet->nPhrase--;
184774  pParse->nPhrase--;
184775  pPhrase = pLast;
184776  }else if( pLast->nTerm==0 ){
184777  fts5ExprPhraseFree(pLast);
184778  pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
184779  pParse->nPhrase--;
184780  pRet->nPhrase--;
184781  }
184782  }
184783  pRet->apPhrase[pRet->nPhrase++] = pPhrase;
184784  }
184785  return pRet;
184786 }
184787 
184788 typedef struct TokenCtx TokenCtx;
184789 struct TokenCtx {
184790  Fts5ExprPhrase *pPhrase;
184791  int rc;
184792 };
184793 
184794 /*
184795 ** Callback for tokenizing terms used by ParseTerm().
184796 */
184797 static int fts5ParseTokenize(
184798  void *pContext, /* Pointer to Fts5InsertCtx object */
184799  int tflags, /* Mask of FTS5_TOKEN_* flags */
184800  const char *pToken, /* Buffer containing token */
184801  int nToken, /* Size of token in bytes */
184802  int iUnused1, /* Start offset of token */
184803  int iUnused2 /* End offset of token */
184804 ){
184805  int rc = SQLITE_OK;
184806  const int SZALLOC = 8;
184807  TokenCtx *pCtx = (TokenCtx*)pContext;
184808  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
184809 
184810  UNUSED_PARAM2(iUnused1, iUnused2);
184811 
184812  /* If an error has already occurred, this is a no-op */
184813  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
184814  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
184815 
184816  if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
184817  Fts5ExprTerm *pSyn;
184818  int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
184819  pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
184820  if( pSyn==0 ){
184821  rc = SQLITE_NOMEM;
184822  }else{
184823  memset(pSyn, 0, nByte);
184824  pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
184825  memcpy(pSyn->zTerm, pToken, nToken);
184826  pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
184827  pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
184828  }
184829  }else{
184830  Fts5ExprTerm *pTerm;
184831  if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
184832  Fts5ExprPhrase *pNew;
184833  int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
184834 
184835  pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
184836  sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
184837  );
184838  if( pNew==0 ){
184839  rc = SQLITE_NOMEM;
184840  }else{
184841  if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
184842  pCtx->pPhrase = pPhrase = pNew;
184843  pNew->nTerm = nNew - SZALLOC;
184844  }
184845  }
184846 
184847  if( rc==SQLITE_OK ){
184848  pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
184849  memset(pTerm, 0, sizeof(Fts5ExprTerm));
184850  pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
184851  }
184852  }
184853 
184854  pCtx->rc = rc;
184855  return rc;
184856 }
184857 
184858 
184859 /*
184860 ** Free the phrase object passed as the only argument.
184861 */
184862 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
184863  fts5ExprPhraseFree(pPhrase);
184864 }
184865 
184866 /*
184867 ** Free the phrase object passed as the second argument.
184868 */
184869 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
184870  if( pNear ){
184871  int i;
184872  for(i=0; i<pNear->nPhrase; i++){
184873  fts5ExprPhraseFree(pNear->apPhrase[i]);
184874  }
184875  sqlite3_free(pNear->pColset);
184876  sqlite3_free(pNear);
184877  }
184878 }
184879 
184880 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
184881  assert( pParse->pExpr==0 );
184882  pParse->pExpr = p;
184883 }
184884 
184885 /*
184886 ** This function is called by the parser to process a string token. The
184887 ** string may or may not be quoted. In any case it is tokenized and a
184888 ** phrase object consisting of all tokens returned.
184889 */
184890 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
184891  Fts5Parse *pParse, /* Parse context */
184892  Fts5ExprPhrase *pAppend, /* Phrase to append to */
184893  Fts5Token *pToken, /* String to tokenize */
184894  int bPrefix /* True if there is a trailing "*" */
184895 ){
184896  Fts5Config *pConfig = pParse->pConfig;
184897  TokenCtx sCtx; /* Context object passed to callback */
184898  int rc; /* Tokenize return code */
184899  char *z = 0;
184900 
184901  memset(&sCtx, 0, sizeof(TokenCtx));
184902  sCtx.pPhrase = pAppend;
184903 
184904  rc = fts5ParseStringFromToken(pToken, &z);
184905  if( rc==SQLITE_OK ){
184906  int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
184907  int n;
184908  sqlite3Fts5Dequote(z);
184909  n = (int)strlen(z);
184910  rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
184911  }
184912  sqlite3_free(z);
184913  if( rc || (rc = sCtx.rc) ){
184914  pParse->rc = rc;
184915  fts5ExprPhraseFree(sCtx.pPhrase);
184916  sCtx.pPhrase = 0;
184917  }else{
184918 
184919  if( pAppend==0 ){
184920  if( (pParse->nPhrase % 8)==0 ){
184921  int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
184922  Fts5ExprPhrase **apNew;
184923  apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
184924  if( apNew==0 ){
184925  pParse->rc = SQLITE_NOMEM;
184926  fts5ExprPhraseFree(sCtx.pPhrase);
184927  return 0;
184928  }
184929  pParse->apPhrase = apNew;
184930  }
184931  pParse->nPhrase++;
184932  }
184933 
184934  if( sCtx.pPhrase==0 ){
184935  /* This happens when parsing a token or quoted phrase that contains
184936  ** no token characters at all. (e.g ... MATCH '""'). */
184937  sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
184938  }else if( sCtx.pPhrase->nTerm ){
184939  sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
184940  }
184941  pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
184942  }
184943 
184944  return sCtx.pPhrase;
184945 }
184946 
184947 /*
184948 ** Create a new FTS5 expression by cloning phrase iPhrase of the
184949 ** expression passed as the second argument.
184950 */
184951 static int sqlite3Fts5ExprClonePhrase(
184952  Fts5Expr *pExpr,
184953  int iPhrase,
184954  Fts5Expr **ppNew
184955 ){
184956  int rc = SQLITE_OK; /* Return code */
184957  Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
184958  Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
184959  TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
184960 
184961  pOrig = pExpr->apExprPhrase[iPhrase];
184962  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
184963  if( rc==SQLITE_OK ){
184964  pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
184965  sizeof(Fts5ExprPhrase*));
184966  }
184967  if( rc==SQLITE_OK ){
184968  pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
184969  sizeof(Fts5ExprNode));
184970  }
184971  if( rc==SQLITE_OK ){
184972  pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
184973  sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
184974  }
184975  if( rc==SQLITE_OK ){
184976  Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
184977  if( pColsetOrig ){
184978  int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
184979  Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
184980  if( pColset ){
184981  memcpy(pColset, pColsetOrig, nByte);
184982  }
184983  pNew->pRoot->pNear->pColset = pColset;
184984  }
184985  }
184986 
184987  if( pOrig->nTerm ){
184988  int i; /* Used to iterate through phrase terms */
184989  for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
184990  int tflags = 0;
184991  Fts5ExprTerm *p;
184992  for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
184993  const char *zTerm = p->zTerm;
184994  rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
184995  0, 0);
184996  tflags = FTS5_TOKEN_COLOCATED;
184997  }
184998  if( rc==SQLITE_OK ){
184999  sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
185000  }
185001  }
185002  }else{
185003  /* This happens when parsing a token or quoted phrase that contains
185004  ** no token characters at all. (e.g ... MATCH '""'). */
185005  sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
185006  }
185007 
185008  if( rc==SQLITE_OK ){
185009  /* All the allocations succeeded. Put the expression object together. */
185010  pNew->pIndex = pExpr->pIndex;
185011  pNew->pConfig = pExpr->pConfig;
185012  pNew->nPhrase = 1;
185013  pNew->apExprPhrase[0] = sCtx.pPhrase;
185014  pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
185015  pNew->pRoot->pNear->nPhrase = 1;
185016  sCtx.pPhrase->pNode = pNew->pRoot;
185017 
185018  if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
185019  pNew->pRoot->eType = FTS5_TERM;
185020  pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
185021  }else{
185022  pNew->pRoot->eType = FTS5_STRING;
185023  pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
185024  }
185025  }else{
185026  sqlite3Fts5ExprFree(pNew);
185027  fts5ExprPhraseFree(sCtx.pPhrase);
185028  pNew = 0;
185029  }
185030 
185031  *ppNew = pNew;
185032  return rc;
185033 }
185034 
185035 
185036 /*
185037 ** Token pTok has appeared in a MATCH expression where the NEAR operator
185038 ** is expected. If token pTok does not contain "NEAR", store an error
185039 ** in the pParse object.
185040 */
185041 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
185042  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
185043  sqlite3Fts5ParseError(
185044  pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
185045  );
185046  }
185047 }
185048 
185049 static void sqlite3Fts5ParseSetDistance(
185050  Fts5Parse *pParse,
185051  Fts5ExprNearset *pNear,
185052  Fts5Token *p
185053 ){
185054  if( pNear ){
185055  int nNear = 0;
185056  int i;
185057  if( p->n ){
185058  for(i=0; i<p->n; i++){
185059  char c = (char)p->p[i];
185060  if( c<'0' || c>'9' ){
185061  sqlite3Fts5ParseError(
185062  pParse, "expected integer, got \"%.*s\"", p->n, p->p
185063  );
185064  return;
185065  }
185066  nNear = nNear * 10 + (p->p[i] - '0');
185067  }
185068  }else{
185069  nNear = FTS5_DEFAULT_NEARDIST;
185070  }
185071  pNear->nNear = nNear;
185072  }
185073 }
185074 
185075 /*
185076 ** The second argument passed to this function may be NULL, or it may be
185077 ** an existing Fts5Colset object. This function returns a pointer to
185078 ** a new colset object containing the contents of (p) with new value column
185079 ** number iCol appended.
185080 **
185081 ** If an OOM error occurs, store an error code in pParse and return NULL.
185082 ** The old colset object (if any) is not freed in this case.
185083 */
185084 static Fts5Colset *fts5ParseColset(
185085  Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
185086  Fts5Colset *p, /* Existing colset object */
185087  int iCol /* New column to add to colset object */
185088 ){
185089  int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
185090  Fts5Colset *pNew; /* New colset object to return */
185091 
185092  assert( pParse->rc==SQLITE_OK );
185093  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
185094 
185095  pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
185096  if( pNew==0 ){
185097  pParse->rc = SQLITE_NOMEM;
185098  }else{
185099  int *aiCol = pNew->aiCol;
185100  int i, j;
185101  for(i=0; i<nCol; i++){
185102  if( aiCol[i]==iCol ) return pNew;
185103  if( aiCol[i]>iCol ) break;
185104  }
185105  for(j=nCol; j>i; j--){
185106  aiCol[j] = aiCol[j-1];
185107  }
185108  aiCol[i] = iCol;
185109  pNew->nCol = nCol+1;
185110 
185111 #ifndef NDEBUG
185112  /* Check that the array is in order and contains no duplicate entries. */
185113  for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
185114 #endif
185115  }
185116 
185117  return pNew;
185118 }
185119 
185120 /*
185121 ** Allocate and return an Fts5Colset object specifying the inverse of
185122 ** the colset passed as the second argument. Free the colset passed
185123 ** as the second argument before returning.
185124 */
185125 static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
185126  Fts5Colset *pRet;
185127  int nCol = pParse->pConfig->nCol;
185128 
185129  pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
185130  sizeof(Fts5Colset) + sizeof(int)*nCol
185131  );
185132  if( pRet ){
185133  int i;
185134  int iOld = 0;
185135  for(i=0; i<nCol; i++){
185136  if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
185137  pRet->aiCol[pRet->nCol++] = i;
185138  }else{
185139  iOld++;
185140  }
185141  }
185142  }
185143 
185144  sqlite3_free(p);
185145  return pRet;
185146 }
185147 
185148 static Fts5Colset *sqlite3Fts5ParseColset(
185149  Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
185150  Fts5Colset *pColset, /* Existing colset object */
185151  Fts5Token *p
185152 ){
185153  Fts5Colset *pRet = 0;
185154  int iCol;
185155  char *z; /* Dequoted copy of token p */
185156 
185157  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
185158  if( pParse->rc==SQLITE_OK ){
185159  Fts5Config *pConfig = pParse->pConfig;
185160  sqlite3Fts5Dequote(z);
185161  for(iCol=0; iCol<pConfig->nCol; iCol++){
185162  if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
185163  }
185164  if( iCol==pConfig->nCol ){
185165  sqlite3Fts5ParseError(pParse, "no such column: %s", z);
185166  }else{
185167  pRet = fts5ParseColset(pParse, pColset, iCol);
185168  }
185169  sqlite3_free(z);
185170  }
185171 
185172  if( pRet==0 ){
185173  assert( pParse->rc!=SQLITE_OK );
185174  sqlite3_free(pColset);
185175  }
185176 
185177  return pRet;
185178 }
185179 
185180 static void sqlite3Fts5ParseSetColset(
185181  Fts5Parse *pParse,
185182  Fts5ExprNearset *pNear,
185183  Fts5Colset *pColset
185184 ){
185185  if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
185186  pParse->rc = SQLITE_ERROR;
185187  pParse->zErr = sqlite3_mprintf(
185188  "fts5: column queries are not supported (detail=none)"
185189  );
185190  sqlite3_free(pColset);
185191  return;
185192  }
185193 
185194  if( pNear ){
185195  pNear->pColset = pColset;
185196  }else{
185197  sqlite3_free(pColset);
185198  }
185199 }
185200 
185201 static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
185202  switch( pNode->eType ){
185203  case FTS5_STRING: {
185204  Fts5ExprNearset *pNear = pNode->pNear;
185205  if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
185206  && pNear->apPhrase[0]->aTerm[0].pSynonym==0
185207  ){
185208  pNode->eType = FTS5_TERM;
185209  pNode->xNext = fts5ExprNodeNext_TERM;
185210  }else{
185211  pNode->xNext = fts5ExprNodeNext_STRING;
185212  }
185213  break;
185214  };
185215 
185216  case FTS5_OR: {
185217  pNode->xNext = fts5ExprNodeNext_OR;
185218  break;
185219  };
185220 
185221  case FTS5_AND: {
185222  pNode->xNext = fts5ExprNodeNext_AND;
185223  break;
185224  };
185225 
185226  default: assert( pNode->eType==FTS5_NOT ); {
185227  pNode->xNext = fts5ExprNodeNext_NOT;
185228  break;
185229  };
185230  }
185231 }
185232 
185233 static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
185234  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
185235  int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
185236  memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
185237  p->nChild += pSub->nChild;
185238  sqlite3_free(pSub);
185239  }else{
185240  p->apChild[p->nChild++] = pSub;
185241  }
185242 }
185243 
185244 /*
185245 ** Allocate and return a new expression object. If anything goes wrong (i.e.
185246 ** OOM error), leave an error code in pParse and return NULL.
185247 */
185248 static Fts5ExprNode *sqlite3Fts5ParseNode(
185249  Fts5Parse *pParse, /* Parse context */
185250  int eType, /* FTS5_STRING, AND, OR or NOT */
185251  Fts5ExprNode *pLeft, /* Left hand child expression */
185252  Fts5ExprNode *pRight, /* Right hand child expression */
185253  Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
185254 ){
185255  Fts5ExprNode *pRet = 0;
185256 
185257  if( pParse->rc==SQLITE_OK ){
185258  int nChild = 0; /* Number of children of returned node */
185259  int nByte; /* Bytes of space to allocate for this node */
185260 
185261  assert( (eType!=FTS5_STRING && !pNear)
185262  || (eType==FTS5_STRING && !pLeft && !pRight)
185263  );
185264  if( eType==FTS5_STRING && pNear==0 ) return 0;
185265  if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
185266  if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
185267 
185268  if( eType==FTS5_NOT ){
185269  nChild = 2;
185270  }else if( eType==FTS5_AND || eType==FTS5_OR ){
185271  nChild = 2;
185272  if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
185273  if( pRight->eType==eType ) nChild += pRight->nChild-1;
185274  }
185275 
185276  nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
185277  pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
185278 
185279  if( pRet ){
185280  pRet->eType = eType;
185281  pRet->pNear = pNear;
185282  fts5ExprAssignXNext(pRet);
185283  if( eType==FTS5_STRING ){
185284  int iPhrase;
185285  for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
185286  pNear->apPhrase[iPhrase]->pNode = pRet;
185287  if( pNear->apPhrase[iPhrase]->nTerm==0 ){
185288  pRet->xNext = 0;
185289  pRet->eType = FTS5_EOF;
185290  }
185291  }
185292 
185293  if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
185294  && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
185295  ){
185296  assert( pParse->rc==SQLITE_OK );
185297  pParse->rc = SQLITE_ERROR;
185298  assert( pParse->zErr==0 );
185299  pParse->zErr = sqlite3_mprintf(
185300  "fts5: %s queries are not supported (detail!=full)",
185301  pNear->nPhrase==1 ? "phrase": "NEAR"
185302  );
185303  sqlite3_free(pRet);
185304  pRet = 0;
185305  }
185306 
185307  }else{
185308  fts5ExprAddChildren(pRet, pLeft);
185309  fts5ExprAddChildren(pRet, pRight);
185310  }
185311  }
185312  }
185313 
185314  if( pRet==0 ){
185315  assert( pParse->rc!=SQLITE_OK );
185316  sqlite3Fts5ParseNodeFree(pLeft);
185317  sqlite3Fts5ParseNodeFree(pRight);
185318  sqlite3Fts5ParseNearsetFree(pNear);
185319  }
185320  return pRet;
185321 }
185322 
185323 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
185324  Fts5Parse *pParse, /* Parse context */
185325  Fts5ExprNode *pLeft, /* Left hand child expression */
185326  Fts5ExprNode *pRight /* Right hand child expression */
185327 ){
185328  Fts5ExprNode *pRet = 0;
185329  Fts5ExprNode *pPrev;
185330 
185331  if( pParse->rc ){
185332  sqlite3Fts5ParseNodeFree(pLeft);
185333  sqlite3Fts5ParseNodeFree(pRight);
185334  }else{
185335 
185336  assert( pLeft->eType==FTS5_STRING
185337  || pLeft->eType==FTS5_TERM
185338  || pLeft->eType==FTS5_EOF
185339  || pLeft->eType==FTS5_AND
185340  );
185341  assert( pRight->eType==FTS5_STRING
185342  || pRight->eType==FTS5_TERM
185343  || pRight->eType==FTS5_EOF
185344  );
185345 
185346  if( pLeft->eType==FTS5_AND ){
185347  pPrev = pLeft->apChild[pLeft->nChild-1];
185348  }else{
185349  pPrev = pLeft;
185350  }
185351  assert( pPrev->eType==FTS5_STRING
185352  || pPrev->eType==FTS5_TERM
185353  || pPrev->eType==FTS5_EOF
185354  );
185355 
185356  if( pRight->eType==FTS5_EOF ){
185357  assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
185358  sqlite3Fts5ParseNodeFree(pRight);
185359  pRet = pLeft;
185360  pParse->nPhrase--;
185361  }
185362  else if( pPrev->eType==FTS5_EOF ){
185363  Fts5ExprPhrase **ap;
185364 
185365  if( pPrev==pLeft ){
185366  pRet = pRight;
185367  }else{
185368  pLeft->apChild[pLeft->nChild-1] = pRight;
185369  pRet = pLeft;
185370  }
185371 
185372  ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
185373  assert( ap[0]==pPrev->pNear->apPhrase[0] );
185374  memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
185375  pParse->nPhrase--;
185376 
185377  sqlite3Fts5ParseNodeFree(pPrev);
185378  }
185379  else{
185380  pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
185381  }
185382  }
185383 
185384  return pRet;
185385 }
185386 
185387 static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
185388  int nByte = 0;
185389  Fts5ExprTerm *p;
185390  char *zQuoted;
185391 
185392  /* Determine the maximum amount of space required. */
185393  for(p=pTerm; p; p=p->pSynonym){
185394  nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
185395  }
185396  zQuoted = sqlite3_malloc(nByte);
185397 
185398  if( zQuoted ){
185399  int i = 0;
185400  for(p=pTerm; p; p=p->pSynonym){
185401  char *zIn = p->zTerm;
185402  zQuoted[i++] = '"';
185403  while( *zIn ){
185404  if( *zIn=='"' ) zQuoted[i++] = '"';
185405  zQuoted[i++] = *zIn++;
185406  }
185407  zQuoted[i++] = '"';
185408  if( p->pSynonym ) zQuoted[i++] = '|';
185409  }
185410  if( pTerm->bPrefix ){
185411  zQuoted[i++] = ' ';
185412  zQuoted[i++] = '*';
185413  }
185414  zQuoted[i++] = '\0';
185415  }
185416  return zQuoted;
185417 }
185418 
185419 static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
185420  char *zNew;
185421  va_list ap;
185422  va_start(ap, zFmt);
185423  zNew = sqlite3_vmprintf(zFmt, ap);
185424  va_end(ap);
185425  if( zApp && zNew ){
185426  char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
185427  sqlite3_free(zNew);
185428  zNew = zNew2;
185429  }
185430  sqlite3_free(zApp);
185431  return zNew;
185432 }
185433 
185434 /*
185435 ** Compose a tcl-readable representation of expression pExpr. Return a
185436 ** pointer to a buffer containing that representation. It is the
185437 ** responsibility of the caller to at some point free the buffer using
185438 ** sqlite3_free().
185439 */
185440 static char *fts5ExprPrintTcl(
185441  Fts5Config *pConfig,
185442  const char *zNearsetCmd,
185443  Fts5ExprNode *pExpr
185444 ){
185445  char *zRet = 0;
185446  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
185447  Fts5ExprNearset *pNear = pExpr->pNear;
185448  int i;
185449  int iTerm;
185450 
185451  zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
185452  if( zRet==0 ) return 0;
185453  if( pNear->pColset ){
185454  int *aiCol = pNear->pColset->aiCol;
185455  int nCol = pNear->pColset->nCol;
185456  if( nCol==1 ){
185457  zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
185458  }else{
185459  zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
185460  for(i=1; i<pNear->pColset->nCol; i++){
185461  zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
185462  }
185463  zRet = fts5PrintfAppend(zRet, "} ");
185464  }
185465  if( zRet==0 ) return 0;
185466  }
185467 
185468  if( pNear->nPhrase>1 ){
185469  zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
185470  if( zRet==0 ) return 0;
185471  }
185472 
185473  zRet = fts5PrintfAppend(zRet, "--");
185474  if( zRet==0 ) return 0;
185475 
185476  for(i=0; i<pNear->nPhrase; i++){
185477  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
185478 
185479  zRet = fts5PrintfAppend(zRet, " {");
185480  for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
185481  char *zTerm = pPhrase->aTerm[iTerm].zTerm;
185482  zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
185483  if( pPhrase->aTerm[iTerm].bPrefix ){
185484  zRet = fts5PrintfAppend(zRet, "*");
185485  }
185486  }
185487 
185488  if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
185489  if( zRet==0 ) return 0;
185490  }
185491 
185492  }else{
185493  char const *zOp = 0;
185494  int i;
185495  switch( pExpr->eType ){
185496  case FTS5_AND: zOp = "AND"; break;
185497  case FTS5_NOT: zOp = "NOT"; break;
185498  default:
185499  assert( pExpr->eType==FTS5_OR );
185500  zOp = "OR";
185501  break;
185502  }
185503 
185504  zRet = sqlite3_mprintf("%s", zOp);
185505  for(i=0; zRet && i<pExpr->nChild; i++){
185506  char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
185507  if( !z ){
185508  sqlite3_free(zRet);
185509  zRet = 0;
185510  }else{
185511  zRet = fts5PrintfAppend(zRet, " [%z]", z);
185512  }
185513  }
185514  }
185515 
185516  return zRet;
185517 }
185518 
185519 static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
185520  char *zRet = 0;
185521  if( pExpr->eType==0 ){
185522  return sqlite3_mprintf("\"\"");
185523  }else
185524  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
185525  Fts5ExprNearset *pNear = pExpr->pNear;
185526  int i;
185527  int iTerm;
185528 
185529  if( pNear->pColset ){
185530  int iCol = pNear->pColset->aiCol[0];
185531  zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
185532  if( zRet==0 ) return 0;
185533  }
185534 
185535  if( pNear->nPhrase>1 ){
185536  zRet = fts5PrintfAppend(zRet, "NEAR(");
185537  if( zRet==0 ) return 0;
185538  }
185539 
185540  for(i=0; i<pNear->nPhrase; i++){
185541  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
185542  if( i!=0 ){
185543  zRet = fts5PrintfAppend(zRet, " ");
185544  if( zRet==0 ) return 0;
185545  }
185546  for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
185547  char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
185548  if( zTerm ){
185549  zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
185550  sqlite3_free(zTerm);
185551  }
185552  if( zTerm==0 || zRet==0 ){
185553  sqlite3_free(zRet);
185554  return 0;
185555  }
185556  }
185557  }
185558 
185559  if( pNear->nPhrase>1 ){
185560  zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
185561  if( zRet==0 ) return 0;
185562  }
185563 
185564  }else{
185565  char const *zOp = 0;
185566  int i;
185567 
185568  switch( pExpr->eType ){
185569  case FTS5_AND: zOp = " AND "; break;
185570  case FTS5_NOT: zOp = " NOT "; break;
185571  default:
185572  assert( pExpr->eType==FTS5_OR );
185573  zOp = " OR ";
185574  break;
185575  }
185576 
185577  for(i=0; i<pExpr->nChild; i++){
185578  char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
185579  if( z==0 ){
185580  sqlite3_free(zRet);
185581  zRet = 0;
185582  }else{
185583  int e = pExpr->apChild[i]->eType;
185584  int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
185585  zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
185586  (i==0 ? "" : zOp),
185587  (b?"(":""), z, (b?")":"")
185588  );
185589  }
185590  if( zRet==0 ) break;
185591  }
185592  }
185593 
185594  return zRet;
185595 }
185596 
185597 /*
185598 ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
185599 ** and fts5_expr_tcl() (bTcl!=0).
185600 */
185601 static void fts5ExprFunction(
185602  sqlite3_context *pCtx, /* Function call context */
185603  int nArg, /* Number of args */
185604  sqlite3_value **apVal, /* Function arguments */
185605  int bTcl
185606 ){
185607  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
185608  sqlite3 *db = sqlite3_context_db_handle(pCtx);
185609  const char *zExpr = 0;
185610  char *zErr = 0;
185611  Fts5Expr *pExpr = 0;
185612  int rc;
185613  int i;
185614 
185615  const char **azConfig; /* Array of arguments for Fts5Config */
185616  const char *zNearsetCmd = "nearset";
185617  int nConfig; /* Size of azConfig[] */
185618  Fts5Config *pConfig = 0;
185619  int iArg = 1;
185620 
185621  if( nArg<1 ){
185622  zErr = sqlite3_mprintf("wrong number of arguments to function %s",
185623  bTcl ? "fts5_expr_tcl" : "fts5_expr"
185624  );
185625  sqlite3_result_error(pCtx, zErr, -1);
185626  sqlite3_free(zErr);
185627  return;
185628  }
185629 
185630  if( bTcl && nArg>1 ){
185631  zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
185632  iArg = 2;
185633  }
185634 
185635  nConfig = 3 + (nArg-iArg);
185636  azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
185637  if( azConfig==0 ){
185638  sqlite3_result_error_nomem(pCtx);
185639  return;
185640  }
185641  azConfig[0] = 0;
185642  azConfig[1] = "main";
185643  azConfig[2] = "tbl";
185644  for(i=3; iArg<nArg; iArg++){
185645  azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
185646  }
185647 
185648  zExpr = (const char*)sqlite3_value_text(apVal[0]);
185649 
185650  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
185651  if( rc==SQLITE_OK ){
185652  rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
185653  }
185654  if( rc==SQLITE_OK ){
185655  char *zText;
185656  if( pExpr->pRoot->xNext==0 ){
185657  zText = sqlite3_mprintf("");
185658  }else if( bTcl ){
185659  zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
185660  }else{
185661  zText = fts5ExprPrint(pConfig, pExpr->pRoot);
185662  }
185663  if( zText==0 ){
185664  rc = SQLITE_NOMEM;
185665  }else{
185666  sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
185667  sqlite3_free(zText);
185668  }
185669  }
185670 
185671  if( rc!=SQLITE_OK ){
185672  if( zErr ){
185673  sqlite3_result_error(pCtx, zErr, -1);
185674  sqlite3_free(zErr);
185675  }else{
185676  sqlite3_result_error_code(pCtx, rc);
185677  }
185678  }
185679  sqlite3_free((void *)azConfig);
185680  sqlite3Fts5ConfigFree(pConfig);
185681  sqlite3Fts5ExprFree(pExpr);
185682 }
185683 
185684 static void fts5ExprFunctionHr(
185685  sqlite3_context *pCtx, /* Function call context */
185686  int nArg, /* Number of args */
185687  sqlite3_value **apVal /* Function arguments */
185688 ){
185689  fts5ExprFunction(pCtx, nArg, apVal, 0);
185690 }
185691 static void fts5ExprFunctionTcl(
185692  sqlite3_context *pCtx, /* Function call context */
185693  int nArg, /* Number of args */
185694  sqlite3_value **apVal /* Function arguments */
185695 ){
185696  fts5ExprFunction(pCtx, nArg, apVal, 1);
185697 }
185698 
185699 /*
185700 ** The implementation of an SQLite user-defined-function that accepts a
185701 ** single integer as an argument. If the integer is an alpha-numeric
185702 ** unicode code point, 1 is returned. Otherwise 0.
185703 */
185704 static void fts5ExprIsAlnum(
185705  sqlite3_context *pCtx, /* Function call context */
185706  int nArg, /* Number of args */
185707  sqlite3_value **apVal /* Function arguments */
185708 ){
185709  int iCode;
185710  if( nArg!=1 ){
185711  sqlite3_result_error(pCtx,
185712  "wrong number of arguments to function fts5_isalnum", -1
185713  );
185714  return;
185715  }
185716  iCode = sqlite3_value_int(apVal[0]);
185717  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
185718 }
185719 
185720 static void fts5ExprFold(
185721  sqlite3_context *pCtx, /* Function call context */
185722  int nArg, /* Number of args */
185723  sqlite3_value **apVal /* Function arguments */
185724 ){
185725  if( nArg!=1 && nArg!=2 ){
185726  sqlite3_result_error(pCtx,
185727  "wrong number of arguments to function fts5_fold", -1
185728  );
185729  }else{
185730  int iCode;
185731  int bRemoveDiacritics = 0;
185732  iCode = sqlite3_value_int(apVal[0]);
185733  if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
185734  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
185735  }
185736 }
185737 
185738 /*
185739 ** This is called during initialization to register the fts5_expr() scalar
185740 ** UDF with the SQLite handle passed as the only argument.
185741 */
185742 static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
185743  struct Fts5ExprFunc {
185744  const char *z;
185745  void (*x)(sqlite3_context*,int,sqlite3_value**);
185746  } aFunc[] = {
185747  { "fts5_expr", fts5ExprFunctionHr },
185748  { "fts5_expr_tcl", fts5ExprFunctionTcl },
185749  { "fts5_isalnum", fts5ExprIsAlnum },
185750  { "fts5_fold", fts5ExprFold },
185751  };
185752  int i;
185753  int rc = SQLITE_OK;
185754  void *pCtx = (void*)pGlobal;
185755 
185756  for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
185757  struct Fts5ExprFunc *p = &aFunc[i];
185758  rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
185759  }
185760 
185761  /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
185762 #ifndef NDEBUG
185763  (void)sqlite3Fts5ParserTrace;
185764 #endif
185765 
185766  return rc;
185767 }
185768 
185769 /*
185770 ** Return the number of phrases in expression pExpr.
185771 */
185772 static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
185773  return (pExpr ? pExpr->nPhrase : 0);
185774 }
185775 
185776 /*
185777 ** Return the number of terms in the iPhrase'th phrase in pExpr.
185778 */
185779 static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
185780  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
185781  return pExpr->apExprPhrase[iPhrase]->nTerm;
185782 }
185783 
185784 /*
185785 ** This function is used to access the current position list for phrase
185786 ** iPhrase.
185787 */
185788 static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
185789  int nRet;
185790  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
185791  Fts5ExprNode *pNode = pPhrase->pNode;
185792  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
185793  *pa = pPhrase->poslist.p;
185794  nRet = pPhrase->poslist.n;
185795  }else{
185796  *pa = 0;
185797  nRet = 0;
185798  }
185799  return nRet;
185800 }
185801 
185802 struct Fts5PoslistPopulator {
185803  Fts5PoslistWriter writer;
185804  int bOk; /* True if ok to populate */
185805  int bMiss;
185806 };
185807 
185808 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
185809  Fts5PoslistPopulator *pRet;
185810  pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
185811  if( pRet ){
185812  int i;
185813  memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
185814  for(i=0; i<pExpr->nPhrase; i++){
185815  Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
185816  Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
185817  assert( pExpr->apExprPhrase[i]->nTerm==1 );
185818  if( bLive &&
185819  (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
185820  ){
185821  pRet[i].bMiss = 1;
185822  }else{
185823  pBuf->n = 0;
185824  }
185825  }
185826  }
185827  return pRet;
185828 }
185829 
185830 struct Fts5ExprCtx {
185831  Fts5Expr *pExpr;
185832  Fts5PoslistPopulator *aPopulator;
185833  i64 iOff;
185834 };
185835 typedef struct Fts5ExprCtx Fts5ExprCtx;
185836 
185837 /*
185838 ** TODO: Make this more efficient!
185839 */
185840 static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
185841  int i;
185842  for(i=0; i<pColset->nCol; i++){
185843  if( pColset->aiCol[i]==iCol ) return 1;
185844  }
185845  return 0;
185846 }
185847 
185848 static int fts5ExprPopulatePoslistsCb(
185849  void *pCtx, /* Copy of 2nd argument to xTokenize() */
185850  int tflags, /* Mask of FTS5_TOKEN_* flags */
185851  const char *pToken, /* Pointer to buffer containing token */
185852  int nToken, /* Size of token in bytes */
185853  int iUnused1, /* Byte offset of token within input text */
185854  int iUnused2 /* Byte offset of end of token within input text */
185855 ){
185856  Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
185857  Fts5Expr *pExpr = p->pExpr;
185858  int i;
185859 
185860  UNUSED_PARAM2(iUnused1, iUnused2);
185861 
185862  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
185863  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
185864  for(i=0; i<pExpr->nPhrase; i++){
185865  Fts5ExprTerm *pTerm;
185866  if( p->aPopulator[i].bOk==0 ) continue;
185867  for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
185868  int nTerm = (int)strlen(pTerm->zTerm);
185869  if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
185870  && memcmp(pTerm->zTerm, pToken, nTerm)==0
185871  ){
185872  int rc = sqlite3Fts5PoslistWriterAppend(
185873  &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
185874  );
185875  if( rc ) return rc;
185876  break;
185877  }
185878  }
185879  }
185880  return SQLITE_OK;
185881 }
185882 
185883 static int sqlite3Fts5ExprPopulatePoslists(
185884  Fts5Config *pConfig,
185885  Fts5Expr *pExpr,
185886  Fts5PoslistPopulator *aPopulator,
185887  int iCol,
185888  const char *z, int n
185889 ){
185890  int i;
185891  Fts5ExprCtx sCtx;
185892  sCtx.pExpr = pExpr;
185893  sCtx.aPopulator = aPopulator;
185894  sCtx.iOff = (((i64)iCol) << 32) - 1;
185895 
185896  for(i=0; i<pExpr->nPhrase; i++){
185897  Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
185898  Fts5Colset *pColset = pNode->pNear->pColset;
185899  if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
185900  || aPopulator[i].bMiss
185901  ){
185902  aPopulator[i].bOk = 0;
185903  }else{
185904  aPopulator[i].bOk = 1;
185905  }
185906  }
185907 
185908  return sqlite3Fts5Tokenize(pConfig,
185909  FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
185910  );
185911 }
185912 
185913 static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
185914  if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
185915  pNode->pNear->apPhrase[0]->poslist.n = 0;
185916  }else{
185917  int i;
185918  for(i=0; i<pNode->nChild; i++){
185919  fts5ExprClearPoslists(pNode->apChild[i]);
185920  }
185921  }
185922 }
185923 
185924 static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
185925  pNode->iRowid = iRowid;
185926  pNode->bEof = 0;
185927  switch( pNode->eType ){
185928  case FTS5_TERM:
185929  case FTS5_STRING:
185930  return (pNode->pNear->apPhrase[0]->poslist.n>0);
185931 
185932  case FTS5_AND: {
185933  int i;
185934  for(i=0; i<pNode->nChild; i++){
185935  if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
185936  fts5ExprClearPoslists(pNode);
185937  return 0;
185938  }
185939  }
185940  break;
185941  }
185942 
185943  case FTS5_OR: {
185944  int i;
185945  int bRet = 0;
185946  for(i=0; i<pNode->nChild; i++){
185947  if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
185948  bRet = 1;
185949  }
185950  }
185951  return bRet;
185952  }
185953 
185954  default: {
185955  assert( pNode->eType==FTS5_NOT );
185956  if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
185957  || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
185958  ){
185959  fts5ExprClearPoslists(pNode);
185960  return 0;
185961  }
185962  break;
185963  }
185964  }
185965  return 1;
185966 }
185967 
185968 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
185969  fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
185970 }
185971 
185972 /*
185973 ** This function is only called for detail=columns tables.
185974 */
185975 static int sqlite3Fts5ExprPhraseCollist(
185976  Fts5Expr *pExpr,
185977  int iPhrase,
185978  const u8 **ppCollist,
185979  int *pnCollist
185980 ){
185981  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
185982  Fts5ExprNode *pNode = pPhrase->pNode;
185983  int rc = SQLITE_OK;
185984 
185985  assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
185986  assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
185987 
185988  if( pNode->bEof==0
185989  && pNode->iRowid==pExpr->pRoot->iRowid
185990  && pPhrase->poslist.n>0
185991  ){
185992  Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
185993  if( pTerm->pSynonym ){
185994  Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
185995  rc = fts5ExprSynonymList(
185996  pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
185997  );
185998  }else{
185999  *ppCollist = pPhrase->aTerm[0].pIter->pData;
186000  *pnCollist = pPhrase->aTerm[0].pIter->nData;
186001  }
186002  }else{
186003  *ppCollist = 0;
186004  *pnCollist = 0;
186005  }
186006 
186007  return rc;
186008 }
186009 
186010 
186011 /*
186012 ** 2014 August 11
186013 **
186014 ** The author disclaims copyright to this source code. In place of
186015 ** a legal notice, here is a blessing:
186016 **
186017 ** May you do good and not evil.
186018 ** May you find forgiveness for yourself and forgive others.
186019 ** May you share freely, never taking more than you give.
186020 **
186021 ******************************************************************************
186022 **
186023 */
186024 
186025 
186026 
186027 /* #include "fts5Int.h" */
186028 
186029 typedef struct Fts5HashEntry Fts5HashEntry;
186030 
186031 /*
186032 ** This file contains the implementation of an in-memory hash table used
186033 ** to accumuluate "term -> doclist" content before it is flused to a level-0
186034 ** segment.
186035 */
186036 
186037 
186038 struct Fts5Hash {
186039  int eDetail; /* Copy of Fts5Config.eDetail */
186040  int *pnByte; /* Pointer to bytes counter */
186041  int nEntry; /* Number of entries currently in hash */
186042  int nSlot; /* Size of aSlot[] array */
186043  Fts5HashEntry *pScan; /* Current ordered scan item */
186044  Fts5HashEntry **aSlot; /* Array of hash slots */
186045 };
186046 
186047 /*
186048 ** Each entry in the hash table is represented by an object of the
186049 ** following type. Each object, its key (zKey[]) and its current data
186050 ** are stored in a single memory allocation. The position list data
186051 ** immediately follows the key data in memory.
186052 **
186053 ** The data that follows the key is in a similar, but not identical format
186054 ** to the doclist data stored in the database. It is:
186055 **
186056 ** * Rowid, as a varint
186057 ** * Position list, without 0x00 terminator.
186058 ** * Size of previous position list and rowid, as a 4 byte
186059 ** big-endian integer.
186060 **
186061 ** iRowidOff:
186062 ** Offset of last rowid written to data area. Relative to first byte of
186063 ** structure.
186064 **
186065 ** nData:
186066 ** Bytes of data written since iRowidOff.
186067 */
186068 struct Fts5HashEntry {
186069  Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
186070  Fts5HashEntry *pScanNext; /* Next entry in sorted order */
186071 
186072  int nAlloc; /* Total size of allocation */
186073  int iSzPoslist; /* Offset of space for 4-byte poslist size */
186074  int nData; /* Total bytes of data (incl. structure) */
186075  int nKey; /* Length of zKey[] in bytes */
186076  u8 bDel; /* Set delete-flag @ iSzPoslist */
186077  u8 bContent; /* Set content-flag (detail=none mode) */
186078  i16 iCol; /* Column of last value written */
186079  int iPos; /* Position of last value written */
186080  i64 iRowid; /* Rowid of last value written */
186081  char zKey[8]; /* Nul-terminated entry key */
186082 };
186083 
186084 /*
186085 ** Size of Fts5HashEntry without the zKey[] array.
186086 */
186087 #define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
186088 
186089 
186090 
186091 /*
186092 ** Allocate a new hash table.
186093 */
186094 static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
186095  int rc = SQLITE_OK;
186096  Fts5Hash *pNew;
186097 
186098  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
186099  if( pNew==0 ){
186100  rc = SQLITE_NOMEM;
186101  }else{
186102  int nByte;
186103  memset(pNew, 0, sizeof(Fts5Hash));
186104  pNew->pnByte = pnByte;
186105  pNew->eDetail = pConfig->eDetail;
186106 
186107  pNew->nSlot = 1024;
186108  nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
186109  pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
186110  if( pNew->aSlot==0 ){
186111  sqlite3_free(pNew);
186112  *ppNew = 0;
186113  rc = SQLITE_NOMEM;
186114  }else{
186115  memset(pNew->aSlot, 0, nByte);
186116  }
186117  }
186118  return rc;
186119 }
186120 
186121 /*
186122 ** Free a hash table object.
186123 */
186124 static void sqlite3Fts5HashFree(Fts5Hash *pHash){
186125  if( pHash ){
186126  sqlite3Fts5HashClear(pHash);
186127  sqlite3_free(pHash->aSlot);
186128  sqlite3_free(pHash);
186129  }
186130 }
186131 
186132 /*
186133 ** Empty (but do not delete) a hash table.
186134 */
186135 static void sqlite3Fts5HashClear(Fts5Hash *pHash){
186136  int i;
186137  for(i=0; i<pHash->nSlot; i++){
186138  Fts5HashEntry *pNext;
186139  Fts5HashEntry *pSlot;
186140  for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
186141  pNext = pSlot->pHashNext;
186142  sqlite3_free(pSlot);
186143  }
186144  }
186145  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
186146  pHash->nEntry = 0;
186147 }
186148 
186149 static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
186150  int i;
186151  unsigned int h = 13;
186152  for(i=n-1; i>=0; i--){
186153  h = (h << 3) ^ h ^ p[i];
186154  }
186155  return (h % nSlot);
186156 }
186157 
186158 static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
186159  int i;
186160  unsigned int h = 13;
186161  for(i=n-1; i>=0; i--){
186162  h = (h << 3) ^ h ^ p[i];
186163  }
186164  h = (h << 3) ^ h ^ b;
186165  return (h % nSlot);
186166 }
186167 
186168 /*
186169 ** Resize the hash table by doubling the number of slots.
186170 */
186171 static int fts5HashResize(Fts5Hash *pHash){
186172  int nNew = pHash->nSlot*2;
186173  int i;
186174  Fts5HashEntry **apNew;
186175  Fts5HashEntry **apOld = pHash->aSlot;
186176 
186177  apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
186178  if( !apNew ) return SQLITE_NOMEM;
186179  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
186180 
186181  for(i=0; i<pHash->nSlot; i++){
186182  while( apOld[i] ){
186183  int iHash;
186184  Fts5HashEntry *p = apOld[i];
186185  apOld[i] = p->pHashNext;
186186  iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey));
186187  p->pHashNext = apNew[iHash];
186188  apNew[iHash] = p;
186189  }
186190  }
186191 
186192  sqlite3_free(apOld);
186193  pHash->nSlot = nNew;
186194  pHash->aSlot = apNew;
186195  return SQLITE_OK;
186196 }
186197 
186198 static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
186199  if( p->iSzPoslist ){
186200  u8 *pPtr = (u8*)p;
186201  if( pHash->eDetail==FTS5_DETAIL_NONE ){
186202  assert( p->nData==p->iSzPoslist );
186203  if( p->bDel ){
186204  pPtr[p->nData++] = 0x00;
186205  if( p->bContent ){
186206  pPtr[p->nData++] = 0x00;
186207  }
186208  }
186209  }else{
186210  int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
186211  int nPos = nSz*2 + p->bDel; /* Value of nPos field */
186212 
186213  assert( p->bDel==0 || p->bDel==1 );
186214  if( nPos<=127 ){
186215  pPtr[p->iSzPoslist] = (u8)nPos;
186216  }else{
186217  int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
186218  memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
186219  sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
186220  p->nData += (nByte-1);
186221  }
186222  }
186223 
186224  p->iSzPoslist = 0;
186225  p->bDel = 0;
186226  p->bContent = 0;
186227  }
186228 }
186229 
186230 /*
186231 ** Add an entry to the in-memory hash table. The key is the concatenation
186232 ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
186233 **
186234 ** (bByte || pToken) -> (iRowid,iCol,iPos)
186235 **
186236 ** Or, if iCol is negative, then the value is a delete marker.
186237 */
186238 static int sqlite3Fts5HashWrite(
186239  Fts5Hash *pHash,
186240  i64 iRowid, /* Rowid for this entry */
186241  int iCol, /* Column token appears in (-ve -> delete) */
186242  int iPos, /* Position of token within column */
186243  char bByte, /* First byte of token */
186244  const char *pToken, int nToken /* Token to add or remove to or from index */
186245 ){
186246  unsigned int iHash;
186247  Fts5HashEntry *p;
186248  u8 *pPtr;
186249  int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
186250  int bNew; /* If non-delete entry should be written */
186251 
186252  bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
186253 
186254  /* Attempt to locate an existing hash entry */
186255  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
186256  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
186257  if( p->zKey[0]==bByte
186258  && p->nKey==nToken
186259  && memcmp(&p->zKey[1], pToken, nToken)==0
186260  ){
186261  break;
186262  }
186263  }
186264 
186265  /* If an existing hash entry cannot be found, create a new one. */
186266  if( p==0 ){
186267  /* Figure out how much space to allocate */
186268  int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
186269  if( nByte<128 ) nByte = 128;
186270 
186271  /* Grow the Fts5Hash.aSlot[] array if necessary. */
186272  if( (pHash->nEntry*2)>=pHash->nSlot ){
186273  int rc = fts5HashResize(pHash);
186274  if( rc!=SQLITE_OK ) return rc;
186275  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
186276  }
186277 
186278  /* Allocate new Fts5HashEntry and add it to the hash table. */
186279  p = (Fts5HashEntry*)sqlite3_malloc(nByte);
186280  if( !p ) return SQLITE_NOMEM;
186281  memset(p, 0, FTS5_HASHENTRYSIZE);
186282  p->nAlloc = nByte;
186283  p->zKey[0] = bByte;
186284  memcpy(&p->zKey[1], pToken, nToken);
186285  assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
186286  p->nKey = nToken;
186287  p->zKey[nToken+1] = '\0';
186288  p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
186289  p->pHashNext = pHash->aSlot[iHash];
186290  pHash->aSlot[iHash] = p;
186291  pHash->nEntry++;
186292 
186293  /* Add the first rowid field to the hash-entry */
186294  p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
186295  p->iRowid = iRowid;
186296 
186297  p->iSzPoslist = p->nData;
186298  if( pHash->eDetail!=FTS5_DETAIL_NONE ){
186299  p->nData += 1;
186300  p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
186301  }
186302 
186303  nIncr += p->nData;
186304  }else{
186305 
186306  /* Appending to an existing hash-entry. Check that there is enough
186307  ** space to append the largest possible new entry. Worst case scenario
186308  ** is:
186309  **
186310  ** + 9 bytes for a new rowid,
186311  ** + 4 byte reserved for the "poslist size" varint.
186312  ** + 1 byte for a "new column" byte,
186313  ** + 3 bytes for a new column number (16-bit max) as a varint,
186314  ** + 5 bytes for the new position offset (32-bit max).
186315  */
186316  if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
186317  int nNew = p->nAlloc * 2;
186318  Fts5HashEntry *pNew;
186319  Fts5HashEntry **pp;
186320  pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
186321  if( pNew==0 ) return SQLITE_NOMEM;
186322  pNew->nAlloc = nNew;
186323  for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
186324  *pp = pNew;
186325  p = pNew;
186326  }
186327  nIncr -= p->nData;
186328  }
186329  assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
186330 
186331  pPtr = (u8*)p;
186332 
186333  /* If this is a new rowid, append the 4-byte size field for the previous
186334  ** entry, and the new rowid for this entry. */
186335  if( iRowid!=p->iRowid ){
186336  fts5HashAddPoslistSize(pHash, p);
186337  p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
186338  p->iRowid = iRowid;
186339  bNew = 1;
186340  p->iSzPoslist = p->nData;
186341  if( pHash->eDetail!=FTS5_DETAIL_NONE ){
186342  p->nData += 1;
186343  p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
186344  p->iPos = 0;
186345  }
186346  }
186347 
186348  if( iCol>=0 ){
186349  if( pHash->eDetail==FTS5_DETAIL_NONE ){
186350  p->bContent = 1;
186351  }else{
186352  /* Append a new column value, if necessary */
186353  assert( iCol>=p->iCol );
186354  if( iCol!=p->iCol ){
186355  if( pHash->eDetail==FTS5_DETAIL_FULL ){
186356  pPtr[p->nData++] = 0x01;
186357  p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
186358  p->iCol = (i16)iCol;
186359  p->iPos = 0;
186360  }else{
186361  bNew = 1;
186362  p->iCol = (i16)(iPos = iCol);
186363  }
186364  }
186365 
186366  /* Append the new position offset, if necessary */
186367  if( bNew ){
186368  p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
186369  p->iPos = iPos;
186370  }
186371  }
186372  }else{
186373  /* This is a delete. Set the delete flag. */
186374  p->bDel = 1;
186375  }
186376 
186377  nIncr += p->nData;
186378  *pHash->pnByte += nIncr;
186379  return SQLITE_OK;
186380 }
186381 
186382 
186383 /*
186384 ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
186385 ** each sorted in key order. This function merges the two lists into a
186386 ** single list and returns a pointer to its first element.
186387 */
186388 static Fts5HashEntry *fts5HashEntryMerge(
186389  Fts5HashEntry *pLeft,
186390  Fts5HashEntry *pRight
186391 ){
186392  Fts5HashEntry *p1 = pLeft;
186393  Fts5HashEntry *p2 = pRight;
186394  Fts5HashEntry *pRet = 0;
186395  Fts5HashEntry **ppOut = &pRet;
186396 
186397  while( p1 || p2 ){
186398  if( p1==0 ){
186399  *ppOut = p2;
186400  p2 = 0;
186401  }else if( p2==0 ){
186402  *ppOut = p1;
186403  p1 = 0;
186404  }else{
186405  int i = 0;
186406  while( p1->zKey[i]==p2->zKey[i] ) i++;
186407 
186408  if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
186409  /* p2 is smaller */
186410  *ppOut = p2;
186411  ppOut = &p2->pScanNext;
186412  p2 = p2->pScanNext;
186413  }else{
186414  /* p1 is smaller */
186415  *ppOut = p1;
186416  ppOut = &p1->pScanNext;
186417  p1 = p1->pScanNext;
186418  }
186419  *ppOut = 0;
186420  }
186421  }
186422 
186423  return pRet;
186424 }
186425 
186426 /*
186427 ** Extract all tokens from hash table iHash and link them into a list
186428 ** in sorted order. The hash table is cleared before returning. It is
186429 ** the responsibility of the caller to free the elements of the returned
186430 ** list.
186431 */
186432 static int fts5HashEntrySort(
186433  Fts5Hash *pHash,
186434  const char *pTerm, int nTerm, /* Query prefix, if any */
186435  Fts5HashEntry **ppSorted
186436 ){
186437  const int nMergeSlot = 32;
186438  Fts5HashEntry **ap;
186439  Fts5HashEntry *pList;
186440  int iSlot;
186441  int i;
186442 
186443  *ppSorted = 0;
186444  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
186445  if( !ap ) return SQLITE_NOMEM;
186446  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
186447 
186448  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
186449  Fts5HashEntry *pIter;
186450  for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
186451  if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
186452  Fts5HashEntry *pEntry = pIter;
186453  pEntry->pScanNext = 0;
186454  for(i=0; ap[i]; i++){
186455  pEntry = fts5HashEntryMerge(pEntry, ap[i]);
186456  ap[i] = 0;
186457  }
186458  ap[i] = pEntry;
186459  }
186460  }
186461  }
186462 
186463  pList = 0;
186464  for(i=0; i<nMergeSlot; i++){
186465  pList = fts5HashEntryMerge(pList, ap[i]);
186466  }
186467 
186468  pHash->nEntry = 0;
186469  sqlite3_free(ap);
186470  *ppSorted = pList;
186471  return SQLITE_OK;
186472 }
186473 
186474 /*
186475 ** Query the hash table for a doclist associated with term pTerm/nTerm.
186476 */
186477 static int sqlite3Fts5HashQuery(
186478  Fts5Hash *pHash, /* Hash table to query */
186479  const char *pTerm, int nTerm, /* Query term */
186480  const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
186481  int *pnDoclist /* OUT: Size of doclist in bytes */
186482 ){
186483  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
186484  Fts5HashEntry *p;
186485 
186486  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
186487  if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
186488  }
186489 
186490  if( p ){
186491  fts5HashAddPoslistSize(pHash, p);
186492  *ppDoclist = (const u8*)&p->zKey[nTerm+1];
186493  *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
186494  }else{
186495  *ppDoclist = 0;
186496  *pnDoclist = 0;
186497  }
186498 
186499  return SQLITE_OK;
186500 }
186501 
186502 static int sqlite3Fts5HashScanInit(
186503  Fts5Hash *p, /* Hash table to query */
186504  const char *pTerm, int nTerm /* Query prefix */
186505 ){
186506  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
186507 }
186508 
186509 static void sqlite3Fts5HashScanNext(Fts5Hash *p){
186510  assert( !sqlite3Fts5HashScanEof(p) );
186511  p->pScan = p->pScan->pScanNext;
186512 }
186513 
186514 static int sqlite3Fts5HashScanEof(Fts5Hash *p){
186515  return (p->pScan==0);
186516 }
186517 
186518 static void sqlite3Fts5HashScanEntry(
186519  Fts5Hash *pHash,
186520  const char **pzTerm, /* OUT: term (nul-terminated) */
186521  const u8 **ppDoclist, /* OUT: pointer to doclist */
186522  int *pnDoclist /* OUT: size of doclist in bytes */
186523 ){
186524  Fts5HashEntry *p;
186525  if( (p = pHash->pScan) ){
186526  int nTerm = (int)strlen(p->zKey);
186527  fts5HashAddPoslistSize(pHash, p);
186528  *pzTerm = p->zKey;
186529  *ppDoclist = (const u8*)&p->zKey[nTerm+1];
186530  *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
186531  }else{
186532  *pzTerm = 0;
186533  *ppDoclist = 0;
186534  *pnDoclist = 0;
186535  }
186536 }
186537 
186538 
186539 /*
186540 ** 2014 May 31
186541 **
186542 ** The author disclaims copyright to this source code. In place of
186543 ** a legal notice, here is a blessing:
186544 **
186545 ** May you do good and not evil.
186546 ** May you find forgiveness for yourself and forgive others.
186547 ** May you share freely, never taking more than you give.
186548 **
186549 ******************************************************************************
186550 **
186551 ** Low level access to the FTS index stored in the database file. The
186552 ** routines in this file file implement all read and write access to the
186553 ** %_data table. Other parts of the system access this functionality via
186554 ** the interface defined in fts5Int.h.
186555 */
186556 
186557 
186558 /* #include "fts5Int.h" */
186559 
186560 /*
186561 ** Overview:
186562 **
186563 ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
186564 ** As well as the main term index, there may be up to 31 prefix indexes.
186565 ** The format is similar to FTS3/4, except that:
186566 **
186567 ** * all segment b-tree leaf data is stored in fixed size page records
186568 ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
186569 ** taken to ensure it is possible to iterate in either direction through
186570 ** the entries in a doclist, or to seek to a specific entry within a
186571 ** doclist, without loading it into memory.
186572 **
186573 ** * large doclists that span many pages have associated "doclist index"
186574 ** records that contain a copy of the first rowid on each page spanned by
186575 ** the doclist. This is used to speed up seek operations, and merges of
186576 ** large doclists with very small doclists.
186577 **
186578 ** * extra fields in the "structure record" record the state of ongoing
186579 ** incremental merge operations.
186580 **
186581 */
186582 
186583 
186584 #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
186585 #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
186586 
186587 #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
186588 
186589 #define FTS5_MAIN_PREFIX '0'
186590 
186591 #if FTS5_MAX_PREFIX_INDEXES > 31
186592 # error "FTS5_MAX_PREFIX_INDEXES is too large"
186593 #endif
186594 
186595 /*
186596 ** Details:
186597 **
186598 ** The %_data table managed by this module,
186599 **
186600 ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
186601 **
186602 ** , contains the following 5 types of records. See the comments surrounding
186603 ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
186604 ** assigned to each fo them.
186605 **
186606 ** 1. Structure Records:
186607 **
186608 ** The set of segments that make up an index - the index structure - are
186609 ** recorded in a single record within the %_data table. The record consists
186610 ** of a single 32-bit configuration cookie value followed by a list of
186611 ** SQLite varints. If the FTS table features more than one index (because
186612 ** there are one or more prefix indexes), it is guaranteed that all share
186613 ** the same cookie value.
186614 **
186615 ** Immediately following the configuration cookie, the record begins with
186616 ** three varints:
186617 **
186618 ** + number of levels,
186619 ** + total number of segments on all levels,
186620 ** + value of write counter.
186621 **
186622 ** Then, for each level from 0 to nMax:
186623 **
186624 ** + number of input segments in ongoing merge.
186625 ** + total number of segments in level.
186626 ** + for each segment from oldest to newest:
186627 ** + segment id (always > 0)
186628 ** + first leaf page number (often 1, always greater than 0)
186629 ** + final leaf page number
186630 **
186631 ** 2. The Averages Record:
186632 **
186633 ** A single record within the %_data table. The data is a list of varints.
186634 ** The first value is the number of rows in the index. Then, for each column
186635 ** from left to right, the total number of tokens in the column for all
186636 ** rows of the table.
186637 **
186638 ** 3. Segment leaves:
186639 **
186640 ** TERM/DOCLIST FORMAT:
186641 **
186642 ** Most of each segment leaf is taken up by term/doclist data. The
186643 ** general format of term/doclist, starting with the first term
186644 ** on the leaf page, is:
186645 **
186646 ** varint : size of first term
186647 ** blob: first term data
186648 ** doclist: first doclist
186649 ** zero-or-more {
186650 ** varint: number of bytes in common with previous term
186651 ** varint: number of bytes of new term data (nNew)
186652 ** blob: nNew bytes of new term data
186653 ** doclist: next doclist
186654 ** }
186655 **
186656 ** doclist format:
186657 **
186658 ** varint: first rowid
186659 ** poslist: first poslist
186660 ** zero-or-more {
186661 ** varint: rowid delta (always > 0)
186662 ** poslist: next poslist
186663 ** }
186664 **
186665 ** poslist format:
186666 **
186667 ** varint: size of poslist in bytes multiplied by 2, not including
186668 ** this field. Plus 1 if this entry carries the "delete" flag.
186669 ** collist: collist for column 0
186670 ** zero-or-more {
186671 ** 0x01 byte
186672 ** varint: column number (I)
186673 ** collist: collist for column I
186674 ** }
186675 **
186676 ** collist format:
186677 **
186678 ** varint: first offset + 2
186679 ** zero-or-more {
186680 ** varint: offset delta + 2
186681 ** }
186682 **
186683 ** PAGE FORMAT
186684 **
186685 ** Each leaf page begins with a 4-byte header containing 2 16-bit
186686 ** unsigned integer fields in big-endian format. They are:
186687 **
186688 ** * The byte offset of the first rowid on the page, if it exists
186689 ** and occurs before the first term (otherwise 0).
186690 **
186691 ** * The byte offset of the start of the page footer. If the page
186692 ** footer is 0 bytes in size, then this field is the same as the
186693 ** size of the leaf page in bytes.
186694 **
186695 ** The page footer consists of a single varint for each term located
186696 ** on the page. Each varint is the byte offset of the current term
186697 ** within the page, delta-compressed against the previous value. In
186698 ** other words, the first varint in the footer is the byte offset of
186699 ** the first term, the second is the byte offset of the second less that
186700 ** of the first, and so on.
186701 **
186702 ** The term/doclist format described above is accurate if the entire
186703 ** term/doclist data fits on a single leaf page. If this is not the case,
186704 ** the format is changed in two ways:
186705 **
186706 ** + if the first rowid on a page occurs before the first term, it
186707 ** is stored as a literal value:
186708 **
186709 ** varint: first rowid
186710 **
186711 ** + the first term on each page is stored in the same way as the
186712 ** very first term of the segment:
186713 **
186714 ** varint : size of first term
186715 ** blob: first term data
186716 **
186717 ** 5. Segment doclist indexes:
186718 **
186719 ** Doclist indexes are themselves b-trees, however they usually consist of
186720 ** a single leaf record only. The format of each doclist index leaf page
186721 ** is:
186722 **
186723 ** * Flags byte. Bits are:
186724 ** 0x01: Clear if leaf is also the root page, otherwise set.
186725 **
186726 ** * Page number of fts index leaf page. As a varint.
186727 **
186728 ** * First rowid on page indicated by previous field. As a varint.
186729 **
186730 ** * A list of varints, one for each subsequent termless page. A
186731 ** positive delta if the termless page contains at least one rowid,
186732 ** or an 0x00 byte otherwise.
186733 **
186734 ** Internal doclist index nodes are:
186735 **
186736 ** * Flags byte. Bits are:
186737 ** 0x01: Clear for root page, otherwise set.
186738 **
186739 ** * Page number of first child page. As a varint.
186740 **
186741 ** * Copy of first rowid on page indicated by previous field. As a varint.
186742 **
186743 ** * A list of delta-encoded varints - the first rowid on each subsequent
186744 ** child page.
186745 **
186746 */
186747 
186748 /*
186749 ** Rowids for the averages and structure records in the %_data table.
186750 */
186751 #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
186752 #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
186753 
186754 /*
186755 ** Macros determining the rowids used by segment leaves and dlidx leaves
186756 ** and nodes. All nodes and leaves are stored in the %_data table with large
186757 ** positive rowids.
186758 **
186759 ** Each segment has a unique non-zero 16-bit id.
186760 **
186761 ** The rowid for each segment leaf is found by passing the segment id and
186762 ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
186763 ** sequentially starting from 1.
186764 */
186765 #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
186766 #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
186767 #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
186768 #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
186769 
186770 #define fts5_dri(segid, dlidx, height, pgno) ( \
186771  ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
186772  ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
186773  ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
186774  ((i64)(pgno)) \
186775 )
186776 
186777 #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
186778 #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
186779 
186780 /*
186781 ** Maximum segments permitted in a single index
186782 */
186783 #define FTS5_MAX_SEGMENT 2000
186784 
186785 #ifdef SQLITE_DEBUG
186786 static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
186787 #endif
186788 
186789 
186790 /*
186791 ** Each time a blob is read from the %_data table, it is padded with this
186792 ** many zero bytes. This makes it easier to decode the various record formats
186793 ** without overreading if the records are corrupt.
186794 */
186795 #define FTS5_DATA_ZERO_PADDING 8
186796 #define FTS5_DATA_PADDING 20
186797 
186798 typedef struct Fts5Data Fts5Data;
186799 typedef struct Fts5DlidxIter Fts5DlidxIter;
186800 typedef struct Fts5DlidxLvl Fts5DlidxLvl;
186801 typedef struct Fts5DlidxWriter Fts5DlidxWriter;
186802 typedef struct Fts5Iter Fts5Iter;
186803 typedef struct Fts5PageWriter Fts5PageWriter;
186804 typedef struct Fts5SegIter Fts5SegIter;
186805 typedef struct Fts5DoclistIter Fts5DoclistIter;
186806 typedef struct Fts5SegWriter Fts5SegWriter;
186807 typedef struct Fts5Structure Fts5Structure;
186808 typedef struct Fts5StructureLevel Fts5StructureLevel;
186809 typedef struct Fts5StructureSegment Fts5StructureSegment;
186810 
186811 struct Fts5Data {
186812  u8 *p; /* Pointer to buffer containing record */
186813  int nn; /* Size of record in bytes */
186814  int szLeaf; /* Size of leaf without page-index */
186815 };
186816 
186817 /*
186818 ** One object per %_data table.
186819 */
186820 struct Fts5Index {
186821  Fts5Config *pConfig; /* Virtual table configuration */
186822  char *zDataTbl; /* Name of %_data table */
186823  int nWorkUnit; /* Leaf pages in a "unit" of work */
186824 
186825  /*
186826  ** Variables related to the accumulation of tokens and doclists within the
186827  ** in-memory hash tables before they are flushed to disk.
186828  */
186829  Fts5Hash *pHash; /* Hash table for in-memory data */
186830  int nPendingData; /* Current bytes of pending data */
186831  i64 iWriteRowid; /* Rowid for current doc being written */
186832  int bDelete; /* Current write is a delete */
186833 
186834  /* Error state. */
186835  int rc; /* Current error code */
186836 
186837  /* State used by the fts5DataXXX() functions. */
186838  sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
186839  sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
186840  sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
186841  sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
186842  sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
186843  sqlite3_stmt *pIdxSelect;
186844  int nRead; /* Total number of blocks read */
186845 
186846  sqlite3_stmt *pDataVersion;
186847  i64 iStructVersion; /* data_version when pStruct read */
186848  Fts5Structure *pStruct; /* Current db structure (or NULL) */
186849 };
186850 
186851 struct Fts5DoclistIter {
186852  u8 *aEof; /* Pointer to 1 byte past end of doclist */
186853 
186854  /* Output variables. aPoslist==0 at EOF */
186855  i64 iRowid;
186856  u8 *aPoslist;
186857  int nPoslist;
186858  int nSize;
186859 };
186860 
186861 /*
186862 ** The contents of the "structure" record for each index are represented
186863 ** using an Fts5Structure record in memory. Which uses instances of the
186864 ** other Fts5StructureXXX types as components.
186865 */
186866 struct Fts5StructureSegment {
186867  int iSegid; /* Segment id */
186868  int pgnoFirst; /* First leaf page number in segment */
186869  int pgnoLast; /* Last leaf page number in segment */
186870 };
186871 struct Fts5StructureLevel {
186872  int nMerge; /* Number of segments in incr-merge */
186873  int nSeg; /* Total number of segments on level */
186874  Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
186875 };
186876 struct Fts5Structure {
186877  int nRef; /* Object reference count */
186878  u64 nWriteCounter; /* Total leaves written to level 0 */
186879  int nSegment; /* Total segments in this structure */
186880  int nLevel; /* Number of levels in this index */
186881  Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
186882 };
186883 
186884 /*
186885 ** An object of type Fts5SegWriter is used to write to segments.
186886 */
186887 struct Fts5PageWriter {
186888  int pgno; /* Page number for this page */
186889  int iPrevPgidx; /* Previous value written into pgidx */
186890  Fts5Buffer buf; /* Buffer containing leaf data */
186891  Fts5Buffer pgidx; /* Buffer containing page-index */
186892  Fts5Buffer term; /* Buffer containing previous term on page */
186893 };
186894 struct Fts5DlidxWriter {
186895  int pgno; /* Page number for this page */
186896  int bPrevValid; /* True if iPrev is valid */
186897  i64 iPrev; /* Previous rowid value written to page */
186898  Fts5Buffer buf; /* Buffer containing page data */
186899 };
186900 struct Fts5SegWriter {
186901  int iSegid; /* Segid to write to */
186902  Fts5PageWriter writer; /* PageWriter object */
186903  i64 iPrevRowid; /* Previous rowid written to current leaf */
186904  u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
186905  u8 bFirstRowidInPage; /* True if next rowid is first in page */
186906  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
186907  u8 bFirstTermInPage; /* True if next term will be first in leaf */
186908  int nLeafWritten; /* Number of leaf pages written */
186909  int nEmpty; /* Number of contiguous term-less nodes */
186910 
186911  int nDlidx; /* Allocated size of aDlidx[] array */
186912  Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
186913 
186914  /* Values to insert into the %_idx table */
186915  Fts5Buffer btterm; /* Next term to insert into %_idx table */
186916  int iBtPage; /* Page number corresponding to btterm */
186917 };
186918 
186919 typedef struct Fts5CResult Fts5CResult;
186920 struct Fts5CResult {
186921  u16 iFirst; /* aSeg[] index of firstest iterator */
186922  u8 bTermEq; /* True if the terms are equal */
186923 };
186924 
186925 /*
186926 ** Object for iterating through a single segment, visiting each term/rowid
186927 ** pair in the segment.
186928 **
186929 ** pSeg:
186930 ** The segment to iterate through.
186931 **
186932 ** iLeafPgno:
186933 ** Current leaf page number within segment.
186934 **
186935 ** iLeafOffset:
186936 ** Byte offset within the current leaf that is the first byte of the
186937 ** position list data (one byte passed the position-list size field).
186938 ** rowid field of the current entry. Usually this is the size field of the
186939 ** position list data. The exception is if the rowid for the current entry
186940 ** is the last thing on the leaf page.
186941 **
186942 ** pLeaf:
186943 ** Buffer containing current leaf page data. Set to NULL at EOF.
186944 **
186945 ** iTermLeafPgno, iTermLeafOffset:
186946 ** Leaf page number containing the last term read from the segment. And
186947 ** the offset immediately following the term data.
186948 **
186949 ** flags:
186950 ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
186951 **
186952 ** FTS5_SEGITER_ONETERM:
186953 ** If set, set the iterator to point to EOF after the current doclist
186954 ** has been exhausted. Do not proceed to the next term in the segment.
186955 **
186956 ** FTS5_SEGITER_REVERSE:
186957 ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
186958 ** it is set, iterate through rowid in descending order instead of the
186959 ** default ascending order.
186960 **
186961 ** iRowidOffset/nRowidOffset/aRowidOffset:
186962 ** These are used if the FTS5_SEGITER_REVERSE flag is set.
186963 **
186964 ** For each rowid on the page corresponding to the current term, the
186965 ** corresponding aRowidOffset[] entry is set to the byte offset of the
186966 ** start of the "position-list-size" field within the page.
186967 **
186968 ** iTermIdx:
186969 ** Index of current term on iTermLeafPgno.
186970 */
186971 struct Fts5SegIter {
186972  Fts5StructureSegment *pSeg; /* Segment to iterate through */
186973  int flags; /* Mask of configuration flags */
186974  int iLeafPgno; /* Current leaf page number */
186975  Fts5Data *pLeaf; /* Current leaf data */
186976  Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
186977  int iLeafOffset; /* Byte offset within current leaf */
186978 
186979  /* Next method */
186980  void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
186981 
186982  /* The page and offset from which the current term was read. The offset
186983  ** is the offset of the first rowid in the current doclist. */
186984  int iTermLeafPgno;
186985  int iTermLeafOffset;
186986 
186987  int iPgidxOff; /* Next offset in pgidx */
186988  int iEndofDoclist;
186989 
186990  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
186991  int iRowidOffset; /* Current entry in aRowidOffset[] */
186992  int nRowidOffset; /* Allocated size of aRowidOffset[] array */
186993  int *aRowidOffset; /* Array of offset to rowid fields */
186994 
186995  Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
186996 
186997  /* Variables populated based on current entry. */
186998  Fts5Buffer term; /* Current term */
186999  i64 iRowid; /* Current rowid */
187000  int nPos; /* Number of bytes in current position list */
187001  u8 bDel; /* True if the delete flag is set */
187002 };
187003 
187004 /*
187005 ** Argument is a pointer to an Fts5Data structure that contains a
187006 ** leaf page.
187007 */
187008 #define ASSERT_SZLEAF_OK(x) assert( \
187009  (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
187010 )
187011 
187012 #define FTS5_SEGITER_ONETERM 0x01
187013 #define FTS5_SEGITER_REVERSE 0x02
187014 
187015 /*
187016 ** Argument is a pointer to an Fts5Data structure that contains a leaf
187017 ** page. This macro evaluates to true if the leaf contains no terms, or
187018 ** false if it contains at least one term.
187019 */
187020 #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
187021 
187022 #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
187023 
187024 #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
187025 
187026 /*
187027 ** Object for iterating through the merged results of one or more segments,
187028 ** visiting each term/rowid pair in the merged data.
187029 **
187030 ** nSeg is always a power of two greater than or equal to the number of
187031 ** segments that this object is merging data from. Both the aSeg[] and
187032 ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
187033 ** with zeroed objects - these are handled as if they were iterators opened
187034 ** on empty segments.
187035 **
187036 ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
187037 ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
187038 ** comparison in this context is the index of the iterator that currently
187039 ** points to the smaller term/rowid combination. Iterators at EOF are
187040 ** considered to be greater than all other iterators.
187041 **
187042 ** aFirst[1] contains the index in aSeg[] of the iterator that points to
187043 ** the smallest key overall. aFirst[0] is unused.
187044 **
187045 ** poslist:
187046 ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
187047 ** There is no way to tell if this is populated or not.
187048 */
187049 struct Fts5Iter {
187050  Fts5IndexIter base; /* Base class containing output vars */
187051 
187052  Fts5Index *pIndex; /* Index that owns this iterator */
187053  Fts5Structure *pStruct; /* Database structure for this iterator */
187054  Fts5Buffer poslist; /* Buffer containing current poslist */
187055  Fts5Colset *pColset; /* Restrict matches to these columns */
187056 
187057  /* Invoked to set output variables. */
187058  void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
187059 
187060  int nSeg; /* Size of aSeg[] array */
187061  int bRev; /* True to iterate in reverse order */
187062  u8 bSkipEmpty; /* True to skip deleted entries */
187063 
187064  i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
187065  Fts5CResult *aFirst; /* Current merge state (see above) */
187066  Fts5SegIter aSeg[1]; /* Array of segment iterators */
187067 };
187068 
187069 
187070 /*
187071 ** An instance of the following type is used to iterate through the contents
187072 ** of a doclist-index record.
187073 **
187074 ** pData:
187075 ** Record containing the doclist-index data.
187076 **
187077 ** bEof:
187078 ** Set to true once iterator has reached EOF.
187079 **
187080 ** iOff:
187081 ** Set to the current offset within record pData.
187082 */
187083 struct Fts5DlidxLvl {
187084  Fts5Data *pData; /* Data for current page of this level */
187085  int iOff; /* Current offset into pData */
187086  int bEof; /* At EOF already */
187087  int iFirstOff; /* Used by reverse iterators */
187088 
187089  /* Output variables */
187090  int iLeafPgno; /* Page number of current leaf page */
187091  i64 iRowid; /* First rowid on leaf iLeafPgno */
187092 };
187093 struct Fts5DlidxIter {
187094  int nLvl;
187095  int iSegid;
187096  Fts5DlidxLvl aLvl[1];
187097 };
187098 
187099 static void fts5PutU16(u8 *aOut, u16 iVal){
187100  aOut[0] = (iVal>>8);
187101  aOut[1] = (iVal&0xFF);
187102 }
187103 
187104 static u16 fts5GetU16(const u8 *aIn){
187105  return ((u16)aIn[0] << 8) + aIn[1];
187106 }
187107 
187108 /*
187109 ** Allocate and return a buffer at least nByte bytes in size.
187110 **
187111 ** If an OOM error is encountered, return NULL and set the error code in
187112 ** the Fts5Index handle passed as the first argument.
187113 */
187114 static void *fts5IdxMalloc(Fts5Index *p, int nByte){
187115  return sqlite3Fts5MallocZero(&p->rc, nByte);
187116 }
187117 
187118 /*
187119 ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
187120 **
187121 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
187122 ** +ve if pRight is smaller than pLeft. In other words:
187123 **
187124 ** res = *pLeft - *pRight
187125 */
187126 #ifdef SQLITE_DEBUG
187127 static int fts5BufferCompareBlob(
187128  Fts5Buffer *pLeft, /* Left hand side of comparison */
187129  const u8 *pRight, int nRight /* Right hand side of comparison */
187130 ){
187131  int nCmp = MIN(pLeft->n, nRight);
187132  int res = memcmp(pLeft->p, pRight, nCmp);
187133  return (res==0 ? (pLeft->n - nRight) : res);
187134 }
187135 #endif
187136 
187137 /*
187138 ** Compare the contents of the two buffers using memcmp(). If one buffer
187139 ** is a prefix of the other, it is considered the lesser.
187140 **
187141 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
187142 ** +ve if pRight is smaller than pLeft. In other words:
187143 **
187144 ** res = *pLeft - *pRight
187145 */
187146 static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
187147  int nCmp = MIN(pLeft->n, pRight->n);
187148  int res = memcmp(pLeft->p, pRight->p, nCmp);
187149  return (res==0 ? (pLeft->n - pRight->n) : res);
187150 }
187151 
187152 static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
187153  int ret;
187154  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
187155  return ret;
187156 }
187157 
187158 /*
187159 ** Close the read-only blob handle, if it is open.
187160 */
187161 static void fts5CloseReader(Fts5Index *p){
187162  if( p->pReader ){
187163  sqlite3_blob *pReader = p->pReader;
187164  p->pReader = 0;
187165  sqlite3_blob_close(pReader);
187166  }
187167 }
187168 
187169 
187170 /*
187171 ** Retrieve a record from the %_data table.
187172 **
187173 ** If an error occurs, NULL is returned and an error left in the
187174 ** Fts5Index object.
187175 */
187176 static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
187177  Fts5Data *pRet = 0;
187178  if( p->rc==SQLITE_OK ){
187179  int rc = SQLITE_OK;
187180 
187181  if( p->pReader ){
187182  /* This call may return SQLITE_ABORT if there has been a savepoint
187183  ** rollback since it was last used. In this case a new blob handle
187184  ** is required. */
187185  sqlite3_blob *pBlob = p->pReader;
187186  p->pReader = 0;
187187  rc = sqlite3_blob_reopen(pBlob, iRowid);
187188  assert( p->pReader==0 );
187189  p->pReader = pBlob;
187190  if( rc!=SQLITE_OK ){
187191  fts5CloseReader(p);
187192  }
187193  if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
187194  }
187195 
187196  /* If the blob handle is not open at this point, open it and seek
187197  ** to the requested entry. */
187198  if( p->pReader==0 && rc==SQLITE_OK ){
187199  Fts5Config *pConfig = p->pConfig;
187200  rc = sqlite3_blob_open(pConfig->db,
187201  pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
187202  );
187203  }
187204 
187205  /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
187206  ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
187207  ** All the reasons those functions might return SQLITE_ERROR - missing
187208  ** table, missing row, non-blob/text in block column - indicate
187209  ** backing store corruption. */
187210  if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
187211 
187212  if( rc==SQLITE_OK ){
187213  u8 *aOut = 0; /* Read blob data into this buffer */
187214  int nByte = sqlite3_blob_bytes(p->pReader);
187215  int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
187216  pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
187217  if( pRet ){
187218  pRet->nn = nByte;
187219  aOut = pRet->p = (u8*)&pRet[1];
187220  }else{
187221  rc = SQLITE_NOMEM;
187222  }
187223 
187224  if( rc==SQLITE_OK ){
187225  rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
187226  }
187227  if( rc!=SQLITE_OK ){
187228  sqlite3_free(pRet);
187229  pRet = 0;
187230  }else{
187231  /* TODO1: Fix this */
187232  pRet->szLeaf = fts5GetU16(&pRet->p[2]);
187233  }
187234  }
187235  p->rc = rc;
187236  p->nRead++;
187237  }
187238 
187239  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
187240  return pRet;
187241 }
187242 
187243 /*
187244 ** Release a reference to data record returned by an earlier call to
187245 ** fts5DataRead().
187246 */
187247 static void fts5DataRelease(Fts5Data *pData){
187248  sqlite3_free(pData);
187249 }
187250 
187251 static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
187252  Fts5Data *pRet = fts5DataRead(p, iRowid);
187253  if( pRet ){
187254  if( pRet->szLeaf>pRet->nn ){
187255  p->rc = FTS5_CORRUPT;
187256  fts5DataRelease(pRet);
187257  pRet = 0;
187258  }
187259  }
187260  return pRet;
187261 }
187262 
187263 static int fts5IndexPrepareStmt(
187264  Fts5Index *p,
187265  sqlite3_stmt **ppStmt,
187266  char *zSql
187267 ){
187268  if( p->rc==SQLITE_OK ){
187269  if( zSql ){
187270  p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
187271  }else{
187272  p->rc = SQLITE_NOMEM;
187273  }
187274  }
187275  sqlite3_free(zSql);
187276  return p->rc;
187277 }
187278 
187279 
187280 /*
187281 ** INSERT OR REPLACE a record into the %_data table.
187282 */
187283 static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
187284  if( p->rc!=SQLITE_OK ) return;
187285 
187286  if( p->pWriter==0 ){
187287  Fts5Config *pConfig = p->pConfig;
187288  fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
187289  "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
187290  pConfig->zDb, pConfig->zName
187291  ));
187292  if( p->rc ) return;
187293  }
187294 
187295  sqlite3_bind_int64(p->pWriter, 1, iRowid);
187296  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
187297  sqlite3_step(p->pWriter);
187298  p->rc = sqlite3_reset(p->pWriter);
187299 }
187300 
187301 /*
187302 ** Execute the following SQL:
187303 **
187304 ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
187305 */
187306 static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
187307  if( p->rc!=SQLITE_OK ) return;
187308 
187309  if( p->pDeleter==0 ){
187310  int rc;
187311  Fts5Config *pConfig = p->pConfig;
187312  char *zSql = sqlite3_mprintf(
187313  "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
187314  pConfig->zDb, pConfig->zName
187315  );
187316  if( zSql==0 ){
187317  rc = SQLITE_NOMEM;
187318  }else{
187319  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
187320  sqlite3_free(zSql);
187321  }
187322  if( rc!=SQLITE_OK ){
187323  p->rc = rc;
187324  return;
187325  }
187326  }
187327 
187328  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
187329  sqlite3_bind_int64(p->pDeleter, 2, iLast);
187330  sqlite3_step(p->pDeleter);
187331  p->rc = sqlite3_reset(p->pDeleter);
187332 }
187333 
187334 /*
187335 ** Remove all records associated with segment iSegid.
187336 */
187337 static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
187338  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
187339  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
187340  fts5DataDelete(p, iFirst, iLast);
187341  if( p->pIdxDeleter==0 ){
187342  Fts5Config *pConfig = p->pConfig;
187343  fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
187344  "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
187345  pConfig->zDb, pConfig->zName
187346  ));
187347  }
187348  if( p->rc==SQLITE_OK ){
187349  sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
187350  sqlite3_step(p->pIdxDeleter);
187351  p->rc = sqlite3_reset(p->pIdxDeleter);
187352  }
187353 }
187354 
187355 /*
187356 ** Release a reference to an Fts5Structure object returned by an earlier
187357 ** call to fts5StructureRead() or fts5StructureDecode().
187358 */
187359 static void fts5StructureRelease(Fts5Structure *pStruct){
187360  if( pStruct && 0>=(--pStruct->nRef) ){
187361  int i;
187362  assert( pStruct->nRef==0 );
187363  for(i=0; i<pStruct->nLevel; i++){
187364  sqlite3_free(pStruct->aLevel[i].aSeg);
187365  }
187366  sqlite3_free(pStruct);
187367  }
187368 }
187369 
187370 static void fts5StructureRef(Fts5Structure *pStruct){
187371  pStruct->nRef++;
187372 }
187373 
187374 /*
187375 ** Deserialize and return the structure record currently stored in serialized
187376 ** form within buffer pData/nData.
187377 **
187378 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
187379 ** are over-allocated by one slot. This allows the structure contents
187380 ** to be more easily edited.
187381 **
187382 ** If an error occurs, *ppOut is set to NULL and an SQLite error code
187383 ** returned. Otherwise, *ppOut is set to point to the new object and
187384 ** SQLITE_OK returned.
187385 */
187386 static int fts5StructureDecode(
187387  const u8 *pData, /* Buffer containing serialized structure */
187388  int nData, /* Size of buffer pData in bytes */
187389  int *piCookie, /* Configuration cookie value */
187390  Fts5Structure **ppOut /* OUT: Deserialized object */
187391 ){
187392  int rc = SQLITE_OK;
187393  int i = 0;
187394  int iLvl;
187395  int nLevel = 0;
187396  int nSegment = 0;
187397  int nByte; /* Bytes of space to allocate at pRet */
187398  Fts5Structure *pRet = 0; /* Structure object to return */
187399 
187400  /* Grab the cookie value */
187401  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
187402  i = 4;
187403 
187404  /* Read the total number of levels and segments from the start of the
187405  ** structure record. */
187406  i += fts5GetVarint32(&pData[i], nLevel);
187407  i += fts5GetVarint32(&pData[i], nSegment);
187408  nByte = (
187409  sizeof(Fts5Structure) + /* Main structure */
187410  sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
187411  );
187412  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
187413 
187414  if( pRet ){
187415  pRet->nRef = 1;
187416  pRet->nLevel = nLevel;
187417  pRet->nSegment = nSegment;
187418  i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
187419 
187420  for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
187421  Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
187422  int nTotal = 0;
187423  int iSeg;
187424 
187425  if( i>=nData ){
187426  rc = FTS5_CORRUPT;
187427  }else{
187428  i += fts5GetVarint32(&pData[i], pLvl->nMerge);
187429  i += fts5GetVarint32(&pData[i], nTotal);
187430  assert( nTotal>=pLvl->nMerge );
187431  pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
187432  nTotal * sizeof(Fts5StructureSegment)
187433  );
187434  }
187435 
187436  if( rc==SQLITE_OK ){
187437  pLvl->nSeg = nTotal;
187438  for(iSeg=0; iSeg<nTotal; iSeg++){
187439  if( i>=nData ){
187440  rc = FTS5_CORRUPT;
187441  break;
187442  }
187443  i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
187444  i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
187445  i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
187446  }
187447  }
187448  }
187449  if( rc!=SQLITE_OK ){
187450  fts5StructureRelease(pRet);
187451  pRet = 0;
187452  }
187453  }
187454 
187455  *ppOut = pRet;
187456  return rc;
187457 }
187458 
187459 /*
187460 **
187461 */
187462 static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
187463  if( *pRc==SQLITE_OK ){
187464  Fts5Structure *pStruct = *ppStruct;
187465  int nLevel = pStruct->nLevel;
187466  int nByte = (
187467  sizeof(Fts5Structure) + /* Main structure */
187468  sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
187469  );
187470 
187471  pStruct = sqlite3_realloc(pStruct, nByte);
187472  if( pStruct ){
187473  memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
187474  pStruct->nLevel++;
187475  *ppStruct = pStruct;
187476  }else{
187477  *pRc = SQLITE_NOMEM;
187478  }
187479  }
187480 }
187481 
187482 /*
187483 ** Extend level iLvl so that there is room for at least nExtra more
187484 ** segments.
187485 */
187486 static void fts5StructureExtendLevel(
187487  int *pRc,
187488  Fts5Structure *pStruct,
187489  int iLvl,
187490  int nExtra,
187491  int bInsert
187492 ){
187493  if( *pRc==SQLITE_OK ){
187494  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
187495  Fts5StructureSegment *aNew;
187496  int nByte;
187497 
187498  nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
187499  aNew = sqlite3_realloc(pLvl->aSeg, nByte);
187500  if( aNew ){
187501  if( bInsert==0 ){
187502  memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
187503  }else{
187504  int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
187505  memmove(&aNew[nExtra], aNew, nMove);
187506  memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
187507  }
187508  pLvl->aSeg = aNew;
187509  }else{
187510  *pRc = SQLITE_NOMEM;
187511  }
187512  }
187513 }
187514 
187515 static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
187516  Fts5Structure *pRet = 0;
187517  Fts5Config *pConfig = p->pConfig;
187518  int iCookie; /* Configuration cookie */
187519  Fts5Data *pData;
187520 
187521  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
187522  if( p->rc==SQLITE_OK ){
187523  /* TODO: Do we need this if the leaf-index is appended? Probably... */
187524  memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
187525  p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
187526  if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
187527  p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
187528  }
187529  fts5DataRelease(pData);
187530  if( p->rc!=SQLITE_OK ){
187531  fts5StructureRelease(pRet);
187532  pRet = 0;
187533  }
187534  }
187535 
187536  return pRet;
187537 }
187538 
187539 static i64 fts5IndexDataVersion(Fts5Index *p){
187540  i64 iVersion = 0;
187541 
187542  if( p->rc==SQLITE_OK ){
187543  if( p->pDataVersion==0 ){
187544  p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
187545  sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
187546  );
187547  if( p->rc ) return 0;
187548  }
187549 
187550  if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
187551  iVersion = sqlite3_column_int64(p->pDataVersion, 0);
187552  }
187553  p->rc = sqlite3_reset(p->pDataVersion);
187554  }
187555 
187556  return iVersion;
187557 }
187558 
187559 /*
187560 ** Read, deserialize and return the structure record.
187561 **
187562 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
187563 ** are over-allocated as described for function fts5StructureDecode()
187564 ** above.
187565 **
187566 ** If an error occurs, NULL is returned and an error code left in the
187567 ** Fts5Index handle. If an error has already occurred when this function
187568 ** is called, it is a no-op.
187569 */
187570 static Fts5Structure *fts5StructureRead(Fts5Index *p){
187571 
187572  if( p->pStruct==0 ){
187573  p->iStructVersion = fts5IndexDataVersion(p);
187574  if( p->rc==SQLITE_OK ){
187575  p->pStruct = fts5StructureReadUncached(p);
187576  }
187577  }
187578 
187579 #if 0
187580  else{
187581  Fts5Structure *pTest = fts5StructureReadUncached(p);
187582  if( pTest ){
187583  int i, j;
187584  assert_nc( p->pStruct->nSegment==pTest->nSegment );
187585  assert_nc( p->pStruct->nLevel==pTest->nLevel );
187586  for(i=0; i<pTest->nLevel; i++){
187587  assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
187588  assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
187589  for(j=0; j<pTest->aLevel[i].nSeg; j++){
187590  Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
187591  Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
187592  assert_nc( p1->iSegid==p2->iSegid );
187593  assert_nc( p1->pgnoFirst==p2->pgnoFirst );
187594  assert_nc( p1->pgnoLast==p2->pgnoLast );
187595  }
187596  }
187597  fts5StructureRelease(pTest);
187598  }
187599  }
187600 #endif
187601 
187602  if( p->rc!=SQLITE_OK ) return 0;
187603  assert( p->iStructVersion!=0 );
187604  assert( p->pStruct!=0 );
187605  fts5StructureRef(p->pStruct);
187606  return p->pStruct;
187607 }
187608 
187609 static void fts5StructureInvalidate(Fts5Index *p){
187610  if( p->pStruct ){
187611  fts5StructureRelease(p->pStruct);
187612  p->pStruct = 0;
187613  }
187614 }
187615 
187616 /*
187617 ** Return the total number of segments in index structure pStruct. This
187618 ** function is only ever used as part of assert() conditions.
187619 */
187620 #ifdef SQLITE_DEBUG
187621 static int fts5StructureCountSegments(Fts5Structure *pStruct){
187622  int nSegment = 0; /* Total number of segments */
187623  if( pStruct ){
187624  int iLvl; /* Used to iterate through levels */
187625  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
187626  nSegment += pStruct->aLevel[iLvl].nSeg;
187627  }
187628  }
187629 
187630  return nSegment;
187631 }
187632 #endif
187633 
187634 #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
187635  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
187636  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
187637  (pBuf)->n += nBlob; \
187638 }
187639 
187640 #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
187641  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
187642  assert( (pBuf)->nSpace>=(pBuf)->n ); \
187643 }
187644 
187645 
187646 /*
187647 ** Serialize and store the "structure" record.
187648 **
187649 ** If an error occurs, leave an error code in the Fts5Index object. If an
187650 ** error has already occurred, this function is a no-op.
187651 */
187652 static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
187653  if( p->rc==SQLITE_OK ){
187654  Fts5Buffer buf; /* Buffer to serialize record into */
187655  int iLvl; /* Used to iterate through levels */
187656  int iCookie; /* Cookie value to store */
187657 
187658  assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
187659  memset(&buf, 0, sizeof(Fts5Buffer));
187660 
187661  /* Append the current configuration cookie */
187662  iCookie = p->pConfig->iCookie;
187663  if( iCookie<0 ) iCookie = 0;
187664 
187665  if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
187666  sqlite3Fts5Put32(buf.p, iCookie);
187667  buf.n = 4;
187668  fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
187669  fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
187670  fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
187671  }
187672 
187673  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
187674  int iSeg; /* Used to iterate through segments */
187675  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
187676  fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
187677  fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
187678  assert( pLvl->nMerge<=pLvl->nSeg );
187679 
187680  for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
187681  fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
187682  fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
187683  fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
187684  }
187685  }
187686 
187687  fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
187688  fts5BufferFree(&buf);
187689  }
187690 }
187691 
187692 #if 0
187693 static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
187694 static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
187695  int rc = SQLITE_OK;
187696  Fts5Buffer buf;
187697  memset(&buf, 0, sizeof(buf));
187698  fts5DebugStructure(&rc, &buf, pStruct);
187699  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
187700  fflush(stdout);
187701  fts5BufferFree(&buf);
187702 }
187703 #else
187704 # define fts5PrintStructure(x,y)
187705 #endif
187706 
187707 static int fts5SegmentSize(Fts5StructureSegment *pSeg){
187708  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
187709 }
187710 
187711 /*
187712 ** Return a copy of index structure pStruct. Except, promote as many
187713 ** segments as possible to level iPromote. If an OOM occurs, NULL is
187714 ** returned.
187715 */
187716 static void fts5StructurePromoteTo(
187717  Fts5Index *p,
187718  int iPromote,
187719  int szPromote,
187720  Fts5Structure *pStruct
187721 ){
187722  int il, is;
187723  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
187724 
187725  if( pOut->nMerge==0 ){
187726  for(il=iPromote+1; il<pStruct->nLevel; il++){
187727  Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
187728  if( pLvl->nMerge ) return;
187729  for(is=pLvl->nSeg-1; is>=0; is--){
187730  int sz = fts5SegmentSize(&pLvl->aSeg[is]);
187731  if( sz>szPromote ) return;
187732  fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
187733  if( p->rc ) return;
187734  memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
187735  pOut->nSeg++;
187736  pLvl->nSeg--;
187737  }
187738  }
187739  }
187740 }
187741 
187742 /*
187743 ** A new segment has just been written to level iLvl of index structure
187744 ** pStruct. This function determines if any segments should be promoted
187745 ** as a result. Segments are promoted in two scenarios:
187746 **
187747 ** a) If the segment just written is smaller than one or more segments
187748 ** within the previous populated level, it is promoted to the previous
187749 ** populated level.
187750 **
187751 ** b) If the segment just written is larger than the newest segment on
187752 ** the next populated level, then that segment, and any other adjacent
187753 ** segments that are also smaller than the one just written, are
187754 ** promoted.
187755 **
187756 ** If one or more segments are promoted, the structure object is updated
187757 ** to reflect this.
187758 */
187759 static void fts5StructurePromote(
187760  Fts5Index *p, /* FTS5 backend object */
187761  int iLvl, /* Index level just updated */
187762  Fts5Structure *pStruct /* Index structure */
187763 ){
187764  if( p->rc==SQLITE_OK ){
187765  int iTst;
187766  int iPromote = -1;
187767  int szPromote = 0; /* Promote anything this size or smaller */
187768  Fts5StructureSegment *pSeg; /* Segment just written */
187769  int szSeg; /* Size of segment just written */
187770  int nSeg = pStruct->aLevel[iLvl].nSeg;
187771 
187772  if( nSeg==0 ) return;
187773  pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
187774  szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
187775 
187776  /* Check for condition (a) */
187777  for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
187778  if( iTst>=0 ){
187779  int i;
187780  int szMax = 0;
187781  Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
187782  assert( pTst->nMerge==0 );
187783  for(i=0; i<pTst->nSeg; i++){
187784  int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
187785  if( sz>szMax ) szMax = sz;
187786  }
187787  if( szMax>=szSeg ){
187788  /* Condition (a) is true. Promote the newest segment on level
187789  ** iLvl to level iTst. */
187790  iPromote = iTst;
187791  szPromote = szMax;
187792  }
187793  }
187794 
187795  /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
187796  ** is a no-op if it is not. */
187797  if( iPromote<0 ){
187798  iPromote = iLvl;
187799  szPromote = szSeg;
187800  }
187801  fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
187802  }
187803 }
187804 
187805 
187806 /*
187807 ** Advance the iterator passed as the only argument. If the end of the
187808 ** doclist-index page is reached, return non-zero.
187809 */
187810 static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
187811  Fts5Data *pData = pLvl->pData;
187812 
187813  if( pLvl->iOff==0 ){
187814  assert( pLvl->bEof==0 );
187815  pLvl->iOff = 1;
187816  pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
187817  pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
187818  pLvl->iFirstOff = pLvl->iOff;
187819  }else{
187820  int iOff;
187821  for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
187822  if( pData->p[iOff] ) break;
187823  }
187824 
187825  if( iOff<pData->nn ){
187826  i64 iVal;
187827  pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
187828  iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
187829  pLvl->iRowid += iVal;
187830  pLvl->iOff = iOff;
187831  }else{
187832  pLvl->bEof = 1;
187833  }
187834  }
187835 
187836  return pLvl->bEof;
187837 }
187838 
187839 /*
187840 ** Advance the iterator passed as the only argument.
187841 */
187842 static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
187843  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
187844 
187845  assert( iLvl<pIter->nLvl );
187846  if( fts5DlidxLvlNext(pLvl) ){
187847  if( (iLvl+1) < pIter->nLvl ){
187848  fts5DlidxIterNextR(p, pIter, iLvl+1);
187849  if( pLvl[1].bEof==0 ){
187850  fts5DataRelease(pLvl->pData);
187851  memset(pLvl, 0, sizeof(Fts5DlidxLvl));
187852  pLvl->pData = fts5DataRead(p,
187853  FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
187854  );
187855  if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
187856  }
187857  }
187858  }
187859 
187860  return pIter->aLvl[0].bEof;
187861 }
187862 static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
187863  return fts5DlidxIterNextR(p, pIter, 0);
187864 }
187865 
187866 /*
187867 ** The iterator passed as the first argument has the following fields set
187868 ** as follows. This function sets up the rest of the iterator so that it
187869 ** points to the first rowid in the doclist-index.
187870 **
187871 ** pData:
187872 ** pointer to doclist-index record,
187873 **
187874 ** When this function is called pIter->iLeafPgno is the page number the
187875 ** doclist is associated with (the one featuring the term).
187876 */
187877 static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
187878  int i;
187879  for(i=0; i<pIter->nLvl; i++){
187880  fts5DlidxLvlNext(&pIter->aLvl[i]);
187881  }
187882  return pIter->aLvl[0].bEof;
187883 }
187884 
187885 
187886 static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
187887  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
187888 }
187889 
187890 static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
187891  int i;
187892 
187893  /* Advance each level to the last entry on the last page */
187894  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
187895  Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
187896  while( fts5DlidxLvlNext(pLvl)==0 );
187897  pLvl->bEof = 0;
187898 
187899  if( i>0 ){
187900  Fts5DlidxLvl *pChild = &pLvl[-1];
187901  fts5DataRelease(pChild->pData);
187902  memset(pChild, 0, sizeof(Fts5DlidxLvl));
187903  pChild->pData = fts5DataRead(p,
187904  FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
187905  );
187906  }
187907  }
187908 }
187909 
187910 /*
187911 ** Move the iterator passed as the only argument to the previous entry.
187912 */
187913 static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
187914  int iOff = pLvl->iOff;
187915 
187916  assert( pLvl->bEof==0 );
187917  if( iOff<=pLvl->iFirstOff ){
187918  pLvl->bEof = 1;
187919  }else{
187920  u8 *a = pLvl->pData->p;
187921  i64 iVal;
187922  int iLimit;
187923  int ii;
187924  int nZero = 0;
187925 
187926  /* Currently iOff points to the first byte of a varint. This block
187927  ** decrements iOff until it points to the first byte of the previous
187928  ** varint. Taking care not to read any memory locations that occur
187929  ** before the buffer in memory. */
187930  iLimit = (iOff>9 ? iOff-9 : 0);
187931  for(iOff--; iOff>iLimit; iOff--){
187932  if( (a[iOff-1] & 0x80)==0 ) break;
187933  }
187934 
187935  fts5GetVarint(&a[iOff], (u64*)&iVal);
187936  pLvl->iRowid -= iVal;
187937  pLvl->iLeafPgno--;
187938 
187939  /* Skip backwards past any 0x00 varints. */
187940  for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
187941  nZero++;
187942  }
187943  if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
187944  /* The byte immediately before the last 0x00 byte has the 0x80 bit
187945  ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
187946  ** bytes before a[ii]. */
187947  int bZero = 0; /* True if last 0x00 counts */
187948  if( (ii-8)>=pLvl->iFirstOff ){
187949  int j;
187950  for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
187951  bZero = (j>8);
187952  }
187953  if( bZero==0 ) nZero--;
187954  }
187955  pLvl->iLeafPgno -= nZero;
187956  pLvl->iOff = iOff - nZero;
187957  }
187958 
187959  return pLvl->bEof;
187960 }
187961 
187962 static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
187963  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
187964 
187965  assert( iLvl<pIter->nLvl );
187966  if( fts5DlidxLvlPrev(pLvl) ){
187967  if( (iLvl+1) < pIter->nLvl ){
187968  fts5DlidxIterPrevR(p, pIter, iLvl+1);
187969  if( pLvl[1].bEof==0 ){
187970  fts5DataRelease(pLvl->pData);
187971  memset(pLvl, 0, sizeof(Fts5DlidxLvl));
187972  pLvl->pData = fts5DataRead(p,
187973  FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
187974  );
187975  if( pLvl->pData ){
187976  while( fts5DlidxLvlNext(pLvl)==0 );
187977  pLvl->bEof = 0;
187978  }
187979  }
187980  }
187981  }
187982 
187983  return pIter->aLvl[0].bEof;
187984 }
187985 static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
187986  return fts5DlidxIterPrevR(p, pIter, 0);
187987 }
187988 
187989 /*
187990 ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
187991 */
187992 static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
187993  if( pIter ){
187994  int i;
187995  for(i=0; i<pIter->nLvl; i++){
187996  fts5DataRelease(pIter->aLvl[i].pData);
187997  }
187998  sqlite3_free(pIter);
187999  }
188000 }
188001 
188002 static Fts5DlidxIter *fts5DlidxIterInit(
188003  Fts5Index *p, /* Fts5 Backend to iterate within */
188004  int bRev, /* True for ORDER BY ASC */
188005  int iSegid, /* Segment id */
188006  int iLeafPg /* Leaf page number to load dlidx for */
188007 ){
188008  Fts5DlidxIter *pIter = 0;
188009  int i;
188010  int bDone = 0;
188011 
188012  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
188013  int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
188014  Fts5DlidxIter *pNew;
188015 
188016  pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
188017  if( pNew==0 ){
188018  p->rc = SQLITE_NOMEM;
188019  }else{
188020  i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
188021  Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
188022  pIter = pNew;
188023  memset(pLvl, 0, sizeof(Fts5DlidxLvl));
188024  pLvl->pData = fts5DataRead(p, iRowid);
188025  if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
188026  bDone = 1;
188027  }
188028  pIter->nLvl = i+1;
188029  }
188030  }
188031 
188032  if( p->rc==SQLITE_OK ){
188033  pIter->iSegid = iSegid;
188034  if( bRev==0 ){
188035  fts5DlidxIterFirst(pIter);
188036  }else{
188037  fts5DlidxIterLast(p, pIter);
188038  }
188039  }
188040 
188041  if( p->rc!=SQLITE_OK ){
188042  fts5DlidxIterFree(pIter);
188043  pIter = 0;
188044  }
188045 
188046  return pIter;
188047 }
188048 
188049 static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
188050  return pIter->aLvl[0].iRowid;
188051 }
188052 static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
188053  return pIter->aLvl[0].iLeafPgno;
188054 }
188055 
188056 /*
188057 ** Load the next leaf page into the segment iterator.
188058 */
188059 static void fts5SegIterNextPage(
188060  Fts5Index *p, /* FTS5 backend object */
188061  Fts5SegIter *pIter /* Iterator to advance to next page */
188062 ){
188063  Fts5Data *pLeaf;
188064  Fts5StructureSegment *pSeg = pIter->pSeg;
188065  fts5DataRelease(pIter->pLeaf);
188066  pIter->iLeafPgno++;
188067  if( pIter->pNextLeaf ){
188068  pIter->pLeaf = pIter->pNextLeaf;
188069  pIter->pNextLeaf = 0;
188070  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
188071  pIter->pLeaf = fts5LeafRead(p,
188072  FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
188073  );
188074  }else{
188075  pIter->pLeaf = 0;
188076  }
188077  pLeaf = pIter->pLeaf;
188078 
188079  if( pLeaf ){
188080  pIter->iPgidxOff = pLeaf->szLeaf;
188081  if( fts5LeafIsTermless(pLeaf) ){
188082  pIter->iEndofDoclist = pLeaf->nn+1;
188083  }else{
188084  pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
188085  pIter->iEndofDoclist
188086  );
188087  }
188088  }
188089 }
188090 
188091 /*
188092 ** Argument p points to a buffer containing a varint to be interpreted as a
188093 ** position list size field. Read the varint and return the number of bytes
188094 ** read. Before returning, set *pnSz to the number of bytes in the position
188095 ** list, and *pbDel to true if the delete flag is set, or false otherwise.
188096 */
188097 static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
188098  int nSz;
188099  int n = 0;
188100  fts5FastGetVarint32(p, n, nSz);
188101  assert_nc( nSz>=0 );
188102  *pnSz = nSz/2;
188103  *pbDel = nSz & 0x0001;
188104  return n;
188105 }
188106 
188107 /*
188108 ** Fts5SegIter.iLeafOffset currently points to the first byte of a
188109 ** position-list size field. Read the value of the field and store it
188110 ** in the following variables:
188111 **
188112 ** Fts5SegIter.nPos
188113 ** Fts5SegIter.bDel
188114 **
188115 ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
188116 ** position list content (if any).
188117 */
188118 static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
188119  if( p->rc==SQLITE_OK ){
188120  int iOff = pIter->iLeafOffset; /* Offset to read at */
188121  ASSERT_SZLEAF_OK(pIter->pLeaf);
188122  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
188123  int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
188124  pIter->bDel = 0;
188125  pIter->nPos = 1;
188126  if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
188127  pIter->bDel = 1;
188128  iOff++;
188129  if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
188130  pIter->nPos = 1;
188131  iOff++;
188132  }else{
188133  pIter->nPos = 0;
188134  }
188135  }
188136  }else{
188137  int nSz;
188138  fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
188139  pIter->bDel = (nSz & 0x0001);
188140  pIter->nPos = nSz>>1;
188141  assert_nc( pIter->nPos>=0 );
188142  }
188143  pIter->iLeafOffset = iOff;
188144  }
188145 }
188146 
188147 static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
188148  u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
188149  int iOff = pIter->iLeafOffset;
188150 
188151  ASSERT_SZLEAF_OK(pIter->pLeaf);
188152  if( iOff>=pIter->pLeaf->szLeaf ){
188153  fts5SegIterNextPage(p, pIter);
188154  if( pIter->pLeaf==0 ){
188155  if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
188156  return;
188157  }
188158  iOff = 4;
188159  a = pIter->pLeaf->p;
188160  }
188161  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
188162  pIter->iLeafOffset = iOff;
188163 }
188164 
188165 /*
188166 ** Fts5SegIter.iLeafOffset currently points to the first byte of the
188167 ** "nSuffix" field of a term. Function parameter nKeep contains the value
188168 ** of the "nPrefix" field (if there was one - it is passed 0 if this is
188169 ** the first term in the segment).
188170 **
188171 ** This function populates:
188172 **
188173 ** Fts5SegIter.term
188174 ** Fts5SegIter.rowid
188175 **
188176 ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
188177 ** the first position list. The position list belonging to document
188178 ** (Fts5SegIter.iRowid).
188179 */
188180 static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
188181  u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
188182  int iOff = pIter->iLeafOffset; /* Offset to read at */
188183  int nNew; /* Bytes of new data */
188184 
188185  iOff += fts5GetVarint32(&a[iOff], nNew);
188186  if( iOff+nNew>pIter->pLeaf->nn ){
188187  p->rc = FTS5_CORRUPT;
188188  return;
188189  }
188190  pIter->term.n = nKeep;
188191  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
188192  iOff += nNew;
188193  pIter->iTermLeafOffset = iOff;
188194  pIter->iTermLeafPgno = pIter->iLeafPgno;
188195  pIter->iLeafOffset = iOff;
188196 
188197  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
188198  pIter->iEndofDoclist = pIter->pLeaf->nn+1;
188199  }else{
188200  int nExtra;
188201  pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
188202  pIter->iEndofDoclist += nExtra;
188203  }
188204 
188205  fts5SegIterLoadRowid(p, pIter);
188206 }
188207 
188208 static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
188209 static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
188210 static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
188211 
188212 static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
188213  if( pIter->flags & FTS5_SEGITER_REVERSE ){
188214  pIter->xNext = fts5SegIterNext_Reverse;
188215  }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
188216  pIter->xNext = fts5SegIterNext_None;
188217  }else{
188218  pIter->xNext = fts5SegIterNext;
188219  }
188220 }
188221 
188222 /*
188223 ** Initialize the iterator object pIter to iterate through the entries in
188224 ** segment pSeg. The iterator is left pointing to the first entry when
188225 ** this function returns.
188226 **
188227 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
188228 ** an error has already occurred when this function is called, it is a no-op.
188229 */
188230 static void fts5SegIterInit(
188231  Fts5Index *p, /* FTS index object */
188232  Fts5StructureSegment *pSeg, /* Description of segment */
188233  Fts5SegIter *pIter /* Object to populate */
188234 ){
188235  if( pSeg->pgnoFirst==0 ){
188236  /* This happens if the segment is being used as an input to an incremental
188237  ** merge and all data has already been "trimmed". See function
188238  ** fts5TrimSegments() for details. In this case leave the iterator empty.
188239  ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
188240  ** at EOF already. */
188241  assert( pIter->pLeaf==0 );
188242  return;
188243  }
188244 
188245  if( p->rc==SQLITE_OK ){
188246  memset(pIter, 0, sizeof(*pIter));
188247  fts5SegIterSetNext(p, pIter);
188248  pIter->pSeg = pSeg;
188249  pIter->iLeafPgno = pSeg->pgnoFirst-1;
188250  fts5SegIterNextPage(p, pIter);
188251  }
188252 
188253  if( p->rc==SQLITE_OK ){
188254  pIter->iLeafOffset = 4;
188255  assert_nc( pIter->pLeaf->nn>4 );
188256  assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
188257  pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
188258  fts5SegIterLoadTerm(p, pIter, 0);
188259  fts5SegIterLoadNPos(p, pIter);
188260  }
188261 }
188262 
188263 /*
188264 ** This function is only ever called on iterators created by calls to
188265 ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
188266 **
188267 ** The iterator is in an unusual state when this function is called: the
188268 ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
188269 ** the position-list size field for the first relevant rowid on the page.
188270 ** Fts5SegIter.rowid is set, but nPos and bDel are not.
188271 **
188272 ** This function advances the iterator so that it points to the last
188273 ** relevant rowid on the page and, if necessary, initializes the
188274 ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
188275 ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
188276 ** byte of the position list content associated with said rowid.
188277 */
188278 static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
188279  int eDetail = p->pConfig->eDetail;
188280  int n = pIter->pLeaf->szLeaf;
188281  int i = pIter->iLeafOffset;
188282  u8 *a = pIter->pLeaf->p;
188283  int iRowidOffset = 0;
188284 
188285  if( n>pIter->iEndofDoclist ){
188286  n = pIter->iEndofDoclist;
188287  }
188288 
188289  ASSERT_SZLEAF_OK(pIter->pLeaf);
188290  while( 1 ){
188291  i64 iDelta = 0;
188292 
188293  if( eDetail==FTS5_DETAIL_NONE ){
188294  /* todo */
188295  if( i<n && a[i]==0 ){
188296  i++;
188297  if( i<n && a[i]==0 ) i++;
188298  }
188299  }else{
188300  int nPos;
188301  int bDummy;
188302  i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
188303  i += nPos;
188304  }
188305  if( i>=n ) break;
188306  i += fts5GetVarint(&a[i], (u64*)&iDelta);
188307  pIter->iRowid += iDelta;
188308 
188309  /* If necessary, grow the pIter->aRowidOffset[] array. */
188310  if( iRowidOffset>=pIter->nRowidOffset ){
188311  int nNew = pIter->nRowidOffset + 8;
188312  int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
188313  if( aNew==0 ){
188314  p->rc = SQLITE_NOMEM;
188315  break;
188316  }
188317  pIter->aRowidOffset = aNew;
188318  pIter->nRowidOffset = nNew;
188319  }
188320 
188321  pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
188322  pIter->iLeafOffset = i;
188323  }
188324  pIter->iRowidOffset = iRowidOffset;
188325  fts5SegIterLoadNPos(p, pIter);
188326 }
188327 
188328 /*
188329 **
188330 */
188331 static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
188332  assert( pIter->flags & FTS5_SEGITER_REVERSE );
188333  assert( pIter->flags & FTS5_SEGITER_ONETERM );
188334 
188335  fts5DataRelease(pIter->pLeaf);
188336  pIter->pLeaf = 0;
188337  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
188338  Fts5Data *pNew;
188339  pIter->iLeafPgno--;
188340  pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
188341  pIter->pSeg->iSegid, pIter->iLeafPgno
188342  ));
188343  if( pNew ){
188344  /* iTermLeafOffset may be equal to szLeaf if the term is the last
188345  ** thing on the page - i.e. the first rowid is on the following page.
188346  ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
188347  if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
188348  assert( pIter->pLeaf==0 );
188349  if( pIter->iTermLeafOffset<pNew->szLeaf ){
188350  pIter->pLeaf = pNew;
188351  pIter->iLeafOffset = pIter->iTermLeafOffset;
188352  }
188353  }else{
188354  int iRowidOff;
188355  iRowidOff = fts5LeafFirstRowidOff(pNew);
188356  if( iRowidOff ){
188357  pIter->pLeaf = pNew;
188358  pIter->iLeafOffset = iRowidOff;
188359  }
188360  }
188361 
188362  if( pIter->pLeaf ){
188363  u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
188364  pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
188365  break;
188366  }else{
188367  fts5DataRelease(pNew);
188368  }
188369  }
188370  }
188371 
188372  if( pIter->pLeaf ){
188373  pIter->iEndofDoclist = pIter->pLeaf->nn+1;
188374  fts5SegIterReverseInitPage(p, pIter);
188375  }
188376 }
188377 
188378 /*
188379 ** Return true if the iterator passed as the second argument currently
188380 ** points to a delete marker. A delete marker is an entry with a 0 byte
188381 ** position-list.
188382 */
188383 static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
188384  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
188385  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
188386 }
188387 
188388 /*
188389 ** Advance iterator pIter to the next entry.
188390 **
188391 ** This version of fts5SegIterNext() is only used by reverse iterators.
188392 */
188393 static void fts5SegIterNext_Reverse(
188394  Fts5Index *p, /* FTS5 backend object */
188395  Fts5SegIter *pIter, /* Iterator to advance */
188396  int *pbUnused /* Unused */
188397 ){
188398  assert( pIter->flags & FTS5_SEGITER_REVERSE );
188399  assert( pIter->pNextLeaf==0 );
188400  UNUSED_PARAM(pbUnused);
188401 
188402  if( pIter->iRowidOffset>0 ){
188403  u8 *a = pIter->pLeaf->p;
188404  int iOff;
188405  i64 iDelta;
188406 
188407  pIter->iRowidOffset--;
188408  pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
188409  fts5SegIterLoadNPos(p, pIter);
188410  iOff = pIter->iLeafOffset;
188411  if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
188412  iOff += pIter->nPos;
188413  }
188414  fts5GetVarint(&a[iOff], (u64*)&iDelta);
188415  pIter->iRowid -= iDelta;
188416  }else{
188417  fts5SegIterReverseNewPage(p, pIter);
188418  }
188419 }
188420 
188421 /*
188422 ** Advance iterator pIter to the next entry.
188423 **
188424 ** This version of fts5SegIterNext() is only used if detail=none and the
188425 ** iterator is not a reverse direction iterator.
188426 */
188427 static void fts5SegIterNext_None(
188428  Fts5Index *p, /* FTS5 backend object */
188429  Fts5SegIter *pIter, /* Iterator to advance */
188430  int *pbNewTerm /* OUT: Set for new term */
188431 ){
188432  int iOff;
188433 
188434  assert( p->rc==SQLITE_OK );
188435  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
188436  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
188437 
188438  ASSERT_SZLEAF_OK(pIter->pLeaf);
188439  iOff = pIter->iLeafOffset;
188440 
188441  /* Next entry is on the next page */
188442  if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
188443  fts5SegIterNextPage(p, pIter);
188444  if( p->rc || pIter->pLeaf==0 ) return;
188445  pIter->iRowid = 0;
188446  iOff = 4;
188447  }
188448 
188449  if( iOff<pIter->iEndofDoclist ){
188450  /* Next entry is on the current page */
188451  i64 iDelta;
188452  iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
188453  pIter->iLeafOffset = iOff;
188454  pIter->iRowid += iDelta;
188455  }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
188456  if( pIter->pSeg ){
188457  int nKeep = 0;
188458  if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
188459  iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
188460  }
188461  pIter->iLeafOffset = iOff;
188462  fts5SegIterLoadTerm(p, pIter, nKeep);
188463  }else{
188464  const u8 *pList = 0;
188465  const char *zTerm = 0;
188466  int nList;
188467  sqlite3Fts5HashScanNext(p->pHash);
188468  sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
188469  if( pList==0 ) goto next_none_eof;
188470  pIter->pLeaf->p = (u8*)pList;
188471  pIter->pLeaf->nn = nList;
188472  pIter->pLeaf->szLeaf = nList;
188473  pIter->iEndofDoclist = nList;
188474  sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
188475  pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
188476  }
188477 
188478  if( pbNewTerm ) *pbNewTerm = 1;
188479  }else{
188480  goto next_none_eof;
188481  }
188482 
188483  fts5SegIterLoadNPos(p, pIter);
188484 
188485  return;
188486  next_none_eof:
188487  fts5DataRelease(pIter->pLeaf);
188488  pIter->pLeaf = 0;
188489 }
188490 
188491 
188492 /*
188493 ** Advance iterator pIter to the next entry.
188494 **
188495 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
188496 ** is not considered an error if the iterator reaches EOF. If an error has
188497 ** already occurred when this function is called, it is a no-op.
188498 */
188499 static void fts5SegIterNext(
188500  Fts5Index *p, /* FTS5 backend object */
188501  Fts5SegIter *pIter, /* Iterator to advance */
188502  int *pbNewTerm /* OUT: Set for new term */
188503 ){
188504  Fts5Data *pLeaf = pIter->pLeaf;
188505  int iOff;
188506  int bNewTerm = 0;
188507  int nKeep = 0;
188508  u8 *a;
188509  int n;
188510 
188511  assert( pbNewTerm==0 || *pbNewTerm==0 );
188512  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
188513 
188514  /* Search for the end of the position list within the current page. */
188515  a = pLeaf->p;
188516  n = pLeaf->szLeaf;
188517 
188518  ASSERT_SZLEAF_OK(pLeaf);
188519  iOff = pIter->iLeafOffset + pIter->nPos;
188520 
188521  if( iOff<n ){
188522  /* The next entry is on the current page. */
188523  assert_nc( iOff<=pIter->iEndofDoclist );
188524  if( iOff>=pIter->iEndofDoclist ){
188525  bNewTerm = 1;
188526  if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
188527  iOff += fts5GetVarint32(&a[iOff], nKeep);
188528  }
188529  }else{
188530  u64 iDelta;
188531  iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
188532  pIter->iRowid += iDelta;
188533  assert_nc( iDelta>0 );
188534  }
188535  pIter->iLeafOffset = iOff;
188536 
188537  }else if( pIter->pSeg==0 ){
188538  const u8 *pList = 0;
188539  const char *zTerm = 0;
188540  int nList = 0;
188541  assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
188542  if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
188543  sqlite3Fts5HashScanNext(p->pHash);
188544  sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
188545  }
188546  if( pList==0 ){
188547  fts5DataRelease(pIter->pLeaf);
188548  pIter->pLeaf = 0;
188549  }else{
188550  pIter->pLeaf->p = (u8*)pList;
188551  pIter->pLeaf->nn = nList;
188552  pIter->pLeaf->szLeaf = nList;
188553  pIter->iEndofDoclist = nList+1;
188554  sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
188555  (u8*)zTerm);
188556  pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
188557  *pbNewTerm = 1;
188558  }
188559  }else{
188560  iOff = 0;
188561  /* Next entry is not on the current page */
188562  while( iOff==0 ){
188563  fts5SegIterNextPage(p, pIter);
188564  pLeaf = pIter->pLeaf;
188565  if( pLeaf==0 ) break;
188566  ASSERT_SZLEAF_OK(pLeaf);
188567  if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
188568  iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
188569  pIter->iLeafOffset = iOff;
188570 
188571  if( pLeaf->nn>pLeaf->szLeaf ){
188572  pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
188573  &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
188574  );
188575  }
188576  }
188577  else if( pLeaf->nn>pLeaf->szLeaf ){
188578  pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
188579  &pLeaf->p[pLeaf->szLeaf], iOff
188580  );
188581  pIter->iLeafOffset = iOff;
188582  pIter->iEndofDoclist = iOff;
188583  bNewTerm = 1;
188584  }
188585  assert_nc( iOff<pLeaf->szLeaf );
188586  if( iOff>pLeaf->szLeaf ){
188587  p->rc = FTS5_CORRUPT;
188588  return;
188589  }
188590  }
188591  }
188592 
188593  /* Check if the iterator is now at EOF. If so, return early. */
188594  if( pIter->pLeaf ){
188595  if( bNewTerm ){
188596  if( pIter->flags & FTS5_SEGITER_ONETERM ){
188597  fts5DataRelease(pIter->pLeaf);
188598  pIter->pLeaf = 0;
188599  }else{
188600  fts5SegIterLoadTerm(p, pIter, nKeep);
188601  fts5SegIterLoadNPos(p, pIter);
188602  if( pbNewTerm ) *pbNewTerm = 1;
188603  }
188604  }else{
188605  /* The following could be done by calling fts5SegIterLoadNPos(). But
188606  ** this block is particularly performance critical, so equivalent
188607  ** code is inlined.
188608  **
188609  ** Later: Switched back to fts5SegIterLoadNPos() because it supports
188610  ** detail=none mode. Not ideal.
188611  */
188612  int nSz;
188613  assert( p->rc==SQLITE_OK );
188614  fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
188615  pIter->bDel = (nSz & 0x0001);
188616  pIter->nPos = nSz>>1;
188617  assert_nc( pIter->nPos>=0 );
188618  }
188619  }
188620 }
188621 
188622 #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
188623 
188624 #define fts5IndexSkipVarint(a, iOff) { \
188625  int iEnd = iOff+9; \
188626  while( (a[iOff++] & 0x80) && iOff<iEnd ); \
188627 }
188628 
188629 /*
188630 ** Iterator pIter currently points to the first rowid in a doclist. This
188631 ** function sets the iterator up so that iterates in reverse order through
188632 ** the doclist.
188633 */
188634 static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
188635  Fts5DlidxIter *pDlidx = pIter->pDlidx;
188636  Fts5Data *pLast = 0;
188637  int pgnoLast = 0;
188638 
188639  if( pDlidx ){
188640  int iSegid = pIter->pSeg->iSegid;
188641  pgnoLast = fts5DlidxIterPgno(pDlidx);
188642  pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
188643  }else{
188644  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
188645 
188646  /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
188647  ** position-list content for the current rowid. Back it up so that it
188648  ** points to the start of the position-list size field. */
188649  int iPoslist;
188650  if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
188651  iPoslist = pIter->iTermLeafOffset;
188652  }else{
188653  iPoslist = 4;
188654  }
188655  fts5IndexSkipVarint(pLeaf->p, iPoslist);
188656  pIter->iLeafOffset = iPoslist;
188657 
188658  /* If this condition is true then the largest rowid for the current
188659  ** term may not be stored on the current page. So search forward to
188660  ** see where said rowid really is. */
188661  if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
188662  int pgno;
188663  Fts5StructureSegment *pSeg = pIter->pSeg;
188664 
188665  /* The last rowid in the doclist may not be on the current page. Search
188666  ** forward to find the page containing the last rowid. */
188667  for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
188668  i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
188669  Fts5Data *pNew = fts5DataRead(p, iAbs);
188670  if( pNew ){
188671  int iRowid, bTermless;
188672  iRowid = fts5LeafFirstRowidOff(pNew);
188673  bTermless = fts5LeafIsTermless(pNew);
188674  if( iRowid ){
188675  SWAPVAL(Fts5Data*, pNew, pLast);
188676  pgnoLast = pgno;
188677  }
188678  fts5DataRelease(pNew);
188679  if( bTermless==0 ) break;
188680  }
188681  }
188682  }
188683  }
188684 
188685  /* If pLast is NULL at this point, then the last rowid for this doclist
188686  ** lies on the page currently indicated by the iterator. In this case
188687  ** pIter->iLeafOffset is already set to point to the position-list size
188688  ** field associated with the first relevant rowid on the page.
188689  **
188690  ** Or, if pLast is non-NULL, then it is the page that contains the last
188691  ** rowid. In this case configure the iterator so that it points to the
188692  ** first rowid on this page.
188693  */
188694  if( pLast ){
188695  int iOff;
188696  fts5DataRelease(pIter->pLeaf);
188697  pIter->pLeaf = pLast;
188698  pIter->iLeafPgno = pgnoLast;
188699  iOff = fts5LeafFirstRowidOff(pLast);
188700  iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
188701  pIter->iLeafOffset = iOff;
188702 
188703  if( fts5LeafIsTermless(pLast) ){
188704  pIter->iEndofDoclist = pLast->nn+1;
188705  }else{
188706  pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
188707  }
188708 
188709  }
188710 
188711  fts5SegIterReverseInitPage(p, pIter);
188712 }
188713 
188714 /*
188715 ** Iterator pIter currently points to the first rowid of a doclist.
188716 ** There is a doclist-index associated with the final term on the current
188717 ** page. If the current term is the last term on the page, load the
188718 ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
188719 */
188720 static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
188721  int iSeg = pIter->pSeg->iSegid;
188722  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
188723  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
188724 
188725  assert( pIter->flags & FTS5_SEGITER_ONETERM );
188726  assert( pIter->pDlidx==0 );
188727 
188728  /* Check if the current doclist ends on this page. If it does, return
188729  ** early without loading the doclist-index (as it belongs to a different
188730  ** term. */
188731  if( pIter->iTermLeafPgno==pIter->iLeafPgno
188732  && pIter->iEndofDoclist<pLeaf->szLeaf
188733  ){
188734  return;
188735  }
188736 
188737  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
188738 }
188739 
188740 /*
188741 ** The iterator object passed as the second argument currently contains
188742 ** no valid values except for the Fts5SegIter.pLeaf member variable. This
188743 ** function searches the leaf page for a term matching (pTerm/nTerm).
188744 **
188745 ** If the specified term is found on the page, then the iterator is left
188746 ** pointing to it. If argument bGe is zero and the term is not found,
188747 ** the iterator is left pointing at EOF.
188748 **
188749 ** If bGe is non-zero and the specified term is not found, then the
188750 ** iterator is left pointing to the smallest term in the segment that
188751 ** is larger than the specified term, even if this term is not on the
188752 ** current page.
188753 */
188754 static void fts5LeafSeek(
188755  Fts5Index *p, /* Leave any error code here */
188756  int bGe, /* True for a >= search */
188757  Fts5SegIter *pIter, /* Iterator to seek */
188758  const u8 *pTerm, int nTerm /* Term to search for */
188759 ){
188760  int iOff;
188761  const u8 *a = pIter->pLeaf->p;
188762  int szLeaf = pIter->pLeaf->szLeaf;
188763  int n = pIter->pLeaf->nn;
188764 
188765  int nMatch = 0;
188766  int nKeep = 0;
188767  int nNew = 0;
188768  int iTermOff;
188769  int iPgidx; /* Current offset in pgidx */
188770  int bEndOfPage = 0;
188771 
188772  assert( p->rc==SQLITE_OK );
188773 
188774  iPgidx = szLeaf;
188775  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
188776  iOff = iTermOff;
188777  if( iOff>n ){
188778  p->rc = FTS5_CORRUPT;
188779  return;
188780  }
188781 
188782  while( 1 ){
188783 
188784  /* Figure out how many new bytes are in this term */
188785  fts5FastGetVarint32(a, iOff, nNew);
188786  if( nKeep<nMatch ){
188787  goto search_failed;
188788  }
188789 
188790  assert( nKeep>=nMatch );
188791  if( nKeep==nMatch ){
188792  int nCmp;
188793  int i;
188794  nCmp = MIN(nNew, nTerm-nMatch);
188795  for(i=0; i<nCmp; i++){
188796  if( a[iOff+i]!=pTerm[nMatch+i] ) break;
188797  }
188798  nMatch += i;
188799 
188800  if( nTerm==nMatch ){
188801  if( i==nNew ){
188802  goto search_success;
188803  }else{
188804  goto search_failed;
188805  }
188806  }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
188807  goto search_failed;
188808  }
188809  }
188810 
188811  if( iPgidx>=n ){
188812  bEndOfPage = 1;
188813  break;
188814  }
188815 
188816  iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
188817  iTermOff += nKeep;
188818  iOff = iTermOff;
188819 
188820  if( iOff>=n ){
188821  p->rc = FTS5_CORRUPT;
188822  return;
188823  }
188824 
188825  /* Read the nKeep field of the next term. */
188826  fts5FastGetVarint32(a, iOff, nKeep);
188827  }
188828 
188829  search_failed:
188830  if( bGe==0 ){
188831  fts5DataRelease(pIter->pLeaf);
188832  pIter->pLeaf = 0;
188833  return;
188834  }else if( bEndOfPage ){
188835  do {
188836  fts5SegIterNextPage(p, pIter);
188837  if( pIter->pLeaf==0 ) return;
188838  a = pIter->pLeaf->p;
188839  if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
188840  iPgidx = pIter->pLeaf->szLeaf;
188841  iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
188842  if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
188843  p->rc = FTS5_CORRUPT;
188844  }else{
188845  nKeep = 0;
188846  iTermOff = iOff;
188847  n = pIter->pLeaf->nn;
188848  iOff += fts5GetVarint32(&a[iOff], nNew);
188849  break;
188850  }
188851  }
188852  }while( 1 );
188853  }
188854 
188855  search_success:
188856 
188857  pIter->iLeafOffset = iOff + nNew;
188858  pIter->iTermLeafOffset = pIter->iLeafOffset;
188859  pIter->iTermLeafPgno = pIter->iLeafPgno;
188860 
188861  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
188862  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
188863 
188864  if( iPgidx>=n ){
188865  pIter->iEndofDoclist = pIter->pLeaf->nn+1;
188866  }else{
188867  int nExtra;
188868  iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
188869  pIter->iEndofDoclist = iTermOff + nExtra;
188870  }
188871  pIter->iPgidxOff = iPgidx;
188872 
188873  fts5SegIterLoadRowid(p, pIter);
188874  fts5SegIterLoadNPos(p, pIter);
188875 }
188876 
188877 static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
188878  if( p->pIdxSelect==0 ){
188879  Fts5Config *pConfig = p->pConfig;
188880  fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
188881  "SELECT pgno FROM '%q'.'%q_idx' WHERE "
188882  "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
188883  pConfig->zDb, pConfig->zName
188884  ));
188885  }
188886  return p->pIdxSelect;
188887 }
188888 
188889 /*
188890 ** Initialize the object pIter to point to term pTerm/nTerm within segment
188891 ** pSeg. If there is no such term in the index, the iterator is set to EOF.
188892 **
188893 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
188894 ** an error has already occurred when this function is called, it is a no-op.
188895 */
188896 static void fts5SegIterSeekInit(
188897  Fts5Index *p, /* FTS5 backend */
188898  const u8 *pTerm, int nTerm, /* Term to seek to */
188899  int flags, /* Mask of FTS5INDEX_XXX flags */
188900  Fts5StructureSegment *pSeg, /* Description of segment */
188901  Fts5SegIter *pIter /* Object to populate */
188902 ){
188903  int iPg = 1;
188904  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
188905  int bDlidx = 0; /* True if there is a doclist-index */
188906  sqlite3_stmt *pIdxSelect = 0;
188907 
188908  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
188909  assert( pTerm && nTerm );
188910  memset(pIter, 0, sizeof(*pIter));
188911  pIter->pSeg = pSeg;
188912 
188913  /* This block sets stack variable iPg to the leaf page number that may
188914  ** contain term (pTerm/nTerm), if it is present in the segment. */
188915  pIdxSelect = fts5IdxSelectStmt(p);
188916  if( p->rc ) return;
188917  sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
188918  sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
188919  if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
188920  i64 val = sqlite3_column_int(pIdxSelect, 0);
188921  iPg = (int)(val>>1);
188922  bDlidx = (val & 0x0001);
188923  }
188924  p->rc = sqlite3_reset(pIdxSelect);
188925 
188926  if( iPg<pSeg->pgnoFirst ){
188927  iPg = pSeg->pgnoFirst;
188928  bDlidx = 0;
188929  }
188930 
188931  pIter->iLeafPgno = iPg - 1;
188932  fts5SegIterNextPage(p, pIter);
188933 
188934  if( pIter->pLeaf ){
188935  fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
188936  }
188937 
188938  if( p->rc==SQLITE_OK && bGe==0 ){
188939  pIter->flags |= FTS5_SEGITER_ONETERM;
188940  if( pIter->pLeaf ){
188941  if( flags & FTS5INDEX_QUERY_DESC ){
188942  pIter->flags |= FTS5_SEGITER_REVERSE;
188943  }
188944  if( bDlidx ){
188945  fts5SegIterLoadDlidx(p, pIter);
188946  }
188947  if( flags & FTS5INDEX_QUERY_DESC ){
188948  fts5SegIterReverse(p, pIter);
188949  }
188950  }
188951  }
188952 
188953  fts5SegIterSetNext(p, pIter);
188954 
188955  /* Either:
188956  **
188957  ** 1) an error has occurred, or
188958  ** 2) the iterator points to EOF, or
188959  ** 3) the iterator points to an entry with term (pTerm/nTerm), or
188960  ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
188961  ** to an entry with a term greater than or equal to (pTerm/nTerm).
188962  */
188963  assert( p->rc!=SQLITE_OK /* 1 */
188964  || pIter->pLeaf==0 /* 2 */
188965  || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
188966  || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
188967  );
188968 }
188969 
188970 /*
188971 ** Initialize the object pIter to point to term pTerm/nTerm within the
188972 ** in-memory hash table. If there is no such term in the hash-table, the
188973 ** iterator is set to EOF.
188974 **
188975 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
188976 ** an error has already occurred when this function is called, it is a no-op.
188977 */
188978 static void fts5SegIterHashInit(
188979  Fts5Index *p, /* FTS5 backend */
188980  const u8 *pTerm, int nTerm, /* Term to seek to */
188981  int flags, /* Mask of FTS5INDEX_XXX flags */
188982  Fts5SegIter *pIter /* Object to populate */
188983 ){
188984  const u8 *pList = 0;
188985  int nList = 0;
188986  const u8 *z = 0;
188987  int n = 0;
188988 
188989  assert( p->pHash );
188990  assert( p->rc==SQLITE_OK );
188991 
188992  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
188993  p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
188994  sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
188995  n = (z ? (int)strlen((const char*)z) : 0);
188996  }else{
188997  pIter->flags |= FTS5_SEGITER_ONETERM;
188998  sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
188999  z = pTerm;
189000  n = nTerm;
189001  }
189002 
189003  if( pList ){
189004  Fts5Data *pLeaf;
189005  sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
189006  pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
189007  if( pLeaf==0 ) return;
189008  pLeaf->p = (u8*)pList;
189009  pLeaf->nn = pLeaf->szLeaf = nList;
189010  pIter->pLeaf = pLeaf;
189011  pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
189012  pIter->iEndofDoclist = pLeaf->nn;
189013 
189014  if( flags & FTS5INDEX_QUERY_DESC ){
189015  pIter->flags |= FTS5_SEGITER_REVERSE;
189016  fts5SegIterReverseInitPage(p, pIter);
189017  }else{
189018  fts5SegIterLoadNPos(p, pIter);
189019  }
189020  }
189021 
189022  fts5SegIterSetNext(p, pIter);
189023 }
189024 
189025 /*
189026 ** Zero the iterator passed as the only argument.
189027 */
189028 static void fts5SegIterClear(Fts5SegIter *pIter){
189029  fts5BufferFree(&pIter->term);
189030  fts5DataRelease(pIter->pLeaf);
189031  fts5DataRelease(pIter->pNextLeaf);
189032  fts5DlidxIterFree(pIter->pDlidx);
189033  sqlite3_free(pIter->aRowidOffset);
189034  memset(pIter, 0, sizeof(Fts5SegIter));
189035 }
189036 
189037 #ifdef SQLITE_DEBUG
189038 
189039 /*
189040 ** This function is used as part of the big assert() procedure implemented by
189041 ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
189042 ** in *pRes is the correct result of comparing the current positions of the
189043 ** two iterators.
189044 */
189045 static void fts5AssertComparisonResult(
189046  Fts5Iter *pIter,
189047  Fts5SegIter *p1,
189048  Fts5SegIter *p2,
189049  Fts5CResult *pRes
189050 ){
189051  int i1 = p1 - pIter->aSeg;
189052  int i2 = p2 - pIter->aSeg;
189053 
189054  if( p1->pLeaf || p2->pLeaf ){
189055  if( p1->pLeaf==0 ){
189056  assert( pRes->iFirst==i2 );
189057  }else if( p2->pLeaf==0 ){
189058  assert( pRes->iFirst==i1 );
189059  }else{
189060  int nMin = MIN(p1->term.n, p2->term.n);
189061  int res = memcmp(p1->term.p, p2->term.p, nMin);
189062  if( res==0 ) res = p1->term.n - p2->term.n;
189063 
189064  if( res==0 ){
189065  assert( pRes->bTermEq==1 );
189066  assert( p1->iRowid!=p2->iRowid );
189067  res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
189068  }else{
189069  assert( pRes->bTermEq==0 );
189070  }
189071 
189072  if( res<0 ){
189073  assert( pRes->iFirst==i1 );
189074  }else{
189075  assert( pRes->iFirst==i2 );
189076  }
189077  }
189078  }
189079 }
189080 
189081 /*
189082 ** This function is a no-op unless SQLITE_DEBUG is defined when this module
189083 ** is compiled. In that case, this function is essentially an assert()
189084 ** statement used to verify that the contents of the pIter->aFirst[] array
189085 ** are correct.
189086 */
189087 static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
189088  if( p->rc==SQLITE_OK ){
189089  Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
189090  int i;
189091 
189092  assert( (pFirst->pLeaf==0)==pIter->base.bEof );
189093 
189094  /* Check that pIter->iSwitchRowid is set correctly. */
189095  for(i=0; i<pIter->nSeg; i++){
189096  Fts5SegIter *p1 = &pIter->aSeg[i];
189097  assert( p1==pFirst
189098  || p1->pLeaf==0
189099  || fts5BufferCompare(&pFirst->term, &p1->term)
189100  || p1->iRowid==pIter->iSwitchRowid
189101  || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
189102  );
189103  }
189104 
189105  for(i=0; i<pIter->nSeg; i+=2){
189106  Fts5SegIter *p1 = &pIter->aSeg[i];
189107  Fts5SegIter *p2 = &pIter->aSeg[i+1];
189108  Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
189109  fts5AssertComparisonResult(pIter, p1, p2, pRes);
189110  }
189111 
189112  for(i=1; i<(pIter->nSeg / 2); i+=2){
189113  Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
189114  Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
189115  Fts5CResult *pRes = &pIter->aFirst[i];
189116  fts5AssertComparisonResult(pIter, p1, p2, pRes);
189117  }
189118  }
189119 }
189120 #else
189121 # define fts5AssertMultiIterSetup(x,y)
189122 #endif
189123 
189124 /*
189125 ** Do the comparison necessary to populate pIter->aFirst[iOut].
189126 **
189127 ** If the returned value is non-zero, then it is the index of an entry
189128 ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
189129 ** to a key that is a duplicate of another, higher priority,
189130 ** segment-iterator in the pSeg->aSeg[] array.
189131 */
189132 static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
189133  int i1; /* Index of left-hand Fts5SegIter */
189134  int i2; /* Index of right-hand Fts5SegIter */
189135  int iRes;
189136  Fts5SegIter *p1; /* Left-hand Fts5SegIter */
189137  Fts5SegIter *p2; /* Right-hand Fts5SegIter */
189138  Fts5CResult *pRes = &pIter->aFirst[iOut];
189139 
189140  assert( iOut<pIter->nSeg && iOut>0 );
189141  assert( pIter->bRev==0 || pIter->bRev==1 );
189142 
189143  if( iOut>=(pIter->nSeg/2) ){
189144  i1 = (iOut - pIter->nSeg/2) * 2;
189145  i2 = i1 + 1;
189146  }else{
189147  i1 = pIter->aFirst[iOut*2].iFirst;
189148  i2 = pIter->aFirst[iOut*2+1].iFirst;
189149  }
189150  p1 = &pIter->aSeg[i1];
189151  p2 = &pIter->aSeg[i2];
189152 
189153  pRes->bTermEq = 0;
189154  if( p1->pLeaf==0 ){ /* If p1 is at EOF */
189155  iRes = i2;
189156  }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
189157  iRes = i1;
189158  }else{
189159  int res = fts5BufferCompare(&p1->term, &p2->term);
189160  if( res==0 ){
189161  assert( i2>i1 );
189162  assert( i2!=0 );
189163  pRes->bTermEq = 1;
189164  if( p1->iRowid==p2->iRowid ){
189165  p1->bDel = p2->bDel;
189166  return i2;
189167  }
189168  res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
189169  }
189170  assert( res!=0 );
189171  if( res<0 ){
189172  iRes = i1;
189173  }else{
189174  iRes = i2;
189175  }
189176  }
189177 
189178  pRes->iFirst = (u16)iRes;
189179  return 0;
189180 }
189181 
189182 /*
189183 ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
189184 ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
189185 */
189186 static void fts5SegIterGotoPage(
189187  Fts5Index *p, /* FTS5 backend object */
189188  Fts5SegIter *pIter, /* Iterator to advance */
189189  int iLeafPgno
189190 ){
189191  assert( iLeafPgno>pIter->iLeafPgno );
189192 
189193  if( iLeafPgno>pIter->pSeg->pgnoLast ){
189194  p->rc = FTS5_CORRUPT;
189195  }else{
189196  fts5DataRelease(pIter->pNextLeaf);
189197  pIter->pNextLeaf = 0;
189198  pIter->iLeafPgno = iLeafPgno-1;
189199  fts5SegIterNextPage(p, pIter);
189200  assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
189201 
189202  if( p->rc==SQLITE_OK ){
189203  int iOff;
189204  u8 *a = pIter->pLeaf->p;
189205  int n = pIter->pLeaf->szLeaf;
189206 
189207  iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
189208  if( iOff<4 || iOff>=n ){
189209  p->rc = FTS5_CORRUPT;
189210  }else{
189211  iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
189212  pIter->iLeafOffset = iOff;
189213  fts5SegIterLoadNPos(p, pIter);
189214  }
189215  }
189216  }
189217 }
189218 
189219 /*
189220 ** Advance the iterator passed as the second argument until it is at or
189221 ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
189222 ** always advanced at least once.
189223 */
189224 static void fts5SegIterNextFrom(
189225  Fts5Index *p, /* FTS5 backend object */
189226  Fts5SegIter *pIter, /* Iterator to advance */
189227  i64 iMatch /* Advance iterator at least this far */
189228 ){
189229  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
189230  Fts5DlidxIter *pDlidx = pIter->pDlidx;
189231  int iLeafPgno = pIter->iLeafPgno;
189232  int bMove = 1;
189233 
189234  assert( pIter->flags & FTS5_SEGITER_ONETERM );
189235  assert( pIter->pDlidx );
189236  assert( pIter->pLeaf );
189237 
189238  if( bRev==0 ){
189239  while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
189240  iLeafPgno = fts5DlidxIterPgno(pDlidx);
189241  fts5DlidxIterNext(p, pDlidx);
189242  }
189243  assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
189244  if( iLeafPgno>pIter->iLeafPgno ){
189245  fts5SegIterGotoPage(p, pIter, iLeafPgno);
189246  bMove = 0;
189247  }
189248  }else{
189249  assert( pIter->pNextLeaf==0 );
189250  assert( iMatch<pIter->iRowid );
189251  while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
189252  fts5DlidxIterPrev(p, pDlidx);
189253  }
189254  iLeafPgno = fts5DlidxIterPgno(pDlidx);
189255 
189256  assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
189257 
189258  if( iLeafPgno<pIter->iLeafPgno ){
189259  pIter->iLeafPgno = iLeafPgno+1;
189260  fts5SegIterReverseNewPage(p, pIter);
189261  bMove = 0;
189262  }
189263  }
189264 
189265  do{
189266  if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
189267  if( pIter->pLeaf==0 ) break;
189268  if( bRev==0 && pIter->iRowid>=iMatch ) break;
189269  if( bRev!=0 && pIter->iRowid<=iMatch ) break;
189270  bMove = 1;
189271  }while( p->rc==SQLITE_OK );
189272 }
189273 
189274 
189275 /*
189276 ** Free the iterator object passed as the second argument.
189277 */
189278 static void fts5MultiIterFree(Fts5Iter *pIter){
189279  if( pIter ){
189280  int i;
189281  for(i=0; i<pIter->nSeg; i++){
189282  fts5SegIterClear(&pIter->aSeg[i]);
189283  }
189284  fts5StructureRelease(pIter->pStruct);
189285  fts5BufferFree(&pIter->poslist);
189286  sqlite3_free(pIter);
189287  }
189288 }
189289 
189290 static void fts5MultiIterAdvanced(
189291  Fts5Index *p, /* FTS5 backend to iterate within */
189292  Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
189293  int iChanged, /* Index of sub-iterator just advanced */
189294  int iMinset /* Minimum entry in aFirst[] to set */
189295 ){
189296  int i;
189297  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
189298  int iEq;
189299  if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
189300  Fts5SegIter *pSeg = &pIter->aSeg[iEq];
189301  assert( p->rc==SQLITE_OK );
189302  pSeg->xNext(p, pSeg, 0);
189303  i = pIter->nSeg + iEq;
189304  }
189305  }
189306 }
189307 
189308 /*
189309 ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
189310 ** points to the same term though - just a different rowid. This function
189311 ** attempts to update the contents of the pIter->aFirst[] accordingly.
189312 ** If it does so successfully, 0 is returned. Otherwise 1.
189313 **
189314 ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
189315 ** on the iterator instead. That function does the same as this one, except
189316 ** that it deals with more complicated cases as well.
189317 */
189318 static int fts5MultiIterAdvanceRowid(
189319  Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
189320  int iChanged, /* Index of sub-iterator just advanced */
189321  Fts5SegIter **ppFirst
189322 ){
189323  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
189324 
189325  if( pNew->iRowid==pIter->iSwitchRowid
189326  || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
189327  ){
189328  int i;
189329  Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
189330  pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
189331  for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
189332  Fts5CResult *pRes = &pIter->aFirst[i];
189333 
189334  assert( pNew->pLeaf );
189335  assert( pRes->bTermEq==0 || pOther->pLeaf );
189336 
189337  if( pRes->bTermEq ){
189338  if( pNew->iRowid==pOther->iRowid ){
189339  return 1;
189340  }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
189341  pIter->iSwitchRowid = pOther->iRowid;
189342  pNew = pOther;
189343  }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
189344  pIter->iSwitchRowid = pOther->iRowid;
189345  }
189346  }
189347  pRes->iFirst = (u16)(pNew - pIter->aSeg);
189348  if( i==1 ) break;
189349 
189350  pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
189351  }
189352  }
189353 
189354  *ppFirst = pNew;
189355  return 0;
189356 }
189357 
189358 /*
189359 ** Set the pIter->bEof variable based on the state of the sub-iterators.
189360 */
189361 static void fts5MultiIterSetEof(Fts5Iter *pIter){
189362  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
189363  pIter->base.bEof = pSeg->pLeaf==0;
189364  pIter->iSwitchRowid = pSeg->iRowid;
189365 }
189366 
189367 /*
189368 ** Move the iterator to the next entry.
189369 **
189370 ** If an error occurs, an error code is left in Fts5Index.rc. It is not
189371 ** considered an error if the iterator reaches EOF, or if it is already at
189372 ** EOF when this function is called.
189373 */
189374 static void fts5MultiIterNext(
189375  Fts5Index *p,
189376  Fts5Iter *pIter,
189377  int bFrom, /* True if argument iFrom is valid */
189378  i64 iFrom /* Advance at least as far as this */
189379 ){
189380  int bUseFrom = bFrom;
189381  while( p->rc==SQLITE_OK ){
189382  int iFirst = pIter->aFirst[1].iFirst;
189383  int bNewTerm = 0;
189384  Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
189385  assert( p->rc==SQLITE_OK );
189386  if( bUseFrom && pSeg->pDlidx ){
189387  fts5SegIterNextFrom(p, pSeg, iFrom);
189388  }else{
189389  pSeg->xNext(p, pSeg, &bNewTerm);
189390  }
189391 
189392  if( pSeg->pLeaf==0 || bNewTerm
189393  || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
189394  ){
189395  fts5MultiIterAdvanced(p, pIter, iFirst, 1);
189396  fts5MultiIterSetEof(pIter);
189397  pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
189398  if( pSeg->pLeaf==0 ) return;
189399  }
189400 
189401  fts5AssertMultiIterSetup(p, pIter);
189402  assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
189403  if( pIter->bSkipEmpty==0 || pSeg->nPos ){
189404  pIter->xSetOutputs(pIter, pSeg);
189405  return;
189406  }
189407  bUseFrom = 0;
189408  }
189409 }
189410 
189411 static void fts5MultiIterNext2(
189412  Fts5Index *p,
189413  Fts5Iter *pIter,
189414  int *pbNewTerm /* OUT: True if *might* be new term */
189415 ){
189416  assert( pIter->bSkipEmpty );
189417  if( p->rc==SQLITE_OK ){
189418  do {
189419  int iFirst = pIter->aFirst[1].iFirst;
189420  Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
189421  int bNewTerm = 0;
189422 
189423  assert( p->rc==SQLITE_OK );
189424  pSeg->xNext(p, pSeg, &bNewTerm);
189425  if( pSeg->pLeaf==0 || bNewTerm
189426  || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
189427  ){
189428  fts5MultiIterAdvanced(p, pIter, iFirst, 1);
189429  fts5MultiIterSetEof(pIter);
189430  *pbNewTerm = 1;
189431  }else{
189432  *pbNewTerm = 0;
189433  }
189434  fts5AssertMultiIterSetup(p, pIter);
189435 
189436  }while( fts5MultiIterIsEmpty(p, pIter) );
189437  }
189438 }
189439 
189440 static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
189441  UNUSED_PARAM2(pUnused1, pUnused2);
189442 }
189443 
189444 static Fts5Iter *fts5MultiIterAlloc(
189445  Fts5Index *p, /* FTS5 backend to iterate within */
189446  int nSeg
189447 ){
189448  Fts5Iter *pNew;
189449  int nSlot; /* Power of two >= nSeg */
189450 
189451  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
189452  pNew = fts5IdxMalloc(p,
189453  sizeof(Fts5Iter) + /* pNew */
189454  sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
189455  sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
189456  );
189457  if( pNew ){
189458  pNew->nSeg = nSlot;
189459  pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
189460  pNew->pIndex = p;
189461  pNew->xSetOutputs = fts5IterSetOutputs_Noop;
189462  }
189463  return pNew;
189464 }
189465 
189466 static void fts5PoslistCallback(
189467  Fts5Index *pUnused,
189468  void *pContext,
189469  const u8 *pChunk, int nChunk
189470 ){
189471  UNUSED_PARAM(pUnused);
189472  assert_nc( nChunk>=0 );
189473  if( nChunk>0 ){
189474  fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
189475  }
189476 }
189477 
189478 typedef struct PoslistCallbackCtx PoslistCallbackCtx;
189479 struct PoslistCallbackCtx {
189480  Fts5Buffer *pBuf; /* Append to this buffer */
189481  Fts5Colset *pColset; /* Restrict matches to this column */
189482  int eState; /* See above */
189483 };
189484 
189485 typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
189486 struct PoslistOffsetsCtx {
189487  Fts5Buffer *pBuf; /* Append to this buffer */
189488  Fts5Colset *pColset; /* Restrict matches to this column */
189489  int iRead;
189490  int iWrite;
189491 };
189492 
189493 /*
189494 ** TODO: Make this more efficient!
189495 */
189496 static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
189497  int i;
189498  for(i=0; i<pColset->nCol; i++){
189499  if( pColset->aiCol[i]==iCol ) return 1;
189500  }
189501  return 0;
189502 }
189503 
189504 static void fts5PoslistOffsetsCallback(
189505  Fts5Index *pUnused,
189506  void *pContext,
189507  const u8 *pChunk, int nChunk
189508 ){
189509  PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
189510  UNUSED_PARAM(pUnused);
189511  assert_nc( nChunk>=0 );
189512  if( nChunk>0 ){
189513  int i = 0;
189514  while( i<nChunk ){
189515  int iVal;
189516  i += fts5GetVarint32(&pChunk[i], iVal);
189517  iVal += pCtx->iRead - 2;
189518  pCtx->iRead = iVal;
189519  if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
189520  fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
189521  pCtx->iWrite = iVal;
189522  }
189523  }
189524  }
189525 }
189526 
189527 static void fts5PoslistFilterCallback(
189528  Fts5Index *pUnused,
189529  void *pContext,
189530  const u8 *pChunk, int nChunk
189531 ){
189532  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
189533  UNUSED_PARAM(pUnused);
189534  assert_nc( nChunk>=0 );
189535  if( nChunk>0 ){
189536  /* Search through to find the first varint with value 1. This is the
189537  ** start of the next columns hits. */
189538  int i = 0;
189539  int iStart = 0;
189540 
189541  if( pCtx->eState==2 ){
189542  int iCol;
189543  fts5FastGetVarint32(pChunk, i, iCol);
189544  if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
189545  pCtx->eState = 1;
189546  fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
189547  }else{
189548  pCtx->eState = 0;
189549  }
189550  }
189551 
189552  do {
189553  while( i<nChunk && pChunk[i]!=0x01 ){
189554  while( pChunk[i] & 0x80 ) i++;
189555  i++;
189556  }
189557  if( pCtx->eState ){
189558  fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
189559  }
189560  if( i<nChunk ){
189561  int iCol;
189562  iStart = i;
189563  i++;
189564  if( i>=nChunk ){
189565  pCtx->eState = 2;
189566  }else{
189567  fts5FastGetVarint32(pChunk, i, iCol);
189568  pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
189569  if( pCtx->eState ){
189570  fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
189571  iStart = i;
189572  }
189573  }
189574  }
189575  }while( i<nChunk );
189576  }
189577 }
189578 
189579 static void fts5ChunkIterate(
189580  Fts5Index *p, /* Index object */
189581  Fts5SegIter *pSeg, /* Poslist of this iterator */
189582  void *pCtx, /* Context pointer for xChunk callback */
189583  void (*xChunk)(Fts5Index*, void*, const u8*, int)
189584 ){
189585  int nRem = pSeg->nPos; /* Number of bytes still to come */
189586  Fts5Data *pData = 0;
189587  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
189588  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
189589  int pgno = pSeg->iLeafPgno;
189590  int pgnoSave = 0;
189591 
189592  /* This function does notmwork with detail=none databases. */
189593  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
189594 
189595  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
189596  pgnoSave = pgno+1;
189597  }
189598 
189599  while( 1 ){
189600  xChunk(p, pCtx, pChunk, nChunk);
189601  nRem -= nChunk;
189602  fts5DataRelease(pData);
189603  if( nRem<=0 ){
189604  break;
189605  }else{
189606  pgno++;
189607  pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
189608  if( pData==0 ) break;
189609  pChunk = &pData->p[4];
189610  nChunk = MIN(nRem, pData->szLeaf - 4);
189611  if( pgno==pgnoSave ){
189612  assert( pSeg->pNextLeaf==0 );
189613  pSeg->pNextLeaf = pData;
189614  pData = 0;
189615  }
189616  }
189617  }
189618 }
189619 
189620 /*
189621 ** Iterator pIter currently points to a valid entry (not EOF). This
189622 ** function appends the position list data for the current entry to
189623 ** buffer pBuf. It does not make a copy of the position-list size
189624 ** field.
189625 */
189626 static void fts5SegiterPoslist(
189627  Fts5Index *p,
189628  Fts5SegIter *pSeg,
189629  Fts5Colset *pColset,
189630  Fts5Buffer *pBuf
189631 ){
189632  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
189633  if( pColset==0 ){
189634  fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
189635  }else{
189636  if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
189637  PoslistCallbackCtx sCtx;
189638  sCtx.pBuf = pBuf;
189639  sCtx.pColset = pColset;
189640  sCtx.eState = fts5IndexColsetTest(pColset, 0);
189641  assert( sCtx.eState==0 || sCtx.eState==1 );
189642  fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
189643  }else{
189644  PoslistOffsetsCtx sCtx;
189645  memset(&sCtx, 0, sizeof(sCtx));
189646  sCtx.pBuf = pBuf;
189647  sCtx.pColset = pColset;
189648  fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
189649  }
189650  }
189651  }
189652 }
189653 
189654 /*
189655 ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
189656 ** the position list contains entries for column iCol, then (*pa) is set
189657 ** to point to the sub-position-list for that column and the number of
189658 ** bytes in it returned. Or, if the argument position list does not
189659 ** contain any entries for column iCol, return 0.
189660 */
189661 static int fts5IndexExtractCol(
189662  const u8 **pa, /* IN/OUT: Pointer to poslist */
189663  int n, /* IN: Size of poslist in bytes */
189664  int iCol /* Column to extract from poslist */
189665 ){
189666  int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
189667  const u8 *p = *pa;
189668  const u8 *pEnd = &p[n]; /* One byte past end of position list */
189669 
189670  while( iCol>iCurrent ){
189671  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
189672  ** not part of a varint. Note that it is not possible for a negative
189673  ** or extremely large varint to occur within an uncorrupted position
189674  ** list. So the last byte of each varint may be assumed to have a clear
189675  ** 0x80 bit. */
189676  while( *p!=0x01 ){
189677  while( *p++ & 0x80 );
189678  if( p>=pEnd ) return 0;
189679  }
189680  *pa = p++;
189681  iCurrent = *p++;
189682  if( iCurrent & 0x80 ){
189683  p--;
189684  p += fts5GetVarint32(p, iCurrent);
189685  }
189686  }
189687  if( iCol!=iCurrent ) return 0;
189688 
189689  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
189690  ** not part of a varint */
189691  while( p<pEnd && *p!=0x01 ){
189692  while( *p++ & 0x80 );
189693  }
189694 
189695  return p - (*pa);
189696 }
189697 
189698 static int fts5IndexExtractColset (
189699  Fts5Colset *pColset, /* Colset to filter on */
189700  const u8 *pPos, int nPos, /* Position list */
189701  Fts5Buffer *pBuf /* Output buffer */
189702 ){
189703  int rc = SQLITE_OK;
189704  int i;
189705 
189706  fts5BufferZero(pBuf);
189707  for(i=0; i<pColset->nCol; i++){
189708  const u8 *pSub = pPos;
189709  int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
189710  if( nSub ){
189711  fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
189712  }
189713  }
189714  return rc;
189715 }
189716 
189717 /*
189718 ** xSetOutputs callback used by detail=none tables.
189719 */
189720 static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
189721  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
189722  pIter->base.iRowid = pSeg->iRowid;
189723  pIter->base.nData = pSeg->nPos;
189724 }
189725 
189726 /*
189727 ** xSetOutputs callback used by detail=full and detail=col tables when no
189728 ** column filters are specified.
189729 */
189730 static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
189731  pIter->base.iRowid = pSeg->iRowid;
189732  pIter->base.nData = pSeg->nPos;
189733 
189734  assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
189735  assert( pIter->pColset==0 );
189736 
189737  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
189738  /* All data is stored on the current page. Populate the output
189739  ** variables to point into the body of the page object. */
189740  pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
189741  }else{
189742  /* The data is distributed over two or more pages. Copy it into the
189743  ** Fts5Iter.poslist buffer and then set the output pointer to point
189744  ** to this buffer. */
189745  fts5BufferZero(&pIter->poslist);
189746  fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
189747  pIter->base.pData = pIter->poslist.p;
189748  }
189749 }
189750 
189751 /*
189752 ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
189753 ** against no columns at all).
189754 */
189755 static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
189756  UNUSED_PARAM(pSeg);
189757  pIter->base.nData = 0;
189758 }
189759 
189760 /*
189761 ** xSetOutputs callback used by detail=col when there is a column filter
189762 ** and there are 100 or more columns. Also called as a fallback from
189763 ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
189764 */
189765 static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
189766  fts5BufferZero(&pIter->poslist);
189767  fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
189768  pIter->base.iRowid = pSeg->iRowid;
189769  pIter->base.pData = pIter->poslist.p;
189770  pIter->base.nData = pIter->poslist.n;
189771 }
189772 
189773 /*
189774 ** xSetOutputs callback used when:
189775 **
189776 ** * detail=col,
189777 ** * there is a column filter, and
189778 ** * the table contains 100 or fewer columns.
189779 **
189780 ** The last point is to ensure all column numbers are stored as
189781 ** single-byte varints.
189782 */
189783 static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
189784 
189785  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
189786  assert( pIter->pColset );
189787 
189788  if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
189789  fts5IterSetOutputs_Col(pIter, pSeg);
189790  }else{
189791  u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
189792  u8 *pEnd = (u8*)&a[pSeg->nPos];
189793  int iPrev = 0;
189794  int *aiCol = pIter->pColset->aiCol;
189795  int *aiColEnd = &aiCol[pIter->pColset->nCol];
189796 
189797  u8 *aOut = pIter->poslist.p;
189798  int iPrevOut = 0;
189799 
189800  pIter->base.iRowid = pSeg->iRowid;
189801 
189802  while( a<pEnd ){
189803  iPrev += (int)a++[0] - 2;
189804  while( *aiCol<iPrev ){
189805  aiCol++;
189806  if( aiCol==aiColEnd ) goto setoutputs_col_out;
189807  }
189808  if( *aiCol==iPrev ){
189809  *aOut++ = (u8)((iPrev - iPrevOut) + 2);
189810  iPrevOut = iPrev;
189811  }
189812  }
189813 
189814 setoutputs_col_out:
189815  pIter->base.pData = pIter->poslist.p;
189816  pIter->base.nData = aOut - pIter->poslist.p;
189817  }
189818 }
189819 
189820 /*
189821 ** xSetOutputs callback used by detail=full when there is a column filter.
189822 */
189823 static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
189824  Fts5Colset *pColset = pIter->pColset;
189825  pIter->base.iRowid = pSeg->iRowid;
189826 
189827  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
189828  assert( pColset );
189829 
189830  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
189831  /* All data is stored on the current page. Populate the output
189832  ** variables to point into the body of the page object. */
189833  const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
189834  if( pColset->nCol==1 ){
189835  pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
189836  pIter->base.pData = a;
189837  }else{
189838  fts5BufferZero(&pIter->poslist);
189839  fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist);
189840  pIter->base.pData = pIter->poslist.p;
189841  pIter->base.nData = pIter->poslist.n;
189842  }
189843  }else{
189844  /* The data is distributed over two or more pages. Copy it into the
189845  ** Fts5Iter.poslist buffer and then set the output pointer to point
189846  ** to this buffer. */
189847  fts5BufferZero(&pIter->poslist);
189848  fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
189849  pIter->base.pData = pIter->poslist.p;
189850  pIter->base.nData = pIter->poslist.n;
189851  }
189852 }
189853 
189854 static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
189855  if( *pRc==SQLITE_OK ){
189856  Fts5Config *pConfig = pIter->pIndex->pConfig;
189857  if( pConfig->eDetail==FTS5_DETAIL_NONE ){
189858  pIter->xSetOutputs = fts5IterSetOutputs_None;
189859  }
189860 
189861  else if( pIter->pColset==0 ){
189862  pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
189863  }
189864 
189865  else if( pIter->pColset->nCol==0 ){
189866  pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
189867  }
189868 
189869  else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
189870  pIter->xSetOutputs = fts5IterSetOutputs_Full;
189871  }
189872 
189873  else{
189874  assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
189875  if( pConfig->nCol<=100 ){
189876  pIter->xSetOutputs = fts5IterSetOutputs_Col100;
189877  sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
189878  }else{
189879  pIter->xSetOutputs = fts5IterSetOutputs_Col;
189880  }
189881  }
189882  }
189883 }
189884 
189885 
189886 /*
189887 ** Allocate a new Fts5Iter object.
189888 **
189889 ** The new object will be used to iterate through data in structure pStruct.
189890 ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
189891 ** is zero or greater, data from the first nSegment segments on level iLevel
189892 ** is merged.
189893 **
189894 ** The iterator initially points to the first term/rowid entry in the
189895 ** iterated data.
189896 */
189897 static void fts5MultiIterNew(
189898  Fts5Index *p, /* FTS5 backend to iterate within */
189899  Fts5Structure *pStruct, /* Structure of specific index */
189900  int flags, /* FTS5INDEX_QUERY_XXX flags */
189901  Fts5Colset *pColset, /* Colset to filter on (or NULL) */
189902  const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
189903  int iLevel, /* Level to iterate (-1 for all) */
189904  int nSegment, /* Number of segments to merge (iLevel>=0) */
189905  Fts5Iter **ppOut /* New object */
189906 ){
189907  int nSeg = 0; /* Number of segment-iters in use */
189908  int iIter = 0; /* */
189909  int iSeg; /* Used to iterate through segments */
189910  Fts5StructureLevel *pLvl;
189911  Fts5Iter *pNew;
189912 
189913  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
189914 
189915  /* Allocate space for the new multi-seg-iterator. */
189916  if( p->rc==SQLITE_OK ){
189917  if( iLevel<0 ){
189918  assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
189919  nSeg = pStruct->nSegment;
189920  nSeg += (p->pHash ? 1 : 0);
189921  }else{
189922  nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
189923  }
189924  }
189925  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
189926  if( pNew==0 ) return;
189927  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
189928  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
189929  pNew->pStruct = pStruct;
189930  pNew->pColset = pColset;
189931  fts5StructureRef(pStruct);
189932  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
189933  fts5IterSetOutputCb(&p->rc, pNew);
189934  }
189935 
189936  /* Initialize each of the component segment iterators. */
189937  if( p->rc==SQLITE_OK ){
189938  if( iLevel<0 ){
189939  Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
189940  if( p->pHash ){
189941  /* Add a segment iterator for the current contents of the hash table. */
189942  Fts5SegIter *pIter = &pNew->aSeg[iIter++];
189943  fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
189944  }
189945  for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
189946  for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
189947  Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
189948  Fts5SegIter *pIter = &pNew->aSeg[iIter++];
189949  if( pTerm==0 ){
189950  fts5SegIterInit(p, pSeg, pIter);
189951  }else{
189952  fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
189953  }
189954  }
189955  }
189956  }else{
189957  pLvl = &pStruct->aLevel[iLevel];
189958  for(iSeg=nSeg-1; iSeg>=0; iSeg--){
189959  fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
189960  }
189961  }
189962  assert( iIter==nSeg );
189963  }
189964 
189965  /* If the above was successful, each component iterators now points
189966  ** to the first entry in its segment. In this case initialize the
189967  ** aFirst[] array. Or, if an error has occurred, free the iterator
189968  ** object and set the output variable to NULL. */
189969  if( p->rc==SQLITE_OK ){
189970  for(iIter=pNew->nSeg-1; iIter>0; iIter--){
189971  int iEq;
189972  if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
189973  Fts5SegIter *pSeg = &pNew->aSeg[iEq];
189974  if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
189975  fts5MultiIterAdvanced(p, pNew, iEq, iIter);
189976  }
189977  }
189978  fts5MultiIterSetEof(pNew);
189979  fts5AssertMultiIterSetup(p, pNew);
189980 
189981  if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
189982  fts5MultiIterNext(p, pNew, 0, 0);
189983  }else if( pNew->base.bEof==0 ){
189984  Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
189985  pNew->xSetOutputs(pNew, pSeg);
189986  }
189987 
189988  }else{
189989  fts5MultiIterFree(pNew);
189990  *ppOut = 0;
189991  }
189992 }
189993 
189994 /*
189995 ** Create an Fts5Iter that iterates through the doclist provided
189996 ** as the second argument.
189997 */
189998 static void fts5MultiIterNew2(
189999  Fts5Index *p, /* FTS5 backend to iterate within */
190000  Fts5Data *pData, /* Doclist to iterate through */
190001  int bDesc, /* True for descending rowid order */
190002  Fts5Iter **ppOut /* New object */
190003 ){
190004  Fts5Iter *pNew;
190005  pNew = fts5MultiIterAlloc(p, 2);
190006  if( pNew ){
190007  Fts5SegIter *pIter = &pNew->aSeg[1];
190008 
190009  pIter->flags = FTS5_SEGITER_ONETERM;
190010  if( pData->szLeaf>0 ){
190011  pIter->pLeaf = pData;
190012  pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
190013  pIter->iEndofDoclist = pData->nn;
190014  pNew->aFirst[1].iFirst = 1;
190015  if( bDesc ){
190016  pNew->bRev = 1;
190017  pIter->flags |= FTS5_SEGITER_REVERSE;
190018  fts5SegIterReverseInitPage(p, pIter);
190019  }else{
190020  fts5SegIterLoadNPos(p, pIter);
190021  }
190022  pData = 0;
190023  }else{
190024  pNew->base.bEof = 1;
190025  }
190026  fts5SegIterSetNext(p, pIter);
190027 
190028  *ppOut = pNew;
190029  }
190030 
190031  fts5DataRelease(pData);
190032 }
190033 
190034 /*
190035 ** Return true if the iterator is at EOF or if an error has occurred.
190036 ** False otherwise.
190037 */
190038 static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
190039  assert( p->rc
190040  || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
190041  );
190042  return (p->rc || pIter->base.bEof);
190043 }
190044 
190045 /*
190046 ** Return the rowid of the entry that the iterator currently points
190047 ** to. If the iterator points to EOF when this function is called the
190048 ** results are undefined.
190049 */
190050 static i64 fts5MultiIterRowid(Fts5Iter *pIter){
190051  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
190052  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
190053 }
190054 
190055 /*
190056 ** Move the iterator to the next entry at or following iMatch.
190057 */
190058 static void fts5MultiIterNextFrom(
190059  Fts5Index *p,
190060  Fts5Iter *pIter,
190061  i64 iMatch
190062 ){
190063  while( 1 ){
190064  i64 iRowid;
190065  fts5MultiIterNext(p, pIter, 1, iMatch);
190066  if( fts5MultiIterEof(p, pIter) ) break;
190067  iRowid = fts5MultiIterRowid(pIter);
190068  if( pIter->bRev==0 && iRowid>=iMatch ) break;
190069  if( pIter->bRev!=0 && iRowid<=iMatch ) break;
190070  }
190071 }
190072 
190073 /*
190074 ** Return a pointer to a buffer containing the term associated with the
190075 ** entry that the iterator currently points to.
190076 */
190077 static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
190078  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
190079  *pn = p->term.n;
190080  return p->term.p;
190081 }
190082 
190083 /*
190084 ** Allocate a new segment-id for the structure pStruct. The new segment
190085 ** id must be between 1 and 65335 inclusive, and must not be used by
190086 ** any currently existing segment. If a free segment id cannot be found,
190087 ** SQLITE_FULL is returned.
190088 **
190089 ** If an error has already occurred, this function is a no-op. 0 is
190090 ** returned in this case.
190091 */
190092 static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
190093  int iSegid = 0;
190094 
190095  if( p->rc==SQLITE_OK ){
190096  if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
190097  p->rc = SQLITE_FULL;
190098  }else{
190099  /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
190100  ** array is 63 elements, or 252 bytes, in size. */
190101  u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
190102  int iLvl, iSeg;
190103  int i;
190104  u32 mask;
190105  memset(aUsed, 0, sizeof(aUsed));
190106  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190107  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
190108  int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
190109  if( iId<=FTS5_MAX_SEGMENT ){
190110  aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
190111  }
190112  }
190113  }
190114 
190115  for(i=0; aUsed[i]==0xFFFFFFFF; i++);
190116  mask = aUsed[i];
190117  for(iSegid=0; mask & (1 << iSegid); iSegid++);
190118  iSegid += 1 + i*32;
190119 
190120 #ifdef SQLITE_DEBUG
190121  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190122  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
190123  assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
190124  }
190125  }
190126  assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
190127 
190128  {
190129  sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
190130  if( p->rc==SQLITE_OK ){
190131  u8 aBlob[2] = {0xff, 0xff};
190132  sqlite3_bind_int(pIdxSelect, 1, iSegid);
190133  sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
190134  assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
190135  p->rc = sqlite3_reset(pIdxSelect);
190136  }
190137  }
190138 #endif
190139  }
190140  }
190141 
190142  return iSegid;
190143 }
190144 
190145 /*
190146 ** Discard all data currently cached in the hash-tables.
190147 */
190148 static void fts5IndexDiscardData(Fts5Index *p){
190149  assert( p->pHash || p->nPendingData==0 );
190150  if( p->pHash ){
190151  sqlite3Fts5HashClear(p->pHash);
190152  p->nPendingData = 0;
190153  }
190154 }
190155 
190156 /*
190157 ** Return the size of the prefix, in bytes, that buffer
190158 ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
190159 **
190160 ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
190161 ** than buffer (pOld/nOld).
190162 */
190163 static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
190164  int i;
190165  for(i=0; i<nOld; i++){
190166  if( pOld[i]!=pNew[i] ) break;
190167  }
190168  return i;
190169 }
190170 
190171 static void fts5WriteDlidxClear(
190172  Fts5Index *p,
190173  Fts5SegWriter *pWriter,
190174  int bFlush /* If true, write dlidx to disk */
190175 ){
190176  int i;
190177  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
190178  for(i=0; i<pWriter->nDlidx; i++){
190179  Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
190180  if( pDlidx->buf.n==0 ) break;
190181  if( bFlush ){
190182  assert( pDlidx->pgno!=0 );
190183  fts5DataWrite(p,
190184  FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
190185  pDlidx->buf.p, pDlidx->buf.n
190186  );
190187  }
190188  sqlite3Fts5BufferZero(&pDlidx->buf);
190189  pDlidx->bPrevValid = 0;
190190  }
190191 }
190192 
190193 /*
190194 ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
190195 ** Any new array elements are zeroed before returning.
190196 */
190197 static int fts5WriteDlidxGrow(
190198  Fts5Index *p,
190199  Fts5SegWriter *pWriter,
190200  int nLvl
190201 ){
190202  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
190203  Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
190204  pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
190205  );
190206  if( aDlidx==0 ){
190207  p->rc = SQLITE_NOMEM;
190208  }else{
190209  int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
190210  memset(&aDlidx[pWriter->nDlidx], 0, nByte);
190211  pWriter->aDlidx = aDlidx;
190212  pWriter->nDlidx = nLvl;
190213  }
190214  }
190215  return p->rc;
190216 }
190217 
190218 /*
190219 ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
190220 ** enough, flush it to disk and return 1. Otherwise discard it and return
190221 ** zero.
190222 */
190223 static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
190224  int bFlag = 0;
190225 
190226  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
190227  ** to the database, also write the doclist-index to disk. */
190228  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
190229  bFlag = 1;
190230  }
190231  fts5WriteDlidxClear(p, pWriter, bFlag);
190232  pWriter->nEmpty = 0;
190233  return bFlag;
190234 }
190235 
190236 /*
190237 ** This function is called whenever processing of the doclist for the
190238 ** last term on leaf page (pWriter->iBtPage) is completed.
190239 **
190240 ** The doclist-index for that term is currently stored in-memory within the
190241 ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
190242 ** writes it out to disk. Or, if it is too small to bother with, discards
190243 ** it.
190244 **
190245 ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
190246 */
190247 static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
190248  int bFlag;
190249 
190250  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
190251  if( pWriter->iBtPage==0 ) return;
190252  bFlag = fts5WriteFlushDlidx(p, pWriter);
190253 
190254  if( p->rc==SQLITE_OK ){
190255  const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
190256  /* The following was already done in fts5WriteInit(): */
190257  /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
190258  sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
190259  sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
190260  sqlite3_step(p->pIdxWriter);
190261  p->rc = sqlite3_reset(p->pIdxWriter);
190262  }
190263  pWriter->iBtPage = 0;
190264 }
190265 
190266 /*
190267 ** This is called once for each leaf page except the first that contains
190268 ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
190269 ** is larger than all terms written to earlier leaves, and equal to or
190270 ** smaller than the first term on the new leaf.
190271 **
190272 ** If an error occurs, an error code is left in Fts5Index.rc. If an error
190273 ** has already occurred when this function is called, it is a no-op.
190274 */
190275 static void fts5WriteBtreeTerm(
190276  Fts5Index *p, /* FTS5 backend object */
190277  Fts5SegWriter *pWriter, /* Writer object */
190278  int nTerm, const u8 *pTerm /* First term on new page */
190279 ){
190280  fts5WriteFlushBtree(p, pWriter);
190281  fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
190282  pWriter->iBtPage = pWriter->writer.pgno;
190283 }
190284 
190285 /*
190286 ** This function is called when flushing a leaf page that contains no
190287 ** terms at all to disk.
190288 */
190289 static void fts5WriteBtreeNoTerm(
190290  Fts5Index *p, /* FTS5 backend object */
190291  Fts5SegWriter *pWriter /* Writer object */
190292 ){
190293  /* If there were no rowids on the leaf page either and the doclist-index
190294  ** has already been started, append an 0x00 byte to it. */
190295  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
190296  Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
190297  assert( pDlidx->bPrevValid );
190298  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
190299  }
190300 
190301  /* Increment the "number of sequential leaves without a term" counter. */
190302  pWriter->nEmpty++;
190303 }
190304 
190305 static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
190306  i64 iRowid;
190307  int iOff;
190308 
190309  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
190310  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
190311  return iRowid;
190312 }
190313 
190314 /*
190315 ** Rowid iRowid has just been appended to the current leaf page. It is the
190316 ** first on the page. This function appends an appropriate entry to the current
190317 ** doclist-index.
190318 */
190319 static void fts5WriteDlidxAppend(
190320  Fts5Index *p,
190321  Fts5SegWriter *pWriter,
190322  i64 iRowid
190323 ){
190324  int i;
190325  int bDone = 0;
190326 
190327  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
190328  i64 iVal;
190329  Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
190330 
190331  if( pDlidx->buf.n>=p->pConfig->pgsz ){
190332  /* The current doclist-index page is full. Write it to disk and push
190333  ** a copy of iRowid (which will become the first rowid on the next
190334  ** doclist-index leaf page) up into the next level of the b-tree
190335  ** hierarchy. If the node being flushed is currently the root node,
190336  ** also push its first rowid upwards. */
190337  pDlidx->buf.p[0] = 0x01; /* Not the root node */
190338  fts5DataWrite(p,
190339  FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
190340  pDlidx->buf.p, pDlidx->buf.n
190341  );
190342  fts5WriteDlidxGrow(p, pWriter, i+2);
190343  pDlidx = &pWriter->aDlidx[i];
190344  if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
190345  i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
190346 
190347  /* This was the root node. Push its first rowid up to the new root. */
190348  pDlidx[1].pgno = pDlidx->pgno;
190349  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
190350  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
190351  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
190352  pDlidx[1].bPrevValid = 1;
190353  pDlidx[1].iPrev = iFirst;
190354  }
190355 
190356  sqlite3Fts5BufferZero(&pDlidx->buf);
190357  pDlidx->bPrevValid = 0;
190358  pDlidx->pgno++;
190359  }else{
190360  bDone = 1;
190361  }
190362 
190363  if( pDlidx->bPrevValid ){
190364  iVal = iRowid - pDlidx->iPrev;
190365  }else{
190366  i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
190367  assert( pDlidx->buf.n==0 );
190368  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
190369  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
190370  iVal = iRowid;
190371  }
190372 
190373  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
190374  pDlidx->bPrevValid = 1;
190375  pDlidx->iPrev = iRowid;
190376  }
190377 }
190378 
190379 static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
190380  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
190381  Fts5PageWriter *pPage = &pWriter->writer;
190382  i64 iRowid;
190383 
190384 static int nCall = 0;
190385 nCall++;
190386 
190387  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
190388 
190389  /* Set the szLeaf header field. */
190390  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
190391  fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
190392 
190393  if( pWriter->bFirstTermInPage ){
190394  /* No term was written to this page. */
190395  assert( pPage->pgidx.n==0 );
190396  fts5WriteBtreeNoTerm(p, pWriter);
190397  }else{
190398  /* Append the pgidx to the page buffer. Set the szLeaf header field. */
190399  fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
190400  }
190401 
190402  /* Write the page out to disk */
190403  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
190404  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
190405 
190406  /* Initialize the next page. */
190407  fts5BufferZero(&pPage->buf);
190408  fts5BufferZero(&pPage->pgidx);
190409  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
190410  pPage->iPrevPgidx = 0;
190411  pPage->pgno++;
190412 
190413  /* Increase the leaves written counter */
190414  pWriter->nLeafWritten++;
190415 
190416  /* The new leaf holds no terms or rowids */
190417  pWriter->bFirstTermInPage = 1;
190418  pWriter->bFirstRowidInPage = 1;
190419 }
190420 
190421 /*
190422 ** Append term pTerm/nTerm to the segment being written by the writer passed
190423 ** as the second argument.
190424 **
190425 ** If an error occurs, set the Fts5Index.rc error code. If an error has
190426 ** already occurred, this function is a no-op.
190427 */
190428 static void fts5WriteAppendTerm(
190429  Fts5Index *p,
190430  Fts5SegWriter *pWriter,
190431  int nTerm, const u8 *pTerm
190432 ){
190433  int nPrefix; /* Bytes of prefix compression for term */
190434  Fts5PageWriter *pPage = &pWriter->writer;
190435  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
190436 
190437  assert( p->rc==SQLITE_OK );
190438  assert( pPage->buf.n>=4 );
190439  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
190440 
190441  /* If the current leaf page is full, flush it to disk. */
190442  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
190443  if( pPage->buf.n>4 ){
190444  fts5WriteFlushLeaf(p, pWriter);
190445  }
190446  fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
190447  }
190448 
190449  /* TODO1: Updating pgidx here. */
190450  pPgidx->n += sqlite3Fts5PutVarint(
190451  &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
190452  );
190453  pPage->iPrevPgidx = pPage->buf.n;
190454 #if 0
190455  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
190456  pPgidx->n += 2;
190457 #endif
190458 
190459  if( pWriter->bFirstTermInPage ){
190460  nPrefix = 0;
190461  if( pPage->pgno!=1 ){
190462  /* This is the first term on a leaf that is not the leftmost leaf in
190463  ** the segment b-tree. In this case it is necessary to add a term to
190464  ** the b-tree hierarchy that is (a) larger than the largest term
190465  ** already written to the segment and (b) smaller than or equal to
190466  ** this term. In other words, a prefix of (pTerm/nTerm) that is one
190467  ** byte longer than the longest prefix (pTerm/nTerm) shares with the
190468  ** previous term.
190469  **
190470  ** Usually, the previous term is available in pPage->term. The exception
190471  ** is if this is the first term written in an incremental-merge step.
190472  ** In this case the previous term is not available, so just write a
190473  ** copy of (pTerm/nTerm) into the parent node. This is slightly
190474  ** inefficient, but still correct. */
190475  int n = nTerm;
190476  if( pPage->term.n ){
190477  n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
190478  }
190479  fts5WriteBtreeTerm(p, pWriter, n, pTerm);
190480  pPage = &pWriter->writer;
190481  }
190482  }else{
190483  nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
190484  fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
190485  }
190486 
190487  /* Append the number of bytes of new data, then the term data itself
190488  ** to the page. */
190489  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
190490  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
190491 
190492  /* Update the Fts5PageWriter.term field. */
190493  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
190494  pWriter->bFirstTermInPage = 0;
190495 
190496  pWriter->bFirstRowidInPage = 0;
190497  pWriter->bFirstRowidInDoclist = 1;
190498 
190499  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
190500  pWriter->aDlidx[0].pgno = pPage->pgno;
190501 }
190502 
190503 /*
190504 ** Append a rowid and position-list size field to the writers output.
190505 */
190506 static void fts5WriteAppendRowid(
190507  Fts5Index *p,
190508  Fts5SegWriter *pWriter,
190509  i64 iRowid
190510 ){
190511  if( p->rc==SQLITE_OK ){
190512  Fts5PageWriter *pPage = &pWriter->writer;
190513 
190514  if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
190515  fts5WriteFlushLeaf(p, pWriter);
190516  }
190517 
190518  /* If this is to be the first rowid written to the page, set the
190519  ** rowid-pointer in the page-header. Also append a value to the dlidx
190520  ** buffer, in case a doclist-index is required. */
190521  if( pWriter->bFirstRowidInPage ){
190522  fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
190523  fts5WriteDlidxAppend(p, pWriter, iRowid);
190524  }
190525 
190526  /* Write the rowid. */
190527  if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
190528  fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
190529  }else{
190530  assert( p->rc || iRowid>pWriter->iPrevRowid );
190531  fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
190532  }
190533  pWriter->iPrevRowid = iRowid;
190534  pWriter->bFirstRowidInDoclist = 0;
190535  pWriter->bFirstRowidInPage = 0;
190536  }
190537 }
190538 
190539 static void fts5WriteAppendPoslistData(
190540  Fts5Index *p,
190541  Fts5SegWriter *pWriter,
190542  const u8 *aData,
190543  int nData
190544 ){
190545  Fts5PageWriter *pPage = &pWriter->writer;
190546  const u8 *a = aData;
190547  int n = nData;
190548 
190549  assert( p->pConfig->pgsz>0 );
190550  while( p->rc==SQLITE_OK
190551  && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
190552  ){
190553  int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
190554  int nCopy = 0;
190555  while( nCopy<nReq ){
190556  i64 dummy;
190557  nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
190558  }
190559  fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
190560  a += nCopy;
190561  n -= nCopy;
190562  fts5WriteFlushLeaf(p, pWriter);
190563  }
190564  if( n>0 ){
190565  fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
190566  }
190567 }
190568 
190569 /*
190570 ** Flush any data cached by the writer object to the database. Free any
190571 ** allocations associated with the writer.
190572 */
190573 static void fts5WriteFinish(
190574  Fts5Index *p,
190575  Fts5SegWriter *pWriter, /* Writer object */
190576  int *pnLeaf /* OUT: Number of leaf pages in b-tree */
190577 ){
190578  int i;
190579  Fts5PageWriter *pLeaf = &pWriter->writer;
190580  if( p->rc==SQLITE_OK ){
190581  assert( pLeaf->pgno>=1 );
190582  if( pLeaf->buf.n>4 ){
190583  fts5WriteFlushLeaf(p, pWriter);
190584  }
190585  *pnLeaf = pLeaf->pgno-1;
190586  if( pLeaf->pgno>1 ){
190587  fts5WriteFlushBtree(p, pWriter);
190588  }
190589  }
190590  fts5BufferFree(&pLeaf->term);
190591  fts5BufferFree(&pLeaf->buf);
190592  fts5BufferFree(&pLeaf->pgidx);
190593  fts5BufferFree(&pWriter->btterm);
190594 
190595  for(i=0; i<pWriter->nDlidx; i++){
190596  sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
190597  }
190598  sqlite3_free(pWriter->aDlidx);
190599 }
190600 
190601 static void fts5WriteInit(
190602  Fts5Index *p,
190603  Fts5SegWriter *pWriter,
190604  int iSegid
190605 ){
190606  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
190607 
190608  memset(pWriter, 0, sizeof(Fts5SegWriter));
190609  pWriter->iSegid = iSegid;
190610 
190611  fts5WriteDlidxGrow(p, pWriter, 1);
190612  pWriter->writer.pgno = 1;
190613  pWriter->bFirstTermInPage = 1;
190614  pWriter->iBtPage = 1;
190615 
190616  assert( pWriter->writer.buf.n==0 );
190617  assert( pWriter->writer.pgidx.n==0 );
190618 
190619  /* Grow the two buffers to pgsz + padding bytes in size. */
190620  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
190621  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
190622 
190623  if( p->pIdxWriter==0 ){
190624  Fts5Config *pConfig = p->pConfig;
190625  fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
190626  "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
190627  pConfig->zDb, pConfig->zName
190628  ));
190629  }
190630 
190631  if( p->rc==SQLITE_OK ){
190632  /* Initialize the 4-byte leaf-page header to 0x00. */
190633  memset(pWriter->writer.buf.p, 0, 4);
190634  pWriter->writer.buf.n = 4;
190635 
190636  /* Bind the current output segment id to the index-writer. This is an
190637  ** optimization over binding the same value over and over as rows are
190638  ** inserted into %_idx by the current writer. */
190639  sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
190640  }
190641 }
190642 
190643 /*
190644 ** Iterator pIter was used to iterate through the input segments of on an
190645 ** incremental merge operation. This function is called if the incremental
190646 ** merge step has finished but the input has not been completely exhausted.
190647 */
190648 static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
190649  int i;
190650  Fts5Buffer buf;
190651  memset(&buf, 0, sizeof(Fts5Buffer));
190652  for(i=0; i<pIter->nSeg; i++){
190653  Fts5SegIter *pSeg = &pIter->aSeg[i];
190654  if( pSeg->pSeg==0 ){
190655  /* no-op */
190656  }else if( pSeg->pLeaf==0 ){
190657  /* All keys from this input segment have been transfered to the output.
190658  ** Set both the first and last page-numbers to 0 to indicate that the
190659  ** segment is now empty. */
190660  pSeg->pSeg->pgnoLast = 0;
190661  pSeg->pSeg->pgnoFirst = 0;
190662  }else{
190663  int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
190664  i64 iLeafRowid;
190665  Fts5Data *pData;
190666  int iId = pSeg->pSeg->iSegid;
190667  u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
190668 
190669  iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
190670  pData = fts5DataRead(p, iLeafRowid);
190671  if( pData ){
190672  fts5BufferZero(&buf);
190673  fts5BufferGrow(&p->rc, &buf, pData->nn);
190674  fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
190675  fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
190676  fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
190677  fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
190678  if( p->rc==SQLITE_OK ){
190679  /* Set the szLeaf field */
190680  fts5PutU16(&buf.p[2], (u16)buf.n);
190681  }
190682 
190683  /* Set up the new page-index array */
190684  fts5BufferAppendVarint(&p->rc, &buf, 4);
190685  if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
190686  && pSeg->iEndofDoclist<pData->szLeaf
190687  ){
190688  int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
190689  fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
190690  fts5BufferAppendBlob(&p->rc, &buf,
190691  pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
190692  );
190693  }
190694 
190695  fts5DataRelease(pData);
190696  pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
190697  fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
190698  fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
190699  }
190700  }
190701  }
190702  fts5BufferFree(&buf);
190703 }
190704 
190705 static void fts5MergeChunkCallback(
190706  Fts5Index *p,
190707  void *pCtx,
190708  const u8 *pChunk, int nChunk
190709 ){
190710  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
190711  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
190712 }
190713 
190714 /*
190715 **
190716 */
190717 static void fts5IndexMergeLevel(
190718  Fts5Index *p, /* FTS5 backend object */
190719  Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
190720  int iLvl, /* Level to read input from */
190721  int *pnRem /* Write up to this many output leaves */
190722 ){
190723  Fts5Structure *pStruct = *ppStruct;
190724  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
190725  Fts5StructureLevel *pLvlOut;
190726  Fts5Iter *pIter = 0; /* Iterator to read input data */
190727  int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
190728  int nInput; /* Number of input segments */
190729  Fts5SegWriter writer; /* Writer object */
190730  Fts5StructureSegment *pSeg; /* Output segment */
190731  Fts5Buffer term;
190732  int bOldest; /* True if the output segment is the oldest */
190733  int eDetail = p->pConfig->eDetail;
190734  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
190735 
190736  assert( iLvl<pStruct->nLevel );
190737  assert( pLvl->nMerge<=pLvl->nSeg );
190738 
190739  memset(&writer, 0, sizeof(Fts5SegWriter));
190740  memset(&term, 0, sizeof(Fts5Buffer));
190741  if( pLvl->nMerge ){
190742  pLvlOut = &pStruct->aLevel[iLvl+1];
190743  assert( pLvlOut->nSeg>0 );
190744  nInput = pLvl->nMerge;
190745  pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
190746 
190747  fts5WriteInit(p, &writer, pSeg->iSegid);
190748  writer.writer.pgno = pSeg->pgnoLast+1;
190749  writer.iBtPage = 0;
190750  }else{
190751  int iSegid = fts5AllocateSegid(p, pStruct);
190752 
190753  /* Extend the Fts5Structure object as required to ensure the output
190754  ** segment exists. */
190755  if( iLvl==pStruct->nLevel-1 ){
190756  fts5StructureAddLevel(&p->rc, ppStruct);
190757  pStruct = *ppStruct;
190758  }
190759  fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
190760  if( p->rc ) return;
190761  pLvl = &pStruct->aLevel[iLvl];
190762  pLvlOut = &pStruct->aLevel[iLvl+1];
190763 
190764  fts5WriteInit(p, &writer, iSegid);
190765 
190766  /* Add the new segment to the output level */
190767  pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
190768  pLvlOut->nSeg++;
190769  pSeg->pgnoFirst = 1;
190770  pSeg->iSegid = iSegid;
190771  pStruct->nSegment++;
190772 
190773  /* Read input from all segments in the input level */
190774  nInput = pLvl->nSeg;
190775  }
190776  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
190777 
190778  assert( iLvl>=0 );
190779  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
190780  fts5MultiIterEof(p, pIter)==0;
190781  fts5MultiIterNext(p, pIter, 0, 0)
190782  ){
190783  Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
190784  int nPos; /* position-list size field value */
190785  int nTerm;
190786  const u8 *pTerm;
190787 
190788  /* Check for key annihilation. */
190789  if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
190790 
190791  pTerm = fts5MultiIterTerm(pIter, &nTerm);
190792  if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
190793  if( pnRem && writer.nLeafWritten>nRem ){
190794  break;
190795  }
190796 
190797  /* This is a new term. Append a term to the output segment. */
190798  fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
190799  fts5BufferSet(&p->rc, &term, nTerm, pTerm);
190800  }
190801 
190802  /* Append the rowid to the output */
190803  /* WRITEPOSLISTSIZE */
190804  fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
190805 
190806  if( eDetail==FTS5_DETAIL_NONE ){
190807  if( pSegIter->bDel ){
190808  fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
190809  if( pSegIter->nPos>0 ){
190810  fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
190811  }
190812  }
190813  }else{
190814  /* Append the position-list data to the output */
190815  nPos = pSegIter->nPos*2 + pSegIter->bDel;
190816  fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
190817  fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
190818  }
190819  }
190820 
190821  /* Flush the last leaf page to disk. Set the output segment b-tree height
190822  ** and last leaf page number at the same time. */
190823  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
190824 
190825  if( fts5MultiIterEof(p, pIter) ){
190826  int i;
190827 
190828  /* Remove the redundant segments from the %_data table */
190829  for(i=0; i<nInput; i++){
190830  fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
190831  }
190832 
190833  /* Remove the redundant segments from the input level */
190834  if( pLvl->nSeg!=nInput ){
190835  int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
190836  memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
190837  }
190838  pStruct->nSegment -= nInput;
190839  pLvl->nSeg -= nInput;
190840  pLvl->nMerge = 0;
190841  if( pSeg->pgnoLast==0 ){
190842  pLvlOut->nSeg--;
190843  pStruct->nSegment--;
190844  }
190845  }else{
190846  assert( pSeg->pgnoLast>0 );
190847  fts5TrimSegments(p, pIter);
190848  pLvl->nMerge = nInput;
190849  }
190850 
190851  fts5MultiIterFree(pIter);
190852  fts5BufferFree(&term);
190853  if( pnRem ) *pnRem -= writer.nLeafWritten;
190854 }
190855 
190856 /*
190857 ** Do up to nPg pages of automerge work on the index.
190858 **
190859 ** Return true if any changes were actually made, or false otherwise.
190860 */
190861 static int fts5IndexMerge(
190862  Fts5Index *p, /* FTS5 backend object */
190863  Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
190864  int nPg, /* Pages of work to do */
190865  int nMin /* Minimum number of segments to merge */
190866 ){
190867  int nRem = nPg;
190868  int bRet = 0;
190869  Fts5Structure *pStruct = *ppStruct;
190870  while( nRem>0 && p->rc==SQLITE_OK ){
190871  int iLvl; /* To iterate through levels */
190872  int iBestLvl = 0; /* Level offering the most input segments */
190873  int nBest = 0; /* Number of input segments on best level */
190874 
190875  /* Set iBestLvl to the level to read input segments from. */
190876  assert( pStruct->nLevel>0 );
190877  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190878  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
190879  if( pLvl->nMerge ){
190880  if( pLvl->nMerge>nBest ){
190881  iBestLvl = iLvl;
190882  nBest = pLvl->nMerge;
190883  }
190884  break;
190885  }
190886  if( pLvl->nSeg>nBest ){
190887  nBest = pLvl->nSeg;
190888  iBestLvl = iLvl;
190889  }
190890  }
190891 
190892  /* If nBest is still 0, then the index must be empty. */
190893 #ifdef SQLITE_DEBUG
190894  for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
190895  assert( pStruct->aLevel[iLvl].nSeg==0 );
190896  }
190897 #endif
190898 
190899  if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
190900  break;
190901  }
190902  bRet = 1;
190903  fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
190904  if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
190905  fts5StructurePromote(p, iBestLvl+1, pStruct);
190906  }
190907  }
190908  *ppStruct = pStruct;
190909  return bRet;
190910 }
190911 
190912 /*
190913 ** A total of nLeaf leaf pages of data has just been flushed to a level-0
190914 ** segment. This function updates the write-counter accordingly and, if
190915 ** necessary, performs incremental merge work.
190916 **
190917 ** If an error occurs, set the Fts5Index.rc error code. If an error has
190918 ** already occurred, this function is a no-op.
190919 */
190920 static void fts5IndexAutomerge(
190921  Fts5Index *p, /* FTS5 backend object */
190922  Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
190923  int nLeaf /* Number of output leaves just written */
190924 ){
190925  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
190926  Fts5Structure *pStruct = *ppStruct;
190927  u64 nWrite; /* Initial value of write-counter */
190928  int nWork; /* Number of work-quanta to perform */
190929  int nRem; /* Number of leaf pages left to write */
190930 
190931  /* Update the write-counter. While doing so, set nWork. */
190932  nWrite = pStruct->nWriteCounter;
190933  nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
190934  pStruct->nWriteCounter += nLeaf;
190935  nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
190936 
190937  fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
190938  }
190939 }
190940 
190941 static void fts5IndexCrisismerge(
190942  Fts5Index *p, /* FTS5 backend object */
190943  Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
190944 ){
190945  const int nCrisis = p->pConfig->nCrisisMerge;
190946  Fts5Structure *pStruct = *ppStruct;
190947  int iLvl = 0;
190948 
190949  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
190950  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
190951  fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
190952  assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
190953  fts5StructurePromote(p, iLvl+1, pStruct);
190954  iLvl++;
190955  }
190956  *ppStruct = pStruct;
190957 }
190958 
190959 static int fts5IndexReturn(Fts5Index *p){
190960  int rc = p->rc;
190961  p->rc = SQLITE_OK;
190962  return rc;
190963 }
190964 
190965 typedef struct Fts5FlushCtx Fts5FlushCtx;
190966 struct Fts5FlushCtx {
190967  Fts5Index *pIdx;
190968  Fts5SegWriter writer;
190969 };
190970 
190971 /*
190972 ** Buffer aBuf[] contains a list of varints, all small enough to fit
190973 ** in a 32-bit integer. Return the size of the largest prefix of this
190974 ** list nMax bytes or less in size.
190975 */
190976 static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
190977  int ret;
190978  u32 dummy;
190979  ret = fts5GetVarint32(aBuf, dummy);
190980  if( ret<nMax ){
190981  while( 1 ){
190982  int i = fts5GetVarint32(&aBuf[ret], dummy);
190983  if( (ret + i) > nMax ) break;
190984  ret += i;
190985  }
190986  }
190987  return ret;
190988 }
190989 
190990 /*
190991 ** Flush the contents of in-memory hash table iHash to a new level-0
190992 ** segment on disk. Also update the corresponding structure record.
190993 **
190994 ** If an error occurs, set the Fts5Index.rc error code. If an error has
190995 ** already occurred, this function is a no-op.
190996 */
190997 static void fts5FlushOneHash(Fts5Index *p){
190998  Fts5Hash *pHash = p->pHash;
190999  Fts5Structure *pStruct;
191000  int iSegid;
191001  int pgnoLast = 0; /* Last leaf page number in segment */
191002 
191003  /* Obtain a reference to the index structure and allocate a new segment-id
191004  ** for the new level-0 segment. */
191005  pStruct = fts5StructureRead(p);
191006  iSegid = fts5AllocateSegid(p, pStruct);
191007  fts5StructureInvalidate(p);
191008 
191009  if( iSegid ){
191010  const int pgsz = p->pConfig->pgsz;
191011  int eDetail = p->pConfig->eDetail;
191012  Fts5StructureSegment *pSeg; /* New segment within pStruct */
191013  Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
191014  Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
191015 
191016  Fts5SegWriter writer;
191017  fts5WriteInit(p, &writer, iSegid);
191018 
191019  pBuf = &writer.writer.buf;
191020  pPgidx = &writer.writer.pgidx;
191021 
191022  /* fts5WriteInit() should have initialized the buffers to (most likely)
191023  ** the maximum space required. */
191024  assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
191025  assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
191026 
191027  /* Begin scanning through hash table entries. This loop runs once for each
191028  ** term/doclist currently stored within the hash table. */
191029  if( p->rc==SQLITE_OK ){
191030  p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
191031  }
191032  while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
191033  const char *zTerm; /* Buffer containing term */
191034  const u8 *pDoclist; /* Pointer to doclist for this term */
191035  int nDoclist; /* Size of doclist in bytes */
191036 
191037  /* Write the term for this entry to disk. */
191038  sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
191039  fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
191040 
191041  assert( writer.bFirstRowidInPage==0 );
191042  if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
191043  /* The entire doclist will fit on the current leaf. */
191044  fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
191045  }else{
191046  i64 iRowid = 0;
191047  i64 iDelta = 0;
191048  int iOff = 0;
191049 
191050  /* The entire doclist will not fit on this leaf. The following
191051  ** loop iterates through the poslists that make up the current
191052  ** doclist. */
191053  while( p->rc==SQLITE_OK && iOff<nDoclist ){
191054  iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
191055  iRowid += iDelta;
191056 
191057  if( writer.bFirstRowidInPage ){
191058  fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
191059  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
191060  writer.bFirstRowidInPage = 0;
191061  fts5WriteDlidxAppend(p, &writer, iRowid);
191062  }else{
191063  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
191064  }
191065  assert( pBuf->n<=pBuf->nSpace );
191066 
191067  if( eDetail==FTS5_DETAIL_NONE ){
191068  if( iOff<nDoclist && pDoclist[iOff]==0 ){
191069  pBuf->p[pBuf->n++] = 0;
191070  iOff++;
191071  if( iOff<nDoclist && pDoclist[iOff]==0 ){
191072  pBuf->p[pBuf->n++] = 0;
191073  iOff++;
191074  }
191075  }
191076  if( (pBuf->n + pPgidx->n)>=pgsz ){
191077  fts5WriteFlushLeaf(p, &writer);
191078  }
191079  }else{
191080  int bDummy;
191081  int nPos;
191082  int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
191083  nCopy += nPos;
191084  if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
191085  /* The entire poslist will fit on the current leaf. So copy
191086  ** it in one go. */
191087  fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
191088  }else{
191089  /* The entire poslist will not fit on this leaf. So it needs
191090  ** to be broken into sections. The only qualification being
191091  ** that each varint must be stored contiguously. */
191092  const u8 *pPoslist = &pDoclist[iOff];
191093  int iPos = 0;
191094  while( p->rc==SQLITE_OK ){
191095  int nSpace = pgsz - pBuf->n - pPgidx->n;
191096  int n = 0;
191097  if( (nCopy - iPos)<=nSpace ){
191098  n = nCopy - iPos;
191099  }else{
191100  n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
191101  }
191102  assert( n>0 );
191103  fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
191104  iPos += n;
191105  if( (pBuf->n + pPgidx->n)>=pgsz ){
191106  fts5WriteFlushLeaf(p, &writer);
191107  }
191108  if( iPos>=nCopy ) break;
191109  }
191110  }
191111  iOff += nCopy;
191112  }
191113  }
191114  }
191115 
191116  /* TODO2: Doclist terminator written here. */
191117  /* pBuf->p[pBuf->n++] = '\0'; */
191118  assert( pBuf->n<=pBuf->nSpace );
191119  sqlite3Fts5HashScanNext(pHash);
191120  }
191121  sqlite3Fts5HashClear(pHash);
191122  fts5WriteFinish(p, &writer, &pgnoLast);
191123 
191124  /* Update the Fts5Structure. It is written back to the database by the
191125  ** fts5StructureRelease() call below. */
191126  if( pStruct->nLevel==0 ){
191127  fts5StructureAddLevel(&p->rc, &pStruct);
191128  }
191129  fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
191130  if( p->rc==SQLITE_OK ){
191131  pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
191132  pSeg->iSegid = iSegid;
191133  pSeg->pgnoFirst = 1;
191134  pSeg->pgnoLast = pgnoLast;
191135  pStruct->nSegment++;
191136  }
191137  fts5StructurePromote(p, 0, pStruct);
191138  }
191139 
191140  fts5IndexAutomerge(p, &pStruct, pgnoLast);
191141  fts5IndexCrisismerge(p, &pStruct);
191142  fts5StructureWrite(p, pStruct);
191143  fts5StructureRelease(pStruct);
191144 }
191145 
191146 /*
191147 ** Flush any data stored in the in-memory hash tables to the database.
191148 */
191149 static void fts5IndexFlush(Fts5Index *p){
191150  /* Unless it is empty, flush the hash table to disk */
191151  if( p->nPendingData ){
191152  assert( p->pHash );
191153  p->nPendingData = 0;
191154  fts5FlushOneHash(p);
191155  }
191156 }
191157 
191158 static Fts5Structure *fts5IndexOptimizeStruct(
191159  Fts5Index *p,
191160  Fts5Structure *pStruct
191161 ){
191162  Fts5Structure *pNew = 0;
191163  int nByte = sizeof(Fts5Structure);
191164  int nSeg = pStruct->nSegment;
191165  int i;
191166 
191167  /* Figure out if this structure requires optimization. A structure does
191168  ** not require optimization if either:
191169  **
191170  ** + it consists of fewer than two segments, or
191171  ** + all segments are on the same level, or
191172  ** + all segments except one are currently inputs to a merge operation.
191173  **
191174  ** In the first case, return NULL. In the second, increment the ref-count
191175  ** on *pStruct and return a copy of the pointer to it.
191176  */
191177  if( nSeg<2 ) return 0;
191178  for(i=0; i<pStruct->nLevel; i++){
191179  int nThis = pStruct->aLevel[i].nSeg;
191180  if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
191181  fts5StructureRef(pStruct);
191182  return pStruct;
191183  }
191184  assert( pStruct->aLevel[i].nMerge<=nThis );
191185  }
191186 
191187  nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
191188  pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
191189 
191190  if( pNew ){
191191  Fts5StructureLevel *pLvl;
191192  nByte = nSeg * sizeof(Fts5StructureSegment);
191193  pNew->nLevel = pStruct->nLevel+1;
191194  pNew->nRef = 1;
191195  pNew->nWriteCounter = pStruct->nWriteCounter;
191196  pLvl = &pNew->aLevel[pStruct->nLevel];
191197  pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
191198  if( pLvl->aSeg ){
191199  int iLvl, iSeg;
191200  int iSegOut = 0;
191201  /* Iterate through all segments, from oldest to newest. Add them to
191202  ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
191203  ** segment in the data structure. */
191204  for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
191205  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
191206  pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
191207  iSegOut++;
191208  }
191209  }
191210  pNew->nSegment = pLvl->nSeg = nSeg;
191211  }else{
191212  sqlite3_free(pNew);
191213  pNew = 0;
191214  }
191215  }
191216 
191217  return pNew;
191218 }
191219 
191220 static int sqlite3Fts5IndexOptimize(Fts5Index *p){
191221  Fts5Structure *pStruct;
191222  Fts5Structure *pNew = 0;
191223 
191224  assert( p->rc==SQLITE_OK );
191225  fts5IndexFlush(p);
191226  pStruct = fts5StructureRead(p);
191227  fts5StructureInvalidate(p);
191228 
191229  if( pStruct ){
191230  pNew = fts5IndexOptimizeStruct(p, pStruct);
191231  }
191232  fts5StructureRelease(pStruct);
191233 
191234  assert( pNew==0 || pNew->nSegment>0 );
191235  if( pNew ){
191236  int iLvl;
191237  for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
191238  while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
191239  int nRem = FTS5_OPT_WORK_UNIT;
191240  fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
191241  }
191242 
191243  fts5StructureWrite(p, pNew);
191244  fts5StructureRelease(pNew);
191245  }
191246 
191247  return fts5IndexReturn(p);
191248 }
191249 
191250 /*
191251 ** This is called to implement the special "VALUES('merge', $nMerge)"
191252 ** INSERT command.
191253 */
191254 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
191255  Fts5Structure *pStruct = fts5StructureRead(p);
191256  if( pStruct ){
191257  int nMin = p->pConfig->nUsermerge;
191258  fts5StructureInvalidate(p);
191259  if( nMerge<0 ){
191260  Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
191261  fts5StructureRelease(pStruct);
191262  pStruct = pNew;
191263  nMin = 2;
191264  nMerge = nMerge*-1;
191265  }
191266  if( pStruct && pStruct->nLevel ){
191267  if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
191268  fts5StructureWrite(p, pStruct);
191269  }
191270  }
191271  fts5StructureRelease(pStruct);
191272  }
191273  return fts5IndexReturn(p);
191274 }
191275 
191276 static void fts5AppendRowid(
191277  Fts5Index *p,
191278  i64 iDelta,
191279  Fts5Iter *pUnused,
191280  Fts5Buffer *pBuf
191281 ){
191282  UNUSED_PARAM(pUnused);
191283  fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
191284 }
191285 
191286 static void fts5AppendPoslist(
191287  Fts5Index *p,
191288  i64 iDelta,
191289  Fts5Iter *pMulti,
191290  Fts5Buffer *pBuf
191291 ){
191292  int nData = pMulti->base.nData;
191293  assert( nData>0 );
191294  if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
191295  fts5BufferSafeAppendVarint(pBuf, iDelta);
191296  fts5BufferSafeAppendVarint(pBuf, nData*2);
191297  fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
191298  }
191299 }
191300 
191301 
191302 static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
191303  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
191304 
191305  assert( pIter->aPoslist );
191306  if( p>=pIter->aEof ){
191307  pIter->aPoslist = 0;
191308  }else{
191309  i64 iDelta;
191310 
191311  p += fts5GetVarint(p, (u64*)&iDelta);
191312  pIter->iRowid += iDelta;
191313 
191314  /* Read position list size */
191315  if( p[0] & 0x80 ){
191316  int nPos;
191317  pIter->nSize = fts5GetVarint32(p, nPos);
191318  pIter->nPoslist = (nPos>>1);
191319  }else{
191320  pIter->nPoslist = ((int)(p[0])) >> 1;
191321  pIter->nSize = 1;
191322  }
191323 
191324  pIter->aPoslist = p;
191325  }
191326 }
191327 
191328 static void fts5DoclistIterInit(
191329  Fts5Buffer *pBuf,
191330  Fts5DoclistIter *pIter
191331 ){
191332  memset(pIter, 0, sizeof(*pIter));
191333  pIter->aPoslist = pBuf->p;
191334  pIter->aEof = &pBuf->p[pBuf->n];
191335  fts5DoclistIterNext(pIter);
191336 }
191337 
191338 #if 0
191339 /*
191340 ** Append a doclist to buffer pBuf.
191341 **
191342 ** This function assumes that space within the buffer has already been
191343 ** allocated.
191344 */
191345 static void fts5MergeAppendDocid(
191346  Fts5Buffer *pBuf, /* Buffer to write to */
191347  i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
191348  i64 iRowid /* Rowid to append */
191349 ){
191350  assert( pBuf->n!=0 || (*piLastRowid)==0 );
191351  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
191352  *piLastRowid = iRowid;
191353 }
191354 #endif
191355 
191356 #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
191357  assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
191358  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
191359  (iLastRowid) = (iRowid); \
191360 }
191361 
191362 /*
191363 ** Swap the contents of buffer *p1 with that of *p2.
191364 */
191365 static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
191366  Fts5Buffer tmp = *p1;
191367  *p1 = *p2;
191368  *p2 = tmp;
191369 }
191370 
191371 static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
191372  int i = *piOff;
191373  if( i>=pBuf->n ){
191374  *piOff = -1;
191375  }else{
191376  u64 iVal;
191377  *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
191378  *piRowid += iVal;
191379  }
191380 }
191381 
191382 /*
191383 ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
191384 ** In this case the buffers consist of a delta-encoded list of rowids only.
191385 */
191386 static void fts5MergeRowidLists(
191387  Fts5Index *p, /* FTS5 backend object */
191388  Fts5Buffer *p1, /* First list to merge */
191389  Fts5Buffer *p2 /* Second list to merge */
191390 ){
191391  int i1 = 0;
191392  int i2 = 0;
191393  i64 iRowid1 = 0;
191394  i64 iRowid2 = 0;
191395  i64 iOut = 0;
191396 
191397  Fts5Buffer out;
191398  memset(&out, 0, sizeof(out));
191399  sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
191400  if( p->rc ) return;
191401 
191402  fts5NextRowid(p1, &i1, &iRowid1);
191403  fts5NextRowid(p2, &i2, &iRowid2);
191404  while( i1>=0 || i2>=0 ){
191405  if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
191406  assert( iOut==0 || iRowid1>iOut );
191407  fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
191408  iOut = iRowid1;
191409  fts5NextRowid(p1, &i1, &iRowid1);
191410  }else{
191411  assert( iOut==0 || iRowid2>iOut );
191412  fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
191413  iOut = iRowid2;
191414  if( i1>=0 && iRowid1==iRowid2 ){
191415  fts5NextRowid(p1, &i1, &iRowid1);
191416  }
191417  fts5NextRowid(p2, &i2, &iRowid2);
191418  }
191419  }
191420 
191421  fts5BufferSwap(&out, p1);
191422  fts5BufferFree(&out);
191423 }
191424 
191425 /*
191426 ** Buffers p1 and p2 contain doclists. This function merges the content
191427 ** of the two doclists together and sets buffer p1 to the result before
191428 ** returning.
191429 **
191430 ** If an error occurs, an error code is left in p->rc. If an error has
191431 ** already occurred, this function is a no-op.
191432 */
191433 static void fts5MergePrefixLists(
191434  Fts5Index *p, /* FTS5 backend object */
191435  Fts5Buffer *p1, /* First list to merge */
191436  Fts5Buffer *p2 /* Second list to merge */
191437 ){
191438  if( p2->n ){
191439  i64 iLastRowid = 0;
191440  Fts5DoclistIter i1;
191441  Fts5DoclistIter i2;
191442  Fts5Buffer out = {0, 0, 0};
191443  Fts5Buffer tmp = {0, 0, 0};
191444 
191445  if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
191446  fts5DoclistIterInit(p1, &i1);
191447  fts5DoclistIterInit(p2, &i2);
191448 
191449  while( 1 ){
191450  if( i1.iRowid<i2.iRowid ){
191451  /* Copy entry from i1 */
191452  fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
191453  fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
191454  fts5DoclistIterNext(&i1);
191455  if( i1.aPoslist==0 ) break;
191456  }
191457  else if( i2.iRowid!=i1.iRowid ){
191458  /* Copy entry from i2 */
191459  fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
191460  fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
191461  fts5DoclistIterNext(&i2);
191462  if( i2.aPoslist==0 ) break;
191463  }
191464  else{
191465  /* Merge the two position lists. */
191466  i64 iPos1 = 0;
191467  i64 iPos2 = 0;
191468  int iOff1 = 0;
191469  int iOff2 = 0;
191470  u8 *a1 = &i1.aPoslist[i1.nSize];
191471  u8 *a2 = &i2.aPoslist[i2.nSize];
191472 
191473  i64 iPrev = 0;
191474  Fts5PoslistWriter writer;
191475  memset(&writer, 0, sizeof(writer));
191476 
191477  fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
191478  fts5BufferZero(&tmp);
191479  sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
191480  if( p->rc ) break;
191481 
191482  sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
191483  sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
191484  assert( iPos1>=0 && iPos2>=0 );
191485 
191486  if( iPos1<iPos2 ){
191487  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
191488  sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
191489  }else{
191490  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
191491  sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
191492  }
191493 
191494  if( iPos1>=0 && iPos2>=0 ){
191495  while( 1 ){
191496  if( iPos1<iPos2 ){
191497  if( iPos1!=iPrev ){
191498  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
191499  }
191500  sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
191501  if( iPos1<0 ) break;
191502  }else{
191503  assert( iPos2!=iPrev );
191504  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
191505  sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
191506  if( iPos2<0 ) break;
191507  }
191508  }
191509  }
191510 
191511  if( iPos1>=0 ){
191512  if( iPos1!=iPrev ){
191513  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
191514  }
191515  fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
191516  }else{
191517  assert( iPos2>=0 && iPos2!=iPrev );
191518  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
191519  fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
191520  }
191521 
191522  /* WRITEPOSLISTSIZE */
191523  fts5BufferSafeAppendVarint(&out, tmp.n * 2);
191524  fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
191525  fts5DoclistIterNext(&i1);
191526  fts5DoclistIterNext(&i2);
191527  if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
191528  }
191529  }
191530 
191531  if( i1.aPoslist ){
191532  fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
191533  fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
191534  }
191535  else if( i2.aPoslist ){
191536  fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
191537  fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
191538  }
191539 
191540  fts5BufferSet(&p->rc, p1, out.n, out.p);
191541  fts5BufferFree(&tmp);
191542  fts5BufferFree(&out);
191543  }
191544 }
191545 
191546 static void fts5SetupPrefixIter(
191547  Fts5Index *p, /* Index to read from */
191548  int bDesc, /* True for "ORDER BY rowid DESC" */
191549  const u8 *pToken, /* Buffer containing prefix to match */
191550  int nToken, /* Size of buffer pToken in bytes */
191551  Fts5Colset *pColset, /* Restrict matches to these columns */
191552  Fts5Iter **ppIter /* OUT: New iterator */
191553 ){
191554  Fts5Structure *pStruct;
191555  Fts5Buffer *aBuf;
191556  const int nBuf = 32;
191557 
191558  void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
191559  void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
191560  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
191561  xMerge = fts5MergeRowidLists;
191562  xAppend = fts5AppendRowid;
191563  }else{
191564  xMerge = fts5MergePrefixLists;
191565  xAppend = fts5AppendPoslist;
191566  }
191567 
191568  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
191569  pStruct = fts5StructureRead(p);
191570 
191571  if( aBuf && pStruct ){
191572  const int flags = FTS5INDEX_QUERY_SCAN
191573  | FTS5INDEX_QUERY_SKIPEMPTY
191574  | FTS5INDEX_QUERY_NOOUTPUT;
191575  int i;
191576  i64 iLastRowid = 0;
191577  Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
191578  Fts5Data *pData;
191579  Fts5Buffer doclist;
191580  int bNewTerm = 1;
191581 
191582  memset(&doclist, 0, sizeof(doclist));
191583  fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
191584  fts5IterSetOutputCb(&p->rc, p1);
191585  for( /* no-op */ ;
191586  fts5MultiIterEof(p, p1)==0;
191587  fts5MultiIterNext2(p, p1, &bNewTerm)
191588  ){
191589  Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
191590  int nTerm = pSeg->term.n;
191591  const u8 *pTerm = pSeg->term.p;
191592  p1->xSetOutputs(p1, pSeg);
191593 
191594  assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
191595  if( bNewTerm ){
191596  if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
191597  }
191598 
191599  if( p1->base.nData==0 ) continue;
191600 
191601  if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
191602  for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
191603  assert( i<nBuf );
191604  if( aBuf[i].n==0 ){
191605  fts5BufferSwap(&doclist, &aBuf[i]);
191606  fts5BufferZero(&doclist);
191607  }else{
191608  xMerge(p, &doclist, &aBuf[i]);
191609  fts5BufferZero(&aBuf[i]);
191610  }
191611  }
191612  iLastRowid = 0;
191613  }
191614 
191615  xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
191616  iLastRowid = p1->base.iRowid;
191617  }
191618 
191619  for(i=0; i<nBuf; i++){
191620  if( p->rc==SQLITE_OK ){
191621  xMerge(p, &doclist, &aBuf[i]);
191622  }
191623  fts5BufferFree(&aBuf[i]);
191624  }
191625  fts5MultiIterFree(p1);
191626 
191627  pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
191628  if( pData ){
191629  pData->p = (u8*)&pData[1];
191630  pData->nn = pData->szLeaf = doclist.n;
191631  memcpy(pData->p, doclist.p, doclist.n);
191632  fts5MultiIterNew2(p, pData, bDesc, ppIter);
191633  }
191634  fts5BufferFree(&doclist);
191635  }
191636 
191637  fts5StructureRelease(pStruct);
191638  sqlite3_free(aBuf);
191639 }
191640 
191641 
191642 /*
191643 ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
191644 ** to the document with rowid iRowid.
191645 */
191646 static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
191647  assert( p->rc==SQLITE_OK );
191648 
191649  /* Allocate the hash table if it has not already been allocated */
191650  if( p->pHash==0 ){
191651  p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
191652  }
191653 
191654  /* Flush the hash table to disk if required */
191655  if( iRowid<p->iWriteRowid
191656  || (iRowid==p->iWriteRowid && p->bDelete==0)
191657  || (p->nPendingData > p->pConfig->nHashSize)
191658  ){
191659  fts5IndexFlush(p);
191660  }
191661 
191662  p->iWriteRowid = iRowid;
191663  p->bDelete = bDelete;
191664  return fts5IndexReturn(p);
191665 }
191666 
191667 /*
191668 ** Commit data to disk.
191669 */
191670 static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
191671  assert( p->rc==SQLITE_OK );
191672  fts5IndexFlush(p);
191673  if( bCommit ) fts5CloseReader(p);
191674  return fts5IndexReturn(p);
191675 }
191676 
191677 /*
191678 ** Discard any data stored in the in-memory hash tables. Do not write it
191679 ** to the database. Additionally, assume that the contents of the %_data
191680 ** table may have changed on disk. So any in-memory caches of %_data
191681 ** records must be invalidated.
191682 */
191683 static int sqlite3Fts5IndexRollback(Fts5Index *p){
191684  fts5CloseReader(p);
191685  fts5IndexDiscardData(p);
191686  fts5StructureInvalidate(p);
191687  /* assert( p->rc==SQLITE_OK ); */
191688  return SQLITE_OK;
191689 }
191690 
191691 /*
191692 ** The %_data table is completely empty when this function is called. This
191693 ** function populates it with the initial structure objects for each index,
191694 ** and the initial version of the "averages" record (a zero-byte blob).
191695 */
191696 static int sqlite3Fts5IndexReinit(Fts5Index *p){
191697  Fts5Structure s;
191698  fts5StructureInvalidate(p);
191699  memset(&s, 0, sizeof(Fts5Structure));
191700  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
191701  fts5StructureWrite(p, &s);
191702  return fts5IndexReturn(p);
191703 }
191704 
191705 /*
191706 ** Open a new Fts5Index handle. If the bCreate argument is true, create
191707 ** and initialize the underlying %_data table.
191708 **
191709 ** If successful, set *pp to point to the new object and return SQLITE_OK.
191710 ** Otherwise, set *pp to NULL and return an SQLite error code.
191711 */
191712 static int sqlite3Fts5IndexOpen(
191713  Fts5Config *pConfig,
191714  int bCreate,
191715  Fts5Index **pp,
191716  char **pzErr
191717 ){
191718  int rc = SQLITE_OK;
191719  Fts5Index *p; /* New object */
191720 
191721  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
191722  if( rc==SQLITE_OK ){
191723  p->pConfig = pConfig;
191724  p->nWorkUnit = FTS5_WORK_UNIT;
191725  p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
191726  if( p->zDataTbl && bCreate ){
191727  rc = sqlite3Fts5CreateTable(
191728  pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
191729  );
191730  if( rc==SQLITE_OK ){
191731  rc = sqlite3Fts5CreateTable(pConfig, "idx",
191732  "segid, term, pgno, PRIMARY KEY(segid, term)",
191733  1, pzErr
191734  );
191735  }
191736  if( rc==SQLITE_OK ){
191737  rc = sqlite3Fts5IndexReinit(p);
191738  }
191739  }
191740  }
191741 
191742  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
191743  if( rc ){
191744  sqlite3Fts5IndexClose(p);
191745  *pp = 0;
191746  }
191747  return rc;
191748 }
191749 
191750 /*
191751 ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
191752 */
191753 static int sqlite3Fts5IndexClose(Fts5Index *p){
191754  int rc = SQLITE_OK;
191755  if( p ){
191756  assert( p->pReader==0 );
191757  fts5StructureInvalidate(p);
191758  sqlite3_finalize(p->pWriter);
191759  sqlite3_finalize(p->pDeleter);
191760  sqlite3_finalize(p->pIdxWriter);
191761  sqlite3_finalize(p->pIdxDeleter);
191762  sqlite3_finalize(p->pIdxSelect);
191763  sqlite3_finalize(p->pDataVersion);
191764  sqlite3Fts5HashFree(p->pHash);
191765  sqlite3_free(p->zDataTbl);
191766  sqlite3_free(p);
191767  }
191768  return rc;
191769 }
191770 
191771 /*
191772 ** Argument p points to a buffer containing utf-8 text that is n bytes in
191773 ** size. Return the number of bytes in the nChar character prefix of the
191774 ** buffer, or 0 if there are less than nChar characters in total.
191775 */
191776 static int sqlite3Fts5IndexCharlenToBytelen(
191777  const char *p,
191778  int nByte,
191779  int nChar
191780 ){
191781  int n = 0;
191782  int i;
191783  for(i=0; i<nChar; i++){
191784  if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
191785  if( (unsigned char)p[n++]>=0xc0 ){
191786  while( (p[n] & 0xc0)==0x80 ) n++;
191787  }
191788  }
191789  return n;
191790 }
191791 
191792 /*
191793 ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
191794 ** unicode characters in the string.
191795 */
191796 static int fts5IndexCharlen(const char *pIn, int nIn){
191797  int nChar = 0;
191798  int i = 0;
191799  while( i<nIn ){
191800  if( (unsigned char)pIn[i++]>=0xc0 ){
191801  while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
191802  }
191803  nChar++;
191804  }
191805  return nChar;
191806 }
191807 
191808 /*
191809 ** Insert or remove data to or from the index. Each time a document is
191810 ** added to or removed from the index, this function is called one or more
191811 ** times.
191812 **
191813 ** For an insert, it must be called once for each token in the new document.
191814 ** If the operation is a delete, it must be called (at least) once for each
191815 ** unique token in the document with an iCol value less than zero. The iPos
191816 ** argument is ignored for a delete.
191817 */
191818 static int sqlite3Fts5IndexWrite(
191819  Fts5Index *p, /* Index to write to */
191820  int iCol, /* Column token appears in (-ve -> delete) */
191821  int iPos, /* Position of token within column */
191822  const char *pToken, int nToken /* Token to add or remove to or from index */
191823 ){
191824  int i; /* Used to iterate through indexes */
191825  int rc = SQLITE_OK; /* Return code */
191826  Fts5Config *pConfig = p->pConfig;
191827 
191828  assert( p->rc==SQLITE_OK );
191829  assert( (iCol<0)==p->bDelete );
191830 
191831  /* Add the entry to the main terms index. */
191832  rc = sqlite3Fts5HashWrite(
191833  p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
191834  );
191835 
191836  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
191837  const int nChar = pConfig->aPrefix[i];
191838  int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
191839  if( nByte ){
191840  rc = sqlite3Fts5HashWrite(p->pHash,
191841  p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
191842  nByte
191843  );
191844  }
191845  }
191846 
191847  return rc;
191848 }
191849 
191850 /*
191851 ** Open a new iterator to iterate though all rowid that match the
191852 ** specified token or token prefix.
191853 */
191854 static int sqlite3Fts5IndexQuery(
191855  Fts5Index *p, /* FTS index to query */
191856  const char *pToken, int nToken, /* Token (or prefix) to query for */
191857  int flags, /* Mask of FTS5INDEX_QUERY_X flags */
191858  Fts5Colset *pColset, /* Match these columns only */
191859  Fts5IndexIter **ppIter /* OUT: New iterator object */
191860 ){
191861  Fts5Config *pConfig = p->pConfig;
191862  Fts5Iter *pRet = 0;
191863  Fts5Buffer buf = {0, 0, 0};
191864 
191865  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
191866  assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
191867 
191868  if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
191869  int iIdx = 0; /* Index to search */
191870  memcpy(&buf.p[1], pToken, nToken);
191871 
191872  /* Figure out which index to search and set iIdx accordingly. If this
191873  ** is a prefix query for which there is no prefix index, set iIdx to
191874  ** greater than pConfig->nPrefix to indicate that the query will be
191875  ** satisfied by scanning multiple terms in the main index.
191876  **
191877  ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
191878  ** prefix-query. Instead of using a prefix-index (if one exists),
191879  ** evaluate the prefix query using the main FTS index. This is used
191880  ** for internal sanity checking by the integrity-check in debug
191881  ** mode only. */
191882 #ifdef SQLITE_DEBUG
191883  if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
191884  assert( flags & FTS5INDEX_QUERY_PREFIX );
191885  iIdx = 1+pConfig->nPrefix;
191886  }else
191887 #endif
191888  if( flags & FTS5INDEX_QUERY_PREFIX ){
191889  int nChar = fts5IndexCharlen(pToken, nToken);
191890  for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
191891  if( pConfig->aPrefix[iIdx-1]==nChar ) break;
191892  }
191893  }
191894 
191895  if( iIdx<=pConfig->nPrefix ){
191896  /* Straight index lookup */
191897  Fts5Structure *pStruct = fts5StructureRead(p);
191898  buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
191899  if( pStruct ){
191900  fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
191901  pColset, buf.p, nToken+1, -1, 0, &pRet
191902  );
191903  fts5StructureRelease(pStruct);
191904  }
191905  }else{
191906  /* Scan multiple terms in the main index */
191907  int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
191908  buf.p[0] = FTS5_MAIN_PREFIX;
191909  fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
191910  assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
191911  fts5IterSetOutputCb(&p->rc, pRet);
191912  if( p->rc==SQLITE_OK ){
191913  Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
191914  if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
191915  }
191916  }
191917 
191918  if( p->rc ){
191919  sqlite3Fts5IterClose(&pRet->base);
191920  pRet = 0;
191921  fts5CloseReader(p);
191922  }
191923 
191924  *ppIter = &pRet->base;
191925  sqlite3Fts5BufferFree(&buf);
191926  }
191927  return fts5IndexReturn(p);
191928 }
191929 
191930 /*
191931 ** Return true if the iterator passed as the only argument is at EOF.
191932 */
191933 /*
191934 ** Move to the next matching rowid.
191935 */
191936 static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
191937  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
191938  assert( pIter->pIndex->rc==SQLITE_OK );
191939  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
191940  return fts5IndexReturn(pIter->pIndex);
191941 }
191942 
191943 /*
191944 ** Move to the next matching term/rowid. Used by the fts5vocab module.
191945 */
191946 static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
191947  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
191948  Fts5Index *p = pIter->pIndex;
191949 
191950  assert( pIter->pIndex->rc==SQLITE_OK );
191951 
191952  fts5MultiIterNext(p, pIter, 0, 0);
191953  if( p->rc==SQLITE_OK ){
191954  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
191955  if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
191956  fts5DataRelease(pSeg->pLeaf);
191957  pSeg->pLeaf = 0;
191958  pIter->base.bEof = 1;
191959  }
191960  }
191961 
191962  return fts5IndexReturn(pIter->pIndex);
191963 }
191964 
191965 /*
191966 ** Move to the next matching rowid that occurs at or after iMatch. The
191967 ** definition of "at or after" depends on whether this iterator iterates
191968 ** in ascending or descending rowid order.
191969 */
191970 static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
191971  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
191972  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
191973  return fts5IndexReturn(pIter->pIndex);
191974 }
191975 
191976 /*
191977 ** Return the current term.
191978 */
191979 static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
191980  int n;
191981  const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
191982  *pn = n-1;
191983  return &z[1];
191984 }
191985 
191986 /*
191987 ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
191988 */
191989 static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
191990  if( pIndexIter ){
191991  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
191992  Fts5Index *pIndex = pIter->pIndex;
191993  fts5MultiIterFree(pIter);
191994  fts5CloseReader(pIndex);
191995  }
191996 }
191997 
191998 /*
191999 ** Read and decode the "averages" record from the database.
192000 **
192001 ** Parameter anSize must point to an array of size nCol, where nCol is
192002 ** the number of user defined columns in the FTS table.
192003 */
192004 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
192005  int nCol = p->pConfig->nCol;
192006  Fts5Data *pData;
192007 
192008  *pnRow = 0;
192009  memset(anSize, 0, sizeof(i64) * nCol);
192010  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
192011  if( p->rc==SQLITE_OK && pData->nn ){
192012  int i = 0;
192013  int iCol;
192014  i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
192015  for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
192016  i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
192017  }
192018  }
192019 
192020  fts5DataRelease(pData);
192021  return fts5IndexReturn(p);
192022 }
192023 
192024 /*
192025 ** Replace the current "averages" record with the contents of the buffer
192026 ** supplied as the second argument.
192027 */
192028 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
192029  assert( p->rc==SQLITE_OK );
192030  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
192031  return fts5IndexReturn(p);
192032 }
192033 
192034 /*
192035 ** Return the total number of blocks this module has read from the %_data
192036 ** table since it was created.
192037 */
192038 static int sqlite3Fts5IndexReads(Fts5Index *p){
192039  return p->nRead;
192040 }
192041 
192042 /*
192043 ** Set the 32-bit cookie value stored at the start of all structure
192044 ** records to the value passed as the second argument.
192045 **
192046 ** Return SQLITE_OK if successful, or an SQLite error code if an error
192047 ** occurs.
192048 */
192049 static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
192050  int rc; /* Return code */
192051  Fts5Config *pConfig = p->pConfig; /* Configuration object */
192052  u8 aCookie[4]; /* Binary representation of iNew */
192053  sqlite3_blob *pBlob = 0;
192054 
192055  assert( p->rc==SQLITE_OK );
192056  sqlite3Fts5Put32(aCookie, iNew);
192057 
192058  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
192059  "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
192060  );
192061  if( rc==SQLITE_OK ){
192062  sqlite3_blob_write(pBlob, aCookie, 4, 0);
192063  rc = sqlite3_blob_close(pBlob);
192064  }
192065 
192066  return rc;
192067 }
192068 
192069 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
192070  Fts5Structure *pStruct;
192071  pStruct = fts5StructureRead(p);
192072  fts5StructureRelease(pStruct);
192073  return fts5IndexReturn(p);
192074 }
192075 
192076 
192077 /*************************************************************************
192078 **************************************************************************
192079 ** Below this point is the implementation of the integrity-check
192080 ** functionality.
192081 */
192082 
192083 /*
192084 ** Return a simple checksum value based on the arguments.
192085 */
192086 static u64 sqlite3Fts5IndexEntryCksum(
192087  i64 iRowid,
192088  int iCol,
192089  int iPos,
192090  int iIdx,
192091  const char *pTerm,
192092  int nTerm
192093 ){
192094  int i;
192095  u64 ret = iRowid;
192096  ret += (ret<<3) + iCol;
192097  ret += (ret<<3) + iPos;
192098  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
192099  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
192100  return ret;
192101 }
192102 
192103 #ifdef SQLITE_DEBUG
192104 /*
192105 ** This function is purely an internal test. It does not contribute to
192106 ** FTS functionality, or even the integrity-check, in any way.
192107 **
192108 ** Instead, it tests that the same set of pgno/rowid combinations are
192109 ** visited regardless of whether the doclist-index identified by parameters
192110 ** iSegid/iLeaf is iterated in forwards or reverse order.
192111 */
192112 static void fts5TestDlidxReverse(
192113  Fts5Index *p,
192114  int iSegid, /* Segment id to load from */
192115  int iLeaf /* Load doclist-index for this leaf */
192116 ){
192117  Fts5DlidxIter *pDlidx = 0;
192118  u64 cksum1 = 13;
192119  u64 cksum2 = 13;
192120 
192121  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
192122  fts5DlidxIterEof(p, pDlidx)==0;
192123  fts5DlidxIterNext(p, pDlidx)
192124  ){
192125  i64 iRowid = fts5DlidxIterRowid(pDlidx);
192126  int pgno = fts5DlidxIterPgno(pDlidx);
192127  assert( pgno>iLeaf );
192128  cksum1 += iRowid + ((i64)pgno<<32);
192129  }
192130  fts5DlidxIterFree(pDlidx);
192131  pDlidx = 0;
192132 
192133  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
192134  fts5DlidxIterEof(p, pDlidx)==0;
192135  fts5DlidxIterPrev(p, pDlidx)
192136  ){
192137  i64 iRowid = fts5DlidxIterRowid(pDlidx);
192138  int pgno = fts5DlidxIterPgno(pDlidx);
192139  assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
192140  cksum2 += iRowid + ((i64)pgno<<32);
192141  }
192142  fts5DlidxIterFree(pDlidx);
192143  pDlidx = 0;
192144 
192145  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
192146 }
192147 
192148 static int fts5QueryCksum(
192149  Fts5Index *p, /* Fts5 index object */
192150  int iIdx,
192151  const char *z, /* Index key to query for */
192152  int n, /* Size of index key in bytes */
192153  int flags, /* Flags for Fts5IndexQuery */
192154  u64 *pCksum /* IN/OUT: Checksum value */
192155 ){
192156  int eDetail = p->pConfig->eDetail;
192157  u64 cksum = *pCksum;
192158  Fts5IndexIter *pIter = 0;
192159  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
192160 
192161  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
192162  i64 rowid = pIter->iRowid;
192163 
192164  if( eDetail==FTS5_DETAIL_NONE ){
192165  cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
192166  }else{
192167  Fts5PoslistReader sReader;
192168  for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
192169  sReader.bEof==0;
192170  sqlite3Fts5PoslistReaderNext(&sReader)
192171  ){
192172  int iCol = FTS5_POS2COLUMN(sReader.iPos);
192173  int iOff = FTS5_POS2OFFSET(sReader.iPos);
192174  cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
192175  }
192176  }
192177  if( rc==SQLITE_OK ){
192178  rc = sqlite3Fts5IterNext(pIter);
192179  }
192180  }
192181  sqlite3Fts5IterClose(pIter);
192182 
192183  *pCksum = cksum;
192184  return rc;
192185 }
192186 
192187 
192188 /*
192189 ** This function is also purely an internal test. It does not contribute to
192190 ** FTS functionality, or even the integrity-check, in any way.
192191 */
192192 static void fts5TestTerm(
192193  Fts5Index *p,
192194  Fts5Buffer *pPrev, /* Previous term */
192195  const char *z, int n, /* Possibly new term to test */
192196  u64 expected,
192197  u64 *pCksum
192198 ){
192199  int rc = p->rc;
192200  if( pPrev->n==0 ){
192201  fts5BufferSet(&rc, pPrev, n, (const u8*)z);
192202  }else
192203  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
192204  u64 cksum3 = *pCksum;
192205  const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
192206  int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
192207  int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
192208  int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
192209  u64 ck1 = 0;
192210  u64 ck2 = 0;
192211 
192212  /* Check that the results returned for ASC and DESC queries are
192213  ** the same. If not, call this corruption. */
192214  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
192215  if( rc==SQLITE_OK ){
192216  int f = flags|FTS5INDEX_QUERY_DESC;
192217  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
192218  }
192219  if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
192220 
192221  /* If this is a prefix query, check that the results returned if the
192222  ** the index is disabled are the same. In both ASC and DESC order.
192223  **
192224  ** This check may only be performed if the hash table is empty. This
192225  ** is because the hash table only supports a single scan query at
192226  ** a time, and the multi-iter loop from which this function is called
192227  ** is already performing such a scan. */
192228  if( p->nPendingData==0 ){
192229  if( iIdx>0 && rc==SQLITE_OK ){
192230  int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
192231  ck2 = 0;
192232  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
192233  if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
192234  }
192235  if( iIdx>0 && rc==SQLITE_OK ){
192236  int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
192237  ck2 = 0;
192238  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
192239  if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
192240  }
192241  }
192242 
192243  cksum3 ^= ck1;
192244  fts5BufferSet(&rc, pPrev, n, (const u8*)z);
192245 
192246  if( rc==SQLITE_OK && cksum3!=expected ){
192247  rc = FTS5_CORRUPT;
192248  }
192249  *pCksum = cksum3;
192250  }
192251  p->rc = rc;
192252 }
192253 
192254 #else
192255 # define fts5TestDlidxReverse(x,y,z)
192256 # define fts5TestTerm(u,v,w,x,y,z)
192257 #endif
192258 
192259 /*
192260 ** Check that:
192261 **
192262 ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
192263 ** contain zero terms.
192264 ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
192265 ** contain zero rowids.
192266 */
192267 static void fts5IndexIntegrityCheckEmpty(
192268  Fts5Index *p,
192269  Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
192270  int iFirst,
192271  int iNoRowid,
192272  int iLast
192273 ){
192274  int i;
192275 
192276  /* Now check that the iter.nEmpty leaves following the current leaf
192277  ** (a) exist and (b) contain no terms. */
192278  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
192279  Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
192280  if( pLeaf ){
192281  if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
192282  if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
192283  }
192284  fts5DataRelease(pLeaf);
192285  }
192286 }
192287 
192288 static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
192289  int iTermOff = 0;
192290  int ii;
192291 
192292  Fts5Buffer buf1 = {0,0,0};
192293  Fts5Buffer buf2 = {0,0,0};
192294 
192295  ii = pLeaf->szLeaf;
192296  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
192297  int res;
192298  int iOff;
192299  int nIncr;
192300 
192301  ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
192302  iTermOff += nIncr;
192303  iOff = iTermOff;
192304 
192305  if( iOff>=pLeaf->szLeaf ){
192306  p->rc = FTS5_CORRUPT;
192307  }else if( iTermOff==nIncr ){
192308  int nByte;
192309  iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
192310  if( (iOff+nByte)>pLeaf->szLeaf ){
192311  p->rc = FTS5_CORRUPT;
192312  }else{
192313  fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
192314  }
192315  }else{
192316  int nKeep, nByte;
192317  iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
192318  iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
192319  if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
192320  p->rc = FTS5_CORRUPT;
192321  }else{
192322  buf1.n = nKeep;
192323  fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
192324  }
192325 
192326  if( p->rc==SQLITE_OK ){
192327  res = fts5BufferCompare(&buf1, &buf2);
192328  if( res<=0 ) p->rc = FTS5_CORRUPT;
192329  }
192330  }
192331  fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
192332  }
192333 
192334  fts5BufferFree(&buf1);
192335  fts5BufferFree(&buf2);
192336 }
192337 
192338 static void fts5IndexIntegrityCheckSegment(
192339  Fts5Index *p, /* FTS5 backend object */
192340  Fts5StructureSegment *pSeg /* Segment to check internal consistency */
192341 ){
192342  Fts5Config *pConfig = p->pConfig;
192343  sqlite3_stmt *pStmt = 0;
192344  int rc2;
192345  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
192346  int iDlidxPrevLeaf = pSeg->pgnoLast;
192347 
192348  if( pSeg->pgnoFirst==0 ) return;
192349 
192350  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
192351  "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
192352  pConfig->zDb, pConfig->zName, pSeg->iSegid
192353  ));
192354 
192355  /* Iterate through the b-tree hierarchy. */
192356  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
192357  i64 iRow; /* Rowid for this leaf */
192358  Fts5Data *pLeaf; /* Data for this leaf */
192359 
192360  int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
192361  const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
192362  int iIdxLeaf = sqlite3_column_int(pStmt, 2);
192363  int bIdxDlidx = sqlite3_column_int(pStmt, 3);
192364 
192365  /* If the leaf in question has already been trimmed from the segment,
192366  ** ignore this b-tree entry. Otherwise, load it into memory. */
192367  if( iIdxLeaf<pSeg->pgnoFirst ) continue;
192368  iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
192369  pLeaf = fts5DataRead(p, iRow);
192370  if( pLeaf==0 ) break;
192371 
192372  /* Check that the leaf contains at least one term, and that it is equal
192373  ** to or larger than the split-key in zIdxTerm. Also check that if there
192374  ** is also a rowid pointer within the leaf page header, it points to a
192375  ** location before the term. */
192376  if( pLeaf->nn<=pLeaf->szLeaf ){
192377  p->rc = FTS5_CORRUPT;
192378  }else{
192379  int iOff; /* Offset of first term on leaf */
192380  int iRowidOff; /* Offset of first rowid on leaf */
192381  int nTerm; /* Size of term on leaf in bytes */
192382  int res; /* Comparison of term and split-key */
192383 
192384  iOff = fts5LeafFirstTermOff(pLeaf);
192385  iRowidOff = fts5LeafFirstRowidOff(pLeaf);
192386  if( iRowidOff>=iOff ){
192387  p->rc = FTS5_CORRUPT;
192388  }else{
192389  iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
192390  res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
192391  if( res==0 ) res = nTerm - nIdxTerm;
192392  if( res<0 ) p->rc = FTS5_CORRUPT;
192393  }
192394 
192395  fts5IntegrityCheckPgidx(p, pLeaf);
192396  }
192397  fts5DataRelease(pLeaf);
192398  if( p->rc ) break;
192399 
192400  /* Now check that the iter.nEmpty leaves following the current leaf
192401  ** (a) exist and (b) contain no terms. */
192402  fts5IndexIntegrityCheckEmpty(
192403  p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
192404  );
192405  if( p->rc ) break;
192406 
192407  /* If there is a doclist-index, check that it looks right. */
192408  if( bIdxDlidx ){
192409  Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
192410  int iPrevLeaf = iIdxLeaf;
192411  int iSegid = pSeg->iSegid;
192412  int iPg = 0;
192413  i64 iKey;
192414 
192415  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
192416  fts5DlidxIterEof(p, pDlidx)==0;
192417  fts5DlidxIterNext(p, pDlidx)
192418  ){
192419 
192420  /* Check any rowid-less pages that occur before the current leaf. */
192421  for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
192422  iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
192423  pLeaf = fts5DataRead(p, iKey);
192424  if( pLeaf ){
192425  if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
192426  fts5DataRelease(pLeaf);
192427  }
192428  }
192429  iPrevLeaf = fts5DlidxIterPgno(pDlidx);
192430 
192431  /* Check that the leaf page indicated by the iterator really does
192432  ** contain the rowid suggested by the same. */
192433  iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
192434  pLeaf = fts5DataRead(p, iKey);
192435  if( pLeaf ){
192436  i64 iRowid;
192437  int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
192438  ASSERT_SZLEAF_OK(pLeaf);
192439  if( iRowidOff>=pLeaf->szLeaf ){
192440  p->rc = FTS5_CORRUPT;
192441  }else{
192442  fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
192443  if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
192444  }
192445  fts5DataRelease(pLeaf);
192446  }
192447  }
192448 
192449  iDlidxPrevLeaf = iPg;
192450  fts5DlidxIterFree(pDlidx);
192451  fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
192452  }else{
192453  iDlidxPrevLeaf = pSeg->pgnoLast;
192454  /* TODO: Check there is no doclist index */
192455  }
192456 
192457  iIdxPrevLeaf = iIdxLeaf;
192458  }
192459 
192460  rc2 = sqlite3_finalize(pStmt);
192461  if( p->rc==SQLITE_OK ) p->rc = rc2;
192462 
192463  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
192464 #if 0
192465  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
192466  p->rc = FTS5_CORRUPT;
192467  }
192468 #endif
192469 }
192470 
192471 
192472 /*
192473 ** Run internal checks to ensure that the FTS index (a) is internally
192474 ** consistent and (b) contains entries for which the XOR of the checksums
192475 ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
192476 **
192477 ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
192478 ** checksum does not match. Return SQLITE_OK if all checks pass without
192479 ** error, or some other SQLite error code if another error (e.g. OOM)
192480 ** occurs.
192481 */
192482 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
192483  int eDetail = p->pConfig->eDetail;
192484  u64 cksum2 = 0; /* Checksum based on contents of indexes */
192485  Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
192486  Fts5Iter *pIter; /* Used to iterate through entire index */
192487  Fts5Structure *pStruct; /* Index structure */
192488 
192489 #ifdef SQLITE_DEBUG
192490  /* Used by extra internal tests only run if NDEBUG is not defined */
192491  u64 cksum3 = 0; /* Checksum based on contents of indexes */
192492  Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
192493 #endif
192494  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
192495 
192496  /* Load the FTS index structure */
192497  pStruct = fts5StructureRead(p);
192498 
192499  /* Check that the internal nodes of each segment match the leaves */
192500  if( pStruct ){
192501  int iLvl, iSeg;
192502  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
192503  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
192504  Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
192505  fts5IndexIntegrityCheckSegment(p, pSeg);
192506  }
192507  }
192508  }
192509 
192510  /* The cksum argument passed to this function is a checksum calculated
192511  ** based on all expected entries in the FTS index (including prefix index
192512  ** entries). This block checks that a checksum calculated based on the
192513  ** actual contents of FTS index is identical.
192514  **
192515  ** Two versions of the same checksum are calculated. The first (stack
192516  ** variable cksum2) based on entries extracted from the full-text index
192517  ** while doing a linear scan of each individual index in turn.
192518  **
192519  ** As each term visited by the linear scans, a separate query for the
192520  ** same term is performed. cksum3 is calculated based on the entries
192521  ** extracted by these queries.
192522  */
192523  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
192524  fts5MultiIterEof(p, pIter)==0;
192525  fts5MultiIterNext(p, pIter, 0, 0)
192526  ){
192527  int n; /* Size of term in bytes */
192528  i64 iPos = 0; /* Position read from poslist */
192529  int iOff = 0; /* Offset within poslist */
192530  i64 iRowid = fts5MultiIterRowid(pIter);
192531  char *z = (char*)fts5MultiIterTerm(pIter, &n);
192532 
192533  /* If this is a new term, query for it. Update cksum3 with the results. */
192534  fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
192535 
192536  if( eDetail==FTS5_DETAIL_NONE ){
192537  if( 0==fts5MultiIterIsEmpty(p, pIter) ){
192538  cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
192539  }
192540  }else{
192541  poslist.n = 0;
192542  fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
192543  while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
192544  int iCol = FTS5_POS2COLUMN(iPos);
192545  int iTokOff = FTS5_POS2OFFSET(iPos);
192546  cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
192547  }
192548  }
192549  }
192550  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
192551 
192552  fts5MultiIterFree(pIter);
192553  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
192554 
192555  fts5StructureRelease(pStruct);
192556 #ifdef SQLITE_DEBUG
192557  fts5BufferFree(&term);
192558 #endif
192559  fts5BufferFree(&poslist);
192560  return fts5IndexReturn(p);
192561 }
192562 
192563 /*************************************************************************
192564 **************************************************************************
192565 ** Below this point is the implementation of the fts5_decode() scalar
192566 ** function only.
192567 */
192568 
192569 /*
192570 ** Decode a segment-data rowid from the %_data table. This function is
192571 ** the opposite of macro FTS5_SEGMENT_ROWID().
192572 */
192573 static void fts5DecodeRowid(
192574  i64 iRowid, /* Rowid from %_data table */
192575  int *piSegid, /* OUT: Segment id */
192576  int *pbDlidx, /* OUT: Dlidx flag */
192577  int *piHeight, /* OUT: Height */
192578  int *piPgno /* OUT: Page number */
192579 ){
192580  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
192581  iRowid >>= FTS5_DATA_PAGE_B;
192582 
192583  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
192584  iRowid >>= FTS5_DATA_HEIGHT_B;
192585 
192586  *pbDlidx = (int)(iRowid & 0x0001);
192587  iRowid >>= FTS5_DATA_DLI_B;
192588 
192589  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
192590 }
192591 
192592 static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
192593  int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
192594  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
192595 
192596  if( iSegid==0 ){
192597  if( iKey==FTS5_AVERAGES_ROWID ){
192598  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
192599  }else{
192600  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
192601  }
192602  }
192603  else{
192604  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
192605  bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
192606  );
192607  }
192608 }
192609 
192610 static void fts5DebugStructure(
192611  int *pRc, /* IN/OUT: error code */
192612  Fts5Buffer *pBuf,
192613  Fts5Structure *p
192614 ){
192615  int iLvl, iSeg; /* Iterate through levels, segments */
192616 
192617  for(iLvl=0; iLvl<p->nLevel; iLvl++){
192618  Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
192619  sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
192620  " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
192621  );
192622  for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
192623  Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
192624  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
192625  pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
192626  );
192627  }
192628  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
192629  }
192630 }
192631 
192632 /*
192633 ** This is part of the fts5_decode() debugging aid.
192634 **
192635 ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
192636 ** function appends a human-readable representation of the same object
192637 ** to the buffer passed as the second argument.
192638 */
192639 static void fts5DecodeStructure(
192640  int *pRc, /* IN/OUT: error code */
192641  Fts5Buffer *pBuf,
192642  const u8 *pBlob, int nBlob
192643 ){
192644  int rc; /* Return code */
192645  Fts5Structure *p = 0; /* Decoded structure object */
192646 
192647  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
192648  if( rc!=SQLITE_OK ){
192649  *pRc = rc;
192650  return;
192651  }
192652 
192653  fts5DebugStructure(pRc, pBuf, p);
192654  fts5StructureRelease(p);
192655 }
192656 
192657 /*
192658 ** This is part of the fts5_decode() debugging aid.
192659 **
192660 ** Arguments pBlob/nBlob contain an "averages" record. This function
192661 ** appends a human-readable representation of record to the buffer passed
192662 ** as the second argument.
192663 */
192664 static void fts5DecodeAverages(
192665  int *pRc, /* IN/OUT: error code */
192666  Fts5Buffer *pBuf,
192667  const u8 *pBlob, int nBlob
192668 ){
192669  int i = 0;
192670  const char *zSpace = "";
192671 
192672  while( i<nBlob ){
192673  u64 iVal;
192674  i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
192675  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
192676  zSpace = " ";
192677  }
192678 }
192679 
192680 /*
192681 ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
192682 ** each varint and append its string representation to buffer pBuf. Return
192683 ** after either the input buffer is exhausted or a 0 value is read.
192684 **
192685 ** The return value is the number of bytes read from the input buffer.
192686 */
192687 static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
192688  int iOff = 0;
192689  while( iOff<n ){
192690  int iVal;
192691  iOff += fts5GetVarint32(&a[iOff], iVal);
192692  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
192693  }
192694  return iOff;
192695 }
192696 
192697 /*
192698 ** The start of buffer (a/n) contains the start of a doclist. The doclist
192699 ** may or may not finish within the buffer. This function appends a text
192700 ** representation of the part of the doclist that is present to buffer
192701 ** pBuf.
192702 **
192703 ** The return value is the number of bytes read from the input buffer.
192704 */
192705 static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
192706  i64 iDocid = 0;
192707  int iOff = 0;
192708 
192709  if( n>0 ){
192710  iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
192711  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
192712  }
192713  while( iOff<n ){
192714  int nPos;
192715  int bDel;
192716  iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
192717  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
192718  iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
192719  if( iOff<n ){
192720  i64 iDelta;
192721  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
192722  iDocid += iDelta;
192723  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
192724  }
192725  }
192726 
192727  return iOff;
192728 }
192729 
192730 /*
192731 ** This function is part of the fts5_decode() debugging function. It is
192732 ** only ever used with detail=none tables.
192733 **
192734 ** Buffer (pData/nData) contains a doclist in the format used by detail=none
192735 ** tables. This function appends a human-readable version of that list to
192736 ** buffer pBuf.
192737 **
192738 ** If *pRc is other than SQLITE_OK when this function is called, it is a
192739 ** no-op. If an OOM or other error occurs within this function, *pRc is
192740 ** set to an SQLite error code before returning. The final state of buffer
192741 ** pBuf is undefined in this case.
192742 */
192743 static void fts5DecodeRowidList(
192744  int *pRc, /* IN/OUT: Error code */
192745  Fts5Buffer *pBuf, /* Buffer to append text to */
192746  const u8 *pData, int nData /* Data to decode list-of-rowids from */
192747 ){
192748  int i = 0;
192749  i64 iRowid = 0;
192750 
192751  while( i<nData ){
192752  const char *zApp = "";
192753  u64 iVal;
192754  i += sqlite3Fts5GetVarint(&pData[i], &iVal);
192755  iRowid += iVal;
192756 
192757  if( i<nData && pData[i]==0x00 ){
192758  i++;
192759  if( i<nData && pData[i]==0x00 ){
192760  i++;
192761  zApp = "+";
192762  }else{
192763  zApp = "*";
192764  }
192765  }
192766 
192767  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
192768  }
192769 }
192770 
192771 /*
192772 ** The implementation of user-defined scalar function fts5_decode().
192773 */
192774 static void fts5DecodeFunction(
192775  sqlite3_context *pCtx, /* Function call context */
192776  int nArg, /* Number of args (always 2) */
192777  sqlite3_value **apVal /* Function arguments */
192778 ){
192779  i64 iRowid; /* Rowid for record being decoded */
192780  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
192781  const u8 *aBlob; int n; /* Record to decode */
192782  u8 *a = 0;
192783  Fts5Buffer s; /* Build up text to return here */
192784  int rc = SQLITE_OK; /* Return code */
192785  int nSpace = 0;
192786  int eDetailNone = (sqlite3_user_data(pCtx)!=0);
192787 
192788  assert( nArg==2 );
192789  UNUSED_PARAM(nArg);
192790  memset(&s, 0, sizeof(Fts5Buffer));
192791  iRowid = sqlite3_value_int64(apVal[0]);
192792 
192793  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
192794  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
192795  ** buffer overreads even if the record is corrupt. */
192796  n = sqlite3_value_bytes(apVal[1]);
192797  aBlob = sqlite3_value_blob(apVal[1]);
192798  nSpace = n + FTS5_DATA_ZERO_PADDING;
192799  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
192800  if( a==0 ) goto decode_out;
192801  memcpy(a, aBlob, n);
192802 
192803 
192804  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
192805 
192806  fts5DebugRowid(&rc, &s, iRowid);
192807  if( bDlidx ){
192808  Fts5Data dlidx;
192809  Fts5DlidxLvl lvl;
192810 
192811  dlidx.p = a;
192812  dlidx.nn = n;
192813 
192814  memset(&lvl, 0, sizeof(Fts5DlidxLvl));
192815  lvl.pData = &dlidx;
192816  lvl.iLeafPgno = iPgno;
192817 
192818  for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
192819  sqlite3Fts5BufferAppendPrintf(&rc, &s,
192820  " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
192821  );
192822  }
192823  }else if( iSegid==0 ){
192824  if( iRowid==FTS5_AVERAGES_ROWID ){
192825  fts5DecodeAverages(&rc, &s, a, n);
192826  }else{
192827  fts5DecodeStructure(&rc, &s, a, n);
192828  }
192829  }else if( eDetailNone ){
192830  Fts5Buffer term; /* Current term read from page */
192831  int szLeaf;
192832  int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
192833  int iTermOff;
192834  int nKeep = 0;
192835  int iOff;
192836 
192837  memset(&term, 0, sizeof(Fts5Buffer));
192838 
192839  /* Decode any entries that occur before the first term. */
192840  if( szLeaf<n ){
192841  iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
192842  }else{
192843  iTermOff = szLeaf;
192844  }
192845  fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
192846 
192847  iOff = iTermOff;
192848  while( iOff<szLeaf ){
192849  int nAppend;
192850 
192851  /* Read the term data for the next term*/
192852  iOff += fts5GetVarint32(&a[iOff], nAppend);
192853  term.n = nKeep;
192854  fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
192855  sqlite3Fts5BufferAppendPrintf(
192856  &rc, &s, " term=%.*s", term.n, (const char*)term.p
192857  );
192858  iOff += nAppend;
192859 
192860  /* Figure out where the doclist for this term ends */
192861  if( iPgidxOff<n ){
192862  int nIncr;
192863  iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
192864  iTermOff += nIncr;
192865  }else{
192866  iTermOff = szLeaf;
192867  }
192868 
192869  fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
192870  iOff = iTermOff;
192871  if( iOff<szLeaf ){
192872  iOff += fts5GetVarint32(&a[iOff], nKeep);
192873  }
192874  }
192875 
192876  fts5BufferFree(&term);
192877  }else{
192878  Fts5Buffer term; /* Current term read from page */
192879  int szLeaf; /* Offset of pgidx in a[] */
192880  int iPgidxOff;
192881  int iPgidxPrev = 0; /* Previous value read from pgidx */
192882  int iTermOff = 0;
192883  int iRowidOff = 0;
192884  int iOff;
192885  int nDoclist;
192886 
192887  memset(&term, 0, sizeof(Fts5Buffer));
192888 
192889  if( n<4 ){
192890  sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
192891  goto decode_out;
192892  }else{
192893  iRowidOff = fts5GetU16(&a[0]);
192894  iPgidxOff = szLeaf = fts5GetU16(&a[2]);
192895  if( iPgidxOff<n ){
192896  fts5GetVarint32(&a[iPgidxOff], iTermOff);
192897  }
192898  }
192899 
192900  /* Decode the position list tail at the start of the page */
192901  if( iRowidOff!=0 ){
192902  iOff = iRowidOff;
192903  }else if( iTermOff!=0 ){
192904  iOff = iTermOff;
192905  }else{
192906  iOff = szLeaf;
192907  }
192908  fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
192909 
192910  /* Decode any more doclist data that appears on the page before the
192911  ** first term. */
192912  nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
192913  fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
192914 
192915  while( iPgidxOff<n ){
192916  int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
192917  int nByte; /* Bytes of data */
192918  int iEnd;
192919 
192920  iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
192921  iPgidxPrev += nByte;
192922  iOff = iPgidxPrev;
192923 
192924  if( iPgidxOff<n ){
192925  fts5GetVarint32(&a[iPgidxOff], nByte);
192926  iEnd = iPgidxPrev + nByte;
192927  }else{
192928  iEnd = szLeaf;
192929  }
192930 
192931  if( bFirst==0 ){
192932  iOff += fts5GetVarint32(&a[iOff], nByte);
192933  term.n = nByte;
192934  }
192935  iOff += fts5GetVarint32(&a[iOff], nByte);
192936  fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
192937  iOff += nByte;
192938 
192939  sqlite3Fts5BufferAppendPrintf(
192940  &rc, &s, " term=%.*s", term.n, (const char*)term.p
192941  );
192942  iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
192943  }
192944 
192945  fts5BufferFree(&term);
192946  }
192947 
192948  decode_out:
192949  sqlite3_free(a);
192950  if( rc==SQLITE_OK ){
192951  sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
192952  }else{
192953  sqlite3_result_error_code(pCtx, rc);
192954  }
192955  fts5BufferFree(&s);
192956 }
192957 
192958 /*
192959 ** The implementation of user-defined scalar function fts5_rowid().
192960 */
192961 static void fts5RowidFunction(
192962  sqlite3_context *pCtx, /* Function call context */
192963  int nArg, /* Number of args (always 2) */
192964  sqlite3_value **apVal /* Function arguments */
192965 ){
192966  const char *zArg;
192967  if( nArg==0 ){
192968  sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
192969  }else{
192970  zArg = (const char*)sqlite3_value_text(apVal[0]);
192971  if( 0==sqlite3_stricmp(zArg, "segment") ){
192972  i64 iRowid;
192973  int segid, pgno;
192974  if( nArg!=3 ){
192975  sqlite3_result_error(pCtx,
192976  "should be: fts5_rowid('segment', segid, pgno))", -1
192977  );
192978  }else{
192979  segid = sqlite3_value_int(apVal[1]);
192980  pgno = sqlite3_value_int(apVal[2]);
192981  iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
192982  sqlite3_result_int64(pCtx, iRowid);
192983  }
192984  }else{
192985  sqlite3_result_error(pCtx,
192986  "first arg to fts5_rowid() must be 'segment'" , -1
192987  );
192988  }
192989  }
192990 }
192991 
192992 /*
192993 ** This is called as part of registering the FTS5 module with database
192994 ** connection db. It registers several user-defined scalar functions useful
192995 ** with FTS5.
192996 **
192997 ** If successful, SQLITE_OK is returned. If an error occurs, some other
192998 ** SQLite error code is returned instead.
192999 */
193000 static int sqlite3Fts5IndexInit(sqlite3 *db){
193001  int rc = sqlite3_create_function(
193002  db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
193003  );
193004 
193005  if( rc==SQLITE_OK ){
193006  rc = sqlite3_create_function(
193007  db, "fts5_decode_none", 2,
193008  SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
193009  );
193010  }
193011 
193012  if( rc==SQLITE_OK ){
193013  rc = sqlite3_create_function(
193014  db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
193015  );
193016  }
193017  return rc;
193018 }
193019 
193020 
193021 static int sqlite3Fts5IndexReset(Fts5Index *p){
193022  assert( p->pStruct==0 || p->iStructVersion!=0 );
193023  if( fts5IndexDataVersion(p)!=p->iStructVersion ){
193024  fts5StructureInvalidate(p);
193025  }
193026  return fts5IndexReturn(p);
193027 }
193028 
193029 /*
193030 ** 2014 Jun 09
193031 **
193032 ** The author disclaims copyright to this source code. In place of
193033 ** a legal notice, here is a blessing:
193034 **
193035 ** May you do good and not evil.
193036 ** May you find forgiveness for yourself and forgive others.
193037 ** May you share freely, never taking more than you give.
193038 **
193039 ******************************************************************************
193040 **
193041 ** This is an SQLite module implementing full-text search.
193042 */
193043 
193044 
193045 /* #include "fts5Int.h" */
193046 
193047 /*
193048 ** This variable is set to false when running tests for which the on disk
193049 ** structures should not be corrupt. Otherwise, true. If it is false, extra
193050 ** assert() conditions in the fts5 code are activated - conditions that are
193051 ** only true if it is guaranteed that the fts5 database is not corrupt.
193052 */
193053 SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
193054 
193055 
193056 typedef struct Fts5Auxdata Fts5Auxdata;
193057 typedef struct Fts5Auxiliary Fts5Auxiliary;
193058 typedef struct Fts5Cursor Fts5Cursor;
193059 typedef struct Fts5Sorter Fts5Sorter;
193060 typedef struct Fts5Table Fts5Table;
193061 typedef struct Fts5TokenizerModule Fts5TokenizerModule;
193062 
193063 /*
193064 ** NOTES ON TRANSACTIONS:
193065 **
193066 ** SQLite invokes the following virtual table methods as transactions are
193067 ** opened and closed by the user:
193068 **
193069 ** xBegin(): Start of a new transaction.
193070 ** xSync(): Initial part of two-phase commit.
193071 ** xCommit(): Final part of two-phase commit.
193072 ** xRollback(): Rollback the transaction.
193073 **
193074 ** Anything that is required as part of a commit that may fail is performed
193075 ** in the xSync() callback. Current versions of SQLite ignore any errors
193076 ** returned by xCommit().
193077 **
193078 ** And as sub-transactions are opened/closed:
193079 **
193080 ** xSavepoint(int S): Open savepoint S.
193081 ** xRelease(int S): Commit and close savepoint S.
193082 ** xRollbackTo(int S): Rollback to start of savepoint S.
193083 **
193084 ** During a write-transaction the fts5_index.c module may cache some data
193085 ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
193086 ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
193087 ** is called.
193088 **
193089 ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
193090 ** structure is used to record the current transaction state. This information
193091 ** is not required, but it is used in the assert() statements executed by
193092 ** function fts5CheckTransactionState() (see below).
193093 */
193094 struct Fts5TransactionState {
193095  int eState; /* 0==closed, 1==open, 2==synced */
193096  int iSavepoint; /* Number of open savepoints (0 -> none) */
193097 };
193098 
193099 /*
193100 ** A single object of this type is allocated when the FTS5 module is
193101 ** registered with a database handle. It is used to store pointers to
193102 ** all registered FTS5 extensions - tokenizers and auxiliary functions.
193103 */
193104 struct Fts5Global {
193105  fts5_api api; /* User visible part of object (see fts5.h) */
193106  sqlite3 *db; /* Associated database connection */
193107  i64 iNextId; /* Used to allocate unique cursor ids */
193108  Fts5Auxiliary *pAux; /* First in list of all aux. functions */
193109  Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
193110  Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
193111  Fts5Cursor *pCsr; /* First in list of all open cursors */
193112 };
193113 
193114 /*
193115 ** Each auxiliary function registered with the FTS5 module is represented
193116 ** by an object of the following type. All such objects are stored as part
193117 ** of the Fts5Global.pAux list.
193118 */
193119 struct Fts5Auxiliary {
193120  Fts5Global *pGlobal; /* Global context for this function */
193121  char *zFunc; /* Function name (nul-terminated) */
193122  void *pUserData; /* User-data pointer */
193123  fts5_extension_function xFunc; /* Callback function */
193124  void (*xDestroy)(void*); /* Destructor function */
193125  Fts5Auxiliary *pNext; /* Next registered auxiliary function */
193126 };
193127 
193128 /*
193129 ** Each tokenizer module registered with the FTS5 module is represented
193130 ** by an object of the following type. All such objects are stored as part
193131 ** of the Fts5Global.pTok list.
193132 */
193133 struct Fts5TokenizerModule {
193134  char *zName; /* Name of tokenizer */
193135  void *pUserData; /* User pointer passed to xCreate() */
193136  fts5_tokenizer x; /* Tokenizer functions */
193137  void (*xDestroy)(void*); /* Destructor function */
193138  Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
193139 };
193140 
193141 /*
193142 ** Virtual-table object.
193143 */
193144 struct Fts5Table {
193145  sqlite3_vtab base; /* Base class used by SQLite core */
193146  Fts5Config *pConfig; /* Virtual table configuration */
193147  Fts5Index *pIndex; /* Full-text index */
193148  Fts5Storage *pStorage; /* Document store */
193149  Fts5Global *pGlobal; /* Global (connection wide) data */
193150  Fts5Cursor *pSortCsr; /* Sort data from this cursor */
193151 #ifdef SQLITE_DEBUG
193152  struct Fts5TransactionState ts;
193153 #endif
193154 };
193155 
193156 struct Fts5MatchPhrase {
193157  Fts5Buffer *pPoslist; /* Pointer to current poslist */
193158  int nTerm; /* Size of phrase in terms */
193159 };
193160 
193161 /*
193162 ** pStmt:
193163 ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
193164 **
193165 ** aIdx[]:
193166 ** There is one entry in the aIdx[] array for each phrase in the query,
193167 ** the value of which is the offset within aPoslist[] following the last
193168 ** byte of the position list for the corresponding phrase.
193169 */
193170 struct Fts5Sorter {
193171  sqlite3_stmt *pStmt;
193172  i64 iRowid; /* Current rowid */
193173  const u8 *aPoslist; /* Position lists for current row */
193174  int nIdx; /* Number of entries in aIdx[] */
193175  int aIdx[1]; /* Offsets into aPoslist for current row */
193176 };
193177 
193178 
193179 /*
193180 ** Virtual-table cursor object.
193181 **
193182 ** iSpecial:
193183 ** If this is a 'special' query (refer to function fts5SpecialMatch()),
193184 ** then this variable contains the result of the query.
193185 **
193186 ** iFirstRowid, iLastRowid:
193187 ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
193188 ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
193189 ** limit of rowids to return, and iLastRowid the upper. In other words, the
193190 ** WHERE clause in the user's query might have been:
193191 **
193192 ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
193193 **
193194 ** If the cursor iterates in descending order of rowid, iFirstRowid
193195 ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
193196 ** the lower.
193197 */
193198 struct Fts5Cursor {
193199  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
193200  Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
193201  int *aColumnSize; /* Values for xColumnSize() */
193202  i64 iCsrId; /* Cursor id */
193203 
193204  /* Zero from this point onwards on cursor reset */
193205  int ePlan; /* FTS5_PLAN_XXX value */
193206  int bDesc; /* True for "ORDER BY rowid DESC" queries */
193207  i64 iFirstRowid; /* Return no rowids earlier than this */
193208  i64 iLastRowid; /* Return no rowids later than this */
193209  sqlite3_stmt *pStmt; /* Statement used to read %_content */
193210  Fts5Expr *pExpr; /* Expression for MATCH queries */
193211  Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
193212  int csrflags; /* Mask of cursor flags (see below) */
193213  i64 iSpecial; /* Result of special query */
193214 
193215  /* "rank" function. Populated on demand from vtab.xColumn(). */
193216  char *zRank; /* Custom rank function */
193217  char *zRankArgs; /* Custom rank function args */
193218  Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
193219  int nRankArg; /* Number of trailing arguments for rank() */
193220  sqlite3_value **apRankArg; /* Array of trailing arguments */
193221  sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
193222 
193223  /* Auxiliary data storage */
193224  Fts5Auxiliary *pAux; /* Currently executing extension function */
193225  Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
193226 
193227  /* Cache used by auxiliary functions xInst() and xInstCount() */
193228  Fts5PoslistReader *aInstIter; /* One for each phrase */
193229  int nInstAlloc; /* Size of aInst[] array (entries / 3) */
193230  int nInstCount; /* Number of phrase instances */
193231  int *aInst; /* 3 integers per phrase instance */
193232 };
193233 
193234 /*
193235 ** Bits that make up the "idxNum" parameter passed indirectly by
193236 ** xBestIndex() to xFilter().
193237 */
193238 #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
193239 #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
193240 #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
193241 #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
193242 #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
193243 
193244 #define FTS5_BI_ORDER_RANK 0x0020
193245 #define FTS5_BI_ORDER_ROWID 0x0040
193246 #define FTS5_BI_ORDER_DESC 0x0080
193247 
193248 /*
193249 ** Values for Fts5Cursor.csrflags
193250 */
193251 #define FTS5CSR_EOF 0x01
193252 #define FTS5CSR_REQUIRE_CONTENT 0x02
193253 #define FTS5CSR_REQUIRE_DOCSIZE 0x04
193254 #define FTS5CSR_REQUIRE_INST 0x08
193255 #define FTS5CSR_FREE_ZRANK 0x10
193256 #define FTS5CSR_REQUIRE_RESEEK 0x20
193257 #define FTS5CSR_REQUIRE_POSLIST 0x40
193258 
193259 #define BitFlagAllTest(x,y) (((x) & (y))==(y))
193260 #define BitFlagTest(x,y) (((x) & (y))!=0)
193261 
193262 
193263 /*
193264 ** Macros to Set(), Clear() and Test() cursor flags.
193265 */
193266 #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
193267 #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
193268 #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
193269 
193270 struct Fts5Auxdata {
193271  Fts5Auxiliary *pAux; /* Extension to which this belongs */
193272  void *pPtr; /* Pointer value */
193273  void(*xDelete)(void*); /* Destructor */
193274  Fts5Auxdata *pNext; /* Next object in linked list */
193275 };
193276 
193277 #ifdef SQLITE_DEBUG
193278 #define FTS5_BEGIN 1
193279 #define FTS5_SYNC 2
193280 #define FTS5_COMMIT 3
193281 #define FTS5_ROLLBACK 4
193282 #define FTS5_SAVEPOINT 5
193283 #define FTS5_RELEASE 6
193284 #define FTS5_ROLLBACKTO 7
193285 static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
193286  switch( op ){
193287  case FTS5_BEGIN:
193288  assert( p->ts.eState==0 );
193289  p->ts.eState = 1;
193290  p->ts.iSavepoint = -1;
193291  break;
193292 
193293  case FTS5_SYNC:
193294  assert( p->ts.eState==1 );
193295  p->ts.eState = 2;
193296  break;
193297 
193298  case FTS5_COMMIT:
193299  assert( p->ts.eState==2 );
193300  p->ts.eState = 0;
193301  break;
193302 
193303  case FTS5_ROLLBACK:
193304  assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
193305  p->ts.eState = 0;
193306  break;
193307 
193308  case FTS5_SAVEPOINT:
193309  assert( p->ts.eState==1 );
193310  assert( iSavepoint>=0 );
193311  assert( iSavepoint>p->ts.iSavepoint );
193312  p->ts.iSavepoint = iSavepoint;
193313  break;
193314 
193315  case FTS5_RELEASE:
193316  assert( p->ts.eState==1 );
193317  assert( iSavepoint>=0 );
193318  assert( iSavepoint<=p->ts.iSavepoint );
193319  p->ts.iSavepoint = iSavepoint-1;
193320  break;
193321 
193322  case FTS5_ROLLBACKTO:
193323  assert( p->ts.eState==1 );
193324  assert( iSavepoint>=0 );
193325  assert( iSavepoint<=p->ts.iSavepoint );
193326  p->ts.iSavepoint = iSavepoint;
193327  break;
193328  }
193329 }
193330 #else
193331 # define fts5CheckTransactionState(x,y,z)
193332 #endif
193333 
193334 /*
193335 ** Return true if pTab is a contentless table.
193336 */
193337 static int fts5IsContentless(Fts5Table *pTab){
193338  return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
193339 }
193340 
193341 /*
193342 ** Delete a virtual table handle allocated by fts5InitVtab().
193343 */
193344 static void fts5FreeVtab(Fts5Table *pTab){
193345  if( pTab ){
193346  sqlite3Fts5IndexClose(pTab->pIndex);
193347  sqlite3Fts5StorageClose(pTab->pStorage);
193348  sqlite3Fts5ConfigFree(pTab->pConfig);
193349  sqlite3_free(pTab);
193350  }
193351 }
193352 
193353 /*
193354 ** The xDisconnect() virtual table method.
193355 */
193356 static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
193357  fts5FreeVtab((Fts5Table*)pVtab);
193358  return SQLITE_OK;
193359 }
193360 
193361 /*
193362 ** The xDestroy() virtual table method.
193363 */
193364 static int fts5DestroyMethod(sqlite3_vtab *pVtab){
193365  Fts5Table *pTab = (Fts5Table*)pVtab;
193366  int rc = sqlite3Fts5DropAll(pTab->pConfig);
193367  if( rc==SQLITE_OK ){
193368  fts5FreeVtab((Fts5Table*)pVtab);
193369  }
193370  return rc;
193371 }
193372 
193373 /*
193374 ** This function is the implementation of both the xConnect and xCreate
193375 ** methods of the FTS3 virtual table.
193376 **
193377 ** The argv[] array contains the following:
193378 **
193379 ** argv[0] -> module name ("fts5")
193380 ** argv[1] -> database name
193381 ** argv[2] -> table name
193382 ** argv[...] -> "column name" and other module argument fields.
193383 */
193384 static int fts5InitVtab(
193385  int bCreate, /* True for xCreate, false for xConnect */
193386  sqlite3 *db, /* The SQLite database connection */
193387  void *pAux, /* Hash table containing tokenizers */
193388  int argc, /* Number of elements in argv array */
193389  const char * const *argv, /* xCreate/xConnect argument array */
193390  sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
193391  char **pzErr /* Write any error message here */
193392 ){
193393  Fts5Global *pGlobal = (Fts5Global*)pAux;
193394  const char **azConfig = (const char**)argv;
193395  int rc = SQLITE_OK; /* Return code */
193396  Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
193397  Fts5Table *pTab = 0; /* New virtual table object */
193398 
193399  /* Allocate the new vtab object and parse the configuration */
193400  pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
193401  if( rc==SQLITE_OK ){
193402  rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
193403  assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
193404  }
193405  if( rc==SQLITE_OK ){
193406  pTab->pConfig = pConfig;
193407  pTab->pGlobal = pGlobal;
193408  }
193409 
193410  /* Open the index sub-system */
193411  if( rc==SQLITE_OK ){
193412  rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
193413  }
193414 
193415  /* Open the storage sub-system */
193416  if( rc==SQLITE_OK ){
193417  rc = sqlite3Fts5StorageOpen(
193418  pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
193419  );
193420  }
193421 
193422  /* Call sqlite3_declare_vtab() */
193423  if( rc==SQLITE_OK ){
193424  rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
193425  }
193426 
193427  /* Load the initial configuration */
193428  if( rc==SQLITE_OK ){
193429  assert( pConfig->pzErrmsg==0 );
193430  pConfig->pzErrmsg = pzErr;
193431  rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
193432  sqlite3Fts5IndexRollback(pTab->pIndex);
193433  pConfig->pzErrmsg = 0;
193434  }
193435 
193436  if( rc!=SQLITE_OK ){
193437  fts5FreeVtab(pTab);
193438  pTab = 0;
193439  }else if( bCreate ){
193440  fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
193441  }
193442  *ppVTab = (sqlite3_vtab*)pTab;
193443  return rc;
193444 }
193445 
193446 /*
193447 ** The xConnect() and xCreate() methods for the virtual table. All the
193448 ** work is done in function fts5InitVtab().
193449 */
193450 static int fts5ConnectMethod(
193451  sqlite3 *db, /* Database connection */
193452  void *pAux, /* Pointer to tokenizer hash table */
193453  int argc, /* Number of elements in argv array */
193454  const char * const *argv, /* xCreate/xConnect argument array */
193455  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
193456  char **pzErr /* OUT: sqlite3_malloc'd error message */
193457 ){
193458  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
193459 }
193460 static int fts5CreateMethod(
193461  sqlite3 *db, /* Database connection */
193462  void *pAux, /* Pointer to tokenizer hash table */
193463  int argc, /* Number of elements in argv array */
193464  const char * const *argv, /* xCreate/xConnect argument array */
193465  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
193466  char **pzErr /* OUT: sqlite3_malloc'd error message */
193467 ){
193468  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
193469 }
193470 
193471 /*
193472 ** The different query plans.
193473 */
193474 #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
193475 #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
193476 #define FTS5_PLAN_SPECIAL 3 /* An internal query */
193477 #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
193478 #define FTS5_PLAN_SCAN 5 /* No usable constraint */
193479 #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
193480 
193481 /*
193482 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
193483 ** extension is currently being used by a version of SQLite too old to
193484 ** support index-info flags. In that case this function is a no-op.
193485 */
193486 static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
193487 #if SQLITE_VERSION_NUMBER>=3008012
193488 #ifndef SQLITE_CORE
193489  if( sqlite3_libversion_number()>=3008012 )
193490 #endif
193491  {
193492  pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
193493  }
193494 #endif
193495 }
193496 
193497 /*
193498 ** Implementation of the xBestIndex method for FTS5 tables. Within the
193499 ** WHERE constraint, it searches for the following:
193500 **
193501 ** 1. A MATCH constraint against the special column.
193502 ** 2. A MATCH constraint against the "rank" column.
193503 ** 3. An == constraint against the rowid column.
193504 ** 4. A < or <= constraint against the rowid column.
193505 ** 5. A > or >= constraint against the rowid column.
193506 **
193507 ** Within the ORDER BY, either:
193508 **
193509 ** 5. ORDER BY rank [ASC|DESC]
193510 ** 6. ORDER BY rowid [ASC|DESC]
193511 **
193512 ** Costs are assigned as follows:
193513 **
193514 ** a) If an unusable MATCH operator is present in the WHERE clause, the
193515 ** cost is unconditionally set to 1e50 (a really big number).
193516 **
193517 ** a) If a MATCH operator is present, the cost depends on the other
193518 ** constraints also present. As follows:
193519 **
193520 ** * No other constraints: cost=1000.0
193521 ** * One rowid range constraint: cost=750.0
193522 ** * Both rowid range constraints: cost=500.0
193523 ** * An == rowid constraint: cost=100.0
193524 **
193525 ** b) Otherwise, if there is no MATCH:
193526 **
193527 ** * No other constraints: cost=1000000.0
193528 ** * One rowid range constraint: cost=750000.0
193529 ** * Both rowid range constraints: cost=250000.0
193530 ** * An == rowid constraint: cost=10.0
193531 **
193532 ** Costs are not modified by the ORDER BY clause.
193533 */
193534 static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
193535  Fts5Table *pTab = (Fts5Table*)pVTab;
193536  Fts5Config *pConfig = pTab->pConfig;
193537  int idxFlags = 0; /* Parameter passed through to xFilter() */
193538  int bHasMatch;
193539  int iNext;
193540  int i;
193541 
193542  struct Constraint {
193543  int op; /* Mask against sqlite3_index_constraint.op */
193544  int fts5op; /* FTS5 mask for idxFlags */
193545  int iCol; /* 0==rowid, 1==tbl, 2==rank */
193546  int omit; /* True to omit this if found */
193547  int iConsIndex; /* Index in pInfo->aConstraint[] */
193548  } aConstraint[] = {
193549  {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
193550  FTS5_BI_MATCH, 1, 1, -1},
193551  {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
193552  FTS5_BI_RANK, 2, 1, -1},
193553  {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
193554  {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
193555  FTS5_BI_ROWID_LE, 0, 0, -1},
193556  {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
193557  FTS5_BI_ROWID_GE, 0, 0, -1},
193558  };
193559 
193560  int aColMap[3];
193561  aColMap[0] = -1;
193562  aColMap[1] = pConfig->nCol;
193563  aColMap[2] = pConfig->nCol+1;
193564 
193565  /* Set idxFlags flags for all WHERE clause terms that will be used. */
193566  for(i=0; i<pInfo->nConstraint; i++){
193567  struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
193568  int j;
193569  for(j=0; j<ArraySize(aConstraint); j++){
193570  struct Constraint *pC = &aConstraint[j];
193571  if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
193572  if( p->usable ){
193573  pC->iConsIndex = i;
193574  idxFlags |= pC->fts5op;
193575  }else if( j==0 ){
193576  /* As there exists an unusable MATCH constraint this is an
193577  ** unusable plan. Set a prohibitively high cost. */
193578  pInfo->estimatedCost = 1e50;
193579  return SQLITE_OK;
193580  }
193581  }
193582  }
193583  }
193584 
193585  /* Set idxFlags flags for the ORDER BY clause */
193586  if( pInfo->nOrderBy==1 ){
193587  int iSort = pInfo->aOrderBy[0].iColumn;
193588  if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
193589  idxFlags |= FTS5_BI_ORDER_RANK;
193590  }else if( iSort==-1 ){
193591  idxFlags |= FTS5_BI_ORDER_ROWID;
193592  }
193593  if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
193594  pInfo->orderByConsumed = 1;
193595  if( pInfo->aOrderBy[0].desc ){
193596  idxFlags |= FTS5_BI_ORDER_DESC;
193597  }
193598  }
193599  }
193600 
193601  /* Calculate the estimated cost based on the flags set in idxFlags. */
193602  bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
193603  if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
193604  pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
193605  if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
193606  }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
193607  pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
193608  }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
193609  pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
193610  }else{
193611  pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
193612  }
193613 
193614  /* Assign argvIndex values to each constraint in use. */
193615  iNext = 1;
193616  for(i=0; i<ArraySize(aConstraint); i++){
193617  struct Constraint *pC = &aConstraint[i];
193618  if( pC->iConsIndex>=0 ){
193619  pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
193620  pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
193621  }
193622  }
193623 
193624  pInfo->idxNum = idxFlags;
193625  return SQLITE_OK;
193626 }
193627 
193628 static int fts5NewTransaction(Fts5Table *pTab){
193629  Fts5Cursor *pCsr;
193630  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
193631  if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
193632  }
193633  return sqlite3Fts5StorageReset(pTab->pStorage);
193634 }
193635 
193636 /*
193637 ** Implementation of xOpen method.
193638 */
193639 static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
193640  Fts5Table *pTab = (Fts5Table*)pVTab;
193641  Fts5Config *pConfig = pTab->pConfig;
193642  Fts5Cursor *pCsr = 0; /* New cursor object */
193643  int nByte; /* Bytes of space to allocate */
193644  int rc; /* Return code */
193645 
193646  rc = fts5NewTransaction(pTab);
193647  if( rc==SQLITE_OK ){
193648  nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
193649  pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
193650  if( pCsr ){
193651  Fts5Global *pGlobal = pTab->pGlobal;
193652  memset(pCsr, 0, nByte);
193653  pCsr->aColumnSize = (int*)&pCsr[1];
193654  pCsr->pNext = pGlobal->pCsr;
193655  pGlobal->pCsr = pCsr;
193656  pCsr->iCsrId = ++pGlobal->iNextId;
193657  }else{
193658  rc = SQLITE_NOMEM;
193659  }
193660  }
193661  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
193662  return rc;
193663 }
193664 
193665 static int fts5StmtType(Fts5Cursor *pCsr){
193666  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
193667  return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
193668  }
193669  return FTS5_STMT_LOOKUP;
193670 }
193671 
193672 /*
193673 ** This function is called after the cursor passed as the only argument
193674 ** is moved to point at a different row. It clears all cached data
193675 ** specific to the previous row stored by the cursor object.
193676 */
193677 static void fts5CsrNewrow(Fts5Cursor *pCsr){
193678  CsrFlagSet(pCsr,
193679  FTS5CSR_REQUIRE_CONTENT
193680  | FTS5CSR_REQUIRE_DOCSIZE
193681  | FTS5CSR_REQUIRE_INST
193682  | FTS5CSR_REQUIRE_POSLIST
193683  );
193684 }
193685 
193686 static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
193687  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193688  Fts5Auxdata *pData;
193689  Fts5Auxdata *pNext;
193690 
193691  sqlite3_free(pCsr->aInstIter);
193692  sqlite3_free(pCsr->aInst);
193693  if( pCsr->pStmt ){
193694  int eStmt = fts5StmtType(pCsr);
193695  sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
193696  }
193697  if( pCsr->pSorter ){
193698  Fts5Sorter *pSorter = pCsr->pSorter;
193699  sqlite3_finalize(pSorter->pStmt);
193700  sqlite3_free(pSorter);
193701  }
193702 
193703  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
193704  sqlite3Fts5ExprFree(pCsr->pExpr);
193705  }
193706 
193707  for(pData=pCsr->pAuxdata; pData; pData=pNext){
193708  pNext = pData->pNext;
193709  if( pData->xDelete ) pData->xDelete(pData->pPtr);
193710  sqlite3_free(pData);
193711  }
193712 
193713  sqlite3_finalize(pCsr->pRankArgStmt);
193714  sqlite3_free(pCsr->apRankArg);
193715 
193716  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
193717  sqlite3_free(pCsr->zRank);
193718  sqlite3_free(pCsr->zRankArgs);
193719  }
193720 
193721  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
193722 }
193723 
193724 
193725 /*
193726 ** Close the cursor. For additional information see the documentation
193727 ** on the xClose method of the virtual table interface.
193728 */
193729 static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
193730  if( pCursor ){
193731  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
193732  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
193733  Fts5Cursor **pp;
193734 
193735  fts5FreeCursorComponents(pCsr);
193736  /* Remove the cursor from the Fts5Global.pCsr list */
193737  for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
193738  *pp = pCsr->pNext;
193739 
193740  sqlite3_free(pCsr);
193741  }
193742  return SQLITE_OK;
193743 }
193744 
193745 static int fts5SorterNext(Fts5Cursor *pCsr){
193746  Fts5Sorter *pSorter = pCsr->pSorter;
193747  int rc;
193748 
193749  rc = sqlite3_step(pSorter->pStmt);
193750  if( rc==SQLITE_DONE ){
193751  rc = SQLITE_OK;
193752  CsrFlagSet(pCsr, FTS5CSR_EOF);
193753  }else if( rc==SQLITE_ROW ){
193754  const u8 *a;
193755  const u8 *aBlob;
193756  int nBlob;
193757  int i;
193758  int iOff = 0;
193759  rc = SQLITE_OK;
193760 
193761  pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
193762  nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
193763  aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
193764 
193765  /* nBlob==0 in detail=none mode. */
193766  if( nBlob>0 ){
193767  for(i=0; i<(pSorter->nIdx-1); i++){
193768  int iVal;
193769  a += fts5GetVarint32(a, iVal);
193770  iOff += iVal;
193771  pSorter->aIdx[i] = iOff;
193772  }
193773  pSorter->aIdx[i] = &aBlob[nBlob] - a;
193774  pSorter->aPoslist = a;
193775  }
193776 
193777  fts5CsrNewrow(pCsr);
193778  }
193779 
193780  return rc;
193781 }
193782 
193783 
193784 /*
193785 ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
193786 ** open on table pTab.
193787 */
193788 static void fts5TripCursors(Fts5Table *pTab){
193789  Fts5Cursor *pCsr;
193790  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
193791  if( pCsr->ePlan==FTS5_PLAN_MATCH
193792  && pCsr->base.pVtab==(sqlite3_vtab*)pTab
193793  ){
193794  CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
193795  }
193796  }
193797 }
193798 
193799 /*
193800 ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
193801 ** argument, close and reopen all Fts5IndexIter iterators that the cursor
193802 ** is using. Then attempt to move the cursor to a rowid equal to or laster
193803 ** (in the cursors sort order - ASC or DESC) than the current rowid.
193804 **
193805 ** If the new rowid is not equal to the old, set output parameter *pbSkip
193806 ** to 1 before returning. Otherwise, leave it unchanged.
193807 **
193808 ** Return SQLITE_OK if successful or if no reseek was required, or an
193809 ** error code if an error occurred.
193810 */
193811 static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
193812  int rc = SQLITE_OK;
193813  assert( *pbSkip==0 );
193814  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
193815  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193816  int bDesc = pCsr->bDesc;
193817  i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
193818 
193819  rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
193820  if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
193821  *pbSkip = 1;
193822  }
193823 
193824  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
193825  fts5CsrNewrow(pCsr);
193826  if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
193827  CsrFlagSet(pCsr, FTS5CSR_EOF);
193828  *pbSkip = 1;
193829  }
193830  }
193831  return rc;
193832 }
193833 
193834 
193835 /*
193836 ** Advance the cursor to the next row in the table that matches the
193837 ** search criteria.
193838 **
193839 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
193840 ** even if we reach end-of-file. The fts5EofMethod() will be called
193841 ** subsequently to determine whether or not an EOF was hit.
193842 */
193843 static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
193844  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
193845  int rc;
193846 
193847  assert( (pCsr->ePlan<3)==
193848  (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
193849  );
193850  assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
193851 
193852  if( pCsr->ePlan<3 ){
193853  int bSkip = 0;
193854  if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
193855  rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
193856  CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
193857  fts5CsrNewrow(pCsr);
193858  }else{
193859  switch( pCsr->ePlan ){
193860  case FTS5_PLAN_SPECIAL: {
193861  CsrFlagSet(pCsr, FTS5CSR_EOF);
193862  rc = SQLITE_OK;
193863  break;
193864  }
193865 
193866  case FTS5_PLAN_SORTED_MATCH: {
193867  rc = fts5SorterNext(pCsr);
193868  break;
193869  }
193870 
193871  default:
193872  rc = sqlite3_step(pCsr->pStmt);
193873  if( rc!=SQLITE_ROW ){
193874  CsrFlagSet(pCsr, FTS5CSR_EOF);
193875  rc = sqlite3_reset(pCsr->pStmt);
193876  }else{
193877  rc = SQLITE_OK;
193878  }
193879  break;
193880  }
193881  }
193882 
193883  return rc;
193884 }
193885 
193886 
193887 static int fts5PrepareStatement(
193888  sqlite3_stmt **ppStmt,
193889  Fts5Config *pConfig,
193890  const char *zFmt,
193891  ...
193892 ){
193893  sqlite3_stmt *pRet = 0;
193894  int rc;
193895  char *zSql;
193896  va_list ap;
193897 
193898  va_start(ap, zFmt);
193899  zSql = sqlite3_vmprintf(zFmt, ap);
193900  if( zSql==0 ){
193901  rc = SQLITE_NOMEM;
193902  }else{
193903  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
193904  if( rc!=SQLITE_OK ){
193905  *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
193906  }
193907  sqlite3_free(zSql);
193908  }
193909 
193910  va_end(ap);
193911  *ppStmt = pRet;
193912  return rc;
193913 }
193914 
193915 static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
193916  Fts5Config *pConfig = pTab->pConfig;
193917  Fts5Sorter *pSorter;
193918  int nPhrase;
193919  int nByte;
193920  int rc;
193921  const char *zRank = pCsr->zRank;
193922  const char *zRankArgs = pCsr->zRankArgs;
193923 
193924  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193925  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
193926  pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
193927  if( pSorter==0 ) return SQLITE_NOMEM;
193928  memset(pSorter, 0, nByte);
193929  pSorter->nIdx = nPhrase;
193930 
193931  /* TODO: It would be better to have some system for reusing statement
193932  ** handles here, rather than preparing a new one for each query. But that
193933  ** is not possible as SQLite reference counts the virtual table objects.
193934  ** And since the statement required here reads from this very virtual
193935  ** table, saving it creates a circular reference.
193936  **
193937  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
193938  rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
193939  "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
193940  pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
193941  (zRankArgs ? ", " : ""),
193942  (zRankArgs ? zRankArgs : ""),
193943  bDesc ? "DESC" : "ASC"
193944  );
193945 
193946  pCsr->pSorter = pSorter;
193947  if( rc==SQLITE_OK ){
193948  assert( pTab->pSortCsr==0 );
193949  pTab->pSortCsr = pCsr;
193950  rc = fts5SorterNext(pCsr);
193951  pTab->pSortCsr = 0;
193952  }
193953 
193954  if( rc!=SQLITE_OK ){
193955  sqlite3_finalize(pSorter->pStmt);
193956  sqlite3_free(pSorter);
193957  pCsr->pSorter = 0;
193958  }
193959 
193960  return rc;
193961 }
193962 
193963 static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
193964  int rc;
193965  Fts5Expr *pExpr = pCsr->pExpr;
193966  rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
193967  if( sqlite3Fts5ExprEof(pExpr) ){
193968  CsrFlagSet(pCsr, FTS5CSR_EOF);
193969  }
193970  fts5CsrNewrow(pCsr);
193971  return rc;
193972 }
193973 
193974 /*
193975 ** Process a "special" query. A special query is identified as one with a
193976 ** MATCH expression that begins with a '*' character. The remainder of
193977 ** the text passed to the MATCH operator are used as the special query
193978 ** parameters.
193979 */
193980 static int fts5SpecialMatch(
193981  Fts5Table *pTab,
193982  Fts5Cursor *pCsr,
193983  const char *zQuery
193984 ){
193985  int rc = SQLITE_OK; /* Return code */
193986  const char *z = zQuery; /* Special query text */
193987  int n; /* Number of bytes in text at z */
193988 
193989  while( z[0]==' ' ) z++;
193990  for(n=0; z[n] && z[n]!=' '; n++);
193991 
193992  assert( pTab->base.zErrMsg==0 );
193993  pCsr->ePlan = FTS5_PLAN_SPECIAL;
193994 
193995  if( 0==sqlite3_strnicmp("reads", z, n) ){
193996  pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
193997  }
193998  else if( 0==sqlite3_strnicmp("id", z, n) ){
193999  pCsr->iSpecial = pCsr->iCsrId;
194000  }
194001  else{
194002  /* An unrecognized directive. Return an error message. */
194003  pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
194004  rc = SQLITE_ERROR;
194005  }
194006 
194007  return rc;
194008 }
194009 
194010 /*
194011 ** Search for an auxiliary function named zName that can be used with table
194012 ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
194013 ** structure. Otherwise, if no such function exists, return NULL.
194014 */
194015 static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
194016  Fts5Auxiliary *pAux;
194017 
194018  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
194019  if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
194020  }
194021 
194022  /* No function of the specified name was found. Return 0. */
194023  return 0;
194024 }
194025 
194026 
194027 static int fts5FindRankFunction(Fts5Cursor *pCsr){
194028  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194029  Fts5Config *pConfig = pTab->pConfig;
194030  int rc = SQLITE_OK;
194031  Fts5Auxiliary *pAux = 0;
194032  const char *zRank = pCsr->zRank;
194033  const char *zRankArgs = pCsr->zRankArgs;
194034 
194035  if( zRankArgs ){
194036  char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
194037  if( zSql ){
194038  sqlite3_stmt *pStmt = 0;
194039  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
194040  sqlite3_free(zSql);
194041  assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
194042  if( rc==SQLITE_OK ){
194043  if( SQLITE_ROW==sqlite3_step(pStmt) ){
194044  int nByte;
194045  pCsr->nRankArg = sqlite3_column_count(pStmt);
194046  nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
194047  pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
194048  if( rc==SQLITE_OK ){
194049  int i;
194050  for(i=0; i<pCsr->nRankArg; i++){
194051  pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
194052  }
194053  }
194054  pCsr->pRankArgStmt = pStmt;
194055  }else{
194056  rc = sqlite3_finalize(pStmt);
194057  assert( rc!=SQLITE_OK );
194058  }
194059  }
194060  }
194061  }
194062 
194063  if( rc==SQLITE_OK ){
194064  pAux = fts5FindAuxiliary(pTab, zRank);
194065  if( pAux==0 ){
194066  assert( pTab->base.zErrMsg==0 );
194067  pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
194068  rc = SQLITE_ERROR;
194069  }
194070  }
194071 
194072  pCsr->pRank = pAux;
194073  return rc;
194074 }
194075 
194076 
194077 static int fts5CursorParseRank(
194078  Fts5Config *pConfig,
194079  Fts5Cursor *pCsr,
194080  sqlite3_value *pRank
194081 ){
194082  int rc = SQLITE_OK;
194083  if( pRank ){
194084  const char *z = (const char*)sqlite3_value_text(pRank);
194085  char *zRank = 0;
194086  char *zRankArgs = 0;
194087 
194088  if( z==0 ){
194089  if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
194090  }else{
194091  rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
194092  }
194093  if( rc==SQLITE_OK ){
194094  pCsr->zRank = zRank;
194095  pCsr->zRankArgs = zRankArgs;
194096  CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
194097  }else if( rc==SQLITE_ERROR ){
194098  pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
194099  "parse error in rank function: %s", z
194100  );
194101  }
194102  }else{
194103  if( pConfig->zRank ){
194104  pCsr->zRank = (char*)pConfig->zRank;
194105  pCsr->zRankArgs = (char*)pConfig->zRankArgs;
194106  }else{
194107  pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
194108  pCsr->zRankArgs = 0;
194109  }
194110  }
194111  return rc;
194112 }
194113 
194114 static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
194115  if( pVal ){
194116  int eType = sqlite3_value_numeric_type(pVal);
194117  if( eType==SQLITE_INTEGER ){
194118  return sqlite3_value_int64(pVal);
194119  }
194120  }
194121  return iDefault;
194122 }
194123 
194124 /*
194125 ** This is the xFilter interface for the virtual table. See
194126 ** the virtual table xFilter method documentation for additional
194127 ** information.
194128 **
194129 ** There are three possible query strategies:
194130 **
194131 ** 1. Full-text search using a MATCH operator.
194132 ** 2. A by-rowid lookup.
194133 ** 3. A full-table scan.
194134 */
194135 static int fts5FilterMethod(
194136  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
194137  int idxNum, /* Strategy index */
194138  const char *zUnused, /* Unused */
194139  int nVal, /* Number of elements in apVal */
194140  sqlite3_value **apVal /* Arguments for the indexing scheme */
194141 ){
194142  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
194143  Fts5Config *pConfig = pTab->pConfig;
194144  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
194145  int rc = SQLITE_OK; /* Error code */
194146  int iVal = 0; /* Counter for apVal[] */
194147  int bDesc; /* True if ORDER BY [rank|rowid] DESC */
194148  int bOrderByRank; /* True if ORDER BY rank */
194149  sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
194150  sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
194151  sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
194152  sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
194153  sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
194154  char **pzErrmsg = pConfig->pzErrmsg;
194155 
194156  UNUSED_PARAM(zUnused);
194157  UNUSED_PARAM(nVal);
194158 
194159  if( pCsr->ePlan ){
194160  fts5FreeCursorComponents(pCsr);
194161  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
194162  }
194163 
194164  assert( pCsr->pStmt==0 );
194165  assert( pCsr->pExpr==0 );
194166  assert( pCsr->csrflags==0 );
194167  assert( pCsr->pRank==0 );
194168  assert( pCsr->zRank==0 );
194169  assert( pCsr->zRankArgs==0 );
194170 
194171  assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
194172  pConfig->pzErrmsg = &pTab->base.zErrMsg;
194173 
194174  /* Decode the arguments passed through to this function.
194175  **
194176  ** Note: The following set of if(...) statements must be in the same
194177  ** order as the corresponding entries in the struct at the top of
194178  ** fts5BestIndexMethod(). */
194179  if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
194180  if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
194181  if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
194182  if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
194183  if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
194184  assert( iVal==nVal );
194185  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
194186  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
194187 
194188  /* Set the cursor upper and lower rowid limits. Only some strategies
194189  ** actually use them. This is ok, as the xBestIndex() method leaves the
194190  ** sqlite3_index_constraint.omit flag clear for range constraints
194191  ** on the rowid field. */
194192  if( pRowidEq ){
194193  pRowidLe = pRowidGe = pRowidEq;
194194  }
194195  if( bDesc ){
194196  pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
194197  pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
194198  }else{
194199  pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
194200  pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
194201  }
194202 
194203  if( pTab->pSortCsr ){
194204  /* If pSortCsr is non-NULL, then this call is being made as part of
194205  ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
194206  ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
194207  ** return results to the user for this query. The current cursor
194208  ** (pCursor) is used to execute the query issued by function
194209  ** fts5CursorFirstSorted() above. */
194210  assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
194211  assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
194212  assert( pCsr->iLastRowid==LARGEST_INT64 );
194213  assert( pCsr->iFirstRowid==SMALLEST_INT64 );
194214  pCsr->ePlan = FTS5_PLAN_SOURCE;
194215  pCsr->pExpr = pTab->pSortCsr->pExpr;
194216  rc = fts5CursorFirst(pTab, pCsr, bDesc);
194217  }else if( pMatch ){
194218  const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
194219  if( zExpr==0 ) zExpr = "";
194220 
194221  rc = fts5CursorParseRank(pConfig, pCsr, pRank);
194222  if( rc==SQLITE_OK ){
194223  if( zExpr[0]=='*' ){
194224  /* The user has issued a query of the form "MATCH '*...'". This
194225  ** indicates that the MATCH expression is not a full text query,
194226  ** but a request for an internal parameter. */
194227  rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
194228  }else{
194229  char **pzErr = &pTab->base.zErrMsg;
194230  rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
194231  if( rc==SQLITE_OK ){
194232  if( bOrderByRank ){
194233  pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
194234  rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
194235  }else{
194236  pCsr->ePlan = FTS5_PLAN_MATCH;
194237  rc = fts5CursorFirst(pTab, pCsr, bDesc);
194238  }
194239  }
194240  }
194241  }
194242  }else if( pConfig->zContent==0 ){
194243  *pConfig->pzErrmsg = sqlite3_mprintf(
194244  "%s: table does not support scanning", pConfig->zName
194245  );
194246  rc = SQLITE_ERROR;
194247  }else{
194248  /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
194249  ** by rowid (ePlan==FTS5_PLAN_ROWID). */
194250  pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
194251  rc = sqlite3Fts5StorageStmt(
194252  pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
194253  );
194254  if( rc==SQLITE_OK ){
194255  if( pCsr->ePlan==FTS5_PLAN_ROWID ){
194256  sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
194257  }else{
194258  sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
194259  sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
194260  }
194261  rc = fts5NextMethod(pCursor);
194262  }
194263  }
194264 
194265  pConfig->pzErrmsg = pzErrmsg;
194266  return rc;
194267 }
194268 
194269 /*
194270 ** This is the xEof method of the virtual table. SQLite calls this
194271 ** routine to find out if it has reached the end of a result set.
194272 */
194273 static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
194274  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
194275  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
194276 }
194277 
194278 /*
194279 ** Return the rowid that the cursor currently points to.
194280 */
194281 static i64 fts5CursorRowid(Fts5Cursor *pCsr){
194282  assert( pCsr->ePlan==FTS5_PLAN_MATCH
194283  || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
194284  || pCsr->ePlan==FTS5_PLAN_SOURCE
194285  );
194286  if( pCsr->pSorter ){
194287  return pCsr->pSorter->iRowid;
194288  }else{
194289  return sqlite3Fts5ExprRowid(pCsr->pExpr);
194290  }
194291 }
194292 
194293 /*
194294 ** This is the xRowid method. The SQLite core calls this routine to
194295 ** retrieve the rowid for the current row of the result set. fts5
194296 ** exposes %_content.rowid as the rowid for the virtual table. The
194297 ** rowid should be written to *pRowid.
194298 */
194299 static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
194300  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
194301  int ePlan = pCsr->ePlan;
194302 
194303  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
194304  switch( ePlan ){
194305  case FTS5_PLAN_SPECIAL:
194306  *pRowid = 0;
194307  break;
194308 
194309  case FTS5_PLAN_SOURCE:
194310  case FTS5_PLAN_MATCH:
194311  case FTS5_PLAN_SORTED_MATCH:
194312  *pRowid = fts5CursorRowid(pCsr);
194313  break;
194314 
194315  default:
194316  *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
194317  break;
194318  }
194319 
194320  return SQLITE_OK;
194321 }
194322 
194323 /*
194324 ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
194325 ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
194326 **
194327 ** If argument bErrormsg is true and an error occurs, an error message may
194328 ** be left in sqlite3_vtab.zErrMsg.
194329 */
194330 static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
194331  int rc = SQLITE_OK;
194332 
194333  /* If the cursor does not yet have a statement handle, obtain one now. */
194334  if( pCsr->pStmt==0 ){
194335  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194336  int eStmt = fts5StmtType(pCsr);
194337  rc = sqlite3Fts5StorageStmt(
194338  pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
194339  );
194340  assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
194341  assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
194342  }
194343 
194344  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
194345  assert( pCsr->pExpr );
194346  sqlite3_reset(pCsr->pStmt);
194347  sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
194348  rc = sqlite3_step(pCsr->pStmt);
194349  if( rc==SQLITE_ROW ){
194350  rc = SQLITE_OK;
194351  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
194352  }else{
194353  rc = sqlite3_reset(pCsr->pStmt);
194354  if( rc==SQLITE_OK ){
194355  rc = FTS5_CORRUPT;
194356  }
194357  }
194358  }
194359  return rc;
194360 }
194361 
194362 static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
194363  va_list ap; /* ... printf arguments */
194364  va_start(ap, zFormat);
194365  assert( p->base.zErrMsg==0 );
194366  p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
194367  va_end(ap);
194368 }
194369 
194370 /*
194371 ** This function is called to handle an FTS INSERT command. In other words,
194372 ** an INSERT statement of the form:
194373 **
194374 ** INSERT INTO fts(fts) VALUES($pCmd)
194375 ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
194376 **
194377 ** Argument pVal is the value assigned to column "fts" by the INSERT
194378 ** statement. This function returns SQLITE_OK if successful, or an SQLite
194379 ** error code if an error occurs.
194380 **
194381 ** The commands implemented by this function are documented in the "Special
194382 ** INSERT Directives" section of the documentation. It should be updated if
194383 ** more commands are added to this function.
194384 */
194385 static int fts5SpecialInsert(
194386  Fts5Table *pTab, /* Fts5 table object */
194387  const char *zCmd, /* Text inserted into table-name column */
194388  sqlite3_value *pVal /* Value inserted into rank column */
194389 ){
194390  Fts5Config *pConfig = pTab->pConfig;
194391  int rc = SQLITE_OK;
194392  int bError = 0;
194393 
194394  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
194395  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194396  fts5SetVtabError(pTab,
194397  "'delete-all' may only be used with a "
194398  "contentless or external content fts5 table"
194399  );
194400  rc = SQLITE_ERROR;
194401  }else{
194402  rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
194403  }
194404  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
194405  if( pConfig->eContent==FTS5_CONTENT_NONE ){
194406  fts5SetVtabError(pTab,
194407  "'rebuild' may not be used with a contentless fts5 table"
194408  );
194409  rc = SQLITE_ERROR;
194410  }else{
194411  rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
194412  }
194413  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
194414  rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
194415  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
194416  int nMerge = sqlite3_value_int(pVal);
194417  rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
194418  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
194419  rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
194420 #ifdef SQLITE_DEBUG
194421  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
194422  pConfig->bPrefixIndex = sqlite3_value_int(pVal);
194423 #endif
194424  }else{
194425  rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
194426  if( rc==SQLITE_OK ){
194427  rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
194428  }
194429  if( rc==SQLITE_OK ){
194430  if( bError ){
194431  rc = SQLITE_ERROR;
194432  }else{
194433  rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
194434  }
194435  }
194436  }
194437  return rc;
194438 }
194439 
194440 static int fts5SpecialDelete(
194441  Fts5Table *pTab,
194442  sqlite3_value **apVal
194443 ){
194444  int rc = SQLITE_OK;
194445  int eType1 = sqlite3_value_type(apVal[1]);
194446  if( eType1==SQLITE_INTEGER ){
194447  sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
194448  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
194449  }
194450  return rc;
194451 }
194452 
194453 static void fts5StorageInsert(
194454  int *pRc,
194455  Fts5Table *pTab,
194456  sqlite3_value **apVal,
194457  i64 *piRowid
194458 ){
194459  int rc = *pRc;
194460  if( rc==SQLITE_OK ){
194461  rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
194462  }
194463  if( rc==SQLITE_OK ){
194464  rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
194465  }
194466  *pRc = rc;
194467 }
194468 
194469 /*
194470 ** This function is the implementation of the xUpdate callback used by
194471 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
194472 ** inserted, updated or deleted.
194473 **
194474 ** A delete specifies a single argument - the rowid of the row to remove.
194475 **
194476 ** Update and insert operations pass:
194477 **
194478 ** 1. The "old" rowid, or NULL.
194479 ** 2. The "new" rowid.
194480 ** 3. Values for each of the nCol matchable columns.
194481 ** 4. Values for the two hidden columns (<tablename> and "rank").
194482 */
194483 static int fts5UpdateMethod(
194484  sqlite3_vtab *pVtab, /* Virtual table handle */
194485  int nArg, /* Size of argument array */
194486  sqlite3_value **apVal, /* Array of arguments */
194487  sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
194488 ){
194489  Fts5Table *pTab = (Fts5Table*)pVtab;
194490  Fts5Config *pConfig = pTab->pConfig;
194491  int eType0; /* value_type() of apVal[0] */
194492  int rc = SQLITE_OK; /* Return code */
194493 
194494  /* A transaction must be open when this is called. */
194495  assert( pTab->ts.eState==1 );
194496 
194497  assert( pVtab->zErrMsg==0 );
194498  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
194499  assert( nArg==1
194500  || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
194501  || sqlite3_value_type(apVal[1])==SQLITE_NULL
194502  );
194503  assert( pTab->pConfig->pzErrmsg==0 );
194504  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
194505 
194506  /* Put any active cursors into REQUIRE_SEEK state. */
194507  fts5TripCursors(pTab);
194508 
194509  eType0 = sqlite3_value_type(apVal[0]);
194510  if( eType0==SQLITE_NULL
194511  && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
194512  ){
194513  /* A "special" INSERT op. These are handled separately. */
194514  const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
194515  if( pConfig->eContent!=FTS5_CONTENT_NORMAL
194516  && 0==sqlite3_stricmp("delete", z)
194517  ){
194518  rc = fts5SpecialDelete(pTab, apVal);
194519  }else{
194520  rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
194521  }
194522  }else{
194523  /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
194524  ** any conflict on the rowid value must be detected before any
194525  ** modifications are made to the database file. There are 4 cases:
194526  **
194527  ** 1) DELETE
194528  ** 2) UPDATE (rowid not modified)
194529  ** 3) UPDATE (rowid modified)
194530  ** 4) INSERT
194531  **
194532  ** Cases 3 and 4 may violate the rowid constraint.
194533  */
194534  int eConflict = SQLITE_ABORT;
194535  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194536  eConflict = sqlite3_vtab_on_conflict(pConfig->db);
194537  }
194538 
194539  assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
194540  assert( nArg!=1 || eType0==SQLITE_INTEGER );
194541 
194542  /* Filter out attempts to run UPDATE or DELETE on contentless tables.
194543  ** This is not suported. */
194544  if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
194545  pTab->base.zErrMsg = sqlite3_mprintf(
194546  "cannot %s contentless fts5 table: %s",
194547  (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
194548  );
194549  rc = SQLITE_ERROR;
194550  }
194551 
194552  /* DELETE */
194553  else if( nArg==1 ){
194554  i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
194555  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
194556  }
194557 
194558  /* INSERT */
194559  else if( eType0!=SQLITE_INTEGER ){
194560  /* If this is a REPLACE, first remove the current entry (if any) */
194561  if( eConflict==SQLITE_REPLACE
194562  && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
194563  ){
194564  i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
194565  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
194566  }
194567  fts5StorageInsert(&rc, pTab, apVal, pRowid);
194568  }
194569 
194570  /* UPDATE */
194571  else{
194572  i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
194573  i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
194574  if( iOld!=iNew ){
194575  if( eConflict==SQLITE_REPLACE ){
194576  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
194577  if( rc==SQLITE_OK ){
194578  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
194579  }
194580  fts5StorageInsert(&rc, pTab, apVal, pRowid);
194581  }else{
194582  rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
194583  if( rc==SQLITE_OK ){
194584  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
194585  }
194586  if( rc==SQLITE_OK ){
194587  rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
194588  }
194589  }
194590  }else{
194591  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
194592  fts5StorageInsert(&rc, pTab, apVal, pRowid);
194593  }
194594  }
194595  }
194596 
194597  pTab->pConfig->pzErrmsg = 0;
194598  return rc;
194599 }
194600 
194601 /*
194602 ** Implementation of xSync() method.
194603 */
194604 static int fts5SyncMethod(sqlite3_vtab *pVtab){
194605  int rc;
194606  Fts5Table *pTab = (Fts5Table*)pVtab;
194607  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
194608  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
194609  fts5TripCursors(pTab);
194610  rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
194611  pTab->pConfig->pzErrmsg = 0;
194612  return rc;
194613 }
194614 
194615 /*
194616 ** Implementation of xBegin() method.
194617 */
194618 static int fts5BeginMethod(sqlite3_vtab *pVtab){
194619  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
194620  fts5NewTransaction((Fts5Table*)pVtab);
194621  return SQLITE_OK;
194622 }
194623 
194624 /*
194625 ** Implementation of xCommit() method. This is a no-op. The contents of
194626 ** the pending-terms hash-table have already been flushed into the database
194627 ** by fts5SyncMethod().
194628 */
194629 static int fts5CommitMethod(sqlite3_vtab *pVtab){
194630  UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
194631  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
194632  return SQLITE_OK;
194633 }
194634 
194635 /*
194636 ** Implementation of xRollback(). Discard the contents of the pending-terms
194637 ** hash-table. Any changes made to the database are reverted by SQLite.
194638 */
194639 static int fts5RollbackMethod(sqlite3_vtab *pVtab){
194640  int rc;
194641  Fts5Table *pTab = (Fts5Table*)pVtab;
194642  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
194643  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
194644  return rc;
194645 }
194646 
194647 static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
194648 
194649 static void *fts5ApiUserData(Fts5Context *pCtx){
194650  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194651  return pCsr->pAux->pUserData;
194652 }
194653 
194654 static int fts5ApiColumnCount(Fts5Context *pCtx){
194655  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194656  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
194657 }
194658 
194659 static int fts5ApiColumnTotalSize(
194660  Fts5Context *pCtx,
194661  int iCol,
194662  sqlite3_int64 *pnToken
194663 ){
194664  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194665  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194666  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
194667 }
194668 
194669 static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
194670  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194671  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194672  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
194673 }
194674 
194675 static int fts5ApiTokenize(
194676  Fts5Context *pCtx,
194677  const char *pText, int nText,
194678  void *pUserData,
194679  int (*xToken)(void*, int, const char*, int, int, int)
194680 ){
194681  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194682  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194683  return sqlite3Fts5Tokenize(
194684  pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
194685  );
194686 }
194687 
194688 static int fts5ApiPhraseCount(Fts5Context *pCtx){
194689  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194690  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
194691 }
194692 
194693 static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
194694  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194695  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
194696 }
194697 
194698 static int fts5ApiColumnText(
194699  Fts5Context *pCtx,
194700  int iCol,
194701  const char **pz,
194702  int *pn
194703 ){
194704  int rc = SQLITE_OK;
194705  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194706  if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
194707  *pz = 0;
194708  *pn = 0;
194709  }else{
194710  rc = fts5SeekCursor(pCsr, 0);
194711  if( rc==SQLITE_OK ){
194712  *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
194713  *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
194714  }
194715  }
194716  return rc;
194717 }
194718 
194719 static int fts5CsrPoslist(
194720  Fts5Cursor *pCsr,
194721  int iPhrase,
194722  const u8 **pa,
194723  int *pn
194724 ){
194725  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
194726  int rc = SQLITE_OK;
194727  int bLive = (pCsr->pSorter==0);
194728 
194729  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
194730 
194731  if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
194732  Fts5PoslistPopulator *aPopulator;
194733  int i;
194734  aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
194735  if( aPopulator==0 ) rc = SQLITE_NOMEM;
194736  for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
194737  int n; const char *z;
194738  rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
194739  if( rc==SQLITE_OK ){
194740  rc = sqlite3Fts5ExprPopulatePoslists(
194741  pConfig, pCsr->pExpr, aPopulator, i, z, n
194742  );
194743  }
194744  }
194745  sqlite3_free(aPopulator);
194746 
194747  if( pCsr->pSorter ){
194748  sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
194749  }
194750  }
194751  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
194752  }
194753 
194754  if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
194755  Fts5Sorter *pSorter = pCsr->pSorter;
194756  int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
194757  *pn = pSorter->aIdx[iPhrase] - i1;
194758  *pa = &pSorter->aPoslist[i1];
194759  }else{
194760  *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
194761  }
194762 
194763  return rc;
194764 }
194765 
194766 /*
194767 ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
194768 ** correctly for the current view. Return SQLITE_OK if successful, or an
194769 ** SQLite error code otherwise.
194770 */
194771 static int fts5CacheInstArray(Fts5Cursor *pCsr){
194772  int rc = SQLITE_OK;
194773  Fts5PoslistReader *aIter; /* One iterator for each phrase */
194774  int nIter; /* Number of iterators/phrases */
194775 
194776  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
194777  if( pCsr->aInstIter==0 ){
194778  int nByte = sizeof(Fts5PoslistReader) * nIter;
194779  pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
194780  }
194781  aIter = pCsr->aInstIter;
194782 
194783  if( aIter ){
194784  int nInst = 0; /* Number instances seen so far */
194785  int i;
194786 
194787  /* Initialize all iterators */
194788  for(i=0; i<nIter && rc==SQLITE_OK; i++){
194789  const u8 *a;
194790  int n;
194791  rc = fts5CsrPoslist(pCsr, i, &a, &n);
194792  if( rc==SQLITE_OK ){
194793  sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
194794  }
194795  }
194796 
194797  if( rc==SQLITE_OK ){
194798  while( 1 ){
194799  int *aInst;
194800  int iBest = -1;
194801  for(i=0; i<nIter; i++){
194802  if( (aIter[i].bEof==0)
194803  && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
194804  ){
194805  iBest = i;
194806  }
194807  }
194808  if( iBest<0 ) break;
194809 
194810  nInst++;
194811  if( nInst>=pCsr->nInstAlloc ){
194812  pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
194813  aInst = (int*)sqlite3_realloc(
194814  pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
194815  );
194816  if( aInst ){
194817  pCsr->aInst = aInst;
194818  }else{
194819  rc = SQLITE_NOMEM;
194820  break;
194821  }
194822  }
194823 
194824  aInst = &pCsr->aInst[3 * (nInst-1)];
194825  aInst[0] = iBest;
194826  aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
194827  aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
194828  sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
194829  }
194830  }
194831 
194832  pCsr->nInstCount = nInst;
194833  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
194834  }
194835  return rc;
194836 }
194837 
194838 static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
194839  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194840  int rc = SQLITE_OK;
194841  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
194842  || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
194843  *pnInst = pCsr->nInstCount;
194844  }
194845  return rc;
194846 }
194847 
194848 static int fts5ApiInst(
194849  Fts5Context *pCtx,
194850  int iIdx,
194851  int *piPhrase,
194852  int *piCol,
194853  int *piOff
194854 ){
194855  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194856  int rc = SQLITE_OK;
194857  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
194858  || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
194859  ){
194860  if( iIdx<0 || iIdx>=pCsr->nInstCount ){
194861  rc = SQLITE_RANGE;
194862 #if 0
194863  }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
194864  *piPhrase = pCsr->aInst[iIdx*3];
194865  *piCol = pCsr->aInst[iIdx*3 + 2];
194866  *piOff = -1;
194867 #endif
194868  }else{
194869  *piPhrase = pCsr->aInst[iIdx*3];
194870  *piCol = pCsr->aInst[iIdx*3 + 1];
194871  *piOff = pCsr->aInst[iIdx*3 + 2];
194872  }
194873  }
194874  return rc;
194875 }
194876 
194877 static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
194878  return fts5CursorRowid((Fts5Cursor*)pCtx);
194879 }
194880 
194881 static int fts5ColumnSizeCb(
194882  void *pContext, /* Pointer to int */
194883  int tflags,
194884  const char *pUnused, /* Buffer containing token */
194885  int nUnused, /* Size of token in bytes */
194886  int iUnused1, /* Start offset of token */
194887  int iUnused2 /* End offset of token */
194888 ){
194889  int *pCnt = (int*)pContext;
194890  UNUSED_PARAM2(pUnused, nUnused);
194891  UNUSED_PARAM2(iUnused1, iUnused2);
194892  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
194893  (*pCnt)++;
194894  }
194895  return SQLITE_OK;
194896 }
194897 
194898 static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
194899  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194900  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194901  Fts5Config *pConfig = pTab->pConfig;
194902  int rc = SQLITE_OK;
194903 
194904  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
194905  if( pConfig->bColumnsize ){
194906  i64 iRowid = fts5CursorRowid(pCsr);
194907  rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
194908  }else if( pConfig->zContent==0 ){
194909  int i;
194910  for(i=0; i<pConfig->nCol; i++){
194911  if( pConfig->abUnindexed[i]==0 ){
194912  pCsr->aColumnSize[i] = -1;
194913  }
194914  }
194915  }else{
194916  int i;
194917  for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
194918  if( pConfig->abUnindexed[i]==0 ){
194919  const char *z; int n;
194920  void *p = (void*)(&pCsr->aColumnSize[i]);
194921  pCsr->aColumnSize[i] = 0;
194922  rc = fts5ApiColumnText(pCtx, i, &z, &n);
194923  if( rc==SQLITE_OK ){
194924  rc = sqlite3Fts5Tokenize(
194925  pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
194926  );
194927  }
194928  }
194929  }
194930  }
194931  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
194932  }
194933  if( iCol<0 ){
194934  int i;
194935  *pnToken = 0;
194936  for(i=0; i<pConfig->nCol; i++){
194937  *pnToken += pCsr->aColumnSize[i];
194938  }
194939  }else if( iCol<pConfig->nCol ){
194940  *pnToken = pCsr->aColumnSize[iCol];
194941  }else{
194942  *pnToken = 0;
194943  rc = SQLITE_RANGE;
194944  }
194945  return rc;
194946 }
194947 
194948 /*
194949 ** Implementation of the xSetAuxdata() method.
194950 */
194951 static int fts5ApiSetAuxdata(
194952  Fts5Context *pCtx, /* Fts5 context */
194953  void *pPtr, /* Pointer to save as auxdata */
194954  void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
194955 ){
194956  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194957  Fts5Auxdata *pData;
194958 
194959  /* Search through the cursors list of Fts5Auxdata objects for one that
194960  ** corresponds to the currently executing auxiliary function. */
194961  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
194962  if( pData->pAux==pCsr->pAux ) break;
194963  }
194964 
194965  if( pData ){
194966  if( pData->xDelete ){
194967  pData->xDelete(pData->pPtr);
194968  }
194969  }else{
194970  int rc = SQLITE_OK;
194971  pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
194972  if( pData==0 ){
194973  if( xDelete ) xDelete(pPtr);
194974  return rc;
194975  }
194976  pData->pAux = pCsr->pAux;
194977  pData->pNext = pCsr->pAuxdata;
194978  pCsr->pAuxdata = pData;
194979  }
194980 
194981  pData->xDelete = xDelete;
194982  pData->pPtr = pPtr;
194983  return SQLITE_OK;
194984 }
194985 
194986 static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
194987  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194988  Fts5Auxdata *pData;
194989  void *pRet = 0;
194990 
194991  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
194992  if( pData->pAux==pCsr->pAux ) break;
194993  }
194994 
194995  if( pData ){
194996  pRet = pData->pPtr;
194997  if( bClear ){
194998  pData->pPtr = 0;
194999  pData->xDelete = 0;
195000  }
195001  }
195002 
195003  return pRet;
195004 }
195005 
195006 static void fts5ApiPhraseNext(
195007  Fts5Context *pUnused,
195008  Fts5PhraseIter *pIter,
195009  int *piCol, int *piOff
195010 ){
195011  UNUSED_PARAM(pUnused);
195012  if( pIter->a>=pIter->b ){
195013  *piCol = -1;
195014  *piOff = -1;
195015  }else{
195016  int iVal;
195017  pIter->a += fts5GetVarint32(pIter->a, iVal);
195018  if( iVal==1 ){
195019  pIter->a += fts5GetVarint32(pIter->a, iVal);
195020  *piCol = iVal;
195021  *piOff = 0;
195022  pIter->a += fts5GetVarint32(pIter->a, iVal);
195023  }
195024  *piOff += (iVal-2);
195025  }
195026 }
195027 
195028 static int fts5ApiPhraseFirst(
195029  Fts5Context *pCtx,
195030  int iPhrase,
195031  Fts5PhraseIter *pIter,
195032  int *piCol, int *piOff
195033 ){
195034  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
195035  int n;
195036  int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
195037  if( rc==SQLITE_OK ){
195038  pIter->b = &pIter->a[n];
195039  *piCol = 0;
195040  *piOff = 0;
195041  fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
195042  }
195043  return rc;
195044 }
195045 
195046 static void fts5ApiPhraseNextColumn(
195047  Fts5Context *pCtx,
195048  Fts5PhraseIter *pIter,
195049  int *piCol
195050 ){
195051  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
195052  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
195053 
195054  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195055  if( pIter->a>=pIter->b ){
195056  *piCol = -1;
195057  }else{
195058  int iIncr;
195059  pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
195060  *piCol += (iIncr-2);
195061  }
195062  }else{
195063  while( 1 ){
195064  int dummy;
195065  if( pIter->a>=pIter->b ){
195066  *piCol = -1;
195067  return;
195068  }
195069  if( pIter->a[0]==0x01 ) break;
195070  pIter->a += fts5GetVarint32(pIter->a, dummy);
195071  }
195072  pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
195073  }
195074 }
195075 
195076 static int fts5ApiPhraseFirstColumn(
195077  Fts5Context *pCtx,
195078  int iPhrase,
195079  Fts5PhraseIter *pIter,
195080  int *piCol
195081 ){
195082  int rc = SQLITE_OK;
195083  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
195084  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
195085 
195086  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195087  Fts5Sorter *pSorter = pCsr->pSorter;
195088  int n;
195089  if( pSorter ){
195090  int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
195091  n = pSorter->aIdx[iPhrase] - i1;
195092  pIter->a = &pSorter->aPoslist[i1];
195093  }else{
195094  rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
195095  }
195096  if( rc==SQLITE_OK ){
195097  pIter->b = &pIter->a[n];
195098  *piCol = 0;
195099  fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
195100  }
195101  }else{
195102  int n;
195103  rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
195104  if( rc==SQLITE_OK ){
195105  pIter->b = &pIter->a[n];
195106  if( n<=0 ){
195107  *piCol = -1;
195108  }else if( pIter->a[0]==0x01 ){
195109  pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
195110  }else{
195111  *piCol = 0;
195112  }
195113  }
195114  }
195115 
195116  return rc;
195117 }
195118 
195119 
195120 static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
195121  int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
195122 );
195123 
195124 static const Fts5ExtensionApi sFts5Api = {
195125  2, /* iVersion */
195126  fts5ApiUserData,
195127  fts5ApiColumnCount,
195128  fts5ApiRowCount,
195129  fts5ApiColumnTotalSize,
195130  fts5ApiTokenize,
195131  fts5ApiPhraseCount,
195132  fts5ApiPhraseSize,
195133  fts5ApiInstCount,
195134  fts5ApiInst,
195135  fts5ApiRowid,
195136  fts5ApiColumnText,
195137  fts5ApiColumnSize,
195138  fts5ApiQueryPhrase,
195139  fts5ApiSetAuxdata,
195140  fts5ApiGetAuxdata,
195141  fts5ApiPhraseFirst,
195142  fts5ApiPhraseNext,
195143  fts5ApiPhraseFirstColumn,
195144  fts5ApiPhraseNextColumn,
195145 };
195146 
195147 /*
195148 ** Implementation of API function xQueryPhrase().
195149 */
195150 static int fts5ApiQueryPhrase(
195151  Fts5Context *pCtx,
195152  int iPhrase,
195153  void *pUserData,
195154  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
195155 ){
195156  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
195157  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
195158  int rc;
195159  Fts5Cursor *pNew = 0;
195160 
195161  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
195162  if( rc==SQLITE_OK ){
195163  pNew->ePlan = FTS5_PLAN_MATCH;
195164  pNew->iFirstRowid = SMALLEST_INT64;
195165  pNew->iLastRowid = LARGEST_INT64;
195166  pNew->base.pVtab = (sqlite3_vtab*)pTab;
195167  rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
195168  }
195169 
195170  if( rc==SQLITE_OK ){
195171  for(rc = fts5CursorFirst(pTab, pNew, 0);
195172  rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
195173  rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
195174  ){
195175  rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
195176  if( rc!=SQLITE_OK ){
195177  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
195178  break;
195179  }
195180  }
195181  }
195182 
195183  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
195184  return rc;
195185 }
195186 
195187 static void fts5ApiInvoke(
195188  Fts5Auxiliary *pAux,
195189  Fts5Cursor *pCsr,
195190  sqlite3_context *context,
195191  int argc,
195192  sqlite3_value **argv
195193 ){
195194  assert( pCsr->pAux==0 );
195195  pCsr->pAux = pAux;
195196  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
195197  pCsr->pAux = 0;
195198 }
195199 
195200 static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
195201  Fts5Cursor *pCsr;
195202  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
195203  if( pCsr->iCsrId==iCsrId ) break;
195204  }
195205  return pCsr;
195206 }
195207 
195208 static void fts5ApiCallback(
195209  sqlite3_context *context,
195210  int argc,
195211  sqlite3_value **argv
195212 ){
195213 
195214  Fts5Auxiliary *pAux;
195215  Fts5Cursor *pCsr;
195216  i64 iCsrId;
195217 
195218  assert( argc>=1 );
195219  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
195220  iCsrId = sqlite3_value_int64(argv[0]);
195221 
195222  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
195223  if( pCsr==0 ){
195224  char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
195225  sqlite3_result_error(context, zErr, -1);
195226  sqlite3_free(zErr);
195227  }else{
195228  fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
195229  }
195230 }
195231 
195232 
195233 /*
195234 ** Given cursor id iId, return a pointer to the corresponding Fts5Index
195235 ** object. Or NULL If the cursor id does not exist.
195236 **
195237 ** If successful, set *ppConfig to point to the associated config object
195238 ** before returning.
195239 */
195240 static Fts5Index *sqlite3Fts5IndexFromCsrid(
195241  Fts5Global *pGlobal, /* FTS5 global context for db handle */
195242  i64 iCsrId, /* Id of cursor to find */
195243  Fts5Config **ppConfig /* OUT: Configuration object */
195244 ){
195245  Fts5Cursor *pCsr;
195246  Fts5Table *pTab;
195247 
195248  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
195249  pTab = (Fts5Table*)pCsr->base.pVtab;
195250  *ppConfig = pTab->pConfig;
195251 
195252  return pTab->pIndex;
195253 }
195254 
195255 /*
195256 ** Return a "position-list blob" corresponding to the current position of
195257 ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
195258 ** the current position-list for each phrase in the query associated with
195259 ** cursor pCsr.
195260 **
195261 ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
195262 ** the number of phrases in the query. Following the varints are the
195263 ** concatenated position lists for each phrase, in order.
195264 **
195265 ** The first varint (if it exists) contains the size of the position list
195266 ** for phrase 0. The second (same disclaimer) contains the size of position
195267 ** list 1. And so on. There is no size field for the final position list,
195268 ** as it can be derived from the total size of the blob.
195269 */
195270 static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
195271  int i;
195272  int rc = SQLITE_OK;
195273  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
195274  Fts5Buffer val;
195275 
195276  memset(&val, 0, sizeof(Fts5Buffer));
195277  switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
195278  case FTS5_DETAIL_FULL:
195279 
195280  /* Append the varints */
195281  for(i=0; i<(nPhrase-1); i++){
195282  const u8 *dummy;
195283  int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
195284  sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
195285  }
195286 
195287  /* Append the position lists */
195288  for(i=0; i<nPhrase; i++){
195289  const u8 *pPoslist;
195290  int nPoslist;
195291  nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
195292  sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
195293  }
195294  break;
195295 
195296  case FTS5_DETAIL_COLUMNS:
195297 
195298  /* Append the varints */
195299  for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
195300  const u8 *dummy;
195301  int nByte;
195302  rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
195303  sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
195304  }
195305 
195306  /* Append the position lists */
195307  for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
195308  const u8 *pPoslist;
195309  int nPoslist;
195310  rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
195311  sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
195312  }
195313  break;
195314 
195315  default:
195316  break;
195317  }
195318 
195319  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
195320  return rc;
195321 }
195322 
195323 /*
195324 ** This is the xColumn method, called by SQLite to request a value from
195325 ** the row that the supplied cursor currently points to.
195326 */
195327 static int fts5ColumnMethod(
195328  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
195329  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
195330  int iCol /* Index of column to read value from */
195331 ){
195332  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
195333  Fts5Config *pConfig = pTab->pConfig;
195334  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
195335  int rc = SQLITE_OK;
195336 
195337  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
195338 
195339  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
195340  if( iCol==pConfig->nCol ){
195341  sqlite3_result_int64(pCtx, pCsr->iSpecial);
195342  }
195343  }else
195344 
195345  if( iCol==pConfig->nCol ){
195346  /* User is requesting the value of the special column with the same name
195347  ** as the table. Return the cursor integer id number. This value is only
195348  ** useful in that it may be passed as the first argument to an FTS5
195349  ** auxiliary function. */
195350  sqlite3_result_int64(pCtx, pCsr->iCsrId);
195351  }else if( iCol==pConfig->nCol+1 ){
195352 
195353  /* The value of the "rank" column. */
195354  if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
195355  fts5PoslistBlob(pCtx, pCsr);
195356  }else if(
195357  pCsr->ePlan==FTS5_PLAN_MATCH
195358  || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
195359  ){
195360  if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
195361  fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
195362  }
195363  }
195364  }else if( !fts5IsContentless(pTab) ){
195365  rc = fts5SeekCursor(pCsr, 1);
195366  if( rc==SQLITE_OK ){
195367  sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
195368  }
195369  }
195370  return rc;
195371 }
195372 
195373 
195374 /*
195375 ** This routine implements the xFindFunction method for the FTS3
195376 ** virtual table.
195377 */
195378 static int fts5FindFunctionMethod(
195379  sqlite3_vtab *pVtab, /* Virtual table handle */
195380  int nUnused, /* Number of SQL function arguments */
195381  const char *zName, /* Name of SQL function */
195382  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
195383  void **ppArg /* OUT: User data for *pxFunc */
195384 ){
195385  Fts5Table *pTab = (Fts5Table*)pVtab;
195386  Fts5Auxiliary *pAux;
195387 
195388  UNUSED_PARAM(nUnused);
195389  pAux = fts5FindAuxiliary(pTab, zName);
195390  if( pAux ){
195391  *pxFunc = fts5ApiCallback;
195392  *ppArg = (void*)pAux;
195393  return 1;
195394  }
195395 
195396  /* No function of the specified name was found. Return 0. */
195397  return 0;
195398 }
195399 
195400 /*
195401 ** Implementation of FTS5 xRename method. Rename an fts5 table.
195402 */
195403 static int fts5RenameMethod(
195404  sqlite3_vtab *pVtab, /* Virtual table handle */
195405  const char *zName /* New name of table */
195406 ){
195407  Fts5Table *pTab = (Fts5Table*)pVtab;
195408  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
195409 }
195410 
195411 /*
195412 ** The xSavepoint() method.
195413 **
195414 ** Flush the contents of the pending-terms table to disk.
195415 */
195416 static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
195417  Fts5Table *pTab = (Fts5Table*)pVtab;
195418  UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
195419  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
195420  fts5TripCursors(pTab);
195421  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
195422 }
195423 
195424 /*
195425 ** The xRelease() method.
195426 **
195427 ** This is a no-op.
195428 */
195429 static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
195430  Fts5Table *pTab = (Fts5Table*)pVtab;
195431  UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
195432  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
195433  fts5TripCursors(pTab);
195434  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
195435 }
195436 
195437 /*
195438 ** The xRollbackTo() method.
195439 **
195440 ** Discard the contents of the pending terms table.
195441 */
195442 static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
195443  Fts5Table *pTab = (Fts5Table*)pVtab;
195444  UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
195445  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
195446  fts5TripCursors(pTab);
195447  return sqlite3Fts5StorageRollback(pTab->pStorage);
195448 }
195449 
195450 /*
195451 ** Register a new auxiliary function with global context pGlobal.
195452 */
195453 static int fts5CreateAux(
195454  fts5_api *pApi, /* Global context (one per db handle) */
195455  const char *zName, /* Name of new function */
195456  void *pUserData, /* User data for aux. function */
195457  fts5_extension_function xFunc, /* Aux. function implementation */
195458  void(*xDestroy)(void*) /* Destructor for pUserData */
195459 ){
195460  Fts5Global *pGlobal = (Fts5Global*)pApi;
195461  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
195462  if( rc==SQLITE_OK ){
195463  Fts5Auxiliary *pAux;
195464  int nName; /* Size of zName in bytes, including \0 */
195465  int nByte; /* Bytes of space to allocate */
195466 
195467  nName = (int)strlen(zName) + 1;
195468  nByte = sizeof(Fts5Auxiliary) + nName;
195469  pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
195470  if( pAux ){
195471  memset(pAux, 0, nByte);
195472  pAux->zFunc = (char*)&pAux[1];
195473  memcpy(pAux->zFunc, zName, nName);
195474  pAux->pGlobal = pGlobal;
195475  pAux->pUserData = pUserData;
195476  pAux->xFunc = xFunc;
195477  pAux->xDestroy = xDestroy;
195478  pAux->pNext = pGlobal->pAux;
195479  pGlobal->pAux = pAux;
195480  }else{
195481  rc = SQLITE_NOMEM;
195482  }
195483  }
195484 
195485  return rc;
195486 }
195487 
195488 /*
195489 ** Register a new tokenizer. This is the implementation of the
195490 ** fts5_api.xCreateTokenizer() method.
195491 */
195492 static int fts5CreateTokenizer(
195493  fts5_api *pApi, /* Global context (one per db handle) */
195494  const char *zName, /* Name of new function */
195495  void *pUserData, /* User data for aux. function */
195496  fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
195497  void(*xDestroy)(void*) /* Destructor for pUserData */
195498 ){
195499  Fts5Global *pGlobal = (Fts5Global*)pApi;
195500  Fts5TokenizerModule *pNew;
195501  int nName; /* Size of zName and its \0 terminator */
195502  int nByte; /* Bytes of space to allocate */
195503  int rc = SQLITE_OK;
195504 
195505  nName = (int)strlen(zName) + 1;
195506  nByte = sizeof(Fts5TokenizerModule) + nName;
195507  pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
195508  if( pNew ){
195509  memset(pNew, 0, nByte);
195510  pNew->zName = (char*)&pNew[1];
195511  memcpy(pNew->zName, zName, nName);
195512  pNew->pUserData = pUserData;
195513  pNew->x = *pTokenizer;
195514  pNew->xDestroy = xDestroy;
195515  pNew->pNext = pGlobal->pTok;
195516  pGlobal->pTok = pNew;
195517  if( pNew->pNext==0 ){
195518  pGlobal->pDfltTok = pNew;
195519  }
195520  }else{
195521  rc = SQLITE_NOMEM;
195522  }
195523 
195524  return rc;
195525 }
195526 
195527 static Fts5TokenizerModule *fts5LocateTokenizer(
195528  Fts5Global *pGlobal,
195529  const char *zName
195530 ){
195531  Fts5TokenizerModule *pMod = 0;
195532 
195533  if( zName==0 ){
195534  pMod = pGlobal->pDfltTok;
195535  }else{
195536  for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
195537  if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
195538  }
195539  }
195540 
195541  return pMod;
195542 }
195543 
195544 /*
195545 ** Find a tokenizer. This is the implementation of the
195546 ** fts5_api.xFindTokenizer() method.
195547 */
195548 static int fts5FindTokenizer(
195549  fts5_api *pApi, /* Global context (one per db handle) */
195550  const char *zName, /* Name of new function */
195551  void **ppUserData,
195552  fts5_tokenizer *pTokenizer /* Populate this object */
195553 ){
195554  int rc = SQLITE_OK;
195555  Fts5TokenizerModule *pMod;
195556 
195557  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
195558  if( pMod ){
195559  *pTokenizer = pMod->x;
195560  *ppUserData = pMod->pUserData;
195561  }else{
195562  memset(pTokenizer, 0, sizeof(fts5_tokenizer));
195563  rc = SQLITE_ERROR;
195564  }
195565 
195566  return rc;
195567 }
195568 
195569 static int sqlite3Fts5GetTokenizer(
195570  Fts5Global *pGlobal,
195571  const char **azArg,
195572  int nArg,
195573  Fts5Tokenizer **ppTok,
195574  fts5_tokenizer **ppTokApi,
195575  char **pzErr
195576 ){
195577  Fts5TokenizerModule *pMod;
195578  int rc = SQLITE_OK;
195579 
195580  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
195581  if( pMod==0 ){
195582  assert( nArg>0 );
195583  rc = SQLITE_ERROR;
195584  *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
195585  }else{
195586  rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
195587  *ppTokApi = &pMod->x;
195588  if( rc!=SQLITE_OK && pzErr ){
195589  *pzErr = sqlite3_mprintf("error in tokenizer constructor");
195590  }
195591  }
195592 
195593  if( rc!=SQLITE_OK ){
195594  *ppTokApi = 0;
195595  *ppTok = 0;
195596  }
195597 
195598  return rc;
195599 }
195600 
195601 static void fts5ModuleDestroy(void *pCtx){
195602  Fts5TokenizerModule *pTok, *pNextTok;
195603  Fts5Auxiliary *pAux, *pNextAux;
195604  Fts5Global *pGlobal = (Fts5Global*)pCtx;
195605 
195606  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
195607  pNextAux = pAux->pNext;
195608  if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
195609  sqlite3_free(pAux);
195610  }
195611 
195612  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
195613  pNextTok = pTok->pNext;
195614  if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
195615  sqlite3_free(pTok);
195616  }
195617 
195618  sqlite3_free(pGlobal);
195619 }
195620 
195621 static void fts5Fts5Func(
195622  sqlite3_context *pCtx, /* Function call context */
195623  int nArg, /* Number of args */
195624  sqlite3_value **apUnused /* Function arguments */
195625 ){
195626  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
195627  char buf[8];
195628  UNUSED_PARAM2(nArg, apUnused);
195629  assert( nArg==0 );
195630  assert( sizeof(buf)>=sizeof(pGlobal) );
195631  memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
195632  sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
195633 }
195634 
195635 /*
195636 ** Implementation of fts5_source_id() function.
195637 */
195638 static void fts5SourceIdFunc(
195639  sqlite3_context *pCtx, /* Function call context */
195640  int nArg, /* Number of args */
195641  sqlite3_value **apUnused /* Function arguments */
195642 ){
195643  assert( nArg==0 );
195644  UNUSED_PARAM2(nArg, apUnused);
195645  sqlite3_result_text(pCtx, "fts5: 2016-11-04 12:08:49 1136863c76576110e710dd5d69ab6bf347c65e36", -1, SQLITE_TRANSIENT);
195646 }
195647 
195648 static int fts5Init(sqlite3 *db){
195649  static const sqlite3_module fts5Mod = {
195650  /* iVersion */ 2,
195651  /* xCreate */ fts5CreateMethod,
195652  /* xConnect */ fts5ConnectMethod,
195653  /* xBestIndex */ fts5BestIndexMethod,
195654  /* xDisconnect */ fts5DisconnectMethod,
195655  /* xDestroy */ fts5DestroyMethod,
195656  /* xOpen */ fts5OpenMethod,
195657  /* xClose */ fts5CloseMethod,
195658  /* xFilter */ fts5FilterMethod,
195659  /* xNext */ fts5NextMethod,
195660  /* xEof */ fts5EofMethod,
195661  /* xColumn */ fts5ColumnMethod,
195662  /* xRowid */ fts5RowidMethod,
195663  /* xUpdate */ fts5UpdateMethod,
195664  /* xBegin */ fts5BeginMethod,
195665  /* xSync */ fts5SyncMethod,
195666  /* xCommit */ fts5CommitMethod,
195667  /* xRollback */ fts5RollbackMethod,
195668  /* xFindFunction */ fts5FindFunctionMethod,
195669  /* xRename */ fts5RenameMethod,
195670  /* xSavepoint */ fts5SavepointMethod,
195671  /* xRelease */ fts5ReleaseMethod,
195672  /* xRollbackTo */ fts5RollbackToMethod,
195673  };
195674 
195675  int rc;
195676  Fts5Global *pGlobal = 0;
195677 
195678  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
195679  if( pGlobal==0 ){
195680  rc = SQLITE_NOMEM;
195681  }else{
195682  void *p = (void*)pGlobal;
195683  memset(pGlobal, 0, sizeof(Fts5Global));
195684  pGlobal->db = db;
195685  pGlobal->api.iVersion = 2;
195686  pGlobal->api.xCreateFunction = fts5CreateAux;
195687  pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
195688  pGlobal->api.xFindTokenizer = fts5FindTokenizer;
195689  rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
195690  if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
195691  if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
195692  if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
195693  if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
195694  if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
195695  if( rc==SQLITE_OK ){
195696  rc = sqlite3_create_function(
195697  db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
195698  );
195699  }
195700  if( rc==SQLITE_OK ){
195701  rc = sqlite3_create_function(
195702  db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
195703  );
195704  }
195705  }
195706 
195707  /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
195708  ** fts5_test_mi.c is compiled and linked into the executable. And call
195709  ** its entry point to enable the matchinfo() demo. */
195710 #ifdef SQLITE_FTS5_ENABLE_TEST_MI
195711  if( rc==SQLITE_OK ){
195712  extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
195713  rc = sqlite3Fts5TestRegisterMatchinfo(db);
195714  }
195715 #endif
195716 
195717  return rc;
195718 }
195719 
195720 /*
195721 ** The following functions are used to register the module with SQLite. If
195722 ** this module is being built as part of the SQLite core (SQLITE_CORE is
195723 ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
195724 **
195725 ** Or, if this module is being built as a loadable extension,
195726 ** sqlite3Fts5Init() is omitted and the two standard entry points
195727 ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
195728 */
195729 #ifndef SQLITE_CORE
195730 #ifdef _WIN32
195731 __declspec(dllexport)
195732 #endif
195733 SQLITE_API int sqlite3_fts_init(
195734  sqlite3 *db,
195735  char **pzErrMsg,
195736  const sqlite3_api_routines *pApi
195737 ){
195738  SQLITE_EXTENSION_INIT2(pApi);
195739  (void)pzErrMsg; /* Unused parameter */
195740  return fts5Init(db);
195741 }
195742 
195743 #ifdef _WIN32
195744 __declspec(dllexport)
195745 #endif
195746 SQLITE_API int sqlite3_fts5_init(
195747  sqlite3 *db,
195748  char **pzErrMsg,
195749  const sqlite3_api_routines *pApi
195750 ){
195751  SQLITE_EXTENSION_INIT2(pApi);
195752  (void)pzErrMsg; /* Unused parameter */
195753  return fts5Init(db);
195754 }
195755 #else
195756 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
195757  return fts5Init(db);
195758 }
195759 #endif
195760 
195761 /*
195762 ** 2014 May 31
195763 **
195764 ** The author disclaims copyright to this source code. In place of
195765 ** a legal notice, here is a blessing:
195766 **
195767 ** May you do good and not evil.
195768 ** May you find forgiveness for yourself and forgive others.
195769 ** May you share freely, never taking more than you give.
195770 **
195771 ******************************************************************************
195772 **
195773 */
195774 
195775 
195776 
195777 /* #include "fts5Int.h" */
195778 
195779 struct Fts5Storage {
195780  Fts5Config *pConfig;
195781  Fts5Index *pIndex;
195782  int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
195783  i64 nTotalRow; /* Total number of rows in FTS table */
195784  i64 *aTotalSize; /* Total sizes of each column */
195785  sqlite3_stmt *aStmt[11];
195786 };
195787 
195788 
195789 #if FTS5_STMT_SCAN_ASC!=0
195790 # error "FTS5_STMT_SCAN_ASC mismatch"
195791 #endif
195792 #if FTS5_STMT_SCAN_DESC!=1
195793 # error "FTS5_STMT_SCAN_DESC mismatch"
195794 #endif
195795 #if FTS5_STMT_LOOKUP!=2
195796 # error "FTS5_STMT_LOOKUP mismatch"
195797 #endif
195798 
195799 #define FTS5_STMT_INSERT_CONTENT 3
195800 #define FTS5_STMT_REPLACE_CONTENT 4
195801 #define FTS5_STMT_DELETE_CONTENT 5
195802 #define FTS5_STMT_REPLACE_DOCSIZE 6
195803 #define FTS5_STMT_DELETE_DOCSIZE 7
195804 #define FTS5_STMT_LOOKUP_DOCSIZE 8
195805 #define FTS5_STMT_REPLACE_CONFIG 9
195806 #define FTS5_STMT_SCAN 10
195807 
195808 /*
195809 ** Prepare the two insert statements - Fts5Storage.pInsertContent and
195810 ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
195811 ** Return SQLITE_OK if successful, or an SQLite error code if an error
195812 ** occurs.
195813 */
195814 static int fts5StorageGetStmt(
195815  Fts5Storage *p, /* Storage handle */
195816  int eStmt, /* FTS5_STMT_XXX constant */
195817  sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
195818  char **pzErrMsg /* OUT: Error message (if any) */
195819 ){
195820  int rc = SQLITE_OK;
195821 
195822  /* If there is no %_docsize table, there should be no requests for
195823  ** statements to operate on it. */
195824  assert( p->pConfig->bColumnsize || (
195825  eStmt!=FTS5_STMT_REPLACE_DOCSIZE
195826  && eStmt!=FTS5_STMT_DELETE_DOCSIZE
195827  && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
195828  ));
195829 
195830  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
195831  if( p->aStmt[eStmt]==0 ){
195832  const char *azStmt[] = {
195833  "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
195834  "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
195835  "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
195836 
195837  "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
195838  "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
195839  "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
195840  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
195841  "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
195842 
195843  "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
195844 
195845  "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
195846  "SELECT %s FROM %s AS T", /* SCAN */
195847  };
195848  Fts5Config *pC = p->pConfig;
195849  char *zSql = 0;
195850 
195851  switch( eStmt ){
195852  case FTS5_STMT_SCAN:
195853  zSql = sqlite3_mprintf(azStmt[eStmt],
195854  pC->zContentExprlist, pC->zContent
195855  );
195856  break;
195857 
195858  case FTS5_STMT_SCAN_ASC:
195859  case FTS5_STMT_SCAN_DESC:
195860  zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
195861  pC->zContent, pC->zContentRowid, pC->zContentRowid,
195862  pC->zContentRowid
195863  );
195864  break;
195865 
195866  case FTS5_STMT_LOOKUP:
195867  zSql = sqlite3_mprintf(azStmt[eStmt],
195868  pC->zContentExprlist, pC->zContent, pC->zContentRowid
195869  );
195870  break;
195871 
195872  case FTS5_STMT_INSERT_CONTENT:
195873  case FTS5_STMT_REPLACE_CONTENT: {
195874  int nCol = pC->nCol + 1;
195875  char *zBind;
195876  int i;
195877 
195878  zBind = sqlite3_malloc(1 + nCol*2);
195879  if( zBind ){
195880  for(i=0; i<nCol; i++){
195881  zBind[i*2] = '?';
195882  zBind[i*2 + 1] = ',';
195883  }
195884  zBind[i*2-1] = '\0';
195885  zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
195886  sqlite3_free(zBind);
195887  }
195888  break;
195889  }
195890 
195891  default:
195892  zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
195893  break;
195894  }
195895 
195896  if( zSql==0 ){
195897  rc = SQLITE_NOMEM;
195898  }else{
195899  rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
195900  sqlite3_free(zSql);
195901  if( rc!=SQLITE_OK && pzErrMsg ){
195902  *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
195903  }
195904  }
195905  }
195906 
195907  *ppStmt = p->aStmt[eStmt];
195908  sqlite3_reset(*ppStmt);
195909  return rc;
195910 }
195911 
195912 
195913 static int fts5ExecPrintf(
195914  sqlite3 *db,
195915  char **pzErr,
195916  const char *zFormat,
195917  ...
195918 ){
195919  int rc;
195920  va_list ap; /* ... printf arguments */
195921  char *zSql;
195922 
195923  va_start(ap, zFormat);
195924  zSql = sqlite3_vmprintf(zFormat, ap);
195925 
195926  if( zSql==0 ){
195927  rc = SQLITE_NOMEM;
195928  }else{
195929  rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
195930  sqlite3_free(zSql);
195931  }
195932 
195933  va_end(ap);
195934  return rc;
195935 }
195936 
195937 /*
195938 ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
195939 ** code otherwise.
195940 */
195941 static int sqlite3Fts5DropAll(Fts5Config *pConfig){
195942  int rc = fts5ExecPrintf(pConfig->db, 0,
195943  "DROP TABLE IF EXISTS %Q.'%q_data';"
195944  "DROP TABLE IF EXISTS %Q.'%q_idx';"
195945  "DROP TABLE IF EXISTS %Q.'%q_config';",
195946  pConfig->zDb, pConfig->zName,
195947  pConfig->zDb, pConfig->zName,
195948  pConfig->zDb, pConfig->zName
195949  );
195950  if( rc==SQLITE_OK && pConfig->bColumnsize ){
195951  rc = fts5ExecPrintf(pConfig->db, 0,
195952  "DROP TABLE IF EXISTS %Q.'%q_docsize';",
195953  pConfig->zDb, pConfig->zName
195954  );
195955  }
195956  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
195957  rc = fts5ExecPrintf(pConfig->db, 0,
195958  "DROP TABLE IF EXISTS %Q.'%q_content';",
195959  pConfig->zDb, pConfig->zName
195960  );
195961  }
195962  return rc;
195963 }
195964 
195965 static void fts5StorageRenameOne(
195966  Fts5Config *pConfig, /* Current FTS5 configuration */
195967  int *pRc, /* IN/OUT: Error code */
195968  const char *zTail, /* Tail of table name e.g. "data", "config" */
195969  const char *zName /* New name of FTS5 table */
195970 ){
195971  if( *pRc==SQLITE_OK ){
195972  *pRc = fts5ExecPrintf(pConfig->db, 0,
195973  "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
195974  pConfig->zDb, pConfig->zName, zTail, zName, zTail
195975  );
195976  }
195977 }
195978 
195979 static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
195980  Fts5Config *pConfig = pStorage->pConfig;
195981  int rc = sqlite3Fts5StorageSync(pStorage, 1);
195982 
195983  fts5StorageRenameOne(pConfig, &rc, "data", zName);
195984  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
195985  fts5StorageRenameOne(pConfig, &rc, "config", zName);
195986  if( pConfig->bColumnsize ){
195987  fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
195988  }
195989  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
195990  fts5StorageRenameOne(pConfig, &rc, "content", zName);
195991  }
195992  return rc;
195993 }
195994 
195995 /*
195996 ** Create the shadow table named zPost, with definition zDefn. Return
195997 ** SQLITE_OK if successful, or an SQLite error code otherwise.
195998 */
195999 static int sqlite3Fts5CreateTable(
196000  Fts5Config *pConfig, /* FTS5 configuration */
196001  const char *zPost, /* Shadow table to create (e.g. "content") */
196002  const char *zDefn, /* Columns etc. for shadow table */
196003  int bWithout, /* True for without rowid */
196004  char **pzErr /* OUT: Error message */
196005 ){
196006  int rc;
196007  char *zErr = 0;
196008 
196009  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
196010  pConfig->zDb, pConfig->zName, zPost, zDefn,
196011 #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
196012  bWithout?" WITHOUT ROWID":
196013 #endif
196014  ""
196015  );
196016  if( zErr ){
196017  *pzErr = sqlite3_mprintf(
196018  "fts5: error creating shadow table %q_%s: %s",
196019  pConfig->zName, zPost, zErr
196020  );
196021  sqlite3_free(zErr);
196022  }
196023 
196024  return rc;
196025 }
196026 
196027 /*
196028 ** Open a new Fts5Index handle. If the bCreate argument is true, create
196029 ** and initialize the underlying tables
196030 **
196031 ** If successful, set *pp to point to the new object and return SQLITE_OK.
196032 ** Otherwise, set *pp to NULL and return an SQLite error code.
196033 */
196034 static int sqlite3Fts5StorageOpen(
196035  Fts5Config *pConfig,
196036  Fts5Index *pIndex,
196037  int bCreate,
196038  Fts5Storage **pp,
196039  char **pzErr /* OUT: Error message */
196040 ){
196041  int rc = SQLITE_OK;
196042  Fts5Storage *p; /* New object */
196043  int nByte; /* Bytes of space to allocate */
196044 
196045  nByte = sizeof(Fts5Storage) /* Fts5Storage object */
196046  + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
196047  *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
196048  if( !p ) return SQLITE_NOMEM;
196049 
196050  memset(p, 0, nByte);
196051  p->aTotalSize = (i64*)&p[1];
196052  p->pConfig = pConfig;
196053  p->pIndex = pIndex;
196054 
196055  if( bCreate ){
196056  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
196057  int nDefn = 32 + pConfig->nCol*10;
196058  char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
196059  if( zDefn==0 ){
196060  rc = SQLITE_NOMEM;
196061  }else{
196062  int i;
196063  int iOff;
196064  sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
196065  iOff = (int)strlen(zDefn);
196066  for(i=0; i<pConfig->nCol; i++){
196067  sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
196068  iOff += (int)strlen(&zDefn[iOff]);
196069  }
196070  rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
196071  }
196072  sqlite3_free(zDefn);
196073  }
196074 
196075  if( rc==SQLITE_OK && pConfig->bColumnsize ){
196076  rc = sqlite3Fts5CreateTable(
196077  pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
196078  );
196079  }
196080  if( rc==SQLITE_OK ){
196081  rc = sqlite3Fts5CreateTable(
196082  pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
196083  );
196084  }
196085  if( rc==SQLITE_OK ){
196086  rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
196087  }
196088  }
196089 
196090  if( rc ){
196091  sqlite3Fts5StorageClose(p);
196092  *pp = 0;
196093  }
196094  return rc;
196095 }
196096 
196097 /*
196098 ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
196099 */
196100 static int sqlite3Fts5StorageClose(Fts5Storage *p){
196101  int rc = SQLITE_OK;
196102  if( p ){
196103  int i;
196104 
196105  /* Finalize all SQL statements */
196106  for(i=0; i<ArraySize(p->aStmt); i++){
196107  sqlite3_finalize(p->aStmt[i]);
196108  }
196109 
196110  sqlite3_free(p);
196111  }
196112  return rc;
196113 }
196114 
196115 typedef struct Fts5InsertCtx Fts5InsertCtx;
196116 struct Fts5InsertCtx {
196117  Fts5Storage *pStorage;
196118  int iCol;
196119  int szCol; /* Size of column value in tokens */
196120 };
196121 
196122 /*
196123 ** Tokenization callback used when inserting tokens into the FTS index.
196124 */
196125 static int fts5StorageInsertCallback(
196126  void *pContext, /* Pointer to Fts5InsertCtx object */
196127  int tflags,
196128  const char *pToken, /* Buffer containing token */
196129  int nToken, /* Size of token in bytes */
196130  int iUnused1, /* Start offset of token */
196131  int iUnused2 /* End offset of token */
196132 ){
196133  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
196134  Fts5Index *pIdx = pCtx->pStorage->pIndex;
196135  UNUSED_PARAM2(iUnused1, iUnused2);
196136  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
196137  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
196138  pCtx->szCol++;
196139  }
196140  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
196141 }
196142 
196143 /*
196144 ** If a row with rowid iDel is present in the %_content table, add the
196145 ** delete-markers to the FTS index necessary to delete it. Do not actually
196146 ** remove the %_content row at this time though.
196147 */
196148 static int fts5StorageDeleteFromIndex(
196149  Fts5Storage *p,
196150  i64 iDel,
196151  sqlite3_value **apVal
196152 ){
196153  Fts5Config *pConfig = p->pConfig;
196154  sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
196155  int rc; /* Return code */
196156  int rc2; /* sqlite3_reset() return code */
196157  int iCol;
196158  Fts5InsertCtx ctx;
196159 
196160  if( apVal==0 ){
196161  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
196162  if( rc!=SQLITE_OK ) return rc;
196163  sqlite3_bind_int64(pSeek, 1, iDel);
196164  if( sqlite3_step(pSeek)!=SQLITE_ROW ){
196165  return sqlite3_reset(pSeek);
196166  }
196167  }
196168 
196169  ctx.pStorage = p;
196170  ctx.iCol = -1;
196171  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
196172  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
196173  if( pConfig->abUnindexed[iCol-1]==0 ){
196174  const char *zText;
196175  int nText;
196176  if( pSeek ){
196177  zText = (const char*)sqlite3_column_text(pSeek, iCol);
196178  nText = sqlite3_column_bytes(pSeek, iCol);
196179  }else{
196180  zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
196181  nText = sqlite3_value_bytes(apVal[iCol-1]);
196182  }
196183  ctx.szCol = 0;
196184  rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
196185  zText, nText, (void*)&ctx, fts5StorageInsertCallback
196186  );
196187  p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
196188  }
196189  }
196190  p->nTotalRow--;
196191 
196192  rc2 = sqlite3_reset(pSeek);
196193  if( rc==SQLITE_OK ) rc = rc2;
196194  return rc;
196195 }
196196 
196197 
196198 /*
196199 ** Insert a record into the %_docsize table. Specifically, do:
196200 **
196201 ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
196202 **
196203 ** If there is no %_docsize table (as happens if the columnsize=0 option
196204 ** is specified when the FTS5 table is created), this function is a no-op.
196205 */
196206 static int fts5StorageInsertDocsize(
196207  Fts5Storage *p, /* Storage module to write to */
196208  i64 iRowid, /* id value */
196209  Fts5Buffer *pBuf /* sz value */
196210 ){
196211  int rc = SQLITE_OK;
196212  if( p->pConfig->bColumnsize ){
196213  sqlite3_stmt *pReplace = 0;
196214  rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
196215  if( rc==SQLITE_OK ){
196216  sqlite3_bind_int64(pReplace, 1, iRowid);
196217  sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
196218  sqlite3_step(pReplace);
196219  rc = sqlite3_reset(pReplace);
196220  }
196221  }
196222  return rc;
196223 }
196224 
196225 /*
196226 ** Load the contents of the "averages" record from disk into the
196227 ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
196228 ** argument bCache is true, set the p->bTotalsValid flag to indicate
196229 ** that the contents of aTotalSize[] and nTotalRow are valid until
196230 ** further notice.
196231 **
196232 ** Return SQLITE_OK if successful, or an SQLite error code if an error
196233 ** occurs.
196234 */
196235 static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
196236  int rc = SQLITE_OK;
196237  if( p->bTotalsValid==0 ){
196238  rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
196239  p->bTotalsValid = bCache;
196240  }
196241  return rc;
196242 }
196243 
196244 /*
196245 ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
196246 ** variables in the "averages" record on disk.
196247 **
196248 ** Return SQLITE_OK if successful, or an SQLite error code if an error
196249 ** occurs.
196250 */
196251 static int fts5StorageSaveTotals(Fts5Storage *p){
196252  int nCol = p->pConfig->nCol;
196253  int i;
196254  Fts5Buffer buf;
196255  int rc = SQLITE_OK;
196256  memset(&buf, 0, sizeof(buf));
196257 
196258  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
196259  for(i=0; i<nCol; i++){
196260  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
196261  }
196262  if( rc==SQLITE_OK ){
196263  rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
196264  }
196265  sqlite3_free(buf.p);
196266 
196267  return rc;
196268 }
196269 
196270 /*
196271 ** Remove a row from the FTS table.
196272 */
196273 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
196274  Fts5Config *pConfig = p->pConfig;
196275  int rc;
196276  sqlite3_stmt *pDel = 0;
196277 
196278  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
196279  rc = fts5StorageLoadTotals(p, 1);
196280 
196281  /* Delete the index records */
196282  if( rc==SQLITE_OK ){
196283  rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
196284  }
196285 
196286  /* Delete the %_docsize record */
196287  if( rc==SQLITE_OK && pConfig->bColumnsize ){
196288  rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
196289  if( rc==SQLITE_OK ){
196290  sqlite3_bind_int64(pDel, 1, iDel);
196291  sqlite3_step(pDel);
196292  rc = sqlite3_reset(pDel);
196293  }
196294  }
196295 
196296  /* Delete the %_content record */
196297  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
196298  if( rc==SQLITE_OK ){
196299  rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
196300  }
196301  if( rc==SQLITE_OK ){
196302  sqlite3_bind_int64(pDel, 1, iDel);
196303  sqlite3_step(pDel);
196304  rc = sqlite3_reset(pDel);
196305  }
196306  }
196307 
196308  /* Write the averages record */
196309  if( rc==SQLITE_OK ){
196310  rc = fts5StorageSaveTotals(p);
196311  }
196312 
196313  return rc;
196314 }
196315 
196316 /*
196317 ** Delete all entries in the FTS5 index.
196318 */
196319 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
196320  Fts5Config *pConfig = p->pConfig;
196321  int rc;
196322 
196323  /* Delete the contents of the %_data and %_docsize tables. */
196324  rc = fts5ExecPrintf(pConfig->db, 0,
196325  "DELETE FROM %Q.'%q_data';"
196326  "DELETE FROM %Q.'%q_idx';",
196327  pConfig->zDb, pConfig->zName,
196328  pConfig->zDb, pConfig->zName
196329  );
196330  if( rc==SQLITE_OK && pConfig->bColumnsize ){
196331  rc = fts5ExecPrintf(pConfig->db, 0,
196332  "DELETE FROM %Q.'%q_docsize';",
196333  pConfig->zDb, pConfig->zName
196334  );
196335  }
196336 
196337  /* Reinitialize the %_data table. This call creates the initial structure
196338  ** and averages records. */
196339  if( rc==SQLITE_OK ){
196340  rc = sqlite3Fts5IndexReinit(p->pIndex);
196341  }
196342  if( rc==SQLITE_OK ){
196343  rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
196344  }
196345  return rc;
196346 }
196347 
196348 static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
196349  Fts5Buffer buf = {0,0,0};
196350  Fts5Config *pConfig = p->pConfig;
196351  sqlite3_stmt *pScan = 0;
196352  Fts5InsertCtx ctx;
196353  int rc;
196354 
196355  memset(&ctx, 0, sizeof(Fts5InsertCtx));
196356  ctx.pStorage = p;
196357  rc = sqlite3Fts5StorageDeleteAll(p);
196358  if( rc==SQLITE_OK ){
196359  rc = fts5StorageLoadTotals(p, 1);
196360  }
196361 
196362  if( rc==SQLITE_OK ){
196363  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
196364  }
196365 
196366  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
196367  i64 iRowid = sqlite3_column_int64(pScan, 0);
196368 
196369  sqlite3Fts5BufferZero(&buf);
196370  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
196371  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
196372  ctx.szCol = 0;
196373  if( pConfig->abUnindexed[ctx.iCol]==0 ){
196374  rc = sqlite3Fts5Tokenize(pConfig,
196375  FTS5_TOKENIZE_DOCUMENT,
196376  (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
196377  sqlite3_column_bytes(pScan, ctx.iCol+1),
196378  (void*)&ctx,
196379  fts5StorageInsertCallback
196380  );
196381  }
196382  sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
196383  p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
196384  }
196385  p->nTotalRow++;
196386 
196387  if( rc==SQLITE_OK ){
196388  rc = fts5StorageInsertDocsize(p, iRowid, &buf);
196389  }
196390  }
196391  sqlite3_free(buf.p);
196392 
196393  /* Write the averages record */
196394  if( rc==SQLITE_OK ){
196395  rc = fts5StorageSaveTotals(p);
196396  }
196397  return rc;
196398 }
196399 
196400 static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
196401  return sqlite3Fts5IndexOptimize(p->pIndex);
196402 }
196403 
196404 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
196405  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
196406 }
196407 
196408 static int sqlite3Fts5StorageReset(Fts5Storage *p){
196409  return sqlite3Fts5IndexReset(p->pIndex);
196410 }
196411 
196412 /*
196413 ** Allocate a new rowid. This is used for "external content" tables when
196414 ** a NULL value is inserted into the rowid column. The new rowid is allocated
196415 ** by inserting a dummy row into the %_docsize table. The dummy will be
196416 ** overwritten later.
196417 **
196418 ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
196419 ** this case the user is required to provide a rowid explicitly.
196420 */
196421 static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
196422  int rc = SQLITE_MISMATCH;
196423  if( p->pConfig->bColumnsize ){
196424  sqlite3_stmt *pReplace = 0;
196425  rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
196426  if( rc==SQLITE_OK ){
196427  sqlite3_bind_null(pReplace, 1);
196428  sqlite3_bind_null(pReplace, 2);
196429  sqlite3_step(pReplace);
196430  rc = sqlite3_reset(pReplace);
196431  }
196432  if( rc==SQLITE_OK ){
196433  *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
196434  }
196435  }
196436  return rc;
196437 }
196438 
196439 /*
196440 ** Insert a new row into the FTS content table.
196441 */
196442 static int sqlite3Fts5StorageContentInsert(
196443  Fts5Storage *p,
196444  sqlite3_value **apVal,
196445  i64 *piRowid
196446 ){
196447  Fts5Config *pConfig = p->pConfig;
196448  int rc = SQLITE_OK;
196449 
196450  /* Insert the new row into the %_content table. */
196451  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
196452  if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
196453  *piRowid = sqlite3_value_int64(apVal[1]);
196454  }else{
196455  rc = fts5StorageNewRowid(p, piRowid);
196456  }
196457  }else{
196458  sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
196459  int i; /* Counter variable */
196460  rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
196461  for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
196462  rc = sqlite3_bind_value(pInsert, i, apVal[i]);
196463  }
196464  if( rc==SQLITE_OK ){
196465  sqlite3_step(pInsert);
196466  rc = sqlite3_reset(pInsert);
196467  }
196468  *piRowid = sqlite3_last_insert_rowid(pConfig->db);
196469  }
196470 
196471  return rc;
196472 }
196473 
196474 /*
196475 ** Insert new entries into the FTS index and %_docsize table.
196476 */
196477 static int sqlite3Fts5StorageIndexInsert(
196478  Fts5Storage *p,
196479  sqlite3_value **apVal,
196480  i64 iRowid
196481 ){
196482  Fts5Config *pConfig = p->pConfig;
196483  int rc = SQLITE_OK; /* Return code */
196484  Fts5InsertCtx ctx; /* Tokenization callback context object */
196485  Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
196486 
196487  memset(&buf, 0, sizeof(Fts5Buffer));
196488  ctx.pStorage = p;
196489  rc = fts5StorageLoadTotals(p, 1);
196490 
196491  if( rc==SQLITE_OK ){
196492  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
196493  }
196494  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
196495  ctx.szCol = 0;
196496  if( pConfig->abUnindexed[ctx.iCol]==0 ){
196497  rc = sqlite3Fts5Tokenize(pConfig,
196498  FTS5_TOKENIZE_DOCUMENT,
196499  (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
196500  sqlite3_value_bytes(apVal[ctx.iCol+2]),
196501  (void*)&ctx,
196502  fts5StorageInsertCallback
196503  );
196504  }
196505  sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
196506  p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
196507  }
196508  p->nTotalRow++;
196509 
196510  /* Write the %_docsize record */
196511  if( rc==SQLITE_OK ){
196512  rc = fts5StorageInsertDocsize(p, iRowid, &buf);
196513  }
196514  sqlite3_free(buf.p);
196515 
196516  /* Write the averages record */
196517  if( rc==SQLITE_OK ){
196518  rc = fts5StorageSaveTotals(p);
196519  }
196520 
196521  return rc;
196522 }
196523 
196524 static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
196525  Fts5Config *pConfig = p->pConfig;
196526  char *zSql;
196527  int rc;
196528 
196529  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
196530  pConfig->zDb, pConfig->zName, zSuffix
196531  );
196532  if( zSql==0 ){
196533  rc = SQLITE_NOMEM;
196534  }else{
196535  sqlite3_stmt *pCnt = 0;
196536  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
196537  if( rc==SQLITE_OK ){
196538  if( SQLITE_ROW==sqlite3_step(pCnt) ){
196539  *pnRow = sqlite3_column_int64(pCnt, 0);
196540  }
196541  rc = sqlite3_finalize(pCnt);
196542  }
196543  }
196544 
196545  sqlite3_free(zSql);
196546  return rc;
196547 }
196548 
196549 /*
196550 ** Context object used by sqlite3Fts5StorageIntegrity().
196551 */
196552 typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
196553 struct Fts5IntegrityCtx {
196554  i64 iRowid;
196555  int iCol;
196556  int szCol;
196557  u64 cksum;
196558  Fts5Termset *pTermset;
196559  Fts5Config *pConfig;
196560 };
196561 
196562 
196563 /*
196564 ** Tokenization callback used by integrity check.
196565 */
196566 static int fts5StorageIntegrityCallback(
196567  void *pContext, /* Pointer to Fts5IntegrityCtx object */
196568  int tflags,
196569  const char *pToken, /* Buffer containing token */
196570  int nToken, /* Size of token in bytes */
196571  int iUnused1, /* Start offset of token */
196572  int iUnused2 /* End offset of token */
196573 ){
196574  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
196575  Fts5Termset *pTermset = pCtx->pTermset;
196576  int bPresent;
196577  int ii;
196578  int rc = SQLITE_OK;
196579  int iPos;
196580  int iCol;
196581 
196582  UNUSED_PARAM2(iUnused1, iUnused2);
196583  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
196584 
196585  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
196586  pCtx->szCol++;
196587  }
196588 
196589  switch( pCtx->pConfig->eDetail ){
196590  case FTS5_DETAIL_FULL:
196591  iPos = pCtx->szCol-1;
196592  iCol = pCtx->iCol;
196593  break;
196594 
196595  case FTS5_DETAIL_COLUMNS:
196596  iPos = pCtx->iCol;
196597  iCol = 0;
196598  break;
196599 
196600  default:
196601  assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
196602  iPos = 0;
196603  iCol = 0;
196604  break;
196605  }
196606 
196607  rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
196608  if( rc==SQLITE_OK && bPresent==0 ){
196609  pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
196610  pCtx->iRowid, iCol, iPos, 0, pToken, nToken
196611  );
196612  }
196613 
196614  for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
196615  const int nChar = pCtx->pConfig->aPrefix[ii];
196616  int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
196617  if( nByte ){
196618  rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
196619  if( bPresent==0 ){
196620  pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
196621  pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
196622  );
196623  }
196624  }
196625  }
196626 
196627  return rc;
196628 }
196629 
196630 /*
196631 ** Check that the contents of the FTS index match that of the %_content
196632 ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
196633 ** some other SQLite error code if an error occurs while attempting to
196634 ** determine this.
196635 */
196636 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
196637  Fts5Config *pConfig = p->pConfig;
196638  int rc; /* Return code */
196639  int *aColSize; /* Array of size pConfig->nCol */
196640  i64 *aTotalSize; /* Array of size pConfig->nCol */
196641  Fts5IntegrityCtx ctx;
196642  sqlite3_stmt *pScan;
196643 
196644  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
196645  ctx.pConfig = p->pConfig;
196646  aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
196647  if( !aTotalSize ) return SQLITE_NOMEM;
196648  aColSize = (int*)&aTotalSize[pConfig->nCol];
196649  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
196650 
196651  /* Generate the expected index checksum based on the contents of the
196652  ** %_content table. This block stores the checksum in ctx.cksum. */
196653  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
196654  if( rc==SQLITE_OK ){
196655  int rc2;
196656  while( SQLITE_ROW==sqlite3_step(pScan) ){
196657  int i;
196658  ctx.iRowid = sqlite3_column_int64(pScan, 0);
196659  ctx.szCol = 0;
196660  if( pConfig->bColumnsize ){
196661  rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
196662  }
196663  if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
196664  rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
196665  }
196666  for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
196667  if( pConfig->abUnindexed[i] ) continue;
196668  ctx.iCol = i;
196669  ctx.szCol = 0;
196670  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
196671  rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
196672  }
196673  if( rc==SQLITE_OK ){
196674  rc = sqlite3Fts5Tokenize(pConfig,
196675  FTS5_TOKENIZE_DOCUMENT,
196676  (const char*)sqlite3_column_text(pScan, i+1),
196677  sqlite3_column_bytes(pScan, i+1),
196678  (void*)&ctx,
196679  fts5StorageIntegrityCallback
196680  );
196681  }
196682  if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
196683  rc = FTS5_CORRUPT;
196684  }
196685  aTotalSize[i] += ctx.szCol;
196686  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
196687  sqlite3Fts5TermsetFree(ctx.pTermset);
196688  ctx.pTermset = 0;
196689  }
196690  }
196691  sqlite3Fts5TermsetFree(ctx.pTermset);
196692  ctx.pTermset = 0;
196693 
196694  if( rc!=SQLITE_OK ) break;
196695  }
196696  rc2 = sqlite3_reset(pScan);
196697  if( rc==SQLITE_OK ) rc = rc2;
196698  }
196699 
196700  /* Test that the "totals" (sometimes called "averages") record looks Ok */
196701  if( rc==SQLITE_OK ){
196702  int i;
196703  rc = fts5StorageLoadTotals(p, 0);
196704  for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
196705  if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
196706  }
196707  }
196708 
196709  /* Check that the %_docsize and %_content tables contain the expected
196710  ** number of rows. */
196711  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
196712  i64 nRow = 0;
196713  rc = fts5StorageCount(p, "content", &nRow);
196714  if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
196715  }
196716  if( rc==SQLITE_OK && pConfig->bColumnsize ){
196717  i64 nRow = 0;
196718  rc = fts5StorageCount(p, "docsize", &nRow);
196719  if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
196720  }
196721 
196722  /* Pass the expected checksum down to the FTS index module. It will
196723  ** verify, amongst other things, that it matches the checksum generated by
196724  ** inspecting the index itself. */
196725  if( rc==SQLITE_OK ){
196726  rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
196727  }
196728 
196729  sqlite3_free(aTotalSize);
196730  return rc;
196731 }
196732 
196733 /*
196734 ** Obtain an SQLite statement handle that may be used to read data from the
196735 ** %_content table.
196736 */
196737 static int sqlite3Fts5StorageStmt(
196738  Fts5Storage *p,
196739  int eStmt,
196740  sqlite3_stmt **pp,
196741  char **pzErrMsg
196742 ){
196743  int rc;
196744  assert( eStmt==FTS5_STMT_SCAN_ASC
196745  || eStmt==FTS5_STMT_SCAN_DESC
196746  || eStmt==FTS5_STMT_LOOKUP
196747  );
196748  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
196749  if( rc==SQLITE_OK ){
196750  assert( p->aStmt[eStmt]==*pp );
196751  p->aStmt[eStmt] = 0;
196752  }
196753  return rc;
196754 }
196755 
196756 /*
196757 ** Release an SQLite statement handle obtained via an earlier call to
196758 ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
196759 ** must match that passed to the sqlite3Fts5StorageStmt() call.
196760 */
196761 static void sqlite3Fts5StorageStmtRelease(
196762  Fts5Storage *p,
196763  int eStmt,
196764  sqlite3_stmt *pStmt
196765 ){
196766  assert( eStmt==FTS5_STMT_SCAN_ASC
196767  || eStmt==FTS5_STMT_SCAN_DESC
196768  || eStmt==FTS5_STMT_LOOKUP
196769  );
196770  if( p->aStmt[eStmt]==0 ){
196771  sqlite3_reset(pStmt);
196772  p->aStmt[eStmt] = pStmt;
196773  }else{
196774  sqlite3_finalize(pStmt);
196775  }
196776 }
196777 
196778 static int fts5StorageDecodeSizeArray(
196779  int *aCol, int nCol, /* Array to populate */
196780  const u8 *aBlob, int nBlob /* Record to read varints from */
196781 ){
196782  int i;
196783  int iOff = 0;
196784  for(i=0; i<nCol; i++){
196785  if( iOff>=nBlob ) return 1;
196786  iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
196787  }
196788  return (iOff!=nBlob);
196789 }
196790 
196791 /*
196792 ** Argument aCol points to an array of integers containing one entry for
196793 ** each table column. This function reads the %_docsize record for the
196794 ** specified rowid and populates aCol[] with the results.
196795 **
196796 ** An SQLite error code is returned if an error occurs, or SQLITE_OK
196797 ** otherwise.
196798 */
196799 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
196800  int nCol = p->pConfig->nCol; /* Number of user columns in table */
196801  sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
196802  int rc; /* Return Code */
196803 
196804  assert( p->pConfig->bColumnsize );
196805  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
196806  if( rc==SQLITE_OK ){
196807  int bCorrupt = 1;
196808  sqlite3_bind_int64(pLookup, 1, iRowid);
196809  if( SQLITE_ROW==sqlite3_step(pLookup) ){
196810  const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
196811  int nBlob = sqlite3_column_bytes(pLookup, 0);
196812  if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
196813  bCorrupt = 0;
196814  }
196815  }
196816  rc = sqlite3_reset(pLookup);
196817  if( bCorrupt && rc==SQLITE_OK ){
196818  rc = FTS5_CORRUPT;
196819  }
196820  }
196821 
196822  return rc;
196823 }
196824 
196825 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
196826  int rc = fts5StorageLoadTotals(p, 0);
196827  if( rc==SQLITE_OK ){
196828  *pnToken = 0;
196829  if( iCol<0 ){
196830  int i;
196831  for(i=0; i<p->pConfig->nCol; i++){
196832  *pnToken += p->aTotalSize[i];
196833  }
196834  }else if( iCol<p->pConfig->nCol ){
196835  *pnToken = p->aTotalSize[iCol];
196836  }else{
196837  rc = SQLITE_RANGE;
196838  }
196839  }
196840  return rc;
196841 }
196842 
196843 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
196844  int rc = fts5StorageLoadTotals(p, 0);
196845  if( rc==SQLITE_OK ){
196846  *pnRow = p->nTotalRow;
196847  }
196848  return rc;
196849 }
196850 
196851 /*
196852 ** Flush any data currently held in-memory to disk.
196853 */
196854 static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
196855  if( bCommit && p->bTotalsValid ){
196856  int rc = fts5StorageSaveTotals(p);
196857  p->bTotalsValid = 0;
196858  if( rc!=SQLITE_OK ) return rc;
196859  }
196860  return sqlite3Fts5IndexSync(p->pIndex, bCommit);
196861 }
196862 
196863 static int sqlite3Fts5StorageRollback(Fts5Storage *p){
196864  p->bTotalsValid = 0;
196865  return sqlite3Fts5IndexRollback(p->pIndex);
196866 }
196867 
196868 static int sqlite3Fts5StorageConfigValue(
196869  Fts5Storage *p,
196870  const char *z,
196871  sqlite3_value *pVal,
196872  int iVal
196873 ){
196874  sqlite3_stmt *pReplace = 0;
196875  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
196876  if( rc==SQLITE_OK ){
196877  sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
196878  if( pVal ){
196879  sqlite3_bind_value(pReplace, 2, pVal);
196880  }else{
196881  sqlite3_bind_int(pReplace, 2, iVal);
196882  }
196883  sqlite3_step(pReplace);
196884  rc = sqlite3_reset(pReplace);
196885  }
196886  if( rc==SQLITE_OK && pVal ){
196887  int iNew = p->pConfig->iCookie + 1;
196888  rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
196889  if( rc==SQLITE_OK ){
196890  p->pConfig->iCookie = iNew;
196891  }
196892  }
196893  return rc;
196894 }
196895 
196896 /*
196897 ** 2014 May 31
196898 **
196899 ** The author disclaims copyright to this source code. In place of
196900 ** a legal notice, here is a blessing:
196901 **
196902 ** May you do good and not evil.
196903 ** May you find forgiveness for yourself and forgive others.
196904 ** May you share freely, never taking more than you give.
196905 **
196906 ******************************************************************************
196907 */
196908 
196909 
196910 /* #include "fts5Int.h" */
196911 
196912 /**************************************************************************
196913 ** Start of ascii tokenizer implementation.
196914 */
196915 
196916 /*
196917 ** For tokenizers with no "unicode" modifier, the set of token characters
196918 ** is the same as the set of ASCII range alphanumeric characters.
196919 */
196920 static unsigned char aAsciiTokenChar[128] = {
196921  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
196922  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
196923  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
196924  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
196925  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
196926  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
196927  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
196928  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
196929 };
196930 
196931 typedef struct AsciiTokenizer AsciiTokenizer;
196932 struct AsciiTokenizer {
196933  unsigned char aTokenChar[128];
196934 };
196935 
196936 static void fts5AsciiAddExceptions(
196937  AsciiTokenizer *p,
196938  const char *zArg,
196939  int bTokenChars
196940 ){
196941  int i;
196942  for(i=0; zArg[i]; i++){
196943  if( (zArg[i] & 0x80)==0 ){
196944  p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
196945  }
196946  }
196947 }
196948 
196949 /*
196950 ** Delete a "ascii" tokenizer.
196951 */
196952 static void fts5AsciiDelete(Fts5Tokenizer *p){
196953  sqlite3_free(p);
196954 }
196955 
196956 /*
196957 ** Create an "ascii" tokenizer.
196958 */
196959 static int fts5AsciiCreate(
196960  void *pUnused,
196961  const char **azArg, int nArg,
196962  Fts5Tokenizer **ppOut
196963 ){
196964  int rc = SQLITE_OK;
196965  AsciiTokenizer *p = 0;
196966  UNUSED_PARAM(pUnused);
196967  if( nArg%2 ){
196968  rc = SQLITE_ERROR;
196969  }else{
196970  p = sqlite3_malloc(sizeof(AsciiTokenizer));
196971  if( p==0 ){
196972  rc = SQLITE_NOMEM;
196973  }else{
196974  int i;
196975  memset(p, 0, sizeof(AsciiTokenizer));
196976  memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
196977  for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
196978  const char *zArg = azArg[i+1];
196979  if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
196980  fts5AsciiAddExceptions(p, zArg, 1);
196981  }else
196982  if( 0==sqlite3_stricmp(azArg[i], "separators") ){
196983  fts5AsciiAddExceptions(p, zArg, 0);
196984  }else{
196985  rc = SQLITE_ERROR;
196986  }
196987  }
196988  if( rc!=SQLITE_OK ){
196989  fts5AsciiDelete((Fts5Tokenizer*)p);
196990  p = 0;
196991  }
196992  }
196993  }
196994 
196995  *ppOut = (Fts5Tokenizer*)p;
196996  return rc;
196997 }
196998 
196999 
197000 static void asciiFold(char *aOut, const char *aIn, int nByte){
197001  int i;
197002  for(i=0; i<nByte; i++){
197003  char c = aIn[i];
197004  if( c>='A' && c<='Z' ) c += 32;
197005  aOut[i] = c;
197006  }
197007 }
197008 
197009 /*
197010 ** Tokenize some text using the ascii tokenizer.
197011 */
197012 static int fts5AsciiTokenize(
197013  Fts5Tokenizer *pTokenizer,
197014  void *pCtx,
197015  int iUnused,
197016  const char *pText, int nText,
197017  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
197018 ){
197019  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
197020  int rc = SQLITE_OK;
197021  int ie;
197022  int is = 0;
197023 
197024  char aFold[64];
197025  int nFold = sizeof(aFold);
197026  char *pFold = aFold;
197027  unsigned char *a = p->aTokenChar;
197028 
197029  UNUSED_PARAM(iUnused);
197030 
197031  while( is<nText && rc==SQLITE_OK ){
197032  int nByte;
197033 
197034  /* Skip any leading divider characters. */
197035  while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
197036  is++;
197037  }
197038  if( is==nText ) break;
197039 
197040  /* Count the token characters */
197041  ie = is+1;
197042  while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
197043  ie++;
197044  }
197045 
197046  /* Fold to lower case */
197047  nByte = ie-is;
197048  if( nByte>nFold ){
197049  if( pFold!=aFold ) sqlite3_free(pFold);
197050  pFold = sqlite3_malloc(nByte*2);
197051  if( pFold==0 ){
197052  rc = SQLITE_NOMEM;
197053  break;
197054  }
197055  nFold = nByte*2;
197056  }
197057  asciiFold(pFold, &pText[is], nByte);
197058 
197059  /* Invoke the token callback */
197060  rc = xToken(pCtx, 0, pFold, nByte, is, ie);
197061  is = ie+1;
197062  }
197063 
197064  if( pFold!=aFold ) sqlite3_free(pFold);
197065  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
197066  return rc;
197067 }
197068 
197069 /**************************************************************************
197070 ** Start of unicode61 tokenizer implementation.
197071 */
197072 
197073 
197074 /*
197075 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
197076 ** from the sqlite3 source file utf.c. If this file is compiled as part
197077 ** of the amalgamation, they are not required.
197078 */
197079 #ifndef SQLITE_AMALGAMATION
197080 
197081 static const unsigned char sqlite3Utf8Trans1[] = {
197082  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
197083  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
197084  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
197085  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
197086  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
197087  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
197088  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
197089  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
197090 };
197091 
197092 #define READ_UTF8(zIn, zTerm, c) \
197093  c = *(zIn++); \
197094  if( c>=0xc0 ){ \
197095  c = sqlite3Utf8Trans1[c-0xc0]; \
197096  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
197097  c = (c<<6) + (0x3f & *(zIn++)); \
197098  } \
197099  if( c<0x80 \
197100  || (c&0xFFFFF800)==0xD800 \
197101  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
197102  }
197103 
197104 
197105 #define WRITE_UTF8(zOut, c) { \
197106  if( c<0x00080 ){ \
197107  *zOut++ = (unsigned char)(c&0xFF); \
197108  } \
197109  else if( c<0x00800 ){ \
197110  *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
197111  *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
197112  } \
197113  else if( c<0x10000 ){ \
197114  *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
197115  *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
197116  *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
197117  }else{ \
197118  *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
197119  *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
197120  *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
197121  *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
197122  } \
197123 }
197124 
197125 #endif /* ifndef SQLITE_AMALGAMATION */
197126 
197127 typedef struct Unicode61Tokenizer Unicode61Tokenizer;
197128 struct Unicode61Tokenizer {
197129  unsigned char aTokenChar[128]; /* ASCII range token characters */
197130  char *aFold; /* Buffer to fold text into */
197131  int nFold; /* Size of aFold[] in bytes */
197132  int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
197133  int nException;
197134  int *aiException;
197135 };
197136 
197137 static int fts5UnicodeAddExceptions(
197138  Unicode61Tokenizer *p, /* Tokenizer object */
197139  const char *z, /* Characters to treat as exceptions */
197140  int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
197141 ){
197142  int rc = SQLITE_OK;
197143  int n = (int)strlen(z);
197144  int *aNew;
197145 
197146  if( n>0 ){
197147  aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
197148  if( aNew ){
197149  int nNew = p->nException;
197150  const unsigned char *zCsr = (const unsigned char*)z;
197151  const unsigned char *zTerm = (const unsigned char*)&z[n];
197152  while( zCsr<zTerm ){
197153  int iCode;
197154  int bToken;
197155  READ_UTF8(zCsr, zTerm, iCode);
197156  if( iCode<128 ){
197157  p->aTokenChar[iCode] = (unsigned char)bTokenChars;
197158  }else{
197159  bToken = sqlite3Fts5UnicodeIsalnum(iCode);
197160  assert( (bToken==0 || bToken==1) );
197161  assert( (bTokenChars==0 || bTokenChars==1) );
197162  if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
197163  int i;
197164  for(i=0; i<nNew; i++){
197165  if( aNew[i]>iCode ) break;
197166  }
197167  memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
197168  aNew[i] = iCode;
197169  nNew++;
197170  }
197171  }
197172  }
197173  p->aiException = aNew;
197174  p->nException = nNew;
197175  }else{
197176  rc = SQLITE_NOMEM;
197177  }
197178  }
197179 
197180  return rc;
197181 }
197182 
197183 /*
197184 ** Return true if the p->aiException[] array contains the value iCode.
197185 */
197186 static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
197187  if( p->nException>0 ){
197188  int *a = p->aiException;
197189  int iLo = 0;
197190  int iHi = p->nException-1;
197191 
197192  while( iHi>=iLo ){
197193  int iTest = (iHi + iLo) / 2;
197194  if( iCode==a[iTest] ){
197195  return 1;
197196  }else if( iCode>a[iTest] ){
197197  iLo = iTest+1;
197198  }else{
197199  iHi = iTest-1;
197200  }
197201  }
197202  }
197203 
197204  return 0;
197205 }
197206 
197207 /*
197208 ** Delete a "unicode61" tokenizer.
197209 */
197210 static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
197211  if( pTok ){
197212  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
197213  sqlite3_free(p->aiException);
197214  sqlite3_free(p->aFold);
197215  sqlite3_free(p);
197216  }
197217  return;
197218 }
197219 
197220 /*
197221 ** Create a "unicode61" tokenizer.
197222 */
197223 static int fts5UnicodeCreate(
197224  void *pUnused,
197225  const char **azArg, int nArg,
197226  Fts5Tokenizer **ppOut
197227 ){
197228  int rc = SQLITE_OK; /* Return code */
197229  Unicode61Tokenizer *p = 0; /* New tokenizer object */
197230 
197231  UNUSED_PARAM(pUnused);
197232 
197233  if( nArg%2 ){
197234  rc = SQLITE_ERROR;
197235  }else{
197236  p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
197237  if( p ){
197238  int i;
197239  memset(p, 0, sizeof(Unicode61Tokenizer));
197240  memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
197241  p->bRemoveDiacritic = 1;
197242  p->nFold = 64;
197243  p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
197244  if( p->aFold==0 ){
197245  rc = SQLITE_NOMEM;
197246  }
197247  for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
197248  const char *zArg = azArg[i+1];
197249  if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
197250  if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
197251  rc = SQLITE_ERROR;
197252  }
197253  p->bRemoveDiacritic = (zArg[0]=='1');
197254  }else
197255  if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
197256  rc = fts5UnicodeAddExceptions(p, zArg, 1);
197257  }else
197258  if( 0==sqlite3_stricmp(azArg[i], "separators") ){
197259  rc = fts5UnicodeAddExceptions(p, zArg, 0);
197260  }else{
197261  rc = SQLITE_ERROR;
197262  }
197263  }
197264  }else{
197265  rc = SQLITE_NOMEM;
197266  }
197267  if( rc!=SQLITE_OK ){
197268  fts5UnicodeDelete((Fts5Tokenizer*)p);
197269  p = 0;
197270  }
197271  *ppOut = (Fts5Tokenizer*)p;
197272  }
197273  return rc;
197274 }
197275 
197276 /*
197277 ** Return true if, for the purposes of tokenizing with the tokenizer
197278 ** passed as the first argument, codepoint iCode is considered a token
197279 ** character (not a separator).
197280 */
197281 static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
197282  assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
197283  return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
197284 }
197285 
197286 static int fts5UnicodeTokenize(
197287  Fts5Tokenizer *pTokenizer,
197288  void *pCtx,
197289  int iUnused,
197290  const char *pText, int nText,
197291  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
197292 ){
197293  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
197294  int rc = SQLITE_OK;
197295  unsigned char *a = p->aTokenChar;
197296 
197297  unsigned char *zTerm = (unsigned char*)&pText[nText];
197298  unsigned char *zCsr = (unsigned char *)pText;
197299 
197300  /* Output buffer */
197301  char *aFold = p->aFold;
197302  int nFold = p->nFold;
197303  const char *pEnd = &aFold[nFold-6];
197304 
197305  UNUSED_PARAM(iUnused);
197306 
197307  /* Each iteration of this loop gobbles up a contiguous run of separators,
197308  ** then the next token. */
197309  while( rc==SQLITE_OK ){
197310  int iCode; /* non-ASCII codepoint read from input */
197311  char *zOut = aFold;
197312  int is;
197313  int ie;
197314 
197315  /* Skip any separator characters. */
197316  while( 1 ){
197317  if( zCsr>=zTerm ) goto tokenize_done;
197318  if( *zCsr & 0x80 ) {
197319  /* A character outside of the ascii range. Skip past it if it is
197320  ** a separator character. Or break out of the loop if it is not. */
197321  is = zCsr - (unsigned char*)pText;
197322  READ_UTF8(zCsr, zTerm, iCode);
197323  if( fts5UnicodeIsAlnum(p, iCode) ){
197324  goto non_ascii_tokenchar;
197325  }
197326  }else{
197327  if( a[*zCsr] ){
197328  is = zCsr - (unsigned char*)pText;
197329  goto ascii_tokenchar;
197330  }
197331  zCsr++;
197332  }
197333  }
197334 
197335  /* Run through the tokenchars. Fold them into the output buffer along
197336  ** the way. */
197337  while( zCsr<zTerm ){
197338 
197339  /* Grow the output buffer so that there is sufficient space to fit the
197340  ** largest possible utf-8 character. */
197341  if( zOut>pEnd ){
197342  aFold = sqlite3_malloc(nFold*2);
197343  if( aFold==0 ){
197344  rc = SQLITE_NOMEM;
197345  goto tokenize_done;
197346  }
197347  zOut = &aFold[zOut - p->aFold];
197348  memcpy(aFold, p->aFold, nFold);
197349  sqlite3_free(p->aFold);
197350  p->aFold = aFold;
197351  p->nFold = nFold = nFold*2;
197352  pEnd = &aFold[nFold-6];
197353  }
197354 
197355  if( *zCsr & 0x80 ){
197356  /* An non-ascii-range character. Fold it into the output buffer if
197357  ** it is a token character, or break out of the loop if it is not. */
197358  READ_UTF8(zCsr, zTerm, iCode);
197359  if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
197360  non_ascii_tokenchar:
197361  iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
197362  if( iCode ) WRITE_UTF8(zOut, iCode);
197363  }else{
197364  break;
197365  }
197366  }else if( a[*zCsr]==0 ){
197367  /* An ascii-range separator character. End of token. */
197368  break;
197369  }else{
197370  ascii_tokenchar:
197371  if( *zCsr>='A' && *zCsr<='Z' ){
197372  *zOut++ = *zCsr + 32;
197373  }else{
197374  *zOut++ = *zCsr;
197375  }
197376  zCsr++;
197377  }
197378  ie = zCsr - (unsigned char*)pText;
197379  }
197380 
197381  /* Invoke the token callback */
197382  rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
197383  }
197384 
197385  tokenize_done:
197386  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
197387  return rc;
197388 }
197389 
197390 /**************************************************************************
197391 ** Start of porter stemmer implementation.
197392 */
197393 
197394 /* Any tokens larger than this (in bytes) are passed through without
197395 ** stemming. */
197396 #define FTS5_PORTER_MAX_TOKEN 64
197397 
197398 typedef struct PorterTokenizer PorterTokenizer;
197399 struct PorterTokenizer {
197400  fts5_tokenizer tokenizer; /* Parent tokenizer module */
197401  Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
197402  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
197403 };
197404 
197405 /*
197406 ** Delete a "porter" tokenizer.
197407 */
197408 static void fts5PorterDelete(Fts5Tokenizer *pTok){
197409  if( pTok ){
197410  PorterTokenizer *p = (PorterTokenizer*)pTok;
197411  if( p->pTokenizer ){
197412  p->tokenizer.xDelete(p->pTokenizer);
197413  }
197414  sqlite3_free(p);
197415  }
197416 }
197417 
197418 /*
197419 ** Create a "porter" tokenizer.
197420 */
197421 static int fts5PorterCreate(
197422  void *pCtx,
197423  const char **azArg, int nArg,
197424  Fts5Tokenizer **ppOut
197425 ){
197426  fts5_api *pApi = (fts5_api*)pCtx;
197427  int rc = SQLITE_OK;
197428  PorterTokenizer *pRet;
197429  void *pUserdata = 0;
197430  const char *zBase = "unicode61";
197431 
197432  if( nArg>0 ){
197433  zBase = azArg[0];
197434  }
197435 
197436  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
197437  if( pRet ){
197438  memset(pRet, 0, sizeof(PorterTokenizer));
197439  rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
197440  }else{
197441  rc = SQLITE_NOMEM;
197442  }
197443  if( rc==SQLITE_OK ){
197444  int nArg2 = (nArg>0 ? nArg-1 : 0);
197445  const char **azArg2 = (nArg2 ? &azArg[1] : 0);
197446  rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
197447  }
197448 
197449  if( rc!=SQLITE_OK ){
197450  fts5PorterDelete((Fts5Tokenizer*)pRet);
197451  pRet = 0;
197452  }
197453  *ppOut = (Fts5Tokenizer*)pRet;
197454  return rc;
197455 }
197456 
197457 typedef struct PorterContext PorterContext;
197458 struct PorterContext {
197459  void *pCtx;
197460  int (*xToken)(void*, int, const char*, int, int, int);
197461  char *aBuf;
197462 };
197463 
197464 typedef struct PorterRule PorterRule;
197465 struct PorterRule {
197466  const char *zSuffix;
197467  int nSuffix;
197468  int (*xCond)(char *zStem, int nStem);
197469  const char *zOutput;
197470  int nOutput;
197471 };
197472 
197473 #if 0
197474 static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
197475  int ret = -1;
197476  int nBuf = *pnBuf;
197477  PorterRule *p;
197478 
197479  for(p=aRule; p->zSuffix; p++){
197480  assert( strlen(p->zSuffix)==p->nSuffix );
197481  assert( strlen(p->zOutput)==p->nOutput );
197482  if( nBuf<p->nSuffix ) continue;
197483  if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
197484  }
197485 
197486  if( p->zSuffix ){
197487  int nStem = nBuf - p->nSuffix;
197488  if( p->xCond==0 || p->xCond(aBuf, nStem) ){
197489  memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
197490  *pnBuf = nStem + p->nOutput;
197491  ret = p - aRule;
197492  }
197493  }
197494 
197495  return ret;
197496 }
197497 #endif
197498 
197499 static int fts5PorterIsVowel(char c, int bYIsVowel){
197500  return (
197501  c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
197502  );
197503 }
197504 
197505 static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
197506  int i;
197507  int bCons = bPrevCons;
197508 
197509  /* Scan for a vowel */
197510  for(i=0; i<nStem; i++){
197511  if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
197512  }
197513 
197514  /* Scan for a consonent */
197515  for(i++; i<nStem; i++){
197516  if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
197517  }
197518  return 0;
197519 }
197520 
197521 /* porter rule condition: (m > 0) */
197522 static int fts5Porter_MGt0(char *zStem, int nStem){
197523  return !!fts5PorterGobbleVC(zStem, nStem, 0);
197524 }
197525 
197526 /* porter rule condition: (m > 1) */
197527 static int fts5Porter_MGt1(char *zStem, int nStem){
197528  int n;
197529  n = fts5PorterGobbleVC(zStem, nStem, 0);
197530  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
197531  return 1;
197532  }
197533  return 0;
197534 }
197535 
197536 /* porter rule condition: (m = 1) */
197537 static int fts5Porter_MEq1(char *zStem, int nStem){
197538  int n;
197539  n = fts5PorterGobbleVC(zStem, nStem, 0);
197540  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
197541  return 1;
197542  }
197543  return 0;
197544 }
197545 
197546 /* porter rule condition: (*o) */
197547 static int fts5Porter_Ostar(char *zStem, int nStem){
197548  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
197549  return 0;
197550  }else{
197551  int i;
197552  int mask = 0;
197553  int bCons = 0;
197554  for(i=0; i<nStem; i++){
197555  bCons = !fts5PorterIsVowel(zStem[i], bCons);
197556  assert( bCons==0 || bCons==1 );
197557  mask = (mask << 1) + bCons;
197558  }
197559  return ((mask & 0x0007)==0x0005);
197560  }
197561 }
197562 
197563 /* porter rule condition: (m > 1 and (*S or *T)) */
197564 static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
197565  assert( nStem>0 );
197566  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
197567  && fts5Porter_MGt1(zStem, nStem);
197568 }
197569 
197570 /* porter rule condition: (*v*) */
197571 static int fts5Porter_Vowel(char *zStem, int nStem){
197572  int i;
197573  for(i=0; i<nStem; i++){
197574  if( fts5PorterIsVowel(zStem[i], i>0) ){
197575  return 1;
197576  }
197577  }
197578  return 0;
197579 }
197580 
197581 
197582 /**************************************************************************
197583 ***************************************************************************
197584 ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
197585 */
197586 
197587 static int fts5PorterStep4(char *aBuf, int *pnBuf){
197588  int ret = 0;
197589  int nBuf = *pnBuf;
197590  switch( aBuf[nBuf-2] ){
197591 
197592  case 'a':
197593  if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
197594  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
197595  *pnBuf = nBuf - 2;
197596  }
197597  }
197598  break;
197599 
197600  case 'c':
197601  if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
197602  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197603  *pnBuf = nBuf - 4;
197604  }
197605  }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
197606  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197607  *pnBuf = nBuf - 4;
197608  }
197609  }
197610  break;
197611 
197612  case 'e':
197613  if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
197614  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
197615  *pnBuf = nBuf - 2;
197616  }
197617  }
197618  break;
197619 
197620  case 'i':
197621  if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
197622  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
197623  *pnBuf = nBuf - 2;
197624  }
197625  }
197626  break;
197627 
197628  case 'l':
197629  if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
197630  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197631  *pnBuf = nBuf - 4;
197632  }
197633  }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
197634  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197635  *pnBuf = nBuf - 4;
197636  }
197637  }
197638  break;
197639 
197640  case 'n':
197641  if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
197642  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197643  *pnBuf = nBuf - 3;
197644  }
197645  }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
197646  if( fts5Porter_MGt1(aBuf, nBuf-5) ){
197647  *pnBuf = nBuf - 5;
197648  }
197649  }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
197650  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197651  *pnBuf = nBuf - 4;
197652  }
197653  }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
197654  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197655  *pnBuf = nBuf - 3;
197656  }
197657  }
197658  break;
197659 
197660  case 'o':
197661  if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
197662  if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
197663  *pnBuf = nBuf - 3;
197664  }
197665  }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
197666  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
197667  *pnBuf = nBuf - 2;
197668  }
197669  }
197670  break;
197671 
197672  case 's':
197673  if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
197674  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197675  *pnBuf = nBuf - 3;
197676  }
197677  }
197678  break;
197679 
197680  case 't':
197681  if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
197682  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197683  *pnBuf = nBuf - 3;
197684  }
197685  }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
197686  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197687  *pnBuf = nBuf - 3;
197688  }
197689  }
197690  break;
197691 
197692  case 'u':
197693  if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
197694  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197695  *pnBuf = nBuf - 3;
197696  }
197697  }
197698  break;
197699 
197700  case 'v':
197701  if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
197702  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197703  *pnBuf = nBuf - 3;
197704  }
197705  }
197706  break;
197707 
197708  case 'z':
197709  if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
197710  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197711  *pnBuf = nBuf - 3;
197712  }
197713  }
197714  break;
197715 
197716  }
197717  return ret;
197718 }
197719 
197720 
197721 static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
197722  int ret = 0;
197723  int nBuf = *pnBuf;
197724  switch( aBuf[nBuf-2] ){
197725 
197726  case 'a':
197727  if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
197728  memcpy(&aBuf[nBuf-2], "ate", 3);
197729  *pnBuf = nBuf - 2 + 3;
197730  ret = 1;
197731  }
197732  break;
197733 
197734  case 'b':
197735  if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
197736  memcpy(&aBuf[nBuf-2], "ble", 3);
197737  *pnBuf = nBuf - 2 + 3;
197738  ret = 1;
197739  }
197740  break;
197741 
197742  case 'i':
197743  if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
197744  memcpy(&aBuf[nBuf-2], "ize", 3);
197745  *pnBuf = nBuf - 2 + 3;
197746  ret = 1;
197747  }
197748  break;
197749 
197750  }
197751  return ret;
197752 }
197753 
197754 
197755 static int fts5PorterStep2(char *aBuf, int *pnBuf){
197756  int ret = 0;
197757  int nBuf = *pnBuf;
197758  switch( aBuf[nBuf-2] ){
197759 
197760  case 'a':
197761  if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
197762  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197763  memcpy(&aBuf[nBuf-7], "ate", 3);
197764  *pnBuf = nBuf - 7 + 3;
197765  }
197766  }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
197767  if( fts5Porter_MGt0(aBuf, nBuf-6) ){
197768  memcpy(&aBuf[nBuf-6], "tion", 4);
197769  *pnBuf = nBuf - 6 + 4;
197770  }
197771  }
197772  break;
197773 
197774  case 'c':
197775  if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
197776  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197777  memcpy(&aBuf[nBuf-4], "ence", 4);
197778  *pnBuf = nBuf - 4 + 4;
197779  }
197780  }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
197781  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197782  memcpy(&aBuf[nBuf-4], "ance", 4);
197783  *pnBuf = nBuf - 4 + 4;
197784  }
197785  }
197786  break;
197787 
197788  case 'e':
197789  if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
197790  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197791  memcpy(&aBuf[nBuf-4], "ize", 3);
197792  *pnBuf = nBuf - 4 + 3;
197793  }
197794  }
197795  break;
197796 
197797  case 'g':
197798  if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
197799  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197800  memcpy(&aBuf[nBuf-4], "log", 3);
197801  *pnBuf = nBuf - 4 + 3;
197802  }
197803  }
197804  break;
197805 
197806  case 'l':
197807  if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
197808  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
197809  memcpy(&aBuf[nBuf-3], "ble", 3);
197810  *pnBuf = nBuf - 3 + 3;
197811  }
197812  }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
197813  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197814  memcpy(&aBuf[nBuf-4], "al", 2);
197815  *pnBuf = nBuf - 4 + 2;
197816  }
197817  }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
197818  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197819  memcpy(&aBuf[nBuf-5], "ent", 3);
197820  *pnBuf = nBuf - 5 + 3;
197821  }
197822  }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
197823  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
197824  memcpy(&aBuf[nBuf-3], "e", 1);
197825  *pnBuf = nBuf - 3 + 1;
197826  }
197827  }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
197828  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197829  memcpy(&aBuf[nBuf-5], "ous", 3);
197830  *pnBuf = nBuf - 5 + 3;
197831  }
197832  }
197833  break;
197834 
197835  case 'o':
197836  if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
197837  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197838  memcpy(&aBuf[nBuf-7], "ize", 3);
197839  *pnBuf = nBuf - 7 + 3;
197840  }
197841  }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
197842  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197843  memcpy(&aBuf[nBuf-5], "ate", 3);
197844  *pnBuf = nBuf - 5 + 3;
197845  }
197846  }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
197847  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197848  memcpy(&aBuf[nBuf-4], "ate", 3);
197849  *pnBuf = nBuf - 4 + 3;
197850  }
197851  }
197852  break;
197853 
197854  case 's':
197855  if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
197856  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197857  memcpy(&aBuf[nBuf-5], "al", 2);
197858  *pnBuf = nBuf - 5 + 2;
197859  }
197860  }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
197861  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197862  memcpy(&aBuf[nBuf-7], "ive", 3);
197863  *pnBuf = nBuf - 7 + 3;
197864  }
197865  }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
197866  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197867  memcpy(&aBuf[nBuf-7], "ful", 3);
197868  *pnBuf = nBuf - 7 + 3;
197869  }
197870  }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
197871  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197872  memcpy(&aBuf[nBuf-7], "ous", 3);
197873  *pnBuf = nBuf - 7 + 3;
197874  }
197875  }
197876  break;
197877 
197878  case 't':
197879  if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
197880  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197881  memcpy(&aBuf[nBuf-5], "al", 2);
197882  *pnBuf = nBuf - 5 + 2;
197883  }
197884  }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
197885  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197886  memcpy(&aBuf[nBuf-5], "ive", 3);
197887  *pnBuf = nBuf - 5 + 3;
197888  }
197889  }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
197890  if( fts5Porter_MGt0(aBuf, nBuf-6) ){
197891  memcpy(&aBuf[nBuf-6], "ble", 3);
197892  *pnBuf = nBuf - 6 + 3;
197893  }
197894  }
197895  break;
197896 
197897  }
197898  return ret;
197899 }
197900 
197901 
197902 static int fts5PorterStep3(char *aBuf, int *pnBuf){
197903  int ret = 0;
197904  int nBuf = *pnBuf;
197905  switch( aBuf[nBuf-2] ){
197906 
197907  case 'a':
197908  if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
197909  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197910  memcpy(&aBuf[nBuf-4], "ic", 2);
197911  *pnBuf = nBuf - 4 + 2;
197912  }
197913  }
197914  break;
197915 
197916  case 's':
197917  if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
197918  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197919  *pnBuf = nBuf - 4;
197920  }
197921  }
197922  break;
197923 
197924  case 't':
197925  if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
197926  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197927  memcpy(&aBuf[nBuf-5], "ic", 2);
197928  *pnBuf = nBuf - 5 + 2;
197929  }
197930  }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
197931  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197932  memcpy(&aBuf[nBuf-5], "ic", 2);
197933  *pnBuf = nBuf - 5 + 2;
197934  }
197935  }
197936  break;
197937 
197938  case 'u':
197939  if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
197940  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
197941  *pnBuf = nBuf - 3;
197942  }
197943  }
197944  break;
197945 
197946  case 'v':
197947  if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
197948  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197949  *pnBuf = nBuf - 5;
197950  }
197951  }
197952  break;
197953 
197954  case 'z':
197955  if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
197956  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197957  memcpy(&aBuf[nBuf-5], "al", 2);
197958  *pnBuf = nBuf - 5 + 2;
197959  }
197960  }
197961  break;
197962 
197963  }
197964  return ret;
197965 }
197966 
197967 
197968 static int fts5PorterStep1B(char *aBuf, int *pnBuf){
197969  int ret = 0;
197970  int nBuf = *pnBuf;
197971  switch( aBuf[nBuf-2] ){
197972 
197973  case 'e':
197974  if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
197975  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
197976  memcpy(&aBuf[nBuf-3], "ee", 2);
197977  *pnBuf = nBuf - 3 + 2;
197978  }
197979  }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
197980  if( fts5Porter_Vowel(aBuf, nBuf-2) ){
197981  *pnBuf = nBuf - 2;
197982  ret = 1;
197983  }
197984  }
197985  break;
197986 
197987  case 'n':
197988  if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
197989  if( fts5Porter_Vowel(aBuf, nBuf-3) ){
197990  *pnBuf = nBuf - 3;
197991  ret = 1;
197992  }
197993  }
197994  break;
197995 
197996  }
197997  return ret;
197998 }
197999 
198000 /*
198001 ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
198002 ***************************************************************************
198003 **************************************************************************/
198004 
198005 static void fts5PorterStep1A(char *aBuf, int *pnBuf){
198006  int nBuf = *pnBuf;
198007  if( aBuf[nBuf-1]=='s' ){
198008  if( aBuf[nBuf-2]=='e' ){
198009  if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
198010  || (nBuf>3 && aBuf[nBuf-3]=='i' )
198011  ){
198012  *pnBuf = nBuf-2;
198013  }else{
198014  *pnBuf = nBuf-1;
198015  }
198016  }
198017  else if( aBuf[nBuf-2]!='s' ){
198018  *pnBuf = nBuf-1;
198019  }
198020  }
198021 }
198022 
198023 static int fts5PorterCb(
198024  void *pCtx,
198025  int tflags,
198026  const char *pToken,
198027  int nToken,
198028  int iStart,
198029  int iEnd
198030 ){
198031  PorterContext *p = (PorterContext*)pCtx;
198032 
198033  char *aBuf;
198034  int nBuf;
198035 
198036  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
198037  aBuf = p->aBuf;
198038  nBuf = nToken;
198039  memcpy(aBuf, pToken, nBuf);
198040 
198041  /* Step 1. */
198042  fts5PorterStep1A(aBuf, &nBuf);
198043  if( fts5PorterStep1B(aBuf, &nBuf) ){
198044  if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
198045  char c = aBuf[nBuf-1];
198046  if( fts5PorterIsVowel(c, 0)==0
198047  && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
198048  ){
198049  nBuf--;
198050  }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
198051  aBuf[nBuf++] = 'e';
198052  }
198053  }
198054  }
198055 
198056  /* Step 1C. */
198057  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
198058  aBuf[nBuf-1] = 'i';
198059  }
198060 
198061  /* Steps 2 through 4. */
198062  fts5PorterStep2(aBuf, &nBuf);
198063  fts5PorterStep3(aBuf, &nBuf);
198064  fts5PorterStep4(aBuf, &nBuf);
198065 
198066  /* Step 5a. */
198067  assert( nBuf>0 );
198068  if( aBuf[nBuf-1]=='e' ){
198069  if( fts5Porter_MGt1(aBuf, nBuf-1)
198070  || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
198071  ){
198072  nBuf--;
198073  }
198074  }
198075 
198076  /* Step 5b. */
198077  if( nBuf>1 && aBuf[nBuf-1]=='l'
198078  && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
198079  ){
198080  nBuf--;
198081  }
198082 
198083  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
198084 
198085  pass_through:
198086  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
198087 }
198088 
198089 /*
198090 ** Tokenize using the porter tokenizer.
198091 */
198092 static int fts5PorterTokenize(
198093  Fts5Tokenizer *pTokenizer,
198094  void *pCtx,
198095  int flags,
198096  const char *pText, int nText,
198097  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
198098 ){
198099  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
198100  PorterContext sCtx;
198101  sCtx.xToken = xToken;
198102  sCtx.pCtx = pCtx;
198103  sCtx.aBuf = p->aBuf;
198104  return p->tokenizer.xTokenize(
198105  p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
198106  );
198107 }
198108 
198109 /*
198110 ** Register all built-in tokenizers with FTS5.
198111 */
198112 static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
198113  struct BuiltinTokenizer {
198114  const char *zName;
198115  fts5_tokenizer x;
198116  } aBuiltin[] = {
198117  { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
198118  { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
198119  { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
198120  };
198121 
198122  int rc = SQLITE_OK; /* Return code */
198123  int i; /* To iterate through builtin functions */
198124 
198125  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
198126  rc = pApi->xCreateTokenizer(pApi,
198127  aBuiltin[i].zName,
198128  (void*)pApi,
198129  &aBuiltin[i].x,
198130  0
198131  );
198132  }
198133 
198134  return rc;
198135 }
198136 
198137 
198138 
198139 /*
198140 ** 2012 May 25
198141 **
198142 ** The author disclaims copyright to this source code. In place of
198143 ** a legal notice, here is a blessing:
198144 **
198145 ** May you do good and not evil.
198146 ** May you find forgiveness for yourself and forgive others.
198147 ** May you share freely, never taking more than you give.
198148 **
198149 ******************************************************************************
198150 */
198151 
198152 /*
198153 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
198154 */
198155 
198156 
198157 /* #include <assert.h> */
198158 
198159 /*
198160 ** Return true if the argument corresponds to a unicode codepoint
198161 ** classified as either a letter or a number. Otherwise false.
198162 **
198163 ** The results are undefined if the value passed to this function
198164 ** is less than zero.
198165 */
198166 static int sqlite3Fts5UnicodeIsalnum(int c){
198167  /* Each unsigned integer in the following array corresponds to a contiguous
198168  ** range of unicode codepoints that are not either letters or numbers (i.e.
198169  ** codepoints for which this function should return 0).
198170  **
198171  ** The most significant 22 bits in each 32-bit value contain the first
198172  ** codepoint in the range. The least significant 10 bits are used to store
198173  ** the size of the range (always at least 1). In other words, the value
198174  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
198175  ** C. It is not possible to represent a range larger than 1023 codepoints
198176  ** using this format.
198177  */
198178  static const unsigned int aEntry[] = {
198179  0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
198180  0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
198181  0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
198182  0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
198183  0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
198184  0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
198185  0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
198186  0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
198187  0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
198188  0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
198189  0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
198190  0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
198191  0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
198192  0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
198193  0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
198194  0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
198195  0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
198196  0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
198197  0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
198198  0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
198199  0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
198200  0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
198201  0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
198202  0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
198203  0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
198204  0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
198205  0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
198206  0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
198207  0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
198208  0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
198209  0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
198210  0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
198211  0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
198212  0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
198213  0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
198214  0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
198215  0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
198216  0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
198217  0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
198218  0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
198219  0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
198220  0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
198221  0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
198222  0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
198223  0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
198224  0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
198225  0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
198226  0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
198227  0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
198228  0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
198229  0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
198230  0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
198231  0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
198232  0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
198233  0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
198234  0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
198235  0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
198236  0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
198237  0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
198238  0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
198239  0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
198240  0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
198241  0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
198242  0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
198243  0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
198244  0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
198245  0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
198246  0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
198247  0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
198248  0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
198249  0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
198250  0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
198251  0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
198252  0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
198253  0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
198254  0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
198255  0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
198256  0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
198257  0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
198258  0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
198259  0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
198260  0x380400F0,
198261  };
198262  static const unsigned int aAscii[4] = {
198263  0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
198264  };
198265 
198266  if( (unsigned int)c<128 ){
198267  return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
198268  }else if( (unsigned int)c<(1<<22) ){
198269  unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
198270  int iRes = 0;
198271  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
198272  int iLo = 0;
198273  while( iHi>=iLo ){
198274  int iTest = (iHi + iLo) / 2;
198275  if( key >= aEntry[iTest] ){
198276  iRes = iTest;
198277  iLo = iTest+1;
198278  }else{
198279  iHi = iTest-1;
198280  }
198281  }
198282  assert( aEntry[0]<key );
198283  assert( key>=aEntry[iRes] );
198284  return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
198285  }
198286  return 1;
198287 }
198288 
198289 
198290 /*
198291 ** If the argument is a codepoint corresponding to a lowercase letter
198292 ** in the ASCII range with a diacritic added, return the codepoint
198293 ** of the ASCII letter only. For example, if passed 235 - "LATIN
198294 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
198295 ** E"). The resuls of passing a codepoint that corresponds to an
198296 ** uppercase letter are undefined.
198297 */
198298 static int fts5_remove_diacritic(int c){
198299  unsigned short aDia[] = {
198300  0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
198301  2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
198302  2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
198303  2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
198304  3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
198305  3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
198306  4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
198307  6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
198308  61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
198309  61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
198310  62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
198311  62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
198312  62924, 63050, 63082, 63274, 63390,
198313  };
198314  char aChar[] = {
198315  '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
198316  'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
198317  's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
198318  'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
198319  'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
198320  '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
198321  'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
198322  'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
198323  'e', 'i', 'o', 'u', 'y',
198324  };
198325 
198326  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
198327  int iRes = 0;
198328  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
198329  int iLo = 0;
198330  while( iHi>=iLo ){
198331  int iTest = (iHi + iLo) / 2;
198332  if( key >= aDia[iTest] ){
198333  iRes = iTest;
198334  iLo = iTest+1;
198335  }else{
198336  iHi = iTest-1;
198337  }
198338  }
198339  assert( key>=aDia[iRes] );
198340  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
198341 }
198342 
198343 
198344 /*
198345 ** Return true if the argument interpreted as a unicode codepoint
198346 ** is a diacritical modifier character.
198347 */
198348 static int sqlite3Fts5UnicodeIsdiacritic(int c){
198349  unsigned int mask0 = 0x08029FDF;
198350  unsigned int mask1 = 0x000361F8;
198351  if( c<768 || c>817 ) return 0;
198352  return (c < 768+32) ?
198353  (mask0 & (1 << (c-768))) :
198354  (mask1 & (1 << (c-768-32)));
198355 }
198356 
198357 
198358 /*
198359 ** Interpret the argument as a unicode codepoint. If the codepoint
198360 ** is an upper case character that has a lower case equivalent,
198361 ** return the codepoint corresponding to the lower case version.
198362 ** Otherwise, return a copy of the argument.
198363 **
198364 ** The results are undefined if the value passed to this function
198365 ** is less than zero.
198366 */
198367 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
198368  /* Each entry in the following array defines a rule for folding a range
198369  ** of codepoints to lower case. The rule applies to a range of nRange
198370  ** codepoints starting at codepoint iCode.
198371  **
198372  ** If the least significant bit in flags is clear, then the rule applies
198373  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
198374  ** need to be folded). Or, if it is set, then the rule only applies to
198375  ** every second codepoint in the range, starting with codepoint C.
198376  **
198377  ** The 7 most significant bits in flags are an index into the aiOff[]
198378  ** array. If a specific codepoint C does require folding, then its lower
198379  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
198380  **
198381  ** The contents of this array are generated by parsing the CaseFolding.txt
198382  ** file distributed as part of the "Unicode Character Database". See
198383  ** http://www.unicode.org for details.
198384  */
198385  static const struct TableEntry {
198386  unsigned short iCode;
198387  unsigned char flags;
198388  unsigned char nRange;
198389  } aEntry[] = {
198390  {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
198391  {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
198392  {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
198393  {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
198394  {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
198395  {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
198396  {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
198397  {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
198398  {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
198399  {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
198400  {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
198401  {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
198402  {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
198403  {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
198404  {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
198405  {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
198406  {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
198407  {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
198408  {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
198409  {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
198410  {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
198411  {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
198412  {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
198413  {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
198414  {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
198415  {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
198416  {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
198417  {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
198418  {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
198419  {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
198420  {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
198421  {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
198422  {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
198423  {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
198424  {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
198425  {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
198426  {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
198427  {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
198428  {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
198429  {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
198430  {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
198431  {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
198432  {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
198433  {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
198434  {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
198435  {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
198436  {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
198437  {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
198438  {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
198439  {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
198440  {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
198441  {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
198442  {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
198443  {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
198444  {65313, 14, 26},
198445  };
198446  static const unsigned short aiOff[] = {
198447  1, 2, 8, 15, 16, 26, 28, 32,
198448  37, 38, 40, 48, 63, 64, 69, 71,
198449  79, 80, 116, 202, 203, 205, 206, 207,
198450  209, 210, 211, 213, 214, 217, 218, 219,
198451  775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
198452  54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
198453  57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
198454  65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
198455  65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
198456  65514, 65521, 65527, 65528, 65529,
198457  };
198458 
198459  int ret = c;
198460 
198461  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
198462 
198463  if( c<128 ){
198464  if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
198465  }else if( c<65536 ){
198466  const struct TableEntry *p;
198467  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
198468  int iLo = 0;
198469  int iRes = -1;
198470 
198471  assert( c>aEntry[0].iCode );
198472  while( iHi>=iLo ){
198473  int iTest = (iHi + iLo) / 2;
198474  int cmp = (c - aEntry[iTest].iCode);
198475  if( cmp>=0 ){
198476  iRes = iTest;
198477  iLo = iTest+1;
198478  }else{
198479  iHi = iTest-1;
198480  }
198481  }
198482 
198483  assert( iRes>=0 && c>=aEntry[iRes].iCode );
198484  p = &aEntry[iRes];
198485  if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
198486  ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
198487  assert( ret>0 );
198488  }
198489 
198490  if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
198491  }
198492 
198493  else if( c>=66560 && c<66600 ){
198494  ret = c + 40;
198495  }
198496 
198497  return ret;
198498 }
198499 
198500 /*
198501 ** 2015 May 30
198502 **
198503 ** The author disclaims copyright to this source code. In place of
198504 ** a legal notice, here is a blessing:
198505 **
198506 ** May you do good and not evil.
198507 ** May you find forgiveness for yourself and forgive others.
198508 ** May you share freely, never taking more than you give.
198509 **
198510 ******************************************************************************
198511 **
198512 ** Routines for varint serialization and deserialization.
198513 */
198514 
198515 
198516 /* #include "fts5Int.h" */
198517 
198518 /*
198519 ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
198520 ** Except, this version does handle the single byte case that the core
198521 ** version depends on being handled before its function is called.
198522 */
198523 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
198524  u32 a,b;
198525 
198526  /* The 1-byte case. Overwhelmingly the most common. */
198527  a = *p;
198528  /* a: p0 (unmasked) */
198529  if (!(a&0x80))
198530  {
198531  /* Values between 0 and 127 */
198532  *v = a;
198533  return 1;
198534  }
198535 
198536  /* The 2-byte case */
198537  p++;
198538  b = *p;
198539  /* b: p1 (unmasked) */
198540  if (!(b&0x80))
198541  {
198542  /* Values between 128 and 16383 */
198543  a &= 0x7f;
198544  a = a<<7;
198545  *v = a | b;
198546  return 2;
198547  }
198548 
198549  /* The 3-byte case */
198550  p++;
198551  a = a<<14;
198552  a |= *p;
198553  /* a: p0<<14 | p2 (unmasked) */
198554  if (!(a&0x80))
198555  {
198556  /* Values between 16384 and 2097151 */
198557  a &= (0x7f<<14)|(0x7f);
198558  b &= 0x7f;
198559  b = b<<7;
198560  *v = a | b;
198561  return 3;
198562  }
198563 
198564  /* A 32-bit varint is used to store size information in btrees.
198565  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
198566  ** A 3-byte varint is sufficient, for example, to record the size
198567  ** of a 1048569-byte BLOB or string.
198568  **
198569  ** We only unroll the first 1-, 2-, and 3- byte cases. The very
198570  ** rare larger cases can be handled by the slower 64-bit varint
198571  ** routine.
198572  */
198573  {
198574  u64 v64;
198575  u8 n;
198576  p -= 2;
198577  n = sqlite3Fts5GetVarint(p, &v64);
198578  *v = (u32)v64;
198579  assert( n>3 && n<=9 );
198580  return n;
198581  }
198582 }
198583 
198584 
198585 /*
198586 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
198587 ** are defined here rather than simply putting the constant expressions
198588 ** inline in order to work around bugs in the RVT compiler.
198589 **
198590 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
198591 **
198592 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
198593 */
198594 #define SLOT_2_0 0x001fc07f
198595 #define SLOT_4_2_0 0xf01fc07f
198596 
198597 /*
198598 ** Read a 64-bit variable-length integer from memory starting at p[0].
198599 ** Return the number of bytes read. The value is stored in *v.
198600 */
198601 static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
198602  u32 a,b,s;
198603 
198604  a = *p;
198605  /* a: p0 (unmasked) */
198606  if (!(a&0x80))
198607  {
198608  *v = a;
198609  return 1;
198610  }
198611 
198612  p++;
198613  b = *p;
198614  /* b: p1 (unmasked) */
198615  if (!(b&0x80))
198616  {
198617  a &= 0x7f;
198618  a = a<<7;
198619  a |= b;
198620  *v = a;
198621  return 2;
198622  }
198623 
198624  /* Verify that constants are precomputed correctly */
198625  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
198626  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
198627 
198628  p++;
198629  a = a<<14;
198630  a |= *p;
198631  /* a: p0<<14 | p2 (unmasked) */
198632  if (!(a&0x80))
198633  {
198634  a &= SLOT_2_0;
198635  b &= 0x7f;
198636  b = b<<7;
198637  a |= b;
198638  *v = a;
198639  return 3;
198640  }
198641 
198642  /* CSE1 from below */
198643  a &= SLOT_2_0;
198644  p++;
198645  b = b<<14;
198646  b |= *p;
198647  /* b: p1<<14 | p3 (unmasked) */
198648  if (!(b&0x80))
198649  {
198650  b &= SLOT_2_0;
198651  /* moved CSE1 up */
198652  /* a &= (0x7f<<14)|(0x7f); */
198653  a = a<<7;
198654  a |= b;
198655  *v = a;
198656  return 4;
198657  }
198658 
198659  /* a: p0<<14 | p2 (masked) */
198660  /* b: p1<<14 | p3 (unmasked) */
198661  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
198662  /* moved CSE1 up */
198663  /* a &= (0x7f<<14)|(0x7f); */
198664  b &= SLOT_2_0;
198665  s = a;
198666  /* s: p0<<14 | p2 (masked) */
198667 
198668  p++;
198669  a = a<<14;
198670  a |= *p;
198671  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
198672  if (!(a&0x80))
198673  {
198674  /* we can skip these cause they were (effectively) done above in calc'ing s */
198675  /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
198676  /* b &= (0x7f<<14)|(0x7f); */
198677  b = b<<7;
198678  a |= b;
198679  s = s>>18;
198680  *v = ((u64)s)<<32 | a;
198681  return 5;
198682  }
198683 
198684  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
198685  s = s<<7;
198686  s |= b;
198687  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
198688 
198689  p++;
198690  b = b<<14;
198691  b |= *p;
198692  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
198693  if (!(b&0x80))
198694  {
198695  /* we can skip this cause it was (effectively) done above in calc'ing s */
198696  /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
198697  a &= SLOT_2_0;
198698  a = a<<7;
198699  a |= b;
198700  s = s>>18;
198701  *v = ((u64)s)<<32 | a;
198702  return 6;
198703  }
198704 
198705  p++;
198706  a = a<<14;
198707  a |= *p;
198708  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
198709  if (!(a&0x80))
198710  {
198711  a &= SLOT_4_2_0;
198712  b &= SLOT_2_0;
198713  b = b<<7;
198714  a |= b;
198715  s = s>>11;
198716  *v = ((u64)s)<<32 | a;
198717  return 7;
198718  }
198719 
198720  /* CSE2 from below */
198721  a &= SLOT_2_0;
198722  p++;
198723  b = b<<14;
198724  b |= *p;
198725  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
198726  if (!(b&0x80))
198727  {
198728  b &= SLOT_4_2_0;
198729  /* moved CSE2 up */
198730  /* a &= (0x7f<<14)|(0x7f); */
198731  a = a<<7;
198732  a |= b;
198733  s = s>>4;
198734  *v = ((u64)s)<<32 | a;
198735  return 8;
198736  }
198737 
198738  p++;
198739  a = a<<15;
198740  a |= *p;
198741  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
198742 
198743  /* moved CSE2 up */
198744  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
198745  b &= SLOT_2_0;
198746  b = b<<8;
198747  a |= b;
198748 
198749  s = s<<4;
198750  b = p[-4];
198751  b &= 0x7f;
198752  b = b>>3;
198753  s |= b;
198754 
198755  *v = ((u64)s)<<32 | a;
198756 
198757  return 9;
198758 }
198759 
198760 /*
198761 ** The variable-length integer encoding is as follows:
198762 **
198763 ** KEY:
198764 ** A = 0xxxxxxx 7 bits of data and one flag bit
198765 ** B = 1xxxxxxx 7 bits of data and one flag bit
198766 ** C = xxxxxxxx 8 bits of data
198767 **
198768 ** 7 bits - A
198769 ** 14 bits - BA
198770 ** 21 bits - BBA
198771 ** 28 bits - BBBA
198772 ** 35 bits - BBBBA
198773 ** 42 bits - BBBBBA
198774 ** 49 bits - BBBBBBA
198775 ** 56 bits - BBBBBBBA
198776 ** 64 bits - BBBBBBBBC
198777 */
198778 
198779 #ifdef SQLITE_NOINLINE
198780 # define FTS5_NOINLINE SQLITE_NOINLINE
198781 #else
198782 # define FTS5_NOINLINE
198783 #endif
198784 
198785 /*
198786 ** Write a 64-bit variable-length integer to memory starting at p[0].
198787 ** The length of data write will be between 1 and 9 bytes. The number
198788 ** of bytes written is returned.
198789 **
198790 ** A variable-length integer consists of the lower 7 bits of each byte
198791 ** for all bytes that have the 8th bit set and one byte with the 8th
198792 ** bit clear. Except, if we get to the 9th byte, it stores the full
198793 ** 8 bits and is the last byte.
198794 */
198795 static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
198796  int i, j, n;
198797  u8 buf[10];
198798  if( v & (((u64)0xff000000)<<32) ){
198799  p[8] = (u8)v;
198800  v >>= 8;
198801  for(i=7; i>=0; i--){
198802  p[i] = (u8)((v & 0x7f) | 0x80);
198803  v >>= 7;
198804  }
198805  return 9;
198806  }
198807  n = 0;
198808  do{
198809  buf[n++] = (u8)((v & 0x7f) | 0x80);
198810  v >>= 7;
198811  }while( v!=0 );
198812  buf[0] &= 0x7f;
198813  assert( n<=9 );
198814  for(i=0, j=n-1; j>=0; j--, i++){
198815  p[i] = buf[j];
198816  }
198817  return n;
198818 }
198819 
198820 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
198821  if( v<=0x7f ){
198822  p[0] = v&0x7f;
198823  return 1;
198824  }
198825  if( v<=0x3fff ){
198826  p[0] = ((v>>7)&0x7f)|0x80;
198827  p[1] = v&0x7f;
198828  return 2;
198829  }
198830  return fts5PutVarint64(p,v);
198831 }
198832 
198833 
198834 static int sqlite3Fts5GetVarintLen(u32 iVal){
198835 #if 0
198836  if( iVal<(1 << 7 ) ) return 1;
198837 #endif
198838  assert( iVal>=(1 << 7) );
198839  if( iVal<(1 << 14) ) return 2;
198840  if( iVal<(1 << 21) ) return 3;
198841  if( iVal<(1 << 28) ) return 4;
198842  return 5;
198843 }
198844 
198845 
198846 /*
198847 ** 2015 May 08
198848 **
198849 ** The author disclaims copyright to this source code. In place of
198850 ** a legal notice, here is a blessing:
198851 **
198852 ** May you do good and not evil.
198853 ** May you find forgiveness for yourself and forgive others.
198854 ** May you share freely, never taking more than you give.
198855 **
198856 ******************************************************************************
198857 **
198858 ** This is an SQLite virtual table module implementing direct access to an
198859 ** existing FTS5 index. The module may create several different types of
198860 ** tables:
198861 **
198862 ** col:
198863 ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
198864 **
198865 ** One row for each term/column combination. The value of $doc is set to
198866 ** the number of fts5 rows that contain at least one instance of term
198867 ** $term within column $col. Field $cnt is set to the total number of
198868 ** instances of term $term in column $col (in any row of the fts5 table).
198869 **
198870 ** row:
198871 ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
198872 **
198873 ** One row for each term in the database. The value of $doc is set to
198874 ** the number of fts5 rows that contain at least one instance of term
198875 ** $term. Field $cnt is set to the total number of instances of term
198876 ** $term in the database.
198877 */
198878 
198879 
198880 /* #include "fts5Int.h" */
198881 
198882 
198883 typedef struct Fts5VocabTable Fts5VocabTable;
198884 typedef struct Fts5VocabCursor Fts5VocabCursor;
198885 
198886 struct Fts5VocabTable {
198887  sqlite3_vtab base;
198888  char *zFts5Tbl; /* Name of fts5 table */
198889  char *zFts5Db; /* Db containing fts5 table */
198890  sqlite3 *db; /* Database handle */
198891  Fts5Global *pGlobal; /* FTS5 global object for this database */
198892  int eType; /* FTS5_VOCAB_COL or ROW */
198893 };
198894 
198895 struct Fts5VocabCursor {
198896  sqlite3_vtab_cursor base;
198897  sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
198898  Fts5Index *pIndex; /* Associated FTS5 index */
198899 
198900  int bEof; /* True if this cursor is at EOF */
198901  Fts5IndexIter *pIter; /* Term/rowid iterator object */
198902 
198903  int nLeTerm; /* Size of zLeTerm in bytes */
198904  char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
198905 
198906  /* These are used by 'col' tables only */
198907  Fts5Config *pConfig; /* Fts5 table configuration */
198908  int iCol;
198909  i64 *aCnt;
198910  i64 *aDoc;
198911 
198912  /* Output values used by 'row' and 'col' tables */
198913  i64 rowid; /* This table's current rowid value */
198914  Fts5Buffer term; /* Current value of 'term' column */
198915 };
198916 
198917 #define FTS5_VOCAB_COL 0
198918 #define FTS5_VOCAB_ROW 1
198919 
198920 #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
198921 #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
198922 
198923 /*
198924 ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
198925 */
198926 #define FTS5_VOCAB_TERM_EQ 0x01
198927 #define FTS5_VOCAB_TERM_GE 0x02
198928 #define FTS5_VOCAB_TERM_LE 0x04
198929 
198930 
198931 /*
198932 ** Translate a string containing an fts5vocab table type to an
198933 ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
198934 ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
198935 ** and return SQLITE_ERROR.
198936 */
198937 static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
198938  int rc = SQLITE_OK;
198939  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
198940  if( rc==SQLITE_OK ){
198941  sqlite3Fts5Dequote(zCopy);
198942  if( sqlite3_stricmp(zCopy, "col")==0 ){
198943  *peType = FTS5_VOCAB_COL;
198944  }else
198945 
198946  if( sqlite3_stricmp(zCopy, "row")==0 ){
198947  *peType = FTS5_VOCAB_ROW;
198948  }else
198949  {
198950  *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
198951  rc = SQLITE_ERROR;
198952  }
198953  sqlite3_free(zCopy);
198954  }
198955 
198956  return rc;
198957 }
198958 
198959 
198960 /*
198961 ** The xDisconnect() virtual table method.
198962 */
198963 static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
198964  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
198965  sqlite3_free(pTab);
198966  return SQLITE_OK;
198967 }
198968 
198969 /*
198970 ** The xDestroy() virtual table method.
198971 */
198972 static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
198973  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
198974  sqlite3_free(pTab);
198975  return SQLITE_OK;
198976 }
198977 
198978 /*
198979 ** This function is the implementation of both the xConnect and xCreate
198980 ** methods of the FTS3 virtual table.
198981 **
198982 ** The argv[] array contains the following:
198983 **
198984 ** argv[0] -> module name ("fts5vocab")
198985 ** argv[1] -> database name
198986 ** argv[2] -> table name
198987 **
198988 ** then:
198989 **
198990 ** argv[3] -> name of fts5 table
198991 ** argv[4] -> type of fts5vocab table
198992 **
198993 ** or, for tables in the TEMP schema only.
198994 **
198995 ** argv[3] -> name of fts5 tables database
198996 ** argv[4] -> name of fts5 table
198997 ** argv[5] -> type of fts5vocab table
198998 */
198999 static int fts5VocabInitVtab(
199000  sqlite3 *db, /* The SQLite database connection */
199001  void *pAux, /* Pointer to Fts5Global object */
199002  int argc, /* Number of elements in argv array */
199003  const char * const *argv, /* xCreate/xConnect argument array */
199004  sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
199005  char **pzErr /* Write any error message here */
199006 ){
199007  const char *azSchema[] = {
199008  "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
199009  "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")"
199010  };
199011 
199012  Fts5VocabTable *pRet = 0;
199013  int rc = SQLITE_OK; /* Return code */
199014  int bDb;
199015 
199016  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
199017 
199018  if( argc!=5 && bDb==0 ){
199019  *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
199020  rc = SQLITE_ERROR;
199021  }else{
199022  int nByte; /* Bytes of space to allocate */
199023  const char *zDb = bDb ? argv[3] : argv[1];
199024  const char *zTab = bDb ? argv[4] : argv[3];
199025  const char *zType = bDb ? argv[5] : argv[4];
199026  int nDb = (int)strlen(zDb)+1;
199027  int nTab = (int)strlen(zTab)+1;
199028  int eType = 0;
199029 
199030  rc = fts5VocabTableType(zType, pzErr, &eType);
199031  if( rc==SQLITE_OK ){
199032  assert( eType>=0 && eType<ArraySize(azSchema) );
199033  rc = sqlite3_declare_vtab(db, azSchema[eType]);
199034  }
199035 
199036  nByte = sizeof(Fts5VocabTable) + nDb + nTab;
199037  pRet = sqlite3Fts5MallocZero(&rc, nByte);
199038  if( pRet ){
199039  pRet->pGlobal = (Fts5Global*)pAux;
199040  pRet->eType = eType;
199041  pRet->db = db;
199042  pRet->zFts5Tbl = (char*)&pRet[1];
199043  pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
199044  memcpy(pRet->zFts5Tbl, zTab, nTab);
199045  memcpy(pRet->zFts5Db, zDb, nDb);
199046  sqlite3Fts5Dequote(pRet->zFts5Tbl);
199047  sqlite3Fts5Dequote(pRet->zFts5Db);
199048  }
199049  }
199050 
199051  *ppVTab = (sqlite3_vtab*)pRet;
199052  return rc;
199053 }
199054 
199055 
199056 /*
199057 ** The xConnect() and xCreate() methods for the virtual table. All the
199058 ** work is done in function fts5VocabInitVtab().
199059 */
199060 static int fts5VocabConnectMethod(
199061  sqlite3 *db, /* Database connection */
199062  void *pAux, /* Pointer to tokenizer hash table */
199063  int argc, /* Number of elements in argv array */
199064  const char * const *argv, /* xCreate/xConnect argument array */
199065  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
199066  char **pzErr /* OUT: sqlite3_malloc'd error message */
199067 ){
199068  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
199069 }
199070 static int fts5VocabCreateMethod(
199071  sqlite3 *db, /* Database connection */
199072  void *pAux, /* Pointer to tokenizer hash table */
199073  int argc, /* Number of elements in argv array */
199074  const char * const *argv, /* xCreate/xConnect argument array */
199075  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
199076  char **pzErr /* OUT: sqlite3_malloc'd error message */
199077 ){
199078  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
199079 }
199080 
199081 /*
199082 ** Implementation of the xBestIndex method.
199083 */
199084 static int fts5VocabBestIndexMethod(
199085  sqlite3_vtab *pUnused,
199086  sqlite3_index_info *pInfo
199087 ){
199088  int i;
199089  int iTermEq = -1;
199090  int iTermGe = -1;
199091  int iTermLe = -1;
199092  int idxNum = 0;
199093  int nArg = 0;
199094 
199095  UNUSED_PARAM(pUnused);
199096 
199097  for(i=0; i<pInfo->nConstraint; i++){
199098  struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
199099  if( p->usable==0 ) continue;
199100  if( p->iColumn==0 ){ /* term column */
199101  if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
199102  if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
199103  if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
199104  if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
199105  if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
199106  }
199107  }
199108 
199109  if( iTermEq>=0 ){
199110  idxNum |= FTS5_VOCAB_TERM_EQ;
199111  pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
199112  pInfo->estimatedCost = 100;
199113  }else{
199114  pInfo->estimatedCost = 1000000;
199115  if( iTermGe>=0 ){
199116  idxNum |= FTS5_VOCAB_TERM_GE;
199117  pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
199118  pInfo->estimatedCost = pInfo->estimatedCost / 2;
199119  }
199120  if( iTermLe>=0 ){
199121  idxNum |= FTS5_VOCAB_TERM_LE;
199122  pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
199123  pInfo->estimatedCost = pInfo->estimatedCost / 2;
199124  }
199125  }
199126 
199127  /* This virtual table always delivers results in ascending order of
199128  ** the "term" column (column 0). So if the user has requested this
199129  ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
199130  ** sqlite3_index_info.orderByConsumed flag to tell the core the results
199131  ** are already in sorted order. */
199132  if( pInfo->nOrderBy==1
199133  && pInfo->aOrderBy[0].iColumn==0
199134  && pInfo->aOrderBy[0].desc==0
199135  ){
199136  pInfo->orderByConsumed = 1;
199137  }
199138 
199139  pInfo->idxNum = idxNum;
199140  return SQLITE_OK;
199141 }
199142 
199143 /*
199144 ** Implementation of xOpen method.
199145 */
199146 static int fts5VocabOpenMethod(
199147  sqlite3_vtab *pVTab,
199148  sqlite3_vtab_cursor **ppCsr
199149 ){
199150  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
199151  Fts5Index *pIndex = 0;
199152  Fts5Config *pConfig = 0;
199153  Fts5VocabCursor *pCsr = 0;
199154  int rc = SQLITE_OK;
199155  sqlite3_stmt *pStmt = 0;
199156  char *zSql = 0;
199157 
199158  zSql = sqlite3Fts5Mprintf(&rc,
199159  "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
199160  pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
199161  );
199162  if( zSql ){
199163  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
199164  }
199165  sqlite3_free(zSql);
199166  assert( rc==SQLITE_OK || pStmt==0 );
199167  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
199168 
199169  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
199170  i64 iId = sqlite3_column_int64(pStmt, 0);
199171  pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
199172  }
199173 
199174  if( rc==SQLITE_OK && pIndex==0 ){
199175  rc = sqlite3_finalize(pStmt);
199176  pStmt = 0;
199177  if( rc==SQLITE_OK ){
199178  pVTab->zErrMsg = sqlite3_mprintf(
199179  "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
199180  );
199181  rc = SQLITE_ERROR;
199182  }
199183  }
199184 
199185  if( rc==SQLITE_OK ){
199186  int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
199187  pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
199188  }
199189 
199190  if( pCsr ){
199191  pCsr->pIndex = pIndex;
199192  pCsr->pStmt = pStmt;
199193  pCsr->pConfig = pConfig;
199194  pCsr->aCnt = (i64*)&pCsr[1];
199195  pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
199196  }else{
199197  sqlite3_finalize(pStmt);
199198  }
199199 
199200  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
199201  return rc;
199202 }
199203 
199204 static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
199205  pCsr->rowid = 0;
199206  sqlite3Fts5IterClose(pCsr->pIter);
199207  pCsr->pIter = 0;
199208  sqlite3_free(pCsr->zLeTerm);
199209  pCsr->nLeTerm = -1;
199210  pCsr->zLeTerm = 0;
199211 }
199212 
199213 /*
199214 ** Close the cursor. For additional information see the documentation
199215 ** on the xClose method of the virtual table interface.
199216 */
199217 static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
199218  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199219  fts5VocabResetCursor(pCsr);
199220  sqlite3Fts5BufferFree(&pCsr->term);
199221  sqlite3_finalize(pCsr->pStmt);
199222  sqlite3_free(pCsr);
199223  return SQLITE_OK;
199224 }
199225 
199226 
199227 /*
199228 ** Advance the cursor to the next row in the table.
199229 */
199230 static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
199231  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199232  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
199233  int rc = SQLITE_OK;
199234  int nCol = pCsr->pConfig->nCol;
199235 
199236  pCsr->rowid++;
199237 
199238  if( pTab->eType==FTS5_VOCAB_COL ){
199239  for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
199240  if( pCsr->aDoc[pCsr->iCol] ) break;
199241  }
199242  }
199243 
199244  if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
199245  if( sqlite3Fts5IterEof(pCsr->pIter) ){
199246  pCsr->bEof = 1;
199247  }else{
199248  const char *zTerm;
199249  int nTerm;
199250 
199251  zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
199252  if( pCsr->nLeTerm>=0 ){
199253  int nCmp = MIN(nTerm, pCsr->nLeTerm);
199254  int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
199255  if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
199256  pCsr->bEof = 1;
199257  return SQLITE_OK;
199258  }
199259  }
199260 
199261  sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
199262  memset(pCsr->aCnt, 0, nCol * sizeof(i64));
199263  memset(pCsr->aDoc, 0, nCol * sizeof(i64));
199264  pCsr->iCol = 0;
199265 
199266  assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
199267  while( rc==SQLITE_OK ){
199268  const u8 *pPos; int nPos; /* Position list */
199269  i64 iPos = 0; /* 64-bit position read from poslist */
199270  int iOff = 0; /* Current offset within position list */
199271 
199272  pPos = pCsr->pIter->pData;
199273  nPos = pCsr->pIter->nData;
199274  switch( pCsr->pConfig->eDetail ){
199275  case FTS5_DETAIL_FULL:
199276  pPos = pCsr->pIter->pData;
199277  nPos = pCsr->pIter->nData;
199278  if( pTab->eType==FTS5_VOCAB_ROW ){
199279  while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
199280  pCsr->aCnt[0]++;
199281  }
199282  pCsr->aDoc[0]++;
199283  }else{
199284  int iCol = -1;
199285  while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
199286  int ii = FTS5_POS2COLUMN(iPos);
199287  pCsr->aCnt[ii]++;
199288  if( iCol!=ii ){
199289  if( ii>=nCol ){
199290  rc = FTS5_CORRUPT;
199291  break;
199292  }
199293  pCsr->aDoc[ii]++;
199294  iCol = ii;
199295  }
199296  }
199297  }
199298  break;
199299 
199300  case FTS5_DETAIL_COLUMNS:
199301  if( pTab->eType==FTS5_VOCAB_ROW ){
199302  pCsr->aDoc[0]++;
199303  }else{
199304  while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
199305  assert_nc( iPos>=0 && iPos<nCol );
199306  if( iPos>=nCol ){
199307  rc = FTS5_CORRUPT;
199308  break;
199309  }
199310  pCsr->aDoc[iPos]++;
199311  }
199312  }
199313  break;
199314 
199315  default:
199316  assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
199317  pCsr->aDoc[0]++;
199318  break;
199319  }
199320 
199321  if( rc==SQLITE_OK ){
199322  rc = sqlite3Fts5IterNextScan(pCsr->pIter);
199323  }
199324 
199325  if( rc==SQLITE_OK ){
199326  zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
199327  if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
199328  break;
199329  }
199330  if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
199331  }
199332  }
199333  }
199334  }
199335 
199336  if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
199337  while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
199338  assert( pCsr->iCol<pCsr->pConfig->nCol );
199339  }
199340  return rc;
199341 }
199342 
199343 /*
199344 ** This is the xFilter implementation for the virtual table.
199345 */
199346 static int fts5VocabFilterMethod(
199347  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
199348  int idxNum, /* Strategy index */
199349  const char *zUnused, /* Unused */
199350  int nUnused, /* Number of elements in apVal */
199351  sqlite3_value **apVal /* Arguments for the indexing scheme */
199352 ){
199353  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199354  int rc = SQLITE_OK;
199355 
199356  int iVal = 0;
199357  int f = FTS5INDEX_QUERY_SCAN;
199358  const char *zTerm = 0;
199359  int nTerm = 0;
199360 
199361  sqlite3_value *pEq = 0;
199362  sqlite3_value *pGe = 0;
199363  sqlite3_value *pLe = 0;
199364 
199365  UNUSED_PARAM2(zUnused, nUnused);
199366 
199367  fts5VocabResetCursor(pCsr);
199368  if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
199369  if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
199370  if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
199371 
199372  if( pEq ){
199373  zTerm = (const char *)sqlite3_value_text(pEq);
199374  nTerm = sqlite3_value_bytes(pEq);
199375  f = 0;
199376  }else{
199377  if( pGe ){
199378  zTerm = (const char *)sqlite3_value_text(pGe);
199379  nTerm = sqlite3_value_bytes(pGe);
199380  }
199381  if( pLe ){
199382  const char *zCopy = (const char *)sqlite3_value_text(pLe);
199383  pCsr->nLeTerm = sqlite3_value_bytes(pLe);
199384  pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
199385  if( pCsr->zLeTerm==0 ){
199386  rc = SQLITE_NOMEM;
199387  }else{
199388  memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
199389  }
199390  }
199391  }
199392 
199393 
199394  if( rc==SQLITE_OK ){
199395  rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
199396  }
199397  if( rc==SQLITE_OK ){
199398  rc = fts5VocabNextMethod(pCursor);
199399  }
199400 
199401  return rc;
199402 }
199403 
199404 /*
199405 ** This is the xEof method of the virtual table. SQLite calls this
199406 ** routine to find out if it has reached the end of a result set.
199407 */
199408 static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
199409  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199410  return pCsr->bEof;
199411 }
199412 
199413 static int fts5VocabColumnMethod(
199414  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
199415  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
199416  int iCol /* Index of column to read value from */
199417 ){
199418  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199419  int eDetail = pCsr->pConfig->eDetail;
199420  int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
199421  i64 iVal = 0;
199422 
199423  if( iCol==0 ){
199424  sqlite3_result_text(
199425  pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
199426  );
199427  }else if( eType==FTS5_VOCAB_COL ){
199428  assert( iCol==1 || iCol==2 || iCol==3 );
199429  if( iCol==1 ){
199430  if( eDetail!=FTS5_DETAIL_NONE ){
199431  const char *z = pCsr->pConfig->azCol[pCsr->iCol];
199432  sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
199433  }
199434  }else if( iCol==2 ){
199435  iVal = pCsr->aDoc[pCsr->iCol];
199436  }else{
199437  iVal = pCsr->aCnt[pCsr->iCol];
199438  }
199439  }else{
199440  assert( iCol==1 || iCol==2 );
199441  if( iCol==1 ){
199442  iVal = pCsr->aDoc[0];
199443  }else{
199444  iVal = pCsr->aCnt[0];
199445  }
199446  }
199447 
199448  if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
199449  return SQLITE_OK;
199450 }
199451 
199452 /*
199453 ** This is the xRowid method. The SQLite core calls this routine to
199454 ** retrieve the rowid for the current row of the result set. The
199455 ** rowid should be written to *pRowid.
199456 */
199457 static int fts5VocabRowidMethod(
199458  sqlite3_vtab_cursor *pCursor,
199459  sqlite_int64 *pRowid
199460 ){
199461  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199462  *pRowid = pCsr->rowid;
199463  return SQLITE_OK;
199464 }
199465 
199466 static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
199467  static const sqlite3_module fts5Vocab = {
199468  /* iVersion */ 2,
199469  /* xCreate */ fts5VocabCreateMethod,
199470  /* xConnect */ fts5VocabConnectMethod,
199471  /* xBestIndex */ fts5VocabBestIndexMethod,
199472  /* xDisconnect */ fts5VocabDisconnectMethod,
199473  /* xDestroy */ fts5VocabDestroyMethod,
199474  /* xOpen */ fts5VocabOpenMethod,
199475  /* xClose */ fts5VocabCloseMethod,
199476  /* xFilter */ fts5VocabFilterMethod,
199477  /* xNext */ fts5VocabNextMethod,
199478  /* xEof */ fts5VocabEofMethod,
199479  /* xColumn */ fts5VocabColumnMethod,
199480  /* xRowid */ fts5VocabRowidMethod,
199481  /* xUpdate */ 0,
199482  /* xBegin */ 0,
199483  /* xSync */ 0,
199484  /* xCommit */ 0,
199485  /* xRollback */ 0,
199486  /* xFindFunction */ 0,
199487  /* xRename */ 0,
199488  /* xSavepoint */ 0,
199489  /* xRelease */ 0,
199490  /* xRollbackTo */ 0,
199491  };
199492  void *p = (void*)pGlobal;
199493 
199494  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
199495 }
199496 
199497 
199498 
199499 
199500 
199501 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
199502 
199503 /************** End of fts5.c ************************************************/
Definition: sqlite3.c:54229
Definition: sqlite3.c:13755
Definition: sqlite3.c:17890
#define assert(x)
Definition: assert.h:37
Definition: mem.c:283